Search in sources :

Example 86 with Action

use of com.hp.oo.sdk.content.annotations.Action in project cs-actions by CloudSlang.

the class HttpClientAction method execute.

/**
 * This operation does an http request and a parsing of the response.
 * It provides features like: http authentication, http secure, connection pool, cookies, proxy.
 * To accomplish this it uses the third parties from Apache: HttpClient 4.3, HttpCore 4.3.
 * It also uses the JCIFS library from the Samba for the 'NTLM' authentication.
 *
 * @param url                                The web address to make the request to. This must be a standard URL as specified in RFC 3986. This is a required input.
 *                                           <br>Format: scheme://domain:port/path?query_string#fragment_id.
 *                                           <br>Examples: https://[fe80::1260:4bff:fe49:42fc]:8080/my/path?key1=val1&key2=val2#my_fragment
 * @param authType                           The type of authentication used by this operation when trying to execute the request on the target server.
 *                                           The authentication is not preemptive: a plain request not including authentication info
 *                                           will be made and only when the server responds with a 'WWW-Authenticate' header the client will
 *                                           send required headers. If the server needs no authentication but you specify one in this input
 *                                           the request will work nevertheless. Then client cannot choose the authentication method and there
 *                                           is no fallback so you have to know which one you need. If the web application and proxy use
 *                                           different authentication types, these must be specified like in the Example model.
 *                                           <br>Default value: basic. Valid values: basic, digest, ntlm, kerberos, any, anonymous, "" or a list of valid values separated by comma.
 * @param preemptiveAuth                     If this field is 'true' authentication info will be sent in the first request.
 *                                           If this is 'false' a request with no authentication info will be made and if server responds
 *                                           with 401 and a header like WWW-Authenticate: Basic realm="myRealm" only then the authentication
 *                                           info will be sent. Default value: true. Valid values: true, false
 * @param username                           The user name used for authentication. For NTLM authentication, the required format is 'domain\\user'
 *                                           and if you only specify the 'user' it will append a dot like '.\\user' so that a local user on the
 *                                           target machine can be used. In order for all authentication schemes to work (except Kerberos) username is required.
 * @param password                           The password used for authentication.
 * @param kerberosConfFile                   A krb5.conf file with content similar to the one in the examples
 *                                           (where you replace CONTOSO.COM with your domain and 'ad.contoso.com' with your kdc FQDN).
 *                                           This configures the Kerberos mechanism required by the Java GSS-API methods.
 *                                           <br>Format: http://web.mit.edu/kerberos/krb5-1.4/krb5-1.4.4/doc/krb5-admin/krb5.conf.html
 * @param kerberosLoginConfFile              A login.conf file needed by the JAAS framework with the content similar to the one in examples
 *                                           Format: http://docs.oracle.com/javase/7/docs/jre/api/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html
 * @param kerberosSkipPortForLookup          Do not include port in the key distribution center database lookup. Default value: true. Valid values: true, false
 * @param proxyHost                          The proxy server used to access the web site.
 * @param proxyPort                          The proxy server port. Default value: 8080. Valid values: -1 and integer values greater than 0.
 *                                           The value '-1' indicates that the proxy port is not set and the scheme default port will be used.
 *                                           If the scheme is 'http://' and the 'proxyPort' is set to '-1' then port '80' will be used.
 * @param proxyUsername                      The user name used when connecting to the proxy. The 'authType' input will be used to choose authentication type.
 *                                           The 'Basic' and 'Digest' proxy authentication types are supported.
 * @param proxyPassword                      The proxy server password associated with the proxyUsername input value.
 * @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
 * @param x509HostnameVerifier               Specifies the way the server hostname must match a domain name in the subject's Common Name (CN)
 *                                           or subjectAltName field of the X.509 certificate. Set this to "allow_all" to skip any checking.
 *                                           For the value "browser_compatible" the hostname verifier works the same way as Curl and Firefox.
 *                                           The hostname must match either the first CN, or any of the subject-alts.
 *                                           A wildcard can occur in the CN, and in any of the subject-alts. The only difference
 *                                           between "browser_compatible" and "strict" is that a wildcard (such as "*.foo.com")
 *                                           with "browser_compatible" matches all subdomains, including "a.b.foo.com".
 *                                           Default value: strict. Valid values: strict,browser_compatible,allow_all
 * @param trustKeystore                      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 protocol (specified by the 'url') is not 'https' or if
 *                                           trustAllRoots is 'true' this input is ignored. Default value: <OO_Home>/java/lib/security/cacerts. Format: Java KeyStore (JKS)
 * @param trustPassword                      The password associated with the TrustStore file. If trustAllRoots is false and trustKeystore is empty,
 *                                           trustPassword default will be supplied. Default value: changeit
 * @param keystore                           The pathname of the Java KeyStore file. You only need this if the server requires client authentication.
 *                                           If the protocol (specified by the 'url') is not 'https' or if trustAllRoots is 'true' this input is ignored.
 *                                           <br>Default value: <OO_Home>/java/lib/security/cacerts. Format: Java KeyStore (JKS)
 * @param keystorePassword                   The password associated with the KeyStore file. If trustAllRoots is false and keystore
 *                                           is empty, keystorePassword default will be supplied. Default value: changeit
 * @param connectTimeout                     The time to wait for a connection to be established, in seconds.
 *                                           A timeout value of '0' represents an infinite timeout. Default value: 0
 * @param socketTimeout                      The timeout for waiting for data (a maximum period inactivity between two consecutive data packets),
 *                                           in seconds. A socketTimeout value of '0' represents an infinite timeout. Default value: 0.
 * @param useCookies                         Specifies whether to enable cookie tracking or not. Cookies are stored between consecutive calls
 *                                           in a serializable session object therefore they will be available on a branch level.
 *                                           If you specify a non-boolean value, the default value is used. Default value: true. Valid values: true, false
 * @param keepAlive                          Specifies whether to create a shared connection that will be used in subsequent calls.
 *                                           If keepAlive is false, the already open connection will be used and after execution it will close it.
 *                                           The operation will use a connection pool stored in a GlobalSessionObject that will be available throughout
 *                                           the execution (the flow and subflows, between parallel split lanes). Default value: true. Valid values: true, false.
 * @param connectionsMaxPerRoute             The maximum limit of connections on a per route basis.
 *                                           The default will create no more than 2 concurrent connections per given route. Default value: 2
 * @param connectionsMaxTotal                The maximum limit of connections in total.
 *                                           The default will create no more than 2 concurrent connections in total. Default value: 20
 * @param headers                            The list containing the headers to use for the request separated by new line (CRLF).
 *                                           The header name - value pair will be separated by ":". Format: According to HTTP standard for headers (RFC 2616).
 *                                           Examples: Accept:text/plain
 * @param responseCharacterSet               The character encoding to be used for the HTTP response.
 *                                           If responseCharacterSet is empty, the charset from the 'Content-Type' HTTP response header will be used.
 *                                           If responseCharacterSet is empty and the charset from the HTTP response Content-Type header is empty,
 *                                           the default value will be used. You should not use this for method=HEAD or OPTIONS. Default value: ISO-8859-1
 * @param destinationFile                    The absolute path of a file on disk where to save the entity returned by the response.
 *                                           'returnResult' will no longer be populated with the entity if this is specified.
 *                                           You should not use this for method=HEAD or OPTIONS. Example: C:\temp\destinationFile.txt
 * @param followRedirects                    Specifies whether the HTTP client automatically follows redirects.
 *                                           Redirects explicitly prohibited by the HTTP specification as requiring user intervention
 *                                           will not be followed (redirects on POST and PUT requests that are converted to GET requests).
 *                                           If you specify a non-boolean value, the default value is used. Default value: true. Valid values: true, false
 * @param queryParams                        The list containing query parameters to append to the URL. The names and the values must not
 *                                           be URL encoded unless you specify "queryParamsAreURLEncoded"=true because if they are encoded
 *                                           and "queryParamsAreURLEncoded"=false they will get double encoded.
 *                                           The separator between name-value pairs is "&". The query name will be separated from query
 *                                           value by "=". Note that you need to URL encode at least "&" to "%26" and "=" to "%3D" and
 *                                           set "queryParamsAreURLEncoded"="true" if you leave the other special URL characters un-encoded
 *                                           they will be encoded by the HTTP Client. Examples: parameterName1=parameterValue1&parameterName2=parameterValue2;
 * @param queryParamsAreURLEncoded           Specifies whether to encode  (according to the url encoding standard) the queryParams.
 *                                           If you set "queryParamsAreURLEncoded"=true and you have invalid characters in 'queryParams'
 *                                           they will get encoded anyway. If "queryParamsAreURLEncoded"=false all characters will be encoded.
 *                                           But the ' ' (space) character will be encoded as + if queryParamsAreURLEncoded is either true or false.
 *                                           Also %20 will be encoded as + if "queryParamsAreURLEncoded"=true.
 *                                           If you specify a non-boolean value, the default value is used.
 *                                           Default value: false. Valid values: true, false
 * @param queryParamsAreFormEncoded          Specifies whether to encode the queryParams in the form request format or not.
 *                                           This format is the default format used by the apache http client library.
 *                                           If queryParamsAreFormEncoded=true then all characters will be encoded based on the queryParamsAreURLEncoded
 *                                           input. If queryParamsAreFormEncoded=false all reserved characters are not encoded no matter of
 *                                           queryParamsAreURLEncoded input. The only exceptions are for ' ' (space) character which is encoded as %20 in both
 *                                           cases of queryParamsAreURLEncoded input and + (plus) which is encoded as %20 if queryParamsAreURLEncoded=true
 *                                           and not encoded if queryParamsAreURLEncoded=false. If the special characters are already encoded
 *                                           and queryParamsAreURLEncoded=true then they will be transformed into their original format.
 *                                           For example: %40 will be @, %2B will be +. But %20 (space) will not be transformed.
 *                                           The list of reserved chars is: ;/?:@&=+,$
 *                                           Default value: true. Valid values: true, false
 *                                           Example: query=test te%20@st will be encoded in query=test%20te%20@st
 * @param formParams                         This input needs to be given in form encoded format and will set the entity to be sent in the request.
 *                                           It will also set the content-type to application/x-www-form-urlencoded.
 *                                           This should only be used with method=POST. Note that you need to URL encode at
 *                                           least "&" to "%26" and "=" to "%3D" and set "queryParamsAreURLEncoded"="true" if you leave the
 *                                           other special URL characters un-encoded they will be encoded by the HTTP Client.
 *                                           <br>Examples: input1=value1&input2=value2. (The client will send: input1=value1&in+put+2=val+u%0A+e2)
 * @param formParamsAreURLEncoded            formParams will be encoding  (according to the url encoding standard) if this is 'true'.
 *                                           If you set "formParamsAreURLEncoded"=true and you have invalid characters in 'formParams'
 *                                           they will get encoded anyway. This should only be used with method=POST.
 *                                           Default value: false. Valid values: true, false
 * @param sourceFile                         The absolute path of a file on disk from where to read the entity for the http request.
 *                                           This will be read using 'requestCharacterSet' or 'contentType' input (see below).
 *                                           This should not be provided for method=GET, HEAD, TRACE. Examples: C:\temp\sourceFile.txt
 * @param body                               The string to include in body for HTTP POST operation. If both sourceFile and body will be provided,
 *                                           the body input has priority over sourceFile. This should not be provided for method=GET, HEAD, TRACE
 * @param contentType                        The content type that should be set in the request header, representing the MIME-type of the
 *                                           data in the message body. Default value: text/plain. Examples: "text/html", "application/x-www-form-urlencoded"
 * @param requestCharacterSet                The character encoding to be used for the HTTP request body.
 *                                           If contentType is empty, the requestCharacterSet will use the default value.
 *                                           If contentType will include charset (ex.: "application/json; charset=UTF-8"),
 *                                           the requestCharacterSet value will overwrite the charset value from contentType input.
 *                                           This should not be provided for method=GET, HEAD, TRACE. Default value: ISO-8859-1
 * @param multipartBodies                    This is a name=textValue list of pairs separated by "&". This will also take into account
 *                                           the "contentType" and "charset" inputs. The request entity will be like:
 *                                           <br>Content-Disposition: form-data; name="name1"
 *                                           <br>Content-Type: text/plain; charset=UTF-8
 *                                           <br>Content-Transfer-Encoding: 8bit
 *                                           <br>
 *                                           <br>textvalue1
 *                                           <br>Examples: name1=textvalue1&name2=textvalue2
 * @param multipartBodiesContentType         Each entity from the multipart entity has a content-type header.
 *                                           You can only specify it once for all the parts and it is the only way to change
 *                                           the characterSet of the encoding. Default value: text/plain; charset=ISO-8859-1
 *                                           Examples: text/plain; charset=UTF-8
 * @param multipartFiles                     This is a list of name=filePath pairs. This will also take into account the "contentType"
 *                                           and "charset" inputs. The request entity will be like:
 *                                           <br>Content-Disposition: form-data; name="name3"; filename="readme.txt"
 *                                           <br>Content-Type: application/octet-stream; charset=UTF-8
 *                                           <br>Content-Transfer-Encoding: binary the text in readme.txt
 *                                           <br>Examples: name3=c:\temp\readme.txt&name4=c:\temp\log4j.properties
 * @param multipartFilesContentType          Each entity from the multipart entity has a content-type header. You can only specify it once for all parts.
 *                                           Default value: application/octet-stream. Examples: image/png,text/plain
 * @param multipartValuesAreURLEncoded       You need to set this to 'true' if the bodies may contain the "&" and "="
 *                                           separators  and you also need to URL encode them so that "&" becomes %26 and "=" becomes %3D
 *                                           (using the URL Encoder operation on each value or by a simple replace). Default value: false
 * @param chunkedRequestEntity               Data is sent in a series of "chunks". It uses the Transfer-Encoding HTTP header in place
 *                                           of the Content-Length header.Generally it is recommended to let HttpClient choose the
 *                                           most appropriate transfer encoding based on the properties of the HTTP message being transferred.
 *                                           It is possible, however, to inform HttpClient that chunk coding is preferred by setting this input to "true".
 *                                           Please note that HttpClient will use this flag as a hint only.
 *                                           This value will be ignored when using HTTP protocol versions that do not support chunk coding, such as HTTP/1.0.
 *                                           This setting is ignored for multipart post entities.
 * @param method                             The HTTP method used. This is a required input.
 * @param httpClientCookieSession            the session object that holds the cookies if the useCookies input is true.
 * @param httpClientPoolingConnectionManager the GlobalSessionObject that holds the http client pooling connection manager.
 * @return a map containing the output of the operation. Keys present in the map are:
 * <br><br><b>returnResult</b> - This will contain the response entity (unless 'destinationFile' is specified).
 * In case of an error this output will contain the error message.
 * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response,
 * this result contains the java stack trace of the runtime exception.
 * <br><b>statusCode</b> - The HTTP status code.
 * <br><i>Format</i>: <br>1xx (Informational - Request received, continuing process),
 * <br>2xx (Success - The action was successfully received, understood, and accepted),
 * <br>3xx (Redirection - Further action must be taken in order to complete the request),
 * <br>4xx (Client Error - The request contains bad syntax or cannot be fulfilled),
 * <br>5xx Server Error - The server failed to fulfil an apparently valid request)
 * <br>Examples: 200, 404
 * <br><br><b>finalLocation</b> - The final location after redirects. Format: URL
 * <br><b>responseHeaders</b> - The list containing the headers of the response message, separated by newline.
 * Format: This is conforming to HTTP standard for headers (RFC 2616).
 * <br><b>protocolVersion</b> - The HTTP protocol version. Examples: HTTP/1.1
 * <br><b>reasonPhrase</b> - The reason phrase from the origin HTTP response. This depends on the status code and are according to RFC 1945 and RFC 2048
 * <br>Examples: (HTTP 1.0): OK, Created, Accepted, No Content, Moved Permanently, Moved Temporarily, Not Modified, Bad Request,
 * Unauthorized, Forbidden, Not Found, Internal Server Error, Not Implemented, Bad Gateway,
 * Service Unavailable	Values (HTTP 1.1): Continue, Temporary Redirect, Method Not Allowed,
 * Conflict, Precondition Failed, Request Too Long, Request-URI Too Long, Unsupported Media Type,
 * Multiple Choices, See Other, Use Proxy, Payment Required, Not Acceptable, Proxy Authentication Required,
 * Request Timeout, Switching Protocols, Non Authoritative Information, Reset Content, Partial Content,
 * Gateway Timeout, Http Version Not Supported, Gone, Length Required, Requested Range Not Satisfiable, Expectation Failed
 * <p/>
 * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
 */
@Action(name = "Http Client", outputs = { @Output(EXCEPTION), @Output(STATUS_CODE), @Output(FINAL_LOCATION), @Output(RESPONSE_HEADERS), @Output(PROTOCOL_VERSION), @Output(REASON_PHRASE), @Output(RETURN_CODE), @Output(RETURN_RESULT) }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR) })
public Map<String, String> execute(@Param(value = HttpClientInputs.URL, required = true) String url, @Param(HttpClientInputs.TLS_VERSION) String tlsVersion, @Param(HttpClientInputs.ALLOWED_CYPHERS) String allowedCyphers, @Param(HttpClientInputs.AUTH_TYPE) String authType, @Param(HttpClientInputs.PREEMPTIVE_AUTH) String preemptiveAuth, @Param(HttpClientInputs.USERNAME) String username, @Param(HttpClientInputs.PASSWORD) String password, @Param(HttpClientInputs.KERBEROS_CONFIG_FILE) String kerberosConfFile, @Param(HttpClientInputs.KERBEROS_LOGIN_CONFIG_FILE) String kerberosLoginConfFile, @Param(HttpClientInputs.KERBEROS_SKIP_PORT_CHECK) String kerberosSkipPortForLookup, @Param(HttpClientInputs.PROXY_HOST) String proxyHost, @Param(HttpClientInputs.PROXY_PORT) String proxyPort, @Param(HttpClientInputs.PROXY_USERNAME) String proxyUsername, @Param(HttpClientInputs.PROXY_PASSWORD) String proxyPassword, @Param(HttpClientInputs.TRUST_ALL_ROOTS) String trustAllRoots, @Param(HttpClientInputs.X509_HOSTNAME_VERIFIER) String x509HostnameVerifier, @Param(HttpClientInputs.TRUST_KEYSTORE) String trustKeystore, @Param(HttpClientInputs.TRUST_PASSWORD) String trustPassword, @Param(HttpClientInputs.KEYSTORE) String keystore, @Param(HttpClientInputs.KEYSTORE_PASSWORD) String keystorePassword, @Param(HttpClientInputs.CONNECT_TIMEOUT) String connectTimeout, @Param(HttpClientInputs.SOCKET_TIMEOUT) String socketTimeout, @Param(HttpClientInputs.EXECUTION_TIMEOUT) String executionTimeout, @Param(HttpClientInputs.USE_COOKIES) String useCookies, @Param(HttpClientInputs.KEEP_ALIVE) String keepAlive, @Param(HttpClientInputs.CONNECTIONS_MAX_PER_ROUTE) String connectionsMaxPerRoute, @Param(HttpClientInputs.CONNECTIONS_MAX_TOTAL) String connectionsMaxTotal, @Param(HttpClientInputs.HEADERS) String headers, @Param(HttpClientInputs.RESPONSE_CHARACTER_SET) String responseCharacterSet, @Param(HttpClientInputs.DESTINATION_FILE) String destinationFile, @Param(HttpClientInputs.FOLLOW_REDIRECTS) String followRedirects, @Param(HttpClientInputs.QUERY_PARAMS) String queryParams, @Param(HttpClientInputs.QUERY_PARAMS_ARE_URLENCODED) String queryParamsAreURLEncoded, @Param(HttpClientInputs.QUERY_PARAMS_ARE_FORM_ENCODED) String queryParamsAreFormEncoded, @Param(HttpClientInputs.FORM_PARAMS) String formParams, @Param(HttpClientInputs.FORM_PARAMS_ARE_URLENCODED) String formParamsAreURLEncoded, @Param(HttpClientInputs.SOURCE_FILE) String sourceFile, @Param(HttpClientInputs.BODY) String body, @Param(HttpClientInputs.CONTENT_TYPE) String contentType, @Param(HttpClientInputs.REQUEST_CHARACTER_SET) String requestCharacterSet, @Param(HttpClientInputs.MULTIPART_BODIES) String multipartBodies, @Param(HttpClientInputs.MULTIPART_BODIES_CONTENT_TYPE) String multipartBodiesContentType, @Param(HttpClientInputs.MULTIPART_FILES) String multipartFiles, @Param(HttpClientInputs.MULTIPART_FILES_CONTENT_TYPE) String multipartFilesContentType, @Param(HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED) String multipartValuesAreURLEncoded, @Param(HttpClientInputs.CHUNKED_REQUEST_ENTITY) String chunkedRequestEntity, @Param(value = HttpClientInputs.METHOD, required = true) String method, @Param(HttpClientInputs.SESSION_COOKIES) SerializableSessionObject httpClientCookieSession, @Param(HttpClientInputs.SESSION_CONNECTION_POOL) GlobalSessionObject httpClientPoolingConnectionManager) {
    HttpClientInputs httpClientInputs = new HttpClientInputs();
    httpClientInputs.setUrl(url);
    httpClientInputs.setAuthType(defaultIfEmpty(authType, BASIC_AUTH));
    httpClientInputs.setPreemptiveAuth(preemptiveAuth);
    httpClientInputs.setUsername(username);
    httpClientInputs.setPassword(password);
    httpClientInputs.setKerberosConfFile(kerberosConfFile);
    httpClientInputs.setKerberosLoginConfFile(kerberosLoginConfFile);
    httpClientInputs.setKerberosSkipPortCheck(kerberosSkipPortForLookup);
    httpClientInputs.setProxyHost(proxyHost);
    httpClientInputs.setProxyPort(proxyPort);
    httpClientInputs.setProxyUsername(proxyUsername);
    httpClientInputs.setProxyPassword(proxyPassword);
    httpClientInputs.setTrustAllRoots(trustAllRoots);
    httpClientInputs.setX509HostnameVerifier(x509HostnameVerifier);
    httpClientInputs.setTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE));
    httpClientInputs.setTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT));
    httpClientInputs.setKeystore(defaultIfEmpty(keystore, DEFAULT_JAVA_KEYSTORE));
    httpClientInputs.setKeystorePassword(defaultIfEmpty(keystorePassword, CHANGEIT));
    httpClientInputs.setConnectTimeout(connectTimeout);
    httpClientInputs.setSocketTimeout(socketTimeout);
    if (StringUtils.isNotEmpty(executionTimeout)) {
        httpClientInputs.setExecutionTimeout(executionTimeout);
    } else {
        httpClientInputs.setExecutionTimeout("0");
    }
    httpClientInputs.setUseCookies(useCookies);
    httpClientInputs.setKeepAlive(keepAlive);
    httpClientInputs.setConnectionsMaxPerRoute(connectionsMaxPerRoute);
    httpClientInputs.setConnectionsMaxTotal(connectionsMaxTotal);
    httpClientInputs.setHeaders(headers);
    httpClientInputs.setResponseCharacterSet(responseCharacterSet);
    httpClientInputs.setDestinationFile(destinationFile);
    httpClientInputs.setFollowRedirects(followRedirects);
    httpClientInputs.setQueryParams(queryParams);
    httpClientInputs.setQueryParamsAreURLEncoded(queryParamsAreURLEncoded);
    httpClientInputs.setQueryParamsAreFormEncoded(queryParamsAreFormEncoded);
    httpClientInputs.setFormParams(formParams);
    httpClientInputs.setFormParamsAreURLEncoded(formParamsAreURLEncoded);
    httpClientInputs.setSourceFile(sourceFile);
    httpClientInputs.setBody(body);
    httpClientInputs.setContentType(contentType);
    httpClientInputs.setRequestCharacterSet(requestCharacterSet);
    httpClientInputs.setMultipartBodies(multipartBodies);
    httpClientInputs.setMultipartFiles(multipartFiles);
    httpClientInputs.setMultipartBodiesContentType(multipartBodiesContentType);
    httpClientInputs.setMultipartFilesContentType(multipartFilesContentType);
    httpClientInputs.setMultipartValuesAreURLEncoded(multipartValuesAreURLEncoded);
    httpClientInputs.setChunkedRequestEntity(chunkedRequestEntity);
    httpClientInputs.setMethod(method);
    httpClientInputs.setTlsVersion(tlsVersion);
    httpClientInputs.setAllowedCyphers(allowedCyphers);
    httpClientInputs.setCookieStoreSessionObject(httpClientCookieSession);
    httpClientInputs.setConnectionPoolSessionObject(httpClientPoolingConnectionManager);
    List<String> exceptions = validateInputs(httpClientInputs);
    if (!exceptions.isEmpty()) {
        String errorMessage = StringUtilities.join(exceptions, NEW_LINE);
        return exceptionResult(errorMessage, new Exception(errorMessage));
    }
    if (!isEmpty(tlsVersion)) {
        if (tlsVersion.toUpperCase().contains(TLSv12.toUpperCase()) && tlsVersion.split(",").length > 1) {
            try {
                httpClientInputs.setTlsVersion(TLSv12);
                return new HttpClientService().execute(httpClientInputs);
            } catch (Exception e) {
                Set<String> otherTls = new HashSet<>(Arrays.asList(tlsVersion.split(",")));
                String tls12 = "";
                for (String protocol : otherTls) {
                    if (protocol.toUpperCase().equals(TLSv12.toUpperCase()))
                        tls12 = protocol;
                }
                otherTls.remove(tls12);
                httpClientInputs.setTlsVersion(otherTls.toString().replace("[", "").replace("]", ""));
                httpClientInputs.setCookieStoreSessionObject(new SerializableSessionObject());
                httpClientInputs.setConnectionPoolSessionObject(new GlobalSessionObject());
                try {
                    return new HttpClientService().execute(httpClientInputs);
                } catch (Exception ex) {
                    return exceptionResult(ex.getMessage(), ex);
                }
            }
        } else {
            try {
                return new HttpClientService().execute(httpClientInputs);
            } catch (Exception e) {
                return exceptionResult(e.getMessage(), e);
            }
        }
    } else {
        try {
            return new HttpClientService().execute(httpClientInputs);
        } catch (Exception e) {
            return exceptionResult(e.getMessage(), e);
        }
    }
}
Also used : HttpClientService(io.cloudslang.content.httpclient.services.HttpClientService) GlobalSessionObject(com.hp.oo.sdk.content.plugin.GlobalSessionObject) SerializableSessionObject(com.hp.oo.sdk.content.plugin.SerializableSessionObject) HttpClientInputs(io.cloudslang.content.httpclient.entities.HttpClientInputs) Action(com.hp.oo.sdk.content.annotations.Action)

Example 87 with Action

use of com.hp.oo.sdk.content.annotations.Action in project cs-actions by CloudSlang.

the class GetUser method execute.

@Action(name = "Get user from Office 365", outputs = { @Output(value = RETURN_RESULT, description = GET_USER_RETURN_RESULT_DESC), @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = DOCUMENT, description = DOCUMENT_DESC), @Output(value = USER_PRINCIPAL_NAME, description = CREATE_USER_PRINCIPAL_NAME_DESC), @Output(value = ID, description = ID_OUTPUT_DESC), @Output(value = EXCEPTION, description = GET_USER_EXCEPTION_DESC), @Output(value = STATUS_CODE, description = STATUS_CODE_DESC) }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, description = FAILURE_DESC) })
public Map<String, String> execute(@Param(value = AUTH_TOKEN, required = true, description = AUTH_TOKEN_DESC) String authToken, @Param(value = USER_PRINCIPAL_NAME, description = CREATE_USER_PRINCIPAL_NAME_DESC) String userPrincipalName, @Param(value = USER_ID, description = USER_ID_DESC) String userId, @Param(value = O_DATA_QUERY, description = O_DATA_QUERY_DESC) String oDataQuery, @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost, @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort, @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword, @Param(value = TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots, @Param(value = X509_HOSTNAME_VERIFIER, description = X509_DESC) String x509HostnameVerifier, @Param(value = TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore, @Param(value = TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword, @Param(value = CONNECT_TIMEOUT, description = CONNECT_TIMEOUT_DESC) String connectTimeout, @Param(value = SOCKET_TIMEOUT, description = SOCKET_TIMEOUT_DESC) String socketTimeout, @Param(value = KEEP_ALIVE, description = KEEP_ALIVE_DESC) String keepAlive, @Param(value = CONNECTIONS_MAX_PER_ROUTE, description = CONN_MAX_ROUTE_DESC) String connectionsMaxPerRoute, @Param(value = CONNECTIONS_MAX_TOTAL, description = CONN_MAX_TOTAL_DESC) String connectionsMaxTotal, @Param(value = RESPONSE_CHARACTER_SET, description = RESPONSE_CHARACTER_SET_DESC) String responseCharacterSet) {
    userPrincipalName = defaultIfEmpty(userPrincipalName, EMPTY);
    userId = defaultIfEmpty(userId, EMPTY);
    oDataQuery = defaultIfEmpty(oDataQuery, EMPTY);
    proxyHost = defaultIfEmpty(proxyHost, EMPTY);
    proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
    proxyUsername = defaultIfEmpty(proxyUsername, EMPTY);
    proxyPassword = defaultIfEmpty(proxyPassword, EMPTY);
    trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE);
    x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT);
    trustKeystore = defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE);
    trustPassword = defaultIfEmpty(trustPassword, CHANGEIT);
    connectTimeout = defaultIfEmpty(connectTimeout, ZERO);
    socketTimeout = defaultIfEmpty(socketTimeout, ZERO);
    keepAlive = defaultIfEmpty(keepAlive, BOOLEAN_FALSE);
    connectionsMaxPerRoute = defaultIfEmpty(connectionsMaxPerRoute, CONNECTIONS_MAX_PER_ROUTE_CONST);
    connectionsMaxTotal = defaultIfEmpty(connectionsMaxTotal, CONNECTIONS_MAX_TOTAL_CONST);
    responseCharacterSet = defaultIfEmpty(responseCharacterSet, UTF8);
    final List<String> exceptionMessages = verifyCommonInputs(userPrincipalName, userId, proxyPort, trustAllRoots, connectTimeout, socketTimeout, keepAlive, connectionsMaxPerRoute, connectionsMaxTotal);
    if (!exceptionMessages.isEmpty()) {
        return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE));
    }
    try {
        final Map<String, String> result = getUser(GetUserInputs.builder().oDataQuery(oDataQuery).commonInputs(Office365CommonInputs.builder().authToken(authToken).proxyHost(proxyHost).proxyPort(proxyPort).proxyUsername(proxyUsername).proxyPassword(proxyPassword).connectionsMaxTotal(connectionsMaxTotal).connectionsMaxPerRoute(connectionsMaxPerRoute).keepAlive(keepAlive).responseCharacterSet(responseCharacterSet).connectTimeout(connectTimeout).trustAllRoots(trustAllRoots).userId(userId).userPrincipalName(userPrincipalName).x509HostnameVerifier(x509HostnameVerifier).trustKeystore(trustKeystore).trustPassword(trustPassword).build()).build());
        final String returnMessage = result.get(RETURN_RESULT);
        final Map<String, String> results = getOperationResults(result, returnMessage, returnMessage, returnMessage);
        final Integer statusCode = Integer.parseInt(result.get(STATUS_CODE));
        if (statusCode >= 200 && statusCode < 300) {
            final JsonParser parser = new JsonParser();
            final JsonObject responseJson = parser.parse(returnMessage).getAsJsonObject();
            if (responseJson.has(USER_PRINCIPAL_NAME)) {
                final String userPrincipalNameOutput = responseJson.get(USER_PRINCIPAL_NAME).getAsString();
                results.put(USER_PRINCIPAL_NAME, userPrincipalNameOutput);
            } else
                results.put(USER_PRINCIPAL_NAME, EMPTY);
            if (responseJson.has(ID)) {
                final String idOutput = responseJson.get(ID).getAsString();
                results.put(ID, idOutput);
            } else
                results.put(ID, EMPTY);
        }
        return results;
    } catch (Exception exception) {
        return getFailureResultsMap(exception);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) JsonParser(com.google.gson.JsonParser) Action(com.hp.oo.sdk.content.annotations.Action)

Example 88 with Action

use of com.hp.oo.sdk.content.annotations.Action in project cs-actions by CloudSlang.

the class GetAuthorizationTokenV2 method execute.

/**
 * @param loginType      Login method according to application type
 *                       Valid values: 'API', 'Native'
 *                       Default: 'API'
 * @param clientId       Service Client ID
 * @param clientSecret   Service Client Secret
 * @param username       Office 365 username
 * @param password       Office 365 password
 * @param loginAuthority The authority URL. Usually, the format for this input is:
 *                       'https://login.windows.net/TENANT_NAME/oauth2/token' where TENANT_NAME is your application
 *                       tenant.
 * @param scope          The scope URL. The scope consists of a series of resource permissions separated " +
 *                       "by a comma (,), i.e.: 'https://graph.microsoft.com/User.Read, https://graph.microsoft.com/Sites.Read'. " +
 *                       "The 'https://graph.microsoft.com/.default' scope means that the user consent to all of the configured permissions " +
 *                       "present on the specific Azure AD Application. For the 'API' loginType, '/.default' scope should be used. \n" +
 *                       "Default: 'https://graph.microsoft.com/.default'
 * @param proxyHost      Proxy server used to access the web site
 * @param proxyPort      Proxy server port
 *                       Default: '8080'
 * @param proxyUsername  User name used when connecting to the proxy
 * @param proxyPassword  The proxy server password associated with the proxyUsername input value
 * @return The authorization token for Office 365
 */
@Action(name = "Get the authorization token for Office 365 V2", outputs = { @Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC), @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = AUTH_TOKEN, description = AUTH_TOKEN_DESC), @Output(value = EXCEPTION, description = EXCEPTION_DESC) }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, description = FAILURE_DESC) })
public Map<String, String> execute(@Param(value = LOGIN_TYPE, description = LOGIN_TYPE_DESC) String loginType, @Param(value = CLIENT_ID, required = true, description = CLIENT_ID_DESC) String clientId, @Param(value = CLIENT_SECRET, encrypted = true, description = CLIENT_SECRET_DESC) String clientSecret, @Param(value = USERNAME, description = USERNAME_DESC) String username, @Param(value = PASSWORD, encrypted = true, description = PASSWORD_DESC) String password, @Param(value = LOGIN_AUTHORITY, required = true, description = LOGIN_AUTHORITY_DESC) String loginAuthority, @Param(value = SCOPE, description = SCOPE_DESC) String scope, @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost, @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort, @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword) {
    loginType = defaultIfEmpty(loginType, DEFAULT_LOGIN_TYPE);
    clientId = defaultIfEmpty(clientId, EMPTY);
    clientSecret = defaultIfEmpty(clientSecret, EMPTY);
    username = defaultIfEmpty(username, EMPTY);
    password = defaultIfEmpty(password, EMPTY);
    scope = defaultIfEmpty(scope, DEFAULT_SCOPE);
    proxyHost = defaultIfEmpty(proxyHost, EMPTY);
    proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
    proxyUsername = defaultIfEmpty(proxyUsername, EMPTY);
    proxyPassword = defaultIfEmpty(proxyPassword, EMPTY);
    final List<String> exceptionMessages = verifyAuthorizationInputs(loginType, clientId, clientSecret, username, password, proxyPort);
    if (!exceptionMessages.isEmpty()) {
        return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE));
    }
    try {
        final IAuthenticationResult result = AuthorizationTokenV2Impl.getToken(AuthorizationTokenInputs.builder().loginType(loginType).clientId(clientId).clientSecret(clientSecret).username(username).password(password).authority(loginAuthority).scope(scope).proxyHost(proxyHost).proxyPort(NumberUtilities.toInteger(proxyPort)).proxyUsername(proxyUsername).proxyPassword(proxyPassword).build());
        final Map<String, String> successResultsMap = getSuccessResultsMap(result.accessToken());
        successResultsMap.put(AUTH_TOKEN, result.accessToken());
        return successResultsMap;
    } catch (Exception exception) {
        return getFailureResultsMap(exception);
    }
}
Also used : IAuthenticationResult(com.microsoft.aad.msal4j.IAuthenticationResult) Action(com.hp.oo.sdk.content.annotations.Action)

Example 89 with Action

use of com.hp.oo.sdk.content.annotations.Action in project cs-actions by CloudSlang.

the class AddAttachment method execute.

@Action(name = "Add an attachment to a message in Office 365", outputs = { @Output(value = RETURN_RESULT, description = ADD_ATTACHMENT_RETURN_RESULT_DESC), @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = DOCUMENT, description = DOCUMENT_DESC), @Output(value = EXCEPTION, description = ADD_ATTACHMENT_EXCEPTION_DESC), @Output(value = STATUS_CODE, description = STATUS_CODE_DESC), @Output(value = ATTACHMENT_ID, description = ATTACHMENT_ID_DESC) }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, description = FAILURE_DESC) })
public Map<String, String> execute(@Param(value = AUTH_TOKEN, required = true, description = AUTH_TOKEN_DESC) String authToken, @Param(value = USER_PRINCIPAL_NAME, description = USER_PRINCIPAL_NAME_DESC) String userPrincipalName, @Param(value = USER_ID, description = USER_ID_DESC) String userId, @Param(value = MESSAGE_ID, required = true, description = MESSAGE_ID_DESC) String messageId, @Param(value = FILE_PATH, description = FILE_PATH_DESC) String filePath, @Param(value = CONTENT_NAME, description = CONTENT_NAME_DESC) String contentName, @Param(value = CONTENT_BYTES, description = CONTENT_BYTES_DESC) String contentBytes, @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost, @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort, @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword, @Param(value = TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots, @Param(value = X509_HOSTNAME_VERIFIER, description = X509_DESC) String x509HostnameVerifier, @Param(value = TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore, @Param(value = TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword, @Param(value = CONNECT_TIMEOUT, description = CONNECT_TIMEOUT_DESC) String connectTimeout, @Param(value = SOCKET_TIMEOUT, description = SOCKET_TIMEOUT_DESC) String socketTimeout, @Param(value = KEEP_ALIVE, description = KEEP_ALIVE_DESC) String keepAlive, @Param(value = CONNECTIONS_MAX_PER_ROUTE, description = CONN_MAX_ROUTE_DESC) String connectionsMaxPerRoute, @Param(value = CONNECTIONS_MAX_TOTAL, description = CONN_MAX_TOTAL_DESC) String connectionsMaxTotal, @Param(value = RESPONSE_CHARACTER_SET, description = RESPONSE_CHARACTER_SET_DESC) String responseCharacterSet) {
    userPrincipalName = defaultIfEmpty(userPrincipalName, EMPTY);
    userId = defaultIfEmpty(userId, EMPTY);
    messageId = defaultIfEmpty(messageId, EMPTY);
    filePath = defaultIfEmpty(filePath, EMPTY);
    contentName = defaultIfEmpty(contentName, EMPTY);
    contentBytes = defaultIfEmpty(contentBytes, EMPTY);
    proxyHost = defaultIfEmpty(proxyHost, EMPTY);
    proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
    proxyUsername = defaultIfEmpty(proxyUsername, EMPTY);
    proxyPassword = defaultIfEmpty(proxyPassword, EMPTY);
    trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE);
    x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT);
    trustKeystore = defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE);
    trustPassword = defaultIfEmpty(trustPassword, CHANGEIT);
    connectTimeout = defaultIfEmpty(connectTimeout, ZERO);
    socketTimeout = defaultIfEmpty(socketTimeout, ZERO);
    keepAlive = defaultIfEmpty(keepAlive, BOOLEAN_FALSE);
    connectionsMaxPerRoute = defaultIfEmpty(connectionsMaxPerRoute, CONNECTIONS_MAX_PER_ROUTE_CONST);
    connectionsMaxTotal = defaultIfEmpty(connectionsMaxTotal, CONNECTIONS_MAX_TOTAL_CONST);
    responseCharacterSet = defaultIfEmpty(responseCharacterSet, UTF8);
    final List<String> exceptionMessages = verifyAddAttachmentInputs(filePath, contentName, contentBytes, userPrincipalName, userId, messageId, proxyPort, trustAllRoots, connectTimeout, socketTimeout, keepAlive, connectionsMaxPerRoute, connectionsMaxTotal);
    if (!exceptionMessages.isEmpty()) {
        return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE));
    }
    try {
        final Map<String, String> result = addAttachment(AddAttachmentInputs.builder().messageId(messageId).filePath(filePath).contentName(contentName).contentBytes(contentBytes).commonInputs(Office365CommonInputs.builder().authToken(authToken).userPrincipalName(userPrincipalName).userId(userId).connectionsMaxPerRoute(connectionsMaxPerRoute).connectionsMaxTotal(connectionsMaxTotal).proxyHost(proxyHost).proxyPort(proxyPort).proxyUsername(proxyUsername).proxyPassword(proxyPassword).keepAlive(keepAlive).responseCharacterSet(responseCharacterSet).connectTimeout(connectTimeout).trustAllRoots(trustAllRoots).x509HostnameVerifier(x509HostnameVerifier).trustKeystore(trustKeystore).trustPassword(trustPassword).build()).build());
        final String returnMessage = result.get(RETURN_RESULT);
        final Map<String, String> results = getOperationResults(result, returnMessage, returnMessage, returnMessage);
        final Integer statusCode = Integer.parseInt(result.get(STATUS_CODE));
        if (statusCode >= 200 && statusCode < 300) {
            addOutput(results, new JsonParser().parse(returnMessage).getAsJsonObject(), ID, ATTACHMENT_ID);
        }
        return results;
    } catch (Exception exception) {
        return getFailureResultsMap(exception);
    }
}
Also used : JsonParser(com.google.gson.JsonParser) Action(com.hp.oo.sdk.content.annotations.Action)

Example 90 with Action

use of com.hp.oo.sdk.content.annotations.Action in project cs-actions by CloudSlang.

the class PwshScriptAction method execute.

/**
 * Executes a PowerShell Core script on a remote host that has PowerShell Core installed.
 *
 * @param host                 The hostname or ip address of the remote host.
 * @param port                 The port to use when connecting to the remote WinRM server.
 * @param protocol             The protocol to use when connecting to the remote server.
 *                             Valid values are 'HTTP' and 'HTTPS'.
 *                             Default value is 'HTTPS'.
 * @param username             The username used to connect to the remote machine.
 * @param password             The password used to connect to the remote machine.
 * @param proxyHost            The proxy server used to access the remote host.
 * @param proxyPort            The proxy server port.
 * @param proxyUsername        The username used when connecting to the proxy.
 * @param proxyPassword        The password used when connecting to the proxy.
 * @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 is 'false'.
 *                             Valid values are 'true' and 'false'.
 * @param x509HostnameVerifier Specifies the way the server hostname must match a domain name in the subject's Common Name (CN) or subjectAltName field of the
 *                             X.509 certificate. The hostname verification system prevents communication with other hosts other than the ones you intended.
 *                             This is done by checking that the hostname is in the subject alternative name extension of the certificate. This system is
 *                             designed to ensure that, if an attacker(Man In The Middle) redirects traffic to his machine, the client will not accept the
 *                             connection. If you set this input to "allow_all", this verification is ignored and you become vulnerable to security attacks.
 *                             For the value "browser_compatible" the hostname verifier works the same way as Curl and Firefox. The hostname must match
 *                             either the first CN, or any of the subject-alts. A wildcard can occur in the CN, and in any of the subject-alts. The only
 *                             difference between "browser_compatible" and "strict" is that a wildcard (such as "*.foo.com") with "browser_compatible" matches
 *                             all subdomains, including "a.b.foo.com". From the security perspective, to provide protection against possible Man-In-The-Middle
 *                             attacks, we strongly recommend to use "strict" option.
 *                             Valid values are 'strict', 'browser_compatible', 'allow_all'.
 *                             Default value is 'strict'.
 * @param trustKeystore        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 protocol selected is not 'https' or if trustAllRoots
 *                             is 'true' this input is ignored.
 *                             Format of the keystore is Java KeyStore (JKS).
 * @param trustPassword        The password associated with the TrustStore file. If trustAllRoots is false and trustKeystore is empty, trustPassword default will be supplied.
 *                             Default value is 'changeit'.
 * @param keystore             The pathname of the Java KeyStore file. You only need this if the server requires client authentication. If the protocol selected is not
 *                             'https' or if trustAllRoots is 'true' this input is ignored.
 *                             Format of the keystore is Java KeyStore (JKS).
 * @param keystorePassword     The password associated with the KeyStore file. If trustAllRoots is false and keystore is empty, keystorePassword default will be supplied.
 *                             Default value is 'changeit'.
 * @param maxEnvelopeSize      The maximum size of a SOAP packet in bytes for all stream content.
 *                             Default value is '153600'.
 * @param script               The PowerShell script that will be executed on the remote shell.
 * @param configurationName    The name of the PSSessionConfiguration to use. This can be used to target specific versions
 *                             of PowerShell if the PSSessionConfiguration is properly configured on the target.
 *                             By default, after PSRemoting is enabled on the target, the configuration name for PowerShell
 *                             v5 or lower is 'microsoft.powershell', for PowerShell v6 is 'PowerShell.6', for PowerShell v7 is 'PowerShell.7'.
 *                             Additional configurations can be created by the user on the target machines.
 *                             Valid values: any PSConfiguration that exists on the host.
 *                             Examples: 'microsoft.powershell', 'PowerShell.6', 'PowerShell.7'.
 * @param modules              Add modules to the current session. The Import-Module cmdlet is used which adds one or more modules to the current session.
 *                             The modules that you import must be installed on the local computer or a remote computer.
 *                             To import a module, use the Name, Assembly, ModuleInfo, MinimumVersion and RequiredVersion parameters to identify the module to import.
 * @param winrmLocale          The WinRM locale to use.
 *                             Default value is 'en-US'.
 * @param operationTimeout     Defines the OperationTimeout value in seconds to indicate that the clients expect a response or a fault within the specified time.
 *                             Default value is '60'.
 * @return
 */
@Action(name = "Pwsh Script Action", outputs = { @Output(RETURN_CODE), @Output(RETURN_RESULT), @Output(STDERR), @Output(SCRIPT_EXIT_CODE), @Output(EXCEPTION) }, responses = { @Response(text = Constants.ResponseNames.SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Constants.ResponseNames.FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = INPUT_HOST, required = true) String host, @Param(value = INPUT_PORT) String port, @Param(value = PROTOCOL) String protocol, @Param(value = USERNAME) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = PROXY_HOST) String proxyHost, @Param(value = PROXY_PORT) String proxyPort, @Param(value = PROXY_USERNAME) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true) String proxyPassword, @Param(value = TRUST_ALL_ROOTS) String trustAllRoots, @Param(value = X509_HOSTNAME_VERIFIER) String x509HostnameVerifier, @Param(value = TRUST_KEYSTORE) String trustKeystore, @Param(value = TRUST_PASSWORD, encrypted = true) String trustPassword, @Param(value = KEYSTORE) String keystore, @Param(value = KEYSTORE_PASSWORD, encrypted = true) String keystorePassword, @Param(value = MAX_ENVELOP_SIZE) String maxEnvelopeSize, @Param(value = INPUT_SCRIPT, required = true) String script, @Param(value = CONFIGURATION_NAME) String configurationName, @Param(value = MODULES) String modules, @Param(value = WINRM_LOCALE) String winrmLocale, @Param(value = OPERATION_TIMEOUT) String operationTimeout) {
    try {
        WSManRequestInputs wsManRequestInputs = new WSManRequestInputs.WSManRequestInputsBuilder().withHost(host).withPort(port).withProtocol(protocol).withUsername(username).withPassword(password).withAuthType("Basic").withScript(script).withConfigurationName(configurationName).withProxyHost(proxyHost).withProxyPort(proxyPort).withProxyUsername(proxyUsername).withProxyPassword(proxyPassword).withMaxEnvelopeSize(maxEnvelopeSize).withTrustAllRoots(trustAllRoots).withX509HostnameVerifier(x509HostnameVerifier).withKeystore(defaultIfEmpty(keystore, DEFAULT_JAVA_KEYSTORE)).withKeystorePassword(defaultIfEmpty(keystorePassword, CHANGEIT)).withTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE)).withTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT)).withModules(modules).withWinrmLocale(winrmLocale).withOperationTimeout(operationTimeout).build();
        Map<String, String> resultMap = new PwshScriptService().execute(wsManRequestInputs);
        verifyScriptExecutionStatus(resultMap);
        return resultMap;
    } catch (Exception e) {
        return getFailureResultsMap(e);
    }
}
Also used : PwshScriptService(io.cloudslang.content.services.PwshScriptService) WSManRequestInputs(io.cloudslang.content.entities.WSManRequestInputs) Action(com.hp.oo.sdk.content.annotations.Action)

Aggregations

Action (com.hp.oo.sdk.content.annotations.Action)230 CommonInputs (io.cloudslang.content.amazon.entities.inputs.CommonInputs)48 QueryApiExecutor (io.cloudslang.content.amazon.execute.QueryApiExecutor)47 CustomInputs (io.cloudslang.content.amazon.entities.inputs.CustomInputs)32 HttpClientInputs (io.cloudslang.content.httpclient.entities.HttpClientInputs)29 HashMap (java.util.HashMap)22 VmInputs (io.cloudslang.content.vmware.entities.VmInputs)21 HttpInputs (io.cloudslang.content.vmware.entities.http.HttpInputs)21 CommonInputs (io.cloudslang.content.couchbase.entities.inputs.CommonInputs)15 CouchbaseService (io.cloudslang.content.couchbase.execute.CouchbaseService)15 InputsUtil.getHttpClientInputs (io.cloudslang.content.couchbase.utils.InputsUtil.getHttpClientInputs)15 NetworkInputs (io.cloudslang.content.amazon.entities.inputs.NetworkInputs)11 Map (java.util.Map)11 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)10 CommonInputs (io.cloudslang.content.amazon.entities.constants.Inputs.CommonInputs)9 InstanceInputs (io.cloudslang.content.amazon.entities.inputs.InstanceInputs)9 JsonNode (com.fasterxml.jackson.databind.JsonNode)8 JsonParser (com.google.gson.JsonParser)8 SFTPService (io.cloudslang.content.rft.services.SFTPService)8 ClusterComputeResourceService (io.cloudslang.content.vmware.services.ClusterComputeResourceService)8