Search in sources :

Example 11 with GlobalSessionObject

use of com.hp.oo.sdk.content.plugin.GlobalSessionObject in project cs-actions by CloudSlang.

the class HttpClientService method execute.

public static Map<String, String> execute(HttpClientInputs httpClientInputs) throws Exception {
    URI uri = UriBuilder.getUri(httpClientInputs);
    HttpUriRequestBase httpRequest = new HttpUriRequestBase(httpClientInputs.getMethod(), uri);
    SSLConnectionSocketFactory socketFactory = CustomSSLSocketFactory.createSSLSocketFactory(httpClientInputs);
    CustomConnectionManager customConnectionManager = new CustomConnectionManager();
    GlobalSessionObject globalSessionObject = httpClientInputs.getConnectionPoolSessionObject();
    if (globalSessionObject == null)
        customConnectionManager.setConnectionPoolHolder(new GlobalSessionObject());
    else
        customConnectionManager.setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject());
    String connectionKey = CustomConnectionManager.buildConnectionManagerMapKey(httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(), httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    customConnectionManager.setConnectionManagerMapKey(connectionKey);
    SerializableSessionObject cookieStoreSessionObject = httpClientInputs.getCookieStoreSessionObject();
    if (cookieStoreSessionObject == null) {
        cookieStoreSessionObject = new SerializableSessionObject();
    }
    CookieStore cookieStore = CookieStoreBuilder.buildCookieStore(cookieStoreSessionObject, httpClientInputs.getUseCookies());
    PoolingHttpClientConnectionManager connectionManager = customConnectionManager.getConnectionManager(httpClientInputs, socketFactory, uri);
    CredentialsProvider credentialsProvider = CustomCredentialsProvider.getCredentialsProvider(httpClientInputs, uri);
    RequestConfig requestConfig = CustomRequestConfig.getDefaultRequestConfig(httpClientInputs);
    HttpClientContext context = CustomHttpClientContext.getHttpClientContext(httpClientInputs, credentialsProvider, uri);
    HttpEntity httpEntity = CustomEntity.getHttpEntity(httpClientInputs);
    httpRequest.setEntity(httpEntity);
    HeaderBuilder.headerBuiler(httpRequest, httpClientInputs);
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig);
    if (cookieStore != null)
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    CloseableHttpClient httpclient = httpClientBuilder.build();
    Map<String, String> result = new HashMap<>();
    if (httpClientInputs.getExecutionTimeout().equals(ZERO))
        try (final CloseableHttpResponse response = httpclient.execute(httpRequest, context)) {
            ResponseHandler.consume(result, response, httpClientInputs.getResponseCharacterSet(), httpClientInputs.getDestinationFile());
            ResponseHandler.getResponseHeaders(result, response.getHeaders());
            ResponseHandler.getStatusResponse(result, response);
            ResponseHandler.getFinalLocationResponse(result, uri, context.getRedirectLocations().getAll());
        }
    else
        ExecutionTimeout.runWithTimeout(new Runnable() {

            @Override
            public void run() {
                try (final CloseableHttpResponse response = httpclient.execute(httpRequest, context)) {
                    ResponseHandler.consume(result, response, httpClientInputs.getResponseCharacterSet(), httpClientInputs.getDestinationFile());
                    ResponseHandler.getResponseHeaders(result, response.getHeaders());
                    ResponseHandler.getStatusResponse(result, response);
                    ResponseHandler.getFinalLocationResponse(result, uri, context.getRedirectLocations().getAll());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, Integer.parseInt(httpClientInputs.getExecutionTimeout()), TimeUnit.SECONDS);
    if (cookieStore != null) {
        try {
            cookieStoreSessionObject.setValue(CookieStoreBuilder.serialize(cookieStore));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    result.put(RETURN_CODE, SUCCESS);
    return result;
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) HttpEntity(org.apache.hc.core5.http.HttpEntity) HashMap(java.util.HashMap) SerializableSessionObject(com.hp.oo.sdk.content.plugin.SerializableSessionObject) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) IOException(java.io.IOException) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager) CookieStore(org.apache.hc.client5.http.cookie.CookieStore) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 12 with GlobalSessionObject

use of com.hp.oo.sdk.content.plugin.GlobalSessionObject in project cloud-slang by CloudSlang.

the class ActionStepsTest method doJavaActionGetKeyFromNonSerializableSessionTest.

@Test(timeout = DEFAULT_TIMEOUT)
public void doJavaActionGetKeyFromNonSerializableSessionTest() {
    // prepare doAction arguments
    HashMap<String, Map<String, Object>> nonSerializableExecutionData = new HashMap<>();
    HashMap<String, Object> globalSessionObject = new HashMap<>();
    GlobalSessionObject<NonSerializableObject> sessionObject = new GlobalSessionObject<>();
    NonSerializableObject employee = new NonSerializableObject("John");
    sessionObject.setResource(new ContentTestActions.NonSerializableSessionResource(employee));
    globalSessionObject.put("name", sessionObject);
    nonSerializableExecutionData.put(GLOBAL_SESSION_OBJECT, globalSessionObject);
    // invoke doAction
    RunEnvironment runEnv = new RunEnvironment();
    actionSteps.doAction(executionRuntimeServicesMock, runEnv, nonSerializableExecutionData, 2L, JAVA, ContentTestActions.class.getName(), "getNameFromNonSerializableSession", GAV_DEFAULT, null, true, DEPENDENCIES_DEFAULT, seqSteps, null, null);
    Map<String, Value> outputs = runEnv.removeReturnValues().getOutputs();
    Assert.assertTrue(outputs.containsKey("name"));
    assertEquals("John", outputs.get("name").get());
}
Also used : NonSerializableObject(io.cloudslang.lang.runtime.steps.ContentTestActions.NonSerializableObject) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) RunEnvironment(io.cloudslang.lang.runtime.env.RunEnvironment) HashMap(java.util.HashMap) Value(io.cloudslang.lang.entities.bindings.values.Value) SerializableSessionObject(com.hp.oo.sdk.content.plugin.SerializableSessionObject) NonSerializableObject(io.cloudslang.lang.runtime.steps.ContentTestActions.NonSerializableObject) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 13 with GlobalSessionObject

use of com.hp.oo.sdk.content.plugin.GlobalSessionObject in project cs-actions by CloudSlang.

the class SQLQuery method execute.

/**
 * @param dbServerName              The hostname or ip address of the database server.
 * @param dbType                    The type of database to connect to
 *                                  Valid values: Oracle, MSSQL, Sybase, Netcool, DB2, PostgreSQL and Custom.
 *                                  Default value: Oracle
 * @param username                  The username to use when connecting to the server.
 * @param password                  The password to use when connecting to the server.
 * @param instance                  The name instance of MSSQL Server. Leave it blank for default instance.
 *                                  Example: MSSQLSERVER
 * @param dbPort                    The port to connect to.
 *                                  Valid values: Oracle: 1521, MSSQL: 1433, Sybase: 5000, Netcool: 4100, DB2: 50000, PostgreSQL: 5432.
 * @param databaseName              The name of the database to connect to.
 * @param authenticationType        The type of authentication used to access the database (applicable only to MSSQL type).
 *                                  Default: sql
 *                                  Values: sql, windows
 * @param dbClass                   The classname of the JDBC driver to use.
 *                                  Examples: "oracle.jdbc.driver.OracleDriver", "org.postgresql.Driver"
 * @param dbURL                     The url required to load up the driver and make your connection.
 *                                  Examples: "jdbc:oracle:drivertype:@database", "jdbc:postgresql://host:port/database"
 * @param command                   The SQL query to execute.
 *                                  Example: "SELECT * FROM table"
 * @param trustAllRoots             Specifies whether to enable weak security over SSL/TSL. A certificate is trusted even if no trusted certification authority issued it.
 *                                  Default value: false
 *                                  Valid values: true, false
 *                                  Note: If trustAllRoots is set to 'false', a trustStore and a trustStorePassword must be provided.
 * @param trustStore                The pathname of the Java TrustStore file. This contains certificates from other parties that you expect to communicate with,
 *                                  or from Certificate Authorities that you trust to identify other parties.
 *                                  If the trustAllRoots input is set to 'true' this input is ignored.
 * @param trustStorePassword        The password associated with the trustStore file.
 * @param authLibraryPath           The path to the folder where sqljdbc_auth.dll is located. This path must be provided when using windows authentication.
 *                                  Note: The sqljdbc_auth.dll can be found inside the sqljdbc driver. The driver can be downloaded from https://www.microsoft.com/en-us/download/details.aspx?id=11774.
 *                                  The downloaded jar should be extracted and the library can be found in the 'auth' folder.
 *                                  The path provided should be the path to the folder where the sqljdbc_auth.dll library is located, not the path to the file itself.
 * @param delimiter                 The delimiter to use between resulted values in "returnResult" and column names in "columnNames".
 * @param key                       The key to help keep multiple query results distinct.
 * @param timeout                   Seconds to wait before timing out the SQL command execution. When the default value is used, there
 *                                  is no limit on the amount of time allowed for a running command to complete.
 *                                  Default values: 0
 * @param databasePoolingProperties Properties for database pooling configuration. Pooling is disabled by default.
 *                                  Default: db.pooling.enable=false
 *                                  Example: db.pooling.enable=true
 * @param resultSetType             the result set type. See JDBC folder description for more details.
 *                                  Valid values: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE,TYPE_SCROLL_SENSITIVE.
 *                                  Default value: TYPE_SCROLL_INSENSITIVE except DB2 which is overridden to TYPE_FORWARD_ONLY
 * @param resultSetConcurrency      the result set concurrency. See JDBC folder description for more details.
 *                                  Valid values: CONCUR_READ_ONLY, CONCUR_UPDATABLE
 *                                  Default value: CONCUR_READ_ONLY
 * @param ignoreCase                If set to true the inputs' letters case will be ignored and converted to lowercase.
 *                                  Valid values: true, false
 *                                  Default value: true
 * @return It contains the data of one row, separated by the "delimiter".
 */
@Action(name = "SQL Query", outputs = { @Output(RETURN_CODE), @Output(RETURN_RESULT), @Output(EXCEPTION), @Output(ROWS_LEFT), @Output(COLUMN_NAMES), @Output(SQL_QUERY) }, responses = { @Response(text = HAS_MORE, field = RETURN_CODE, value = SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = NO_MORE, field = RETURN_CODE, value = DBReturnCodes.NO_MORE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = DB_SERVER_NAME, required = true) String dbServerName, @Param(value = DB_TYPE) String dbType, @Param(value = USERNAME) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = INSTANCE) String instance, @Param(value = DB_PORT) String dbPort, @Param(value = DATABASE_NAME, required = true) String databaseName, @Param(value = AUTHENTICATION_TYPE) String authenticationType, @Param(value = DB_CLASS) String dbClass, @Param(value = DB_URL) String dbURL, @Param(value = COMMAND, required = true) String command, @Param(value = TRUST_ALL_ROOTS) String trustAllRoots, @Param(value = TRUST_STORE) String trustStore, @Param(value = TRUST_STORE_PASSWORD) String trustStorePassword, @Param(value = AUTH_LIBRARY_PATH) String authLibraryPath, @Param(value = DELIMITER, required = true) String delimiter, @Param(value = KEY, required = true) String key, @Param(value = TIMEOUT) String timeout, @Param(value = DATABASE_POOLING_PROPERTIES) String databasePoolingProperties, @Param(value = RESULT_SET_TYPE) String resultSetType, @Param(value = RESULT_SET_CONCURRENCY) String resultSetConcurrency, @Param(value = IGNORE_CASE) String ignoreCase, @Param(value = GLOBAL_SESSION_OBJECT) GlobalSessionObject<Map<String, Object>> globalSessionObject) {
    dbType = defaultIfEmpty(dbType, ORACLE_DB_TYPE);
    username = defaultIfEmpty(username, EMPTY);
    password = defaultIfEmpty(password, EMPTY);
    instance = defaultIfEmpty(instance, EMPTY);
    authenticationType = defaultIfEmpty(authenticationType, AUTH_SQL);
    trustAllRoots = defaultIfEmpty(trustAllRoots, FALSE);
    trustStore = defaultIfEmpty(trustStore, EMPTY);
    trustStorePassword = defaultIfEmpty(trustStorePassword, EMPTY);
    timeout = defaultIfEmpty(timeout, DEFAULT_TIMEOUT);
    resultSetType = defaultIfEmpty(resultSetType, TYPE_SCROLL_INSENSITIVE);
    resultSetConcurrency = defaultIfEmpty(resultSetConcurrency, CONCUR_READ_ONLY);
    ignoreCase = defaultIfEmpty(ignoreCase, TRUE);
    final List<String> preInputsValidation = validateSqlQueryInputs(dbServerName, dbType, username, password, instance, dbPort, databaseName, authenticationType, command, trustAllRoots, trustStore, trustStorePassword, timeout, resultSetType, resultSetConcurrency, ignoreCase, authLibraryPath);
    if (!preInputsValidation.isEmpty()) {
        return getFailureResultsMap(StringUtils.join(preInputsValidation, NEW_LINE));
    }
    final boolean ignoreCaseBool = toBoolean(ignoreCase);
    dbType = getDbType(dbType);
    final SQLInputs sqlInputs = SQLInputs.builder().dbServer(dbServerName).dbType(dbType).username(username).password(password).instance(getOrLower(instance, ignoreCaseBool)).dbPort(getOrDefaultDBPort(dbPort, dbType)).dbName(getOrLower(defaultIfEmpty(databaseName, EMPTY), ignoreCaseBool)).authenticationType(authenticationType).dbClass(getOrDefaultDBClass(dbClass, dbType)).dbUrl(defaultIfEmpty(dbURL, EMPTY)).sqlCommand(command).trustAllRoots(toBoolean(trustAllRoots)).trustStore(trustStore).trustStorePassword(trustStorePassword).authLibraryPath(authLibraryPath).strDelim(delimiter).key(key).timeout(toInteger(timeout)).databasePoolingProperties(getOrDefaultDBPoolingProperties(databasePoolingProperties, EMPTY)).resultSetType(getResultSetTypeForDbType(resultSetType, dbType)).resultSetConcurrency(getResultSetConcurrency(resultSetConcurrency)).ignoreCase(ignoreCaseBool).isNetcool(checkIsNetcool(dbType)).build();
    try {
        final String aKey = getSqlKey(sqlInputs);
        globalSessionObject = getOrDefaultGlobalSessionObj(globalSessionObject);
        final Map<String, Object> globalMap = globalSessionObject.get();
        if (globalMap.containsKey(aKey)) {
            sqlInputs.setLRows(getRowsFromGlobalSessionMap(globalSessionObject, aKey));
        } else {
            SQLQueryService.executeSqlQuery(sqlInputs);
        }
        Map<String, String> result = new HashMap<>();
        if (!sqlInputs.getLRows().isEmpty()) {
            final String getFirstRow = sqlInputs.getLRows().remove(0);
            result = getSuccessResultsMap(getFirstRow);
            result.put(COLUMN_NAMES, sqlInputs.getStrColumns());
            result.put(ROWS_LEFT, String.valueOf(sqlInputs.getLRows().size()));
            globalMap.put(aKey, sqlInputs.getLRows());
            globalSessionObject.setResource(new SQLSessionResource(globalMap));
        } else {
            result.put(SQL_QUERY, sqlInputs.getSqlCommand());
            result.put(RETURN_RESULT, NO_MORE);
            result.put(ROWS_LEFT, ZERO);
            result.put(RETURN_CODE, DBReturnCodes.NO_MORE);
            globalMap.put(aKey, null);
        }
        return result;
    } catch (Exception e) {
        final Map<String, String> failureMap = getFailureResultsMap(e);
        failureMap.put(ROWS_LEFT, ZERO);
        return failureMap;
    }
}
Also used : HashMap(java.util.HashMap) SQLInputs(io.cloudslang.content.database.utils.SQLInputs) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) HashMap(java.util.HashMap) OutputUtilities.getSuccessResultsMap(io.cloudslang.content.utils.OutputUtilities.getSuccessResultsMap) Map(java.util.Map) SQLUtils.getRowsFromGlobalSessionMap(io.cloudslang.content.database.utils.SQLUtils.getRowsFromGlobalSessionMap) OutputUtilities.getFailureResultsMap(io.cloudslang.content.utils.OutputUtilities.getFailureResultsMap) SQLSessionResource(io.cloudslang.content.database.utils.SQLSessionResource) Action(com.hp.oo.sdk.content.annotations.Action)

Example 14 with GlobalSessionObject

use of com.hp.oo.sdk.content.plugin.GlobalSessionObject in project cs-actions by CloudSlang.

the class SQLQueryLOB method execute.

/**
 * @param dbServerName              The hostname or ip address of the database server.
 * @param dbType                    The type of database to connect to
 *                                  Valid values: Oracle, MSSQL, Sybase, Netcool, DB2, PostgreSQL and Custom.
 *                                  Default value: Oracle
 * @param username                  The username to use when connecting to the server.
 * @param password                  The password to use when connecting to the server.
 * @param instance                  The name instance of MSSQL Server. Leave it blank for default instance.
 *                                  Example: MSSQLSERVER
 * @param dbPort                    The port to connect to.
 *                                  Valid values: Oracle: 1521, MSSQL: 1433, Sybase: 5000, Netcool: 4100, DB2: 50000, PostgreSQL: 5432.
 * @param databaseName              The name of the database to connect to.
 * @param authenticationType        The type of authentication used to access the database (applicable only to MSSQL type).
 *                                  Default: sql
 *                                  Values: sql, windows
 * @param dbClass                   The classname of the JDBC driver to use.
 *                                  Examples: "oracle.jdbc.driver.OracleDriver", "org.postgresql.Driver"
 * @param dbURL                     The url required to load up the driver and make your connection.
 *                                  Examples: "jdbc:oracle:drivertype:@database", "jdbc:postgresql://host:port/database"
 * @param command                   The SQL query to execute.
 *                                  Example: "SELECT * FROM table"
 * @param trustAllRoots             Specifies whether to enable weak security over SSL/TSL. A certificate is trusted even if no trusted certification authority issued it.
 *                                  Default value: false
 *                                  Valid values: true, false
 *                                  Note: If trustAllRoots is set to 'false', a trustStore and a trustStorePassword must be provided.
 * @param trustStore                The pathname of the Java TrustStore file. This contains certificates from other parties that you expect to communicate with,
 *                                  or from Certificate Authorities that you trust to identify other parties.
 *                                  If the trustAllRoots input is set to 'true' this input is ignored.
 * @param trustStorePassword        The password associated with the trustStore file.
 * @param authLibraryPath           The path to the folder where sqljdbc_auth.dll is located. This path must be provided when using windows authentication.
 *                                  Note: The sqljdbc_auth.dll can be found inside the sqljdbc driver. The driver can be downloaded from https://www.microsoft.com/en-us/download/details.aspx?id=11774.
 *                                  The downloaded jar should be extracted and the library can be found in the 'auth' folder.
 *                                  The path provided should be the path to the folder where the sqljdbc_auth.dll library is located, not the path to the file itself.
 * @param delimiter                 The delimiter to use between resulted values in "returnResult" and column names in "columnNames".
 * @param key                       The key to help keep multiple query results distinct.
 * @param timeout                   Seconds to wait before timing out the SQL command execution. When the default value is used, there
 *                                  is no limit on the amount of time allowed for a running command to complete.
 *                                  Default values: 0
 * @param databasePoolingProperties Properties for database pooling configuration. Pooling is disabled by default.
 *                                  Default: db.pooling.enable=false
 *                                  Example: db.pooling.enable=true
 * @param resultSetType             the result set type. See JDBC folder description for more details.
 *                                  Valid values: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE,TYPE_SCROLL_SENSITIVE.
 *                                  Default value: TYPE_SCROLL_INSENSITIVE except DB2 which is overridden to TYPE_FORWARD_ONLY
 * @param resultSetConcurrency      the result set concurrency. See JDBC folder description for more details.
 *                                  Valid values: CONCUR_READ_ONLY, CONCUR_UPDATABLE
 *                                  Default value: CONCUR_READ_ONLY
 * @return Returns the data of a row returned from query. It is delimited by <delimiter>.
 */
@Action(name = "SQL Query LOB", outputs = { @Output(RETURN_CODE), @Output(RETURN_RESULT), @Output(EXCEPTION), @Output(ROWS_LEFT), @Output(SQL_QUERY), @Output(COLUMN_NAMES) }, responses = { @Response(text = HAS_MORE, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED), @Response(text = NO_MORE, field = RETURN_CODE, value = DBReturnCodes.NO_MORE, matchType = COMPARE_EQUAL, responseType = RESOLVED), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = DB_SERVER_NAME, required = true) String dbServerName, @Param(value = DB_TYPE) String dbType, @Param(value = USERNAME) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = INSTANCE) String instance, @Param(value = DB_PORT) String dbPort, @Param(value = DATABASE_NAME, required = true) String databaseName, @Param(value = AUTHENTICATION_TYPE) String authenticationType, @Param(value = DB_CLASS) String dbClass, @Param(value = DB_URL) String dbURL, @Param(value = COMMAND, required = true) String command, @Param(value = TRUST_ALL_ROOTS) String trustAllRoots, @Param(value = TRUST_STORE) String trustStore, @Param(value = TRUST_STORE_PASSWORD) String trustStorePassword, @Param(value = AUTH_LIBRARY_PATH) String authLibraryPath, @Param(value = DELIMITER, required = true) String delimiter, @Param(value = KEY, required = true) String key, @Param(value = TIMEOUT) String timeout, @Param(value = DATABASE_POOLING_PROPERTIES) String databasePoolingProperties, @Param(value = RESULT_SET_TYPE) String resultSetType, @Param(value = RESULT_SET_CONCURRENCY) String resultSetConcurrency, @Param(value = GLOBAL_SESSION_OBJECT) GlobalSessionObject<Map<String, Object>> globalSessionObject) {
    dbType = defaultIfEmpty(dbType, ORACLE_DB_TYPE);
    username = defaultIfEmpty(username, EMPTY);
    password = defaultIfEmpty(password, EMPTY);
    instance = defaultIfEmpty(instance, EMPTY);
    authenticationType = defaultIfEmpty(authenticationType, AUTH_SQL);
    trustAllRoots = defaultIfEmpty(trustAllRoots, FALSE);
    trustStore = defaultIfEmpty(trustStore, EMPTY);
    trustStorePassword = defaultIfEmpty(trustStorePassword, EMPTY);
    timeout = defaultIfEmpty(timeout, DEFAULT_TIMEOUT);
    resultSetType = defaultIfEmpty(resultSetType, TYPE_SCROLL_INSENSITIVE);
    resultSetConcurrency = defaultIfEmpty(resultSetConcurrency, CONCUR_READ_ONLY);
    final List<String> preInputsValidation = validateSqlQueryLOBInputs(dbServerName, dbType, username, password, instance, dbPort, databaseName, authenticationType, command, trustAllRoots, trustStore, trustStorePassword, timeout, resultSetType, resultSetConcurrency, authLibraryPath);
    if (!preInputsValidation.isEmpty()) {
        return getFailureResultsMap(StringUtils.join(preInputsValidation, NEW_LINE));
    }
    dbType = getDbType(dbType);
    final SQLInputs sqlInputs = SQLInputs.builder().dbServer(dbServerName).dbType(dbType).username(username).password(password).instance(getOrLower(instance, true)).dbPort(getOrDefaultDBPort(dbPort, dbType)).dbName(getOrLower(defaultIfEmpty(databaseName, EMPTY), true)).authenticationType(authenticationType).dbClass(getOrDefaultDBClass(dbClass, dbType)).dbUrl(defaultIfEmpty(dbURL, EMPTY)).sqlCommand(command).trustAllRoots(BooleanUtilities.toBoolean(trustAllRoots)).trustStore(trustStore).trustStorePassword(defaultIfEmpty(trustStorePassword, EMPTY)).authLibraryPath(authLibraryPath).strDelim(delimiter).key(key).timeout(toInteger(timeout)).databasePoolingProperties(getOrDefaultDBPoolingProperties(databasePoolingProperties, EMPTY)).resultSetType(getResultSetTypeForDbType(resultSetType, dbType)).resultSetConcurrency(getResultSetConcurrency(resultSetConcurrency)).ignoreCase(true).isNetcool(checkIsNetcool(dbType)).build();
    try {
        final String aKey = SQLInputsUtils.getSqlKey(sqlInputs);
        final String strKeyCol = format(KEY_COLUMNS, aKey);
        final String strKeyFiles = format(KEY_FILES, aKey);
        final String strKeyNames = format(KEY_CLOB_NAMES, aKey);
        final String strKeySkip = format(KEY_SKIP, aKey);
        globalSessionObject = getOrDefaultGlobalSessionObj(globalSessionObject);
        final Map<String, Object> sqlConnectionMap = globalSessionObject.get();
        Map<String, String> result = new HashMap<>();
        if (sqlConnectionMap.containsKey(aKey)) {
            sqlInputs.setLRows(getRowsFromGlobalSessionMap(globalSessionObject, aKey));
            sqlInputs.setStrColumns(getStrColumns(globalSessionObject, strKeyCol));
            if (sqlConnectionMap.get(strKeyFiles) != null) {
                sqlInputs.setSkip((Long) sqlConnectionMap.get(strKeySkip));
                sqlInputs.setLRowsFiles((List) sqlConnectionMap.get(strKeyFiles));
                sqlInputs.setLRowsNames((List) sqlConnectionMap.get(strKeyNames));
            }
            if (sqlInputs.getLRows().isEmpty() && (sqlInputs.getLRowsFiles() == null || sqlInputs.getLRowsFiles().isEmpty())) {
                sqlConnectionMap.put(aKey, null);
                sqlConnectionMap.put(strKeyCol, null);
                sqlConnectionMap.put(strKeyFiles, null);
                sqlConnectionMap.put(strKeyNames, null);
                sqlConnectionMap.put(strKeySkip, 0L);
                result.put(RETURN_RESULT, NO_MORE);
                result.put(ROWS_LEFT, ZERO);
                result.put(RETURN_CODE, DBReturnCodes.NO_MORE);
            } else if (sqlInputs.getLRowsFiles() == null || sqlInputs.getLRowsFiles().isEmpty() || (sqlInputs.getLRows().size() == sqlInputs.getLRowsFiles().size())) {
                final String getFirstRow = sqlInputs.getLRows().remove(0);
                result.put(RETURN_RESULT, getFirstRow);
                result.put(COLUMN_NAMES, sqlInputs.getStrColumns());
                result.put(ROWS_LEFT, String.valueOf(sqlInputs.getLRows().size()));
                result.put(RETURN_CODE, SUCCESS);
                sqlConnectionMap.put(aKey, sqlInputs.getLRows());
            } else {
                final String colName = "CLOB column: " + ((List) sqlInputs.getLRowsNames().get(0)).get(0);
                final File tmpFile = new File(sqlInputs.getLRowsFiles().get(0).get(0));
                final String fileContent = FileUtils.readFileToString(tmpFile, StandardCharsets.UTF_8);
                FileUtils.deleteQuietly(tmpFile);
                sqlInputs.getLRowsFiles().get(0).remove(0);
                sqlInputs.getLRowsNames().get(0).remove(0);
                if (sqlInputs.getLRowsFiles().get(0).isEmpty()) {
                    sqlInputs.getLRowsFiles().remove(0);
                    sqlInputs.getLRowsNames().remove(0);
                }
                result.put(RETURN_RESULT, fileContent);
                result.put(COLUMN_NAMES, colName);
                result.put(ROWS_LEFT, String.valueOf(sqlInputs.getLRows().size()));
                result.put(RETURN_CODE, SUCCESS);
                sqlConnectionMap.put(strKeyFiles, sqlInputs.getLRowsFiles());
                sqlConnectionMap.put(strKeyNames, sqlInputs.getLRowsNames());
                sqlConnectionMap.put(strKeySkip, sqlInputs.getSkip());
            }
            globalSessionObject.setResource(new SQLSessionResource(sqlConnectionMap));
        } else {
            // globalSessionObject
            boolean isLOB = SQLQueryLobService.executeSqlQueryLob(sqlInputs);
            if (!sqlInputs.getLRows().isEmpty()) {
                final String getFirstRow = sqlInputs.getLRows().remove(0);
                result.put(RETURN_RESULT, getFirstRow);
                result.put(ROWS_LEFT, String.valueOf(sqlInputs.getLRows().size()));
                result.put(COLUMN_NAMES, sqlInputs.getStrColumns());
                result.put(RETURN_CODE, SUCCESS);
                sqlConnectionMap.put(aKey, sqlInputs.getLRows());
                sqlConnectionMap.put(strKeyCol, sqlInputs.getStrColumns());
                if (isLOB) {
                    sqlConnectionMap.put(strKeyFiles, sqlInputs.getLRowsFiles());
                    sqlConnectionMap.put(strKeyNames, sqlInputs.getLRowsNames());
                    sqlConnectionMap.put(strKeySkip, 0L);
                }
                globalSessionObject.setResource(new SQLSessionResource(sqlConnectionMap));
            } else {
                result.put(SQL_QUERY, sqlInputs.getSqlCommand());
                result.put(RETURN_RESULT, NO_MORE);
                result.put(ROWS_LEFT, ZERO);
                result.put(RETURN_CODE, DBReturnCodes.NO_MORE);
            }
        }
        globalSessionObject.setResource(new SQLSessionResource(sqlConnectionMap));
        return result;
    } catch (Exception e) {
        final Map<String, String> failureMap = OutputUtilities.getFailureResultsMap(e);
        failureMap.put(ROWS_LEFT, ZERO);
        return failureMap;
    }
}
Also used : HashMap(java.util.HashMap) SQLInputs(io.cloudslang.content.database.utils.SQLInputs) SQLSessionResource(io.cloudslang.content.database.utils.SQLSessionResource) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) List(java.util.List) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) SQLUtils.getRowsFromGlobalSessionMap(io.cloudslang.content.database.utils.SQLUtils.getRowsFromGlobalSessionMap) OutputUtilities.getFailureResultsMap(io.cloudslang.content.utils.OutputUtilities.getFailureResultsMap) Action(com.hp.oo.sdk.content.annotations.Action)

Example 15 with GlobalSessionObject

use of com.hp.oo.sdk.content.plugin.GlobalSessionObject in project cs-actions by CloudSlang.

the class SQLQueryLOBTest method executeSuccessHasMore.

@Test
public void executeSuccessHasMore() throws Exception {
    final String aKey = "akey";
    final GlobalSessionObject<Map<String, Object>> globalSessionObject = new GlobalSessionObject<>();
    final Map<String, Object> stringMap = new HashMap<>();
    final List<String> aList = new ArrayList<>();
    aList.add("a");
    stringMap.put(aKey, aList);
    globalSessionObject.setResource(new SQLSessionResource(stringMap));
    mockStatic(SQLInputsUtils.class);
    when(SQLInputsUtils.getSqlKey(any(SQLInputs.class))).thenReturn(aKey);
    when(SQLInputsUtils.getOrDefaultGlobalSessionObj(any(GlobalSessionObject.class))).thenReturn(globalSessionObject);
    final Map<String, String> resultMap = sqlQueryLOB.execute("1", MSSQL_DB_TYPE, "username", "Password", "someInstance", "123", "db", AUTH_SQL, EMPTY, EMPTY, "something", "true", EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, globalSessionObject);
    verifyStatic();
    assertThat(resultMap.get(RETURN_CODE), is(SUCCESS));
    assertThat(resultMap.get(RETURN_RESULT), is("a"));
}
Also used : GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) SQLInputs(io.cloudslang.content.database.utils.SQLInputs) HashMap(java.util.HashMap) Map(java.util.Map) SQLSessionResource(io.cloudslang.content.database.utils.SQLSessionResource) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

GlobalSessionObject (com.hp.oo.sdk.content.plugin.GlobalSessionObject)21 HashMap (java.util.HashMap)16 Map (java.util.Map)10 Test (org.junit.Test)8 SerializableSessionObject (com.hp.oo.sdk.content.plugin.SerializableSessionObject)6 SQLInputs (io.cloudslang.content.database.utils.SQLInputs)6 SQLSessionResource (io.cloudslang.content.database.utils.SQLSessionResource)6 Action (com.hp.oo.sdk.content.annotations.Action)5 SQLUtils.getRowsFromGlobalSessionMap (io.cloudslang.content.database.utils.SQLUtils.getRowsFromGlobalSessionMap)3 OutputUtilities.getFailureResultsMap (io.cloudslang.content.utils.OutputUtilities.getFailureResultsMap)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 OutputUtilities.getSuccessResultsMap (io.cloudslang.content.utils.OutputUtilities.getSuccessResultsMap)2 Value (io.cloudslang.lang.entities.bindings.values.Value)2 RunEnvironment (io.cloudslang.lang.runtime.env.RunEnvironment)2 NonSerializableObject (io.cloudslang.lang.runtime.steps.ContentTestActions.NonSerializableObject)2 Output (com.hp.oo.sdk.content.annotations.Output)1 Param (com.hp.oo.sdk.content.annotations.Param)1 Response (com.hp.oo.sdk.content.annotations.Response)1 MatchType (com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType)1 ResponseType (com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType)1