repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/actions/Validate.java | Validate.execute | @Action(name = "Validate",
outputs = {
@Output(RETURN_CODE),
@Output(RESULT_TEXT),
@Output(RETURN_RESULT),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = XML_DOCUMENT, required = true) String xmlDocument,
@Param(value = XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = XSD_DOCUMENT) String xsdDocument,
@Param(value = XSD_DOCUMENT_SOURCE) String xsdDocumentSource,
@Param(value = USERNAME) String username,
@Param(value = PASSWORD, encrypted = true) String password,
@Param(value = TRUST_ALL_ROOTS) String trustAllRoots,
@Param(value = KEYSTORE) String keystore,
@Param(value = KEYSTORE_PASSWORD, encrypted = true) String keystorePassword,
@Param(value = TRUST_KEYSTORE) String trustKeystore,
@Param(value = TRUST_PASSWORD, encrypted = true) String trustPassword,
@Param(value = X_509_HOSTNAME_VERIFIER) String x509HostnameVerifier,
@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 = SECURE_PROCESSING) String secureProcessing) {
final CommonInputs inputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withUsername(username)
.withPassword(password)
.withTrustAllRoots(trustAllRoots)
.withKeystore(keystore)
.withKeystorePassword(keystorePassword)
.withTrustKeystore(trustKeystore)
.withTrustPassword(trustPassword)
.withX509HostnameVerifier(x509HostnameVerifier)
.withProxyHost(proxyHost)
.withProxyPort(proxyPort)
.withProxyUsername(proxyUsername)
.withProxyPassword(proxyPassword)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withXsdDocument(xsdDocument)
.withXsdDocumentSource(xsdDocumentSource)
.build();
return new ValidateService().execute(inputs, customInputs);
} | java | @Action(name = "Validate",
outputs = {
@Output(RETURN_CODE),
@Output(RESULT_TEXT),
@Output(RETURN_RESULT),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = XML_DOCUMENT, required = true) String xmlDocument,
@Param(value = XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = XSD_DOCUMENT) String xsdDocument,
@Param(value = XSD_DOCUMENT_SOURCE) String xsdDocumentSource,
@Param(value = USERNAME) String username,
@Param(value = PASSWORD, encrypted = true) String password,
@Param(value = TRUST_ALL_ROOTS) String trustAllRoots,
@Param(value = KEYSTORE) String keystore,
@Param(value = KEYSTORE_PASSWORD, encrypted = true) String keystorePassword,
@Param(value = TRUST_KEYSTORE) String trustKeystore,
@Param(value = TRUST_PASSWORD, encrypted = true) String trustPassword,
@Param(value = X_509_HOSTNAME_VERIFIER) String x509HostnameVerifier,
@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 = SECURE_PROCESSING) String secureProcessing) {
final CommonInputs inputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withUsername(username)
.withPassword(password)
.withTrustAllRoots(trustAllRoots)
.withKeystore(keystore)
.withKeystorePassword(keystorePassword)
.withTrustKeystore(trustKeystore)
.withTrustPassword(trustPassword)
.withX509HostnameVerifier(x509HostnameVerifier)
.withProxyHost(proxyHost)
.withProxyPort(proxyPort)
.withProxyUsername(proxyUsername)
.withProxyPassword(proxyPassword)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withXsdDocument(xsdDocument)
.withXsdDocumentSource(xsdDocumentSource)
.build();
return new ValidateService().execute(inputs, customInputs);
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Validate\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RESULT_TEXT",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"ERROR_MESSAGE",
")"... | Service to validate an XML document. Input must be given for either "xmlDocument" or for "xmlLocation".
The "'xsdLocation" input is optional, but if specified then the XML document will be validated against the XSD schema.
@param xmlDocument XML string to test
@param xmlDocumentSource The source type of the xml document.
Valid values: xmlString, xmlPath, xmlUrl
Default value: xmlString
@param xsdDocument optional - XSD to test given XML against
@param xsdDocumentSource The source type of the xsd document.
Valid values: xsdString, xsdPath
Default value: xsdString
@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 secureProcessing optional - whether to use secure processing
@return map of results containing success or failure text and a result message | [
"Service",
"to",
"validate",
"an",
"XML",
"document",
".",
"Input",
"must",
"be",
"given",
"for",
"either",
"xmlDocument",
"or",
"for",
"xmlLocation",
".",
"The",
"xsdLocation",
"input",
"is",
"optional",
"but",
"if",
"specified",
"then",
"the",
"XML",
"docu... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/actions/Validate.java#L94-L146 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/actions/Remove.java | Remove.execute | @Action(name = "Remove",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(RESULT_XML),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = Constants.Inputs.XML_DOCUMENT, required = true) String xmlDocument,
@Param(Constants.Inputs.XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = Constants.Inputs.XPATH_ELEMENT_QUERY, required = true) String xPathQuery,
@Param(Constants.Inputs.ATTRIBUTE_NAME) String attributeName,
@Param(Constants.Inputs.SECURE_PROCESSING) String secureProcessing) {
Map<String, String> result = new HashMap<>();
try {
final CommonInputs inputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withXpathQuery(xPathQuery)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withAttributeName(attributeName)
.build();
result = new RemoveService().execute(inputs, customInputs);
} catch (Exception e) {
ResultUtils.populateFailureResult(result, Constants.ErrorMessages.PARSING_ERROR + e.getMessage());
}
return result;
} | java | @Action(name = "Remove",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(RESULT_XML),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = Constants.Inputs.XML_DOCUMENT, required = true) String xmlDocument,
@Param(Constants.Inputs.XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = Constants.Inputs.XPATH_ELEMENT_QUERY, required = true) String xPathQuery,
@Param(Constants.Inputs.ATTRIBUTE_NAME) String attributeName,
@Param(Constants.Inputs.SECURE_PROCESSING) String secureProcessing) {
Map<String, String> result = new HashMap<>();
try {
final CommonInputs inputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withXpathQuery(xPathQuery)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withAttributeName(attributeName)
.build();
result = new RemoveService().execute(inputs, customInputs);
} catch (Exception e) {
ResultUtils.populateFailureResult(result, Constants.ErrorMessages.PARSING_ERROR + e.getMessage());
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Remove\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RESULT_XML",
")",
",",
"@",
"Output",
"(",
"ERROR_MESSAGE",
")",
... | Removes an element or attribute from an XML document.
@param xmlDocument XML string to remove element or attribute from
@param xmlDocumentSource The source type of the xml document.
Valid values: xmlString, xmlPath
Default value: xmlString
@param xPathQuery XPATH query that results in an element or element list to remove or the element or
element list containing the attribute to remove
@param attributeName optional - name of attribute to remove if removing an attribute; leave empty if removing
an element
@param secureProcessing optional - whether to use secure processing
@return map of results containing success or failure text, a result message, and the modified XML | [
"Removes",
"an",
"element",
"or",
"attribute",
"from",
"an",
"XML",
"document",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/actions/Remove.java#L45-L79 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/utils/ResourceLoader.java | ResourceLoader.loadAsString | public static String loadAsString(String resourceFileName) throws IOException, URISyntaxException {
try (InputStream is = ResourceLoader.class.getClassLoader().getResourceAsStream(resourceFileName)) {
StringWriter stringWriter = new StringWriter();
IOUtils.copy(is, stringWriter, StandardCharsets.UTF_8);
return stringWriter.toString();
}
} | java | public static String loadAsString(String resourceFileName) throws IOException, URISyntaxException {
try (InputStream is = ResourceLoader.class.getClassLoader().getResourceAsStream(resourceFileName)) {
StringWriter stringWriter = new StringWriter();
IOUtils.copy(is, stringWriter, StandardCharsets.UTF_8);
return stringWriter.toString();
}
} | [
"public",
"static",
"String",
"loadAsString",
"(",
"String",
"resourceFileName",
")",
"throws",
"IOException",
",",
"URISyntaxException",
"{",
"try",
"(",
"InputStream",
"is",
"=",
"ResourceLoader",
".",
"class",
".",
"getClassLoader",
"(",
")",
".",
"getResourceA... | Loads the contents of a project resource file in a string.
@param resourceFileName The name of the resource file.
@return A string value representing the entire content of the resource.
@throws IOException
@throws URISyntaxException | [
"Loads",
"the",
"contents",
"of",
"a",
"project",
"resource",
"file",
"in",
"a",
"string",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/utils/ResourceLoader.java#L44-L50 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListItemGrabberAction.java | ListItemGrabberAction.grabItemFromList | @Action(name = "List Item Grabber",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RESPONSE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> grabItemFromList(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter,
@Param(value = INDEX, required = true) String index) {
Map<String, String> result = new HashMap<>();
try {
String[] table = ListProcessor.toArray(list, delimiter);
int resolvedIndex;
try {
resolvedIndex = ListProcessor.getIndex(index, table.length);
} catch (NumberFormatException e) {
throw new NumberFormatException(e.getMessage() + WHILE_PARSING_INDEX);
}
String value = table[resolvedIndex];
result.put(RESULT_TEXT, value);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, value);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | java | @Action(name = "List Item Grabber",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RESPONSE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> grabItemFromList(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter,
@Param(value = INDEX, required = true) String index) {
Map<String, String> result = new HashMap<>();
try {
String[] table = ListProcessor.toArray(list, delimiter);
int resolvedIndex;
try {
resolvedIndex = ListProcessor.getIndex(index, table.length);
} catch (NumberFormatException e) {
throw new NumberFormatException(e.getMessage() + WHILE_PARSING_INDEX);
}
String value = table[resolvedIndex];
result.put(RESULT_TEXT, value);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, value);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List Item Grabber\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESULT_TEXT",
")",
",",
"@",
"Output",
"(",
"RESPONSE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
... | This operation is used to retrieve a value from a list. When the index of an element from a list is known,
this operation can be used to extract the element.
@param list The list to get the value from.
@param delimiter The delimiter that separates values in the list.
@param index The index of the value (starting with 0) to retrieve from the list.
@return It returns the value found at the specified index in the list, if the value specified for
the @index parameter is positive and less than the size of the list. Otherwise, it returns
the value specified for @index. | [
"This",
"operation",
"is",
"used",
"to",
"retrieve",
"a",
"value",
"from",
"a",
"list",
".",
"When",
"the",
"index",
"of",
"an",
"element",
"from",
"a",
"list",
"is",
"known",
"this",
"operation",
"can",
"be",
"used",
"to",
"extract",
"the",
"element",
... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListItemGrabberAction.java#L60-L96 | train |
CloudSlang/cs-actions | cs-utilities/src/main/java/io/cloudslang/content/utilities/actions/DefaultIfEmpty.java | DefaultIfEmpty.execute | @Action(name = "Default if empty",
description = OPERATION_DESC,
outputs = {
@Output(value = RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = RETURN_RESULT, description = RETURN_RESULT_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, isOnFail = true, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = INITIAL_VALUE, description = INITIAL_VALUE_DESC) String initialValue,
@Param(value = DEFAULT_VALUE, required = true, description = DEFAULT_VALUE_DESC) String defaultValue,
@Param(value = TRIM, description = TRIM_DESC) String trim) {
try {
trim = defaultIfBlank(trim, BooleanValues.TRUE);
final boolean validTrim = toBoolean(trim);
return getSuccessResultsMap(DefaultIfEmptyService.defaultIfBlankOrEmpty(initialValue, defaultValue, validTrim));
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | java | @Action(name = "Default if empty",
description = OPERATION_DESC,
outputs = {
@Output(value = RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = RETURN_RESULT, description = RETURN_RESULT_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, isOnFail = true, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = INITIAL_VALUE, description = INITIAL_VALUE_DESC) String initialValue,
@Param(value = DEFAULT_VALUE, required = true, description = DEFAULT_VALUE_DESC) String defaultValue,
@Param(value = TRIM, description = TRIM_DESC) String trim) {
try {
trim = defaultIfBlank(trim, BooleanValues.TRUE);
final boolean validTrim = toBoolean(trim);
return getSuccessResultsMap(DefaultIfEmptyService.defaultIfBlankOrEmpty(initialValue, defaultValue, validTrim));
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Default if empty\"",
",",
"description",
"=",
"OPERATION_DESC",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"value",
"=",
"RETURN_CODE",
",",
"description",
"=",
"RETURN_CODE_DESC",
")",
",",
"@",
"Output",
"(",
"value",... | This operation checks if a string is blank or empty and if it's true a default value
will be assigned instead of the initial string.
@param initialValue The initial string.
@param defaultValue The default value used to replace the initial string.
@param trim A variable used to check if the initial string is blank or empty.
@return a map containing the output of the operation. Keys present in the map are:
returnResult - This will contain the replaced string with the default value.
exception - 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.
returnCode - The returnCode of the operation: 0 for success, -1 for failure. | [
"This",
"operation",
"checks",
"if",
"a",
"string",
"is",
"blank",
"or",
"empty",
"and",
"if",
"it",
"s",
"true",
"a",
"default",
"value",
"will",
"be",
"assigned",
"instead",
"of",
"the",
"initial",
"string",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-utilities/src/main/java/io/cloudslang/content/utilities/actions/DefaultIfEmpty.java#L66-L92 | train |
CloudSlang/cs-actions | cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java | SendMail.validateDelimiters | protected void validateDelimiters(String rowDelimiter, String columnDelimiter) throws Exception {
if (rowDelimiter.equals(columnDelimiter)) {
throw new Exception(INVALID_DELIMITERS);
}
if (StringUtils.contains(columnDelimiter, rowDelimiter)) {
throw new Exception(INVALID_ROW_DELIMITER);
}
} | java | protected void validateDelimiters(String rowDelimiter, String columnDelimiter) throws Exception {
if (rowDelimiter.equals(columnDelimiter)) {
throw new Exception(INVALID_DELIMITERS);
}
if (StringUtils.contains(columnDelimiter, rowDelimiter)) {
throw new Exception(INVALID_ROW_DELIMITER);
}
} | [
"protected",
"void",
"validateDelimiters",
"(",
"String",
"rowDelimiter",
",",
"String",
"columnDelimiter",
")",
"throws",
"Exception",
"{",
"if",
"(",
"rowDelimiter",
".",
"equals",
"(",
"columnDelimiter",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"INVAL... | This method checks if the delimiters are equal and if the row delimiter is a substring of the column delimiter
and throws an exception with the appropriate message.
@param rowDelimiter
@param columnDelimiter
@throws Exception | [
"This",
"method",
"checks",
"if",
"the",
"delimiters",
"are",
"equal",
"and",
"if",
"the",
"row",
"delimiter",
"is",
"a",
"substring",
"of",
"the",
"column",
"delimiter",
"and",
"throws",
"an",
"exception",
"with",
"the",
"appropriate",
"message",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java#L460-L467 | train |
CloudSlang/cs-actions | cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java | SendMail.extractHeaderNamesAndValues | protected Object[] extractHeaderNamesAndValues(String headersMap, String rowDelimiter, String columnDelimiter)
throws Exception {
String[] rows = headersMap.split(Pattern.quote(rowDelimiter));
ArrayList<String> headerNames = new ArrayList<>();
ArrayList<String> headerValues = new ArrayList<>();
for (int i = 0; i < rows.length; i++) {
if (isEmpty(rows[i])) {
continue;
} else {
if (validateRow(rows[i], columnDelimiter, i)) {
String[] headerNameAndValue = rows[i].split(Pattern.quote(columnDelimiter));
headerNames.add(i, headerNameAndValue[0].trim());
headerValues.add(i, headerNameAndValue[1].trim());
}
}
}
return new Object[]{headerNames, headerValues};
} | java | protected Object[] extractHeaderNamesAndValues(String headersMap, String rowDelimiter, String columnDelimiter)
throws Exception {
String[] rows = headersMap.split(Pattern.quote(rowDelimiter));
ArrayList<String> headerNames = new ArrayList<>();
ArrayList<String> headerValues = new ArrayList<>();
for (int i = 0; i < rows.length; i++) {
if (isEmpty(rows[i])) {
continue;
} else {
if (validateRow(rows[i], columnDelimiter, i)) {
String[] headerNameAndValue = rows[i].split(Pattern.quote(columnDelimiter));
headerNames.add(i, headerNameAndValue[0].trim());
headerValues.add(i, headerNameAndValue[1].trim());
}
}
}
return new Object[]{headerNames, headerValues};
} | [
"protected",
"Object",
"[",
"]",
"extractHeaderNamesAndValues",
"(",
"String",
"headersMap",
",",
"String",
"rowDelimiter",
",",
"String",
"columnDelimiter",
")",
"throws",
"Exception",
"{",
"String",
"[",
"]",
"rows",
"=",
"headersMap",
".",
"split",
"(",
"Patt... | This method extracts and returns an object containing two Lists. A list with the header names and a list with the
header values. Values found on same position in the two lists correspond to each other.
@param headersMap
@param rowDelimiter
@param columnDelimiter
@return
@throws Exception | [
"This",
"method",
"extracts",
"and",
"returns",
"an",
"object",
"containing",
"two",
"Lists",
".",
"A",
"list",
"with",
"the",
"header",
"names",
"and",
"a",
"list",
"with",
"the",
"header",
"values",
".",
"Values",
"found",
"on",
"same",
"position",
"in",... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java#L478-L495 | train |
CloudSlang/cs-actions | cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java | SendMail.validateRow | protected boolean validateRow(String row, String columnDelimiter, int rowNumber) throws Exception {
if (row.contains(columnDelimiter)) {
if (row.equals(columnDelimiter)) {
throw new Exception(format(ROW_WITH_EMPTY_HEADERS_INPUT, rowNumber + 1));
} else {
String[] headerNameAndValue = row.split(Pattern.quote(columnDelimiter));
if (StringUtils.countMatches(row, columnDelimiter) > 1) {
throw new Exception(format(ROW_WITH_MULTIPLE_COLUMN_DELIMITERS_IN_HEADERS_INPUT, rowNumber + 1));
} else {
if (headerNameAndValue.length == 1) {
throw new Exception(format(ROW_WITH_MISSING_VALUE_FOR_HEADER, rowNumber + 1));
} else {
return true;
}
}
}
} else {
throw new Exception("Row #" + (rowNumber + 1) + " in the 'headers' input has no column delimiter.");
}
} | java | protected boolean validateRow(String row, String columnDelimiter, int rowNumber) throws Exception {
if (row.contains(columnDelimiter)) {
if (row.equals(columnDelimiter)) {
throw new Exception(format(ROW_WITH_EMPTY_HEADERS_INPUT, rowNumber + 1));
} else {
String[] headerNameAndValue = row.split(Pattern.quote(columnDelimiter));
if (StringUtils.countMatches(row, columnDelimiter) > 1) {
throw new Exception(format(ROW_WITH_MULTIPLE_COLUMN_DELIMITERS_IN_HEADERS_INPUT, rowNumber + 1));
} else {
if (headerNameAndValue.length == 1) {
throw new Exception(format(ROW_WITH_MISSING_VALUE_FOR_HEADER, rowNumber + 1));
} else {
return true;
}
}
}
} else {
throw new Exception("Row #" + (rowNumber + 1) + " in the 'headers' input has no column delimiter.");
}
} | [
"protected",
"boolean",
"validateRow",
"(",
"String",
"row",
",",
"String",
"columnDelimiter",
",",
"int",
"rowNumber",
")",
"throws",
"Exception",
"{",
"if",
"(",
"row",
".",
"contains",
"(",
"columnDelimiter",
")",
")",
"{",
"if",
"(",
"row",
".",
"equal... | This method validates a row contained in the 'headers' input of the operation.
@param row The value of the row to be validated.
@param columnDelimiter The delimiter that separates the header name from the header value.
@param rowNumber The row number inside the 'headers' input.
@return This method returns true if the row contains a header name and a header value.
@throws Exception | [
"This",
"method",
"validates",
"a",
"row",
"contained",
"in",
"the",
"headers",
"input",
"of",
"the",
"operation",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java#L505-L524 | train |
CloudSlang/cs-actions | cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java | SendMail.addHeadersToSMTPMessage | protected SMTPMessage addHeadersToSMTPMessage(SMTPMessage message, List<String> headerNames,
List<String> headerValues) throws MessagingException {
SMTPMessage msg = new SMTPMessage(message);
Iterator namesIter = headerNames.iterator();
Iterator valuesIter = headerValues.iterator();
while (namesIter.hasNext() && valuesIter.hasNext()) {
String headerName = (String) namesIter.next();
String headerValue = (String) valuesIter.next();
if (msg.getHeader(headerName) != null) {
// then a header with this name already exists, add the headerValue to the existing values list.
msg.addHeader(headerName, headerValue);
} else {
msg.setHeader(headerName, headerValue);
}
}
return msg;
} | java | protected SMTPMessage addHeadersToSMTPMessage(SMTPMessage message, List<String> headerNames,
List<String> headerValues) throws MessagingException {
SMTPMessage msg = new SMTPMessage(message);
Iterator namesIter = headerNames.iterator();
Iterator valuesIter = headerValues.iterator();
while (namesIter.hasNext() && valuesIter.hasNext()) {
String headerName = (String) namesIter.next();
String headerValue = (String) valuesIter.next();
if (msg.getHeader(headerName) != null) {
// then a header with this name already exists, add the headerValue to the existing values list.
msg.addHeader(headerName, headerValue);
} else {
msg.setHeader(headerName, headerValue);
}
}
return msg;
} | [
"protected",
"SMTPMessage",
"addHeadersToSMTPMessage",
"(",
"SMTPMessage",
"message",
",",
"List",
"<",
"String",
">",
"headerNames",
",",
"List",
"<",
"String",
">",
"headerValues",
")",
"throws",
"MessagingException",
"{",
"SMTPMessage",
"msg",
"=",
"new",
"SMTP... | The method creates a copy of the SMTPMessage object passed through the arguments list and adds the headers to the
copied object then returns it. If the header is already present in the message then its values list will be
updated with the given header value.
@param message The SMTPMessage object to which the headers are added or updated.
@param headerNames A list of strings containing the header names that need to be added or updated.
@param headerValues A list of strings containing the header values that need to be added.
@return The method returns the message with the headers added.
@throws MessagingException | [
"The",
"method",
"creates",
"a",
"copy",
"of",
"the",
"SMTPMessage",
"object",
"passed",
"through",
"the",
"arguments",
"list",
"and",
"adds",
"the",
"headers",
"to",
"the",
"copied",
"object",
"then",
"returns",
"it",
".",
"If",
"the",
"header",
"is",
"al... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java#L536-L552 | train |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/BooleanUtilities.java | BooleanUtilities.getLowerCaseString | @NotNull
private static String getLowerCaseString(@NotNull final String string) {
return StringUtils.strip(string).toLowerCase();
} | java | @NotNull
private static String getLowerCaseString(@NotNull final String string) {
return StringUtils.strip(string).toLowerCase();
} | [
"@",
"NotNull",
"private",
"static",
"String",
"getLowerCaseString",
"(",
"@",
"NotNull",
"final",
"String",
"string",
")",
"{",
"return",
"StringUtils",
".",
"strip",
"(",
"string",
")",
".",
"toLowerCase",
"(",
")",
";",
"}"
] | Given a string, it lowercase it and strips the blank spaces from the ends
@param string the string to check
@return the string in lowercase | [
"Given",
"a",
"string",
"it",
"lowercase",
"it",
"and",
"strips",
"the",
"blank",
"spaces",
"from",
"the",
"ends"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/BooleanUtilities.java#L42-L45 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListContainsAction.java | ListContainsAction.containsElement | @Action(name = "List Contains All",
outputs = {
@Output(RESPONSE_TEXT),
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> containsElement(@Param(value = SUBLIST, required = true) String sublist,
@Param(value = CONTAINER, required = true) String container,
@Param(value = DELIMITER) String delimiter,
@Param(value = IGNORE_CASE) String ignoreCase
) {
Map<String, String> result = new HashMap<>();
try {
delimiter = InputsUtils.getInputDefaultValue(delimiter, Constants.DEFAULT_DELIMITER);
String[] subArray = sublist.split(delimiter);
String[] containerArray = container.split(delimiter);
String[] uncontainedArray = ListProcessor.getUncontainedArray(subArray, containerArray, InputsUtils.toBoolean(ignoreCase, true, IGNORE_CASE));
if (ListProcessor.arrayElementsAreNull(uncontainedArray)) {
result.put(RESPONSE_TEXT, TRUE);
result.put(RETURN_RESULT, EMPTY_STRING);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
result.put(EXCEPTION, EMPTY_STRING);
} else {
result.put(RESPONSE, FALSE);
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
result.put(RETURN_RESULT, StringUtils.join(uncontainedArray, delimiter));
result.put(EXCEPTION, EMPTY_STRING);
}
} catch (Exception e) {
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, EMPTY_STRING);
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
result.put(EXCEPTION, e.getMessage());
}
return result;
} | java | @Action(name = "List Contains All",
outputs = {
@Output(RESPONSE_TEXT),
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> containsElement(@Param(value = SUBLIST, required = true) String sublist,
@Param(value = CONTAINER, required = true) String container,
@Param(value = DELIMITER) String delimiter,
@Param(value = IGNORE_CASE) String ignoreCase
) {
Map<String, String> result = new HashMap<>();
try {
delimiter = InputsUtils.getInputDefaultValue(delimiter, Constants.DEFAULT_DELIMITER);
String[] subArray = sublist.split(delimiter);
String[] containerArray = container.split(delimiter);
String[] uncontainedArray = ListProcessor.getUncontainedArray(subArray, containerArray, InputsUtils.toBoolean(ignoreCase, true, IGNORE_CASE));
if (ListProcessor.arrayElementsAreNull(uncontainedArray)) {
result.put(RESPONSE_TEXT, TRUE);
result.put(RETURN_RESULT, EMPTY_STRING);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
result.put(EXCEPTION, EMPTY_STRING);
} else {
result.put(RESPONSE, FALSE);
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
result.put(RETURN_RESULT, StringUtils.join(uncontainedArray, delimiter));
result.put(EXCEPTION, EMPTY_STRING);
}
} catch (Exception e) {
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, EMPTY_STRING);
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
result.put(EXCEPTION, e.getMessage());
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List Contains All\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESPONSE_TEXT",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"EXCEPTION"... | This method checks to see if a list contains every element in another list.
@param sublist The contained list.
@param container The containing list.
@param delimiter A delimiter separating elements in the two lists. Default is a comma.
@param ignoreCase If set to 'True' then the compare is not case sensitive. Default is True.
@return sublist is contained in container or not. | [
"This",
"method",
"checks",
"to",
"see",
"if",
"a",
"list",
"contains",
"every",
"element",
"in",
"another",
"list",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListContainsAction.java#L66-L108 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/SQLQueryAllRowsService.java | SQLQueryAllRowsService.execQueryAllRows | public static String execQueryAllRows(@NotNull final SQLInputs sqlInputs) throws Exception {
ConnectionService connectionService = new ConnectionService();
try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {
connection.setReadOnly(true);
Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
statement.setQueryTimeout(sqlInputs.getTimeout());
final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());
final String resultSetToDelimitedColsAndRows = Format.resultSetToDelimitedColsAndRows(resultSet, sqlInputs.isNetcool(), sqlInputs.getColDelimiter(), sqlInputs.getRowDelimiter());
if (resultSet != null) {
resultSet.close();
}
return resultSetToDelimitedColsAndRows;
}
} | java | public static String execQueryAllRows(@NotNull final SQLInputs sqlInputs) throws Exception {
ConnectionService connectionService = new ConnectionService();
try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {
connection.setReadOnly(true);
Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
statement.setQueryTimeout(sqlInputs.getTimeout());
final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());
final String resultSetToDelimitedColsAndRows = Format.resultSetToDelimitedColsAndRows(resultSet, sqlInputs.isNetcool(), sqlInputs.getColDelimiter(), sqlInputs.getRowDelimiter());
if (resultSet != null) {
resultSet.close();
}
return resultSetToDelimitedColsAndRows;
}
} | [
"public",
"static",
"String",
"execQueryAllRows",
"(",
"@",
"NotNull",
"final",
"SQLInputs",
"sqlInputs",
")",
"throws",
"Exception",
"{",
"ConnectionService",
"connectionService",
"=",
"new",
"ConnectionService",
"(",
")",
";",
"try",
"(",
"final",
"Connection",
... | todo
Run a SQL query with given configuration
@return the formatted result set by colDelimiter and rowDelimiter
@throws ClassNotFoundException
@throws java.sql.SQLException | [
"todo",
"Run",
"a",
"SQL",
"query",
"with",
"given",
"configuration"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/SQLQueryAllRowsService.java#L40-L56 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/helpers/GetObjectProperties.java | GetObjectProperties.getObjectProperties | @NotNull
public static ObjectContent[] getObjectProperties(ConnectionResources connectionResources,
ManagedObjectReference mor,
String[] properties)
throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
if (mor == null) {
return new ObjectContent[0];
}
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.getPropSet().add(new PropertySpec());
if ((properties == null || properties.length == 0)) {
spec.getPropSet().get(0).setAll(true);
} else {
spec.getPropSet().get(0).setAll(false);
}
spec.getPropSet().get(0).setType(mor.getType());
spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(properties));
spec.getObjectSet().add(new ObjectSpec());
spec.getObjectSet().get(0).setObj(mor);
spec.getObjectSet().get(0).setSkip(false);
List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<>(1);
propertyFilterSpecs.add(spec);
List<ObjectContent> objectContentList = retrievePropertiesAllObjects(connectionResources, propertyFilterSpecs);
return objectContentList.toArray(new ObjectContent[objectContentList.size()]);
} | java | @NotNull
public static ObjectContent[] getObjectProperties(ConnectionResources connectionResources,
ManagedObjectReference mor,
String[] properties)
throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
if (mor == null) {
return new ObjectContent[0];
}
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.getPropSet().add(new PropertySpec());
if ((properties == null || properties.length == 0)) {
spec.getPropSet().get(0).setAll(true);
} else {
spec.getPropSet().get(0).setAll(false);
}
spec.getPropSet().get(0).setType(mor.getType());
spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(properties));
spec.getObjectSet().add(new ObjectSpec());
spec.getObjectSet().get(0).setObj(mor);
spec.getObjectSet().get(0).setSkip(false);
List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<>(1);
propertyFilterSpecs.add(spec);
List<ObjectContent> objectContentList = retrievePropertiesAllObjects(connectionResources, propertyFilterSpecs);
return objectContentList.toArray(new ObjectContent[objectContentList.size()]);
} | [
"@",
"NotNull",
"public",
"static",
"ObjectContent",
"[",
"]",
"getObjectProperties",
"(",
"ConnectionResources",
"connectionResources",
",",
"ManagedObjectReference",
"mor",
",",
"String",
"[",
"]",
"properties",
")",
"throws",
"RuntimeFaultFaultMsg",
",",
"InvalidProp... | Retrieve contents for a single object based on the property collector
registered with the service.
@param mor Managed Object Reference to get contents for
@param properties names of properties of object to retrieve
@return retrieved object contents | [
"Retrieve",
"contents",
"for",
"a",
"single",
"object",
"based",
"on",
"the",
"property",
"collector",
"registered",
"with",
"the",
"service",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/helpers/GetObjectProperties.java#L39-L68 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/helpers/GetObjectProperties.java | GetObjectProperties.retrievePropertiesAllObjects | private static List<ObjectContent> retrievePropertiesAllObjects(ConnectionResources connectionResources,
List<PropertyFilterSpec> propertyFilterSpecList)
throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
VimPortType vimPort = connectionResources.getVimPortType();
ManagedObjectReference serviceInstance = connectionResources.getServiceInstance();
ServiceContent serviceContent = vimPort.retrieveServiceContent(serviceInstance);
ManagedObjectReference propertyCollectorReference = serviceContent.getPropertyCollector();
RetrieveOptions propertyObjectRetrieveOptions = new RetrieveOptions();
List<ObjectContent> objectContentList = new ArrayList<>();
RetrieveResult results = vimPort.retrievePropertiesEx(propertyCollectorReference,
propertyFilterSpecList,
propertyObjectRetrieveOptions);
if (results != null && results.getObjects() != null && !results.getObjects().isEmpty()) {
objectContentList.addAll(results.getObjects());
}
String token = null;
if (results != null && results.getToken() != null) {
token = results.getToken();
}
while (token != null && !token.isEmpty()) {
results = vimPort.continueRetrievePropertiesEx(propertyCollectorReference, token);
token = null;
if (results != null) {
token = results.getToken();
if (results.getObjects() != null && !results.getObjects().isEmpty()) {
objectContentList.addAll(results.getObjects());
}
}
}
return objectContentList;
} | java | private static List<ObjectContent> retrievePropertiesAllObjects(ConnectionResources connectionResources,
List<PropertyFilterSpec> propertyFilterSpecList)
throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
VimPortType vimPort = connectionResources.getVimPortType();
ManagedObjectReference serviceInstance = connectionResources.getServiceInstance();
ServiceContent serviceContent = vimPort.retrieveServiceContent(serviceInstance);
ManagedObjectReference propertyCollectorReference = serviceContent.getPropertyCollector();
RetrieveOptions propertyObjectRetrieveOptions = new RetrieveOptions();
List<ObjectContent> objectContentList = new ArrayList<>();
RetrieveResult results = vimPort.retrievePropertiesEx(propertyCollectorReference,
propertyFilterSpecList,
propertyObjectRetrieveOptions);
if (results != null && results.getObjects() != null && !results.getObjects().isEmpty()) {
objectContentList.addAll(results.getObjects());
}
String token = null;
if (results != null && results.getToken() != null) {
token = results.getToken();
}
while (token != null && !token.isEmpty()) {
results = vimPort.continueRetrievePropertiesEx(propertyCollectorReference, token);
token = null;
if (results != null) {
token = results.getToken();
if (results.getObjects() != null && !results.getObjects().isEmpty()) {
objectContentList.addAll(results.getObjects());
}
}
}
return objectContentList;
} | [
"private",
"static",
"List",
"<",
"ObjectContent",
">",
"retrievePropertiesAllObjects",
"(",
"ConnectionResources",
"connectionResources",
",",
"List",
"<",
"PropertyFilterSpec",
">",
"propertyFilterSpecList",
")",
"throws",
"RuntimeFaultFaultMsg",
",",
"InvalidPropertyFaultM... | Uses the new RetrievePropertiesEx method to emulate the now deprecated
RetrieveProperties method
@param propertyFilterSpecList
@return list of object content
@throws Exception | [
"Uses",
"the",
"new",
"RetrievePropertiesEx",
"method",
"to",
"emulate",
"the",
"now",
"deprecated",
"RetrieveProperties",
"method"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/helpers/GetObjectProperties.java#L90-L126 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/utils/ValidateUtils.java | ValidateUtils.validateInputs | public static void validateInputs(EditXmlInputs inputs) throws Exception {
validateXmlAndFilePathInputs(inputs.getXml(), inputs.getFilePath());
if (Constants.Inputs.MOVE_ACTION.equals(inputs.getAction())) {
validateIsNotEmpty(inputs.getXpath2(), "xpath2 input is required for action 'move' ");
}
if (!Constants.Inputs.SUBNODE_ACTION.equals(inputs.getAction()) && !Constants.Inputs.MOVE_ACTION.equals(inputs.getAction())) {
validateIsNotEmpty(inputs.getType(), "type input is required for action '" + inputs.getAction() + "'");
if (!Constants.Inputs.TYPE_ELEM.equals(inputs.getType()) && !Constants.Inputs.TYPE_ATTR.equals(inputs.getType()) && !Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) {
throw new Exception("Invalid type. Only supported : " + Constants.Inputs.TYPE_ELEM + ", " + Constants.Inputs.TYPE_ATTR + ", " + Constants.Inputs.TYPE_TEXT);
}
if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) {
validateIsNotEmpty(inputs.getName(), "name input is required for type 'attr' ");
}
}
} | java | public static void validateInputs(EditXmlInputs inputs) throws Exception {
validateXmlAndFilePathInputs(inputs.getXml(), inputs.getFilePath());
if (Constants.Inputs.MOVE_ACTION.equals(inputs.getAction())) {
validateIsNotEmpty(inputs.getXpath2(), "xpath2 input is required for action 'move' ");
}
if (!Constants.Inputs.SUBNODE_ACTION.equals(inputs.getAction()) && !Constants.Inputs.MOVE_ACTION.equals(inputs.getAction())) {
validateIsNotEmpty(inputs.getType(), "type input is required for action '" + inputs.getAction() + "'");
if (!Constants.Inputs.TYPE_ELEM.equals(inputs.getType()) && !Constants.Inputs.TYPE_ATTR.equals(inputs.getType()) && !Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) {
throw new Exception("Invalid type. Only supported : " + Constants.Inputs.TYPE_ELEM + ", " + Constants.Inputs.TYPE_ATTR + ", " + Constants.Inputs.TYPE_TEXT);
}
if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) {
validateIsNotEmpty(inputs.getName(), "name input is required for type 'attr' ");
}
}
} | [
"public",
"static",
"void",
"validateInputs",
"(",
"EditXmlInputs",
"inputs",
")",
"throws",
"Exception",
"{",
"validateXmlAndFilePathInputs",
"(",
"inputs",
".",
"getXml",
"(",
")",
",",
"inputs",
".",
"getFilePath",
"(",
")",
")",
";",
"if",
"(",
"Constants"... | Validates the operation inputs.
@param inputs@throws Exception for invalid inputs | [
"Validates",
"the",
"operation",
"inputs",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/utils/ValidateUtils.java#L33-L48 | train |
CloudSlang/cs-actions | cs-azure/src/main/java/io/cloudslang/content/azure/actions/utils/GetSharedAccessKeyToken.java | GetSharedAccessKeyToken.execute | @Action(name = "Get shared access key token for Azure",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED),
@Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR)
})
public Map<String, String> execute(@Param(value = IDENTIFIER, required = true) final String identifier,
@Param(value = PRIMARY_OR_SECONDARY_KEY, required = true) final String primaryOrSecondaryKey,
@Param(value = EXPIRY, required = true) final String expiry) {
final List<String> exceptionMessages = InputsValidation.verifySharedAccessInputs(identifier, primaryOrSecondaryKey, expiry);
if (!exceptionMessages.isEmpty()) {
final String errorMessage = StringUtilities.join(exceptionMessages, System.lineSeparator());
return getFailureResultsMap(errorMessage);
}
try {
final Date expiryDate = DateUtilities.parseDate(expiry.trim());
return getSuccessResultsMap(getToken(identifier.trim(), primaryOrSecondaryKey.trim(), expiryDate));
} catch (Exception exception) {
return getFailureResultsMap(exception);
}
} | java | @Action(name = "Get shared access key token for Azure",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED),
@Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR)
})
public Map<String, String> execute(@Param(value = IDENTIFIER, required = true) final String identifier,
@Param(value = PRIMARY_OR_SECONDARY_KEY, required = true) final String primaryOrSecondaryKey,
@Param(value = EXPIRY, required = true) final String expiry) {
final List<String> exceptionMessages = InputsValidation.verifySharedAccessInputs(identifier, primaryOrSecondaryKey, expiry);
if (!exceptionMessages.isEmpty()) {
final String errorMessage = StringUtilities.join(exceptionMessages, System.lineSeparator());
return getFailureResultsMap(errorMessage);
}
try {
final Date expiryDate = DateUtilities.parseDate(expiry.trim());
return getSuccessResultsMap(getToken(identifier.trim(), primaryOrSecondaryKey.trim(), expiryDate));
} catch (Exception exception) {
return getFailureResultsMap(exception);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Get shared access key token for Azure\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"EXCEPTION",
")",
"}",
",",
"responses",
... | Generates the shared access key token for Azure API calls.
@param identifier The Identifier text box in the Credentials section of the Service Management API tab
of System Settings
@param primaryOrSecondaryKey The Primary Key or the Secondary Key in the Credentials section of the Service
Management API tab of System Settings
@param expiry The expiration date and time for the access token, the value must be in the format "MM/DD/YYYY H:MM PM|AM"
Example: 08/04/2014 10:03 PM
@return The SharedAccessKey token for Azure | [
"Generates",
"the",
"shared",
"access",
"key",
"token",
"for",
"Azure",
"API",
"calls",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-azure/src/main/java/io/cloudslang/content/azure/actions/utils/GetSharedAccessKeyToken.java#L64-L88 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListSortAction.java | ListSortAction.sortList | @Action(name = "List Sort",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> sortList(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter,
@Param(value = REVERSE) String reverse) {
Map<String, String> result = new HashMap<>();
try {
String sortedList = sort(list, Boolean.parseBoolean(reverse), delimiter);
result.put(RESULT_TEXT, sortedList);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, sortedList);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | java | @Action(name = "List Sort",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> sortList(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter,
@Param(value = REVERSE) String reverse) {
Map<String, String> result = new HashMap<>();
try {
String sortedList = sort(list, Boolean.parseBoolean(reverse), delimiter);
result.put(RESULT_TEXT, sortedList);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, sortedList);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List Sort\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESULT_TEXT",
")",
",",
"@",
"Output",
"(",
"RESPONSE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
... | This method sorts a list of strings. If the list contains only numerical strings, it is sorted in numerical order.
Otherwise it is sorted alphabetically.
@param list The list to be sorted.
@param delimiter The list delimiter.
@param reverse A boolean value for sorting the list in reverse order.
@return The sorted list. | [
"This",
"method",
"sorts",
"a",
"list",
"of",
"strings",
".",
"If",
"the",
"list",
"contains",
"only",
"numerical",
"strings",
"it",
"is",
"sorted",
"in",
"numerical",
"order",
".",
"Otherwise",
"it",
"is",
"sorted",
"alphabetically",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListSortAction.java#L57-L86 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListRemoverAction.java | ListRemoverAction.removeElement | @Action(name = "List Remover",
outputs = {
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> removeElement(@Param(value = LIST, required = true) String list,
@Param(value = ELEMENT, required = true) String index,
@Param(value = DELIMITER, required = true) String delimiter) {
Map<String, String> result = new HashMap<>();
try {
if (StringUtils.isEmpty(list) || StringUtils.isEmpty(index) || StringUtils.isEmpty(delimiter)) {
throw new RuntimeException(EMPTY_INPUT_EXCEPTION);
} else {
String[] elements = StringUtils.split(list, delimiter);
elements = ArrayUtils.remove(elements, Integer.parseInt(index));
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, StringUtils.join(elements, delimiter));
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
}
} catch (Exception e) {
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | java | @Action(name = "List Remover",
outputs = {
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> removeElement(@Param(value = LIST, required = true) String list,
@Param(value = ELEMENT, required = true) String index,
@Param(value = DELIMITER, required = true) String delimiter) {
Map<String, String> result = new HashMap<>();
try {
if (StringUtils.isEmpty(list) || StringUtils.isEmpty(index) || StringUtils.isEmpty(delimiter)) {
throw new RuntimeException(EMPTY_INPUT_EXCEPTION);
} else {
String[] elements = StringUtils.split(list, delimiter);
elements = ArrayUtils.remove(elements, Integer.parseInt(index));
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, StringUtils.join(elements, delimiter));
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
}
} catch (Exception e) {
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List Remover\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESPONSE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
"}",
",",
"responses",
"=",
"{",
"@",
"Res... | This method removes an element from a list of strings.
@param list The list to remove from.
@param index The index of the element to remove from the list.
@param delimiter The list delimiter.
@return The new list. | [
"This",
"method",
"removes",
"an",
"element",
"from",
"a",
"list",
"of",
"strings",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListRemoverAction.java#L57-L87 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/C3P0PooledDataSourceProvider.java | C3P0PooledDataSourceProvider.openPooledDataSource | public DataSource openPooledDataSource(DBType aDbType, String aDbUrl, String aUsername, String aPassword) throws SQLException {
final DataSource unPooledDS = DataSources.unpooledDataSource(aDbUrl, aUsername, aPassword);
//override the default properties with ours
final Map<String, String> props = this.getPoolingProperties(aDbType);
return DataSources.pooledDataSource(unPooledDS, props);
} | java | public DataSource openPooledDataSource(DBType aDbType, String aDbUrl, String aUsername, String aPassword) throws SQLException {
final DataSource unPooledDS = DataSources.unpooledDataSource(aDbUrl, aUsername, aPassword);
//override the default properties with ours
final Map<String, String> props = this.getPoolingProperties(aDbType);
return DataSources.pooledDataSource(unPooledDS, props);
} | [
"public",
"DataSource",
"openPooledDataSource",
"(",
"DBType",
"aDbType",
",",
"String",
"aDbUrl",
",",
"String",
"aUsername",
",",
"String",
"aPassword",
")",
"throws",
"SQLException",
"{",
"final",
"DataSource",
"unPooledDS",
"=",
"DataSources",
".",
"unpooledData... | get the pooled datasource from c3p0 pool
@param aDbType a supported database type.
@param aDbUrl a connection url
@param aUsername a username for the database
@param aPassword a password for the database connection
@return a DataSource a pooled data source
@throws SQLException | [
"get",
"the",
"pooled",
"datasource",
"from",
"c3p0",
"pool"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/C3P0PooledDataSourceProvider.java#L111-L120 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/C3P0PooledDataSourceProvider.java | C3P0PooledDataSourceProvider.getPoolingProperties | private Map<String, String> getPoolingProperties(DBType aDbType) {
Map<String, String> retMap = new HashMap<>();
//general properties
//acquire increment size
String acqIncSize = this.getPropStringValue(CONNECTION_ACQUIREINCREMENT_SIZE_NAME,
CONNECTION_ACQUIREINCREMENT_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_ACQUIRE_INCREMENT_NAME, acqIncSize);
//retry counts
String retryCount = this.getPropStringValue(CONNECTION_RETRY_COUNT_NAME,
CONNECTION_RETRY_COUNT_DEFAULT_VALUE);
retMap.put(C3P0_ACQUIRE_RETRY_ATTEMPTS_NAME, retryCount);
//retry deplay this will be value of milseconds
String retryDelay = this.getPropStringValue(CONNECTION_RETRY_DELAY_NAME,
CONNECTION_RETRY_DELAY_DEFAULT_VALUE);
retMap.put(C3P0_ACQUIRE_RETRY_DELAY_NAME, retryDelay);
//test period
String testPeriod = this.getPropStringValue(CONNECTION_TEST_PERIOD_NAME,
CONNECTION_TEST_PERIOD_DEFAULT_VALUE);
retMap.put(C3P0_IDLE_CONNECTION_TEST_PERIOD_NAME, testPeriod);
//test on check in
String bTestOnCheckIn = this.getPropStringValue(CONNECTION_TEST_ONCHECKIN_NAME,
CONNECTION_TEST_ONCHECKIN_DEFAULT_VALUE);
retMap.put(C3P0_TEST_CONNECTION_ON_CHECKIN_NAME, bTestOnCheckIn);
//test on check out
String bTestOnCheckOut = this.getPropStringValue(CONNECTION_TEST_ONCHECKOUT_NAME,
CONNECTION_TEST_ONCHECKOUT_DEFAULT_VALUE);
retMap.put(C3P0_TEST_CONNECTION_ON_CHECKOUT_NAME, bTestOnCheckOut);
//max idle time
String maxIdleTime = this.getPropStringValue(CONNECTION_MAX_IDLETIME_NAME,
CONNECTION_MAX_IDLETIME_DEFAULT_VALUE);
retMap.put(C3P0_MAX_IDLE_TIME_NAME, maxIdleTime);
//max pool size
String maxPoolSize = this.getPropStringValue(MAX_POOL_SIZE_NAME,
MAX_POOL_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_MAX_POOL_SIZE_NAME, maxPoolSize);
//min pool size
String minPoolSize = this.getPropStringValue(MIN_POOL_SIZE_NAME,
MIN_POOL_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_MIN_POOL_SIZE_NAME, minPoolSize);
//init pool size
String initPoolSize = this.getPropStringValue(INIT_POOL_SIZE_NAME,
INIT_POOL_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_INIT_POOL_SIZE_NAME, initPoolSize);
//connection timeout
String conTimeout = this.getPropStringValue(CONNECTION_CHECKOUT_TIMEOUT_NAME,
CONNECTION_CHECKOUT_TIMEOUT_DEFAULT_VALUE);
retMap.put(C3P0_CHECKOUT_TIMEOUT_NAME, conTimeout);
//connection break after acquire failure
String breakAfterFailure = this.getPropStringValue(CONNECTION_BREAKAFTERACQUIREFAILURE_NAME,
CONNECTION_BREAKAFTERACQUIREFAILURE_DEFAULT_VALUE);
retMap.put(C3P0_BREAK_AFTERACQUIREFAILURE_NAME, breakAfterFailure);
//db specific properties
//connection life time
String conLifeTimeName;
switch (aDbType) {
case ORACLE:
conLifeTimeName = ORACLE_CONNECTION_LIFETIME_NAME;
break;
case MSSQL:
conLifeTimeName = MSSQL_CONNECTION_LIFETIME_NAME;
break;
case MYSQL:
conLifeTimeName = MYSQL_CONNECTION_LIFETIME_NAME;
break;
case SYBASE:
conLifeTimeName = SYBASE_CONNECTION_LIFETIME_NAME;
break;
case DB2:
conLifeTimeName = DB2_CONNECTION_LIFETIME_NAME;
break;
case NETCOOL:
conLifeTimeName = NETCOOL_CONNECTION_LIFETIME_NAME;
break;
default:
conLifeTimeName = CUSTOM_CONNECTION_LIFETIME_NAME;
break;
}
String connectionLifetime =
this.getPropStringValue(conLifeTimeName, CONNECTION_LIFETIME_DEFAULT_VALUE);
retMap.put(C3P0_MAX_CONNECTION_AGE_NAME, connectionLifetime);
return retMap;
} | java | private Map<String, String> getPoolingProperties(DBType aDbType) {
Map<String, String> retMap = new HashMap<>();
//general properties
//acquire increment size
String acqIncSize = this.getPropStringValue(CONNECTION_ACQUIREINCREMENT_SIZE_NAME,
CONNECTION_ACQUIREINCREMENT_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_ACQUIRE_INCREMENT_NAME, acqIncSize);
//retry counts
String retryCount = this.getPropStringValue(CONNECTION_RETRY_COUNT_NAME,
CONNECTION_RETRY_COUNT_DEFAULT_VALUE);
retMap.put(C3P0_ACQUIRE_RETRY_ATTEMPTS_NAME, retryCount);
//retry deplay this will be value of milseconds
String retryDelay = this.getPropStringValue(CONNECTION_RETRY_DELAY_NAME,
CONNECTION_RETRY_DELAY_DEFAULT_VALUE);
retMap.put(C3P0_ACQUIRE_RETRY_DELAY_NAME, retryDelay);
//test period
String testPeriod = this.getPropStringValue(CONNECTION_TEST_PERIOD_NAME,
CONNECTION_TEST_PERIOD_DEFAULT_VALUE);
retMap.put(C3P0_IDLE_CONNECTION_TEST_PERIOD_NAME, testPeriod);
//test on check in
String bTestOnCheckIn = this.getPropStringValue(CONNECTION_TEST_ONCHECKIN_NAME,
CONNECTION_TEST_ONCHECKIN_DEFAULT_VALUE);
retMap.put(C3P0_TEST_CONNECTION_ON_CHECKIN_NAME, bTestOnCheckIn);
//test on check out
String bTestOnCheckOut = this.getPropStringValue(CONNECTION_TEST_ONCHECKOUT_NAME,
CONNECTION_TEST_ONCHECKOUT_DEFAULT_VALUE);
retMap.put(C3P0_TEST_CONNECTION_ON_CHECKOUT_NAME, bTestOnCheckOut);
//max idle time
String maxIdleTime = this.getPropStringValue(CONNECTION_MAX_IDLETIME_NAME,
CONNECTION_MAX_IDLETIME_DEFAULT_VALUE);
retMap.put(C3P0_MAX_IDLE_TIME_NAME, maxIdleTime);
//max pool size
String maxPoolSize = this.getPropStringValue(MAX_POOL_SIZE_NAME,
MAX_POOL_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_MAX_POOL_SIZE_NAME, maxPoolSize);
//min pool size
String minPoolSize = this.getPropStringValue(MIN_POOL_SIZE_NAME,
MIN_POOL_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_MIN_POOL_SIZE_NAME, minPoolSize);
//init pool size
String initPoolSize = this.getPropStringValue(INIT_POOL_SIZE_NAME,
INIT_POOL_SIZE_DEFAULT_VALUE);
retMap.put(C3P0_INIT_POOL_SIZE_NAME, initPoolSize);
//connection timeout
String conTimeout = this.getPropStringValue(CONNECTION_CHECKOUT_TIMEOUT_NAME,
CONNECTION_CHECKOUT_TIMEOUT_DEFAULT_VALUE);
retMap.put(C3P0_CHECKOUT_TIMEOUT_NAME, conTimeout);
//connection break after acquire failure
String breakAfterFailure = this.getPropStringValue(CONNECTION_BREAKAFTERACQUIREFAILURE_NAME,
CONNECTION_BREAKAFTERACQUIREFAILURE_DEFAULT_VALUE);
retMap.put(C3P0_BREAK_AFTERACQUIREFAILURE_NAME, breakAfterFailure);
//db specific properties
//connection life time
String conLifeTimeName;
switch (aDbType) {
case ORACLE:
conLifeTimeName = ORACLE_CONNECTION_LIFETIME_NAME;
break;
case MSSQL:
conLifeTimeName = MSSQL_CONNECTION_LIFETIME_NAME;
break;
case MYSQL:
conLifeTimeName = MYSQL_CONNECTION_LIFETIME_NAME;
break;
case SYBASE:
conLifeTimeName = SYBASE_CONNECTION_LIFETIME_NAME;
break;
case DB2:
conLifeTimeName = DB2_CONNECTION_LIFETIME_NAME;
break;
case NETCOOL:
conLifeTimeName = NETCOOL_CONNECTION_LIFETIME_NAME;
break;
default:
conLifeTimeName = CUSTOM_CONNECTION_LIFETIME_NAME;
break;
}
String connectionLifetime =
this.getPropStringValue(conLifeTimeName, CONNECTION_LIFETIME_DEFAULT_VALUE);
retMap.put(C3P0_MAX_CONNECTION_AGE_NAME, connectionLifetime);
return retMap;
} | [
"private",
"Map",
"<",
"String",
",",
"String",
">",
"getPoolingProperties",
"(",
"DBType",
"aDbType",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"retMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"//general properties",
"//acquire increment size",... | set up the properties for c3p0 based on the properties values in
databasePooling.properties.
@param aDbType a supported db type.
@return a HashMap of c3p0 db pooling properties. | [
"set",
"up",
"the",
"properties",
"for",
"c3p0",
"based",
"on",
"the",
"properties",
"values",
"in",
"databasePooling",
".",
"properties",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/C3P0PooledDataSourceProvider.java#L129-L231 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/C3P0PooledDataSourceProvider.java | C3P0PooledDataSourceProvider.getAllConnectionNumber | public int getAllConnectionNumber(DataSource aPooledDataSource) throws SQLException {
PooledDataSource pDs = (PooledDataSource) aPooledDataSource;
return pDs.getNumConnectionsAllUsers();
} | java | public int getAllConnectionNumber(DataSource aPooledDataSource) throws SQLException {
PooledDataSource pDs = (PooledDataSource) aPooledDataSource;
return pDs.getNumConnectionsAllUsers();
} | [
"public",
"int",
"getAllConnectionNumber",
"(",
"DataSource",
"aPooledDataSource",
")",
"throws",
"SQLException",
"{",
"PooledDataSource",
"pDs",
"=",
"(",
"PooledDataSource",
")",
"aPooledDataSource",
";",
"return",
"pDs",
".",
"getNumConnectionsAllUsers",
"(",
")",
... | The followings are only for testing purpose | [
"The",
"followings",
"are",
"only",
"for",
"testing",
"purpose"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/C3P0PooledDataSourceProvider.java#L234-L237 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/utils/SQLUtils.java | SQLUtils.getIPv4OrIPv6WithSquareBracketsHost | public static String getIPv4OrIPv6WithSquareBracketsHost(String dbServer) {
final Address address = new Address(dbServer);
return address.getURIIPV6Literal();
} | java | public static String getIPv4OrIPv6WithSquareBracketsHost(String dbServer) {
final Address address = new Address(dbServer);
return address.getURIIPV6Literal();
} | [
"public",
"static",
"String",
"getIPv4OrIPv6WithSquareBracketsHost",
"(",
"String",
"dbServer",
")",
"{",
"final",
"Address",
"address",
"=",
"new",
"Address",
"(",
"dbServer",
")",
";",
"return",
"address",
".",
"getURIIPV6Literal",
"(",
")",
";",
"}"
] | Method returning the host surrounded by square brackets if 'dbServer' is IPv6 format.
Otherwise the returned string will be the same.
@return | [
"Method",
"returning",
"the",
"host",
"surrounded",
"by",
"square",
"brackets",
"if",
"dbServer",
"is",
"IPv6",
"format",
".",
"Otherwise",
"the",
"returned",
"string",
"will",
"be",
"the",
"same",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/utils/SQLUtils.java#L71-L74 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/utils/SQLUtils.java | SQLUtils.computeSessionId | @NotNull
public static String computeSessionId(@NotNull final String aString) {
final byte[] byteData = DigestUtils.sha256(aString.getBytes());
final StringBuilder sb = new StringBuilder("SQLQuery:");
for (final byte aByteData : byteData) {
final String hex = Integer.toHexString(0xFF & aByteData);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
} | java | @NotNull
public static String computeSessionId(@NotNull final String aString) {
final byte[] byteData = DigestUtils.sha256(aString.getBytes());
final StringBuilder sb = new StringBuilder("SQLQuery:");
for (final byte aByteData : byteData) {
final String hex = Integer.toHexString(0xFF & aByteData);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
} | [
"@",
"NotNull",
"public",
"static",
"String",
"computeSessionId",
"(",
"@",
"NotNull",
"final",
"String",
"aString",
")",
"{",
"final",
"byte",
"[",
"]",
"byteData",
"=",
"DigestUtils",
".",
"sha256",
"(",
"aString",
".",
"getBytes",
"(",
")",
")",
";",
... | compute session id for JDBC operations | [
"compute",
"session",
"id",
"for",
"JDBC",
"operations"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/utils/SQLUtils.java#L93-L106 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java | DBConnectionManager.cleanDataSources | public void cleanDataSources() {
Hashtable<String, List<String>> removedDsKeyTable = null;
//gather all the empty ds's key, can't remove item while iterate
Enumeration<String> allPoolKeys = dbmsPoolTable.keys();
while (allPoolKeys.hasMoreElements()) {
String dbPoolKey = allPoolKeys.nextElement();
Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(dbPoolKey);
Enumeration<String> allDsKeys = dsTable.keys();
while (allDsKeys.hasMoreElements()) {
String dsKey = allDsKeys.nextElement();
DataSource ds = dsTable.get(dsKey);
//c3p0 impl
if (ds != null && ds instanceof PooledDataSource) {
PooledDataSource pDs = (PooledDataSource) ds;
int conCount;
try {
conCount = pDs.getNumConnectionsAllUsers();
} catch (SQLException e) {
// todo logger.error
// ("Failed to get total number of connections for datasource. dbmsPoolKey = "
// + dbPoolKey, e);
continue;
}
//no connections
if (conCount == 0) {
List<String> removedList = null;
if (removedDsKeyTable == null) {
removedDsKeyTable = new Hashtable<>();
} else {
removedList = removedDsKeyTable.get(dbPoolKey);
}
if (removedList == null) {
removedList = new ArrayList<>();
removedList.add(dsKey);
removedDsKeyTable.put(dbPoolKey, removedList);
} else {
removedList.add(dsKey);
}
}
}
}
}
//have empty ds
if (removedDsKeyTable != null && !removedDsKeyTable.isEmpty()) {
Enumeration<String> removedPoolKeys = removedDsKeyTable.keys();
while (removedPoolKeys.hasMoreElements()) {
String removedPoolKey = removedPoolKeys.nextElement();
PooledDataSourceProvider provider = this.getProvider(removedPoolKey);
List<String> removedDsList = removedDsKeyTable.get(removedPoolKey);
Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(removedPoolKey);
for (String dsKey : removedDsList) {
DataSource removedDs = dsTable.remove(dsKey);
try {
provider.closePooledDataSource(removedDs);
} catch (SQLException e) {
//can't show the dsKey since it has encrypted password there
// todo logger.error("Failed to close datadsource in dmbs poolKey = "
// + removedPoolKey, e);
continue;
}
//tracing
// todo if (logger.isDebugEnabled()) {
// logger.debug("Removed one datasource in dbms poolKey = "
// + removedPoolKey);
// }
}
//don't have any ds for the pool key
if (dsTable.isEmpty()) {
dbmsPoolTable.remove(removedPoolKey);
//tracing
// todo if (logger.isDebugEnabled()) {
// logger.debug("Removed dbms poolKey = " + removedPoolKey);
// }
}
}
}
} | java | public void cleanDataSources() {
Hashtable<String, List<String>> removedDsKeyTable = null;
//gather all the empty ds's key, can't remove item while iterate
Enumeration<String> allPoolKeys = dbmsPoolTable.keys();
while (allPoolKeys.hasMoreElements()) {
String dbPoolKey = allPoolKeys.nextElement();
Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(dbPoolKey);
Enumeration<String> allDsKeys = dsTable.keys();
while (allDsKeys.hasMoreElements()) {
String dsKey = allDsKeys.nextElement();
DataSource ds = dsTable.get(dsKey);
//c3p0 impl
if (ds != null && ds instanceof PooledDataSource) {
PooledDataSource pDs = (PooledDataSource) ds;
int conCount;
try {
conCount = pDs.getNumConnectionsAllUsers();
} catch (SQLException e) {
// todo logger.error
// ("Failed to get total number of connections for datasource. dbmsPoolKey = "
// + dbPoolKey, e);
continue;
}
//no connections
if (conCount == 0) {
List<String> removedList = null;
if (removedDsKeyTable == null) {
removedDsKeyTable = new Hashtable<>();
} else {
removedList = removedDsKeyTable.get(dbPoolKey);
}
if (removedList == null) {
removedList = new ArrayList<>();
removedList.add(dsKey);
removedDsKeyTable.put(dbPoolKey, removedList);
} else {
removedList.add(dsKey);
}
}
}
}
}
//have empty ds
if (removedDsKeyTable != null && !removedDsKeyTable.isEmpty()) {
Enumeration<String> removedPoolKeys = removedDsKeyTable.keys();
while (removedPoolKeys.hasMoreElements()) {
String removedPoolKey = removedPoolKeys.nextElement();
PooledDataSourceProvider provider = this.getProvider(removedPoolKey);
List<String> removedDsList = removedDsKeyTable.get(removedPoolKey);
Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(removedPoolKey);
for (String dsKey : removedDsList) {
DataSource removedDs = dsTable.remove(dsKey);
try {
provider.closePooledDataSource(removedDs);
} catch (SQLException e) {
//can't show the dsKey since it has encrypted password there
// todo logger.error("Failed to close datadsource in dmbs poolKey = "
// + removedPoolKey, e);
continue;
}
//tracing
// todo if (logger.isDebugEnabled()) {
// logger.debug("Removed one datasource in dbms poolKey = "
// + removedPoolKey);
// }
}
//don't have any ds for the pool key
if (dsTable.isEmpty()) {
dbmsPoolTable.remove(removedPoolKey);
//tracing
// todo if (logger.isDebugEnabled()) {
// logger.debug("Removed dbms poolKey = " + removedPoolKey);
// }
}
}
}
} | [
"public",
"void",
"cleanDataSources",
"(",
")",
"{",
"Hashtable",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"removedDsKeyTable",
"=",
"null",
";",
"//gather all the empty ds's key, can't remove item while iterate",
"Enumeration",
"<",
"String",
">",
"allPoo... | clean any empty datasource and pool in the dbmsPool table. | [
"clean",
"any",
"empty",
"datasource",
"and",
"pool",
"in",
"the",
"dbmsPool",
"table",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java#L215-L297 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java | DBConnectionManager.shutdownDbmsPools | public synchronized void shutdownDbmsPools() {
//force shutdown
//runnable
datasourceCleaner.shutdown();
datasourceCleaner = null;
//shell for the runnable
cleanerThread.interrupt();//stop the thread
cleanerThread = null;
if (dbmsPoolTable == null) {
return;
}
Enumeration<String> allDbmsKeys = dbmsPoolTable.keys();
while (allDbmsKeys.hasMoreElements()) {
String dbmsKey = allDbmsKeys.nextElement();
PooledDataSourceProvider provider = this.getProvider(dbmsKey);
Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(dbmsKey);
for (DataSource ds : dsTable.values()) {
try {
provider.closePooledDataSource(ds);
} catch (SQLException e) {
// todo logger.error("Failed to close datasource in dbms poolKey = "
// + dbmsKey);
}
}
dsTable.clear();
}
dbmsPoolTable.clear();
dbmsPoolTable = null;
} | java | public synchronized void shutdownDbmsPools() {
//force shutdown
//runnable
datasourceCleaner.shutdown();
datasourceCleaner = null;
//shell for the runnable
cleanerThread.interrupt();//stop the thread
cleanerThread = null;
if (dbmsPoolTable == null) {
return;
}
Enumeration<String> allDbmsKeys = dbmsPoolTable.keys();
while (allDbmsKeys.hasMoreElements()) {
String dbmsKey = allDbmsKeys.nextElement();
PooledDataSourceProvider provider = this.getProvider(dbmsKey);
Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(dbmsKey);
for (DataSource ds : dsTable.values()) {
try {
provider.closePooledDataSource(ds);
} catch (SQLException e) {
// todo logger.error("Failed to close datasource in dbms poolKey = "
// + dbmsKey);
}
}
dsTable.clear();
}
dbmsPoolTable.clear();
dbmsPoolTable = null;
} | [
"public",
"synchronized",
"void",
"shutdownDbmsPools",
"(",
")",
"{",
"//force shutdown",
"//runnable",
"datasourceCleaner",
".",
"shutdown",
"(",
")",
";",
"datasourceCleaner",
"=",
"null",
";",
"//shell for the runnable",
"cleanerThread",
".",
"interrupt",
"(",
")",... | force shutdown everything | [
"force",
"shutdown",
"everything"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java#L302-L331 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java | DBConnectionManager.getPropBooleanValue | protected boolean getPropBooleanValue(String aPropName, String aDefaultValue) {
boolean retValue;
String temp = dbPoolingProperties.getProperty(aPropName, aDefaultValue);
retValue = Boolean.valueOf(temp);
return retValue;
} | java | protected boolean getPropBooleanValue(String aPropName, String aDefaultValue) {
boolean retValue;
String temp = dbPoolingProperties.getProperty(aPropName, aDefaultValue);
retValue = Boolean.valueOf(temp);
return retValue;
} | [
"protected",
"boolean",
"getPropBooleanValue",
"(",
"String",
"aPropName",
",",
"String",
"aDefaultValue",
")",
"{",
"boolean",
"retValue",
";",
"String",
"temp",
"=",
"dbPoolingProperties",
".",
"getProperty",
"(",
"aPropName",
",",
"aDefaultValue",
")",
";",
"re... | get boolean value based on the property name from property file
the property file is databasePooling.properties
@param aPropName a property name
@param aDefaultValue a default value for that property, if the property is not there.
@return boolean value of that property | [
"get",
"boolean",
"value",
"based",
"on",
"the",
"property",
"name",
"from",
"property",
"file",
"the",
"property",
"file",
"is",
"databasePooling",
".",
"properties"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java#L341-L348 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java | DBConnectionManager.getPropIntValue | protected int getPropIntValue(String aPropName, String aDefaultValue) {
int retValue;
String temp = dbPoolingProperties.getProperty(aPropName, aDefaultValue);
retValue = Integer.valueOf(temp);
return retValue;
} | java | protected int getPropIntValue(String aPropName, String aDefaultValue) {
int retValue;
String temp = dbPoolingProperties.getProperty(aPropName, aDefaultValue);
retValue = Integer.valueOf(temp);
return retValue;
} | [
"protected",
"int",
"getPropIntValue",
"(",
"String",
"aPropName",
",",
"String",
"aDefaultValue",
")",
"{",
"int",
"retValue",
";",
"String",
"temp",
"=",
"dbPoolingProperties",
".",
"getProperty",
"(",
"aPropName",
",",
"aDefaultValue",
")",
";",
"retValue",
"... | get int value based on the property name from property file
the property file is databasePooling.properties
@param aPropName a property name
@param aDefaultValue a default value for that property, if the property is not there.
@return int value of that property | [
"get",
"int",
"value",
"based",
"on",
"the",
"property",
"name",
"from",
"property",
"file",
"the",
"property",
"file",
"is",
"databasePooling",
".",
"properties"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java#L358-L365 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java | DBConnectionManager.createCleaner | private void createCleaner() {
if (cleanerThread == null) {
int interval = getPropIntValue
(DB_DATASOURCE_CLEAN_INTERNAL_NAME,
DB_DATASOURCE_CLEAN_INTERNAL_DEFAULT_VALUE);
//this runnable
this.datasourceCleaner = new PooledDataSourceCleaner(this, interval);
//submit it to the thread to run
this.cleanerThread = new Thread(datasourceCleaner);
this.cleanerThread.setDaemon(true);
this.cleanerThread.start();
}
} | java | private void createCleaner() {
if (cleanerThread == null) {
int interval = getPropIntValue
(DB_DATASOURCE_CLEAN_INTERNAL_NAME,
DB_DATASOURCE_CLEAN_INTERNAL_DEFAULT_VALUE);
//this runnable
this.datasourceCleaner = new PooledDataSourceCleaner(this, interval);
//submit it to the thread to run
this.cleanerThread = new Thread(datasourceCleaner);
this.cleanerThread.setDaemon(true);
this.cleanerThread.start();
}
} | [
"private",
"void",
"createCleaner",
"(",
")",
"{",
"if",
"(",
"cleanerThread",
"==",
"null",
")",
"{",
"int",
"interval",
"=",
"getPropIntValue",
"(",
"DB_DATASOURCE_CLEAN_INTERNAL_NAME",
",",
"DB_DATASOURCE_CLEAN_INTERNAL_DEFAULT_VALUE",
")",
";",
"//this runnable",
... | create and start a pool cleaner if pooling is enabled. | [
"create",
"and",
"start",
"a",
"pool",
"cleaner",
"if",
"pooling",
"is",
"enabled",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java#L370-L384 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java | DBConnectionManager.createDataSource | protected DataSource createDataSource(DBType aDbType,
String aDbUrl,
String aUsername,
String aPassword,
Hashtable<String, DataSource> aDsTable)
throws SQLException {
DataSource retDatasource;
String totalMaxPoolSizeName;
switch (aDbType) {
case ORACLE:
totalMaxPoolSizeName = ORACLE_MAX_POOL_SIZE_NAME;
break;
case MSSQL:
totalMaxPoolSizeName = MSSQL_MAX_POOL_SIZE_NAME;
break;
case MYSQL:
totalMaxPoolSizeName = MYSQL_MAX_POOL_SIZE_NAME;
break;
case SYBASE:
totalMaxPoolSizeName = SYBASE_MAX_POOL_SIZE_NAME;
break;
case DB2:
totalMaxPoolSizeName = DB2_MAX_POOL_SIZE_NAME;
break;
case NETCOOL:
totalMaxPoolSizeName = NETCOOL_MAX_POOL_SIZE_NAME;
break;
default:
totalMaxPoolSizeName = CUSTOM_MAX_POOL_SIZE_NAME;
break;
}
int totalMaxPoolSize = this.getPropIntValue(totalMaxPoolSizeName,
MAX_TOTAL_POOL_SIZE_DEFAULT_VALUE);
int perUserMaxPoolSize =
this.getPropIntValue(PooledDataSourceProvider.MAX_POOL_SIZE_NAME,
PooledDataSourceProvider.MAX_POOL_SIZE_DEFAULT_VALUE);
int numDs = aDsTable.size();
int actualTotal = perUserMaxPoolSize * numDs;
if (actualTotal >= totalMaxPoolSize) {
throw new TotalMaxPoolSizeExceedException
("Can not create another datasource, the total max pool size exceeded. " +
" Expected total max pool size = " + totalMaxPoolSize +
" Actual total max pool size = " + actualTotal);
}
retDatasource = this.createDataSource(aDbType, aDbUrl, aUsername, aPassword);
return retDatasource;
} | java | protected DataSource createDataSource(DBType aDbType,
String aDbUrl,
String aUsername,
String aPassword,
Hashtable<String, DataSource> aDsTable)
throws SQLException {
DataSource retDatasource;
String totalMaxPoolSizeName;
switch (aDbType) {
case ORACLE:
totalMaxPoolSizeName = ORACLE_MAX_POOL_SIZE_NAME;
break;
case MSSQL:
totalMaxPoolSizeName = MSSQL_MAX_POOL_SIZE_NAME;
break;
case MYSQL:
totalMaxPoolSizeName = MYSQL_MAX_POOL_SIZE_NAME;
break;
case SYBASE:
totalMaxPoolSizeName = SYBASE_MAX_POOL_SIZE_NAME;
break;
case DB2:
totalMaxPoolSizeName = DB2_MAX_POOL_SIZE_NAME;
break;
case NETCOOL:
totalMaxPoolSizeName = NETCOOL_MAX_POOL_SIZE_NAME;
break;
default:
totalMaxPoolSizeName = CUSTOM_MAX_POOL_SIZE_NAME;
break;
}
int totalMaxPoolSize = this.getPropIntValue(totalMaxPoolSizeName,
MAX_TOTAL_POOL_SIZE_DEFAULT_VALUE);
int perUserMaxPoolSize =
this.getPropIntValue(PooledDataSourceProvider.MAX_POOL_SIZE_NAME,
PooledDataSourceProvider.MAX_POOL_SIZE_DEFAULT_VALUE);
int numDs = aDsTable.size();
int actualTotal = perUserMaxPoolSize * numDs;
if (actualTotal >= totalMaxPoolSize) {
throw new TotalMaxPoolSizeExceedException
("Can not create another datasource, the total max pool size exceeded. " +
" Expected total max pool size = " + totalMaxPoolSize +
" Actual total max pool size = " + actualTotal);
}
retDatasource = this.createDataSource(aDbType, aDbUrl, aUsername, aPassword);
return retDatasource;
} | [
"protected",
"DataSource",
"createDataSource",
"(",
"DBType",
"aDbType",
",",
"String",
"aDbUrl",
",",
"String",
"aUsername",
",",
"String",
"aPassword",
",",
"Hashtable",
"<",
"String",
",",
"DataSource",
">",
"aDsTable",
")",
"throws",
"SQLException",
"{",
"Da... | create a new pooled datasource if total max pool size for the dbms is still
ok. total max pool size per user <= total max pool size specified for
specific db type.
for example, max pool size per user = 20, total max pool size for oracle
dbms is 100. only 5 datasource can be opened.
@param aDbType one of the supported db type, for example ORACLE, NETCOOL
@param aDbUrl connection url
@param aUsername username to connect to db
@param aPassword password to connect to db
@param aDsTable is used to check if total max pool size for that dbms exceed
@return a pooled datasource
@throws SQLException | [
"create",
"a",
"new",
"pooled",
"datasource",
"if",
"total",
"max",
"pool",
"size",
"for",
"the",
"dbms",
"is",
"still",
"ok",
".",
"total",
"max",
"pool",
"size",
"per",
"user",
"<",
"=",
"total",
"max",
"pool",
"size",
"specified",
"for",
"specific",
... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/DBConnectionManager.java#L515-L569 | train |
CloudSlang/cs-actions | cs-json/src/main/java/io/cloudslang/content/json/services/JsonService.java | JsonService.retrieveWrappingQuoteTypeOfJsonMemberNames | private char retrieveWrappingQuoteTypeOfJsonMemberNames(String jsonString) {
char quote = '\"'; // the default quote character used to specify json member names and string value according to the json specification
for (char c : jsonString.toCharArray()) {
if (c == '\'' || c == '\"') {
quote = c;
break;
}
}
return quote;
} | java | private char retrieveWrappingQuoteTypeOfJsonMemberNames(String jsonString) {
char quote = '\"'; // the default quote character used to specify json member names and string value according to the json specification
for (char c : jsonString.toCharArray()) {
if (c == '\'' || c == '\"') {
quote = c;
break;
}
}
return quote;
} | [
"private",
"char",
"retrieveWrappingQuoteTypeOfJsonMemberNames",
"(",
"String",
"jsonString",
")",
"{",
"char",
"quote",
"=",
"'",
"'",
";",
"// the default quote character used to specify json member names and string value according to the json specification",
"for",
"(",
"char",... | Returns the quote character used for specifying json member names and String values of json members
@param jsonString the source json from which to extract the wrapping quote
@return either one of the characters ' (single quote)or " (double quote) | [
"Returns",
"the",
"quote",
"character",
"used",
"for",
"specifying",
"json",
"member",
"names",
"and",
"String",
"values",
"of",
"json",
"members"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-json/src/main/java/io/cloudslang/content/json/services/JsonService.java#L88-L97 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/GuestService.java | GuestService.customizeVM | public Map<String, String> customizeVM(HttpInputs httpInputs, VmInputs vmInputs, GuestInputs guestInputs, boolean isWin)
throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler()
.getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
CustomizationSpec customizationSpec = isWin ? new GuestConfigSpecs().getWinCustomizationSpec(guestInputs)
: new GuestConfigSpecs().getLinuxCustomizationSpec(guestInputs);
connectionResources.getVimPortType().checkCustomizationSpec(vmMor, customizationSpec);
ManagedObjectReference task = connectionResources.getVimPortType().customizeVMTask(vmMor, customizationSpec);
return new ResponseHelper(connectionResources, task)
.getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was successfully customized. The taskId is: " +
task.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be customized.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> customizeVM(HttpInputs httpInputs, VmInputs vmInputs, GuestInputs guestInputs, boolean isWin)
throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler()
.getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
CustomizationSpec customizationSpec = isWin ? new GuestConfigSpecs().getWinCustomizationSpec(guestInputs)
: new GuestConfigSpecs().getLinuxCustomizationSpec(guestInputs);
connectionResources.getVimPortType().checkCustomizationSpec(vmMor, customizationSpec);
ManagedObjectReference task = connectionResources.getVimPortType().customizeVMTask(vmMor, customizationSpec);
return new ResponseHelper(connectionResources, task)
.getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was successfully customized. The taskId is: " +
task.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be customized.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"customizeVM",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
",",
"GuestInputs",
"guestInputs",
",",
"boolean",
"isWin",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources"... | Method used to connect to specified data center and customize the windows OS based virtual machine identified
by the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted virtual machine
@param guestInputs Object that has all specific inputs necessary to customize specified virtual machine
@return Map with String as key and value that contains returnCode of the operation, success message with task id
of the execution or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"specified",
"data",
"center",
"and",
"customize",
"the",
"windows",
"OS",
"based",
"virtual",
"machine",
"identified",
"by",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/GuestService.java#L41-L69 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/GuestService.java | GuestService.mountTools | public Map<String, String> mountTools(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler()
.getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
connectionResources.getVimPortType().mountToolsInstaller(vmMor);
return ResponseUtils.getResultsMap(INITIATED_TOOLS_INSTALLER_MOUNT + vmInputs.getVirtualMachineName(),
Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> mountTools(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler()
.getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
connectionResources.getVimPortType().mountToolsInstaller(vmMor);
return ResponseUtils.getResultsMap(INITIATED_TOOLS_INSTALLER_MOUNT + vmInputs.getVirtualMachineName(),
Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"mountTools",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
... | Method used to connect to specified data center and start the Install Tools process on virtual machine identified
by the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted virtual machine
@return Map with String as key and value that contains returnCode of the operation, success message or failure
message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"specified",
"data",
"center",
"and",
"start",
"the",
"Install",
"Tools",
"process",
"on",
"virtual",
"machine",
"identified",
"by",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/GuestService.java#L81-L101 | train |
CloudSlang/cs-actions | cs-postgres/src/main/java/io/cloudslang/content/postgres/services/ConfigService.java | ConfigService.validateAndBuildKeyValuesMap | public static Map<String, Object> validateAndBuildKeyValuesMap(String listenAddresses, String port, String ssl, String sslCaFile, String sslCertFile,
String sslKeyFile, String maxConnections, String sharedBuffers,
String effectiveCacheSize, String autovacuum, String workMem) {
Map<String, Object> keyValues = new HashMap<>();
if (listenAddresses != null && listenAddresses.length() > 0) {
keyValues.put(LISTEN_ADDRESSES, listenAddresses);
}
if (StringUtils.isNumeric(port)) {
keyValues.put(PORT, Integer.parseInt(port));
}
if (StringUtils.isNotEmpty(ssl)) {
keyValues.put(SSL, ssl);
}
if (StringUtils.isNotEmpty(sslCaFile)) {
keyValues.put(SSL_CA_FILE, sslCaFile);
}
if (StringUtils.isNotEmpty(sslCertFile)) {
keyValues.put(SSL_CERT_FILE, sslCertFile);
}
if (StringUtils.isNotEmpty(sslKeyFile)) {
keyValues.put(SSL_KEY_FILE, sslKeyFile);
}
if (StringUtils.isNumeric(maxConnections)) {
keyValues.put(MAX_CONNECTIONS, Integer.parseInt(maxConnections));
}
if (StringUtils.isNotEmpty(sharedBuffers)) {
keyValues.put(SHARED_BUFFERS, sharedBuffers);
}
if (StringUtils.isNotEmpty(effectiveCacheSize)) {
keyValues.put(EFFECTIVE_CACHE_SIZE, effectiveCacheSize);
}
if (StringUtils.isNotEmpty(autovacuum)) {
keyValues.put(AUTOVACUUM, autovacuum);
}
if (StringUtils.isNotEmpty(workMem)) {
keyValues.put(WORK_MEM, workMem);
}
return keyValues;
} | java | public static Map<String, Object> validateAndBuildKeyValuesMap(String listenAddresses, String port, String ssl, String sslCaFile, String sslCertFile,
String sslKeyFile, String maxConnections, String sharedBuffers,
String effectiveCacheSize, String autovacuum, String workMem) {
Map<String, Object> keyValues = new HashMap<>();
if (listenAddresses != null && listenAddresses.length() > 0) {
keyValues.put(LISTEN_ADDRESSES, listenAddresses);
}
if (StringUtils.isNumeric(port)) {
keyValues.put(PORT, Integer.parseInt(port));
}
if (StringUtils.isNotEmpty(ssl)) {
keyValues.put(SSL, ssl);
}
if (StringUtils.isNotEmpty(sslCaFile)) {
keyValues.put(SSL_CA_FILE, sslCaFile);
}
if (StringUtils.isNotEmpty(sslCertFile)) {
keyValues.put(SSL_CERT_FILE, sslCertFile);
}
if (StringUtils.isNotEmpty(sslKeyFile)) {
keyValues.put(SSL_KEY_FILE, sslKeyFile);
}
if (StringUtils.isNumeric(maxConnections)) {
keyValues.put(MAX_CONNECTIONS, Integer.parseInt(maxConnections));
}
if (StringUtils.isNotEmpty(sharedBuffers)) {
keyValues.put(SHARED_BUFFERS, sharedBuffers);
}
if (StringUtils.isNotEmpty(effectiveCacheSize)) {
keyValues.put(EFFECTIVE_CACHE_SIZE, effectiveCacheSize);
}
if (StringUtils.isNotEmpty(autovacuum)) {
keyValues.put(AUTOVACUUM, autovacuum);
}
if (StringUtils.isNotEmpty(workMem)) {
keyValues.put(WORK_MEM, workMem);
}
return keyValues;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"validateAndBuildKeyValuesMap",
"(",
"String",
"listenAddresses",
",",
"String",
"port",
",",
"String",
"ssl",
",",
"String",
"sslCaFile",
",",
"String",
"sslCertFile",
",",
"String",
"sslKeyFile",
",... | Method to validate inputs and consolidate to a map.
@param listenAddresses The list of addresses where the PostgreSQL database listens
@param port The port the PostgreSQL database should listen.
@param ssl Enable SSL connections.
@param sslCaFile Name of the file containing the SSL server certificate authority (CA).
@param sslCertFile Name of the file containing the SSL server certificate.
@param sslKeyFile Name of the file containing the SSL server private key.
@param maxConnections The maximum number of client connections allowed.
@param sharedBuffers Determines how much memory is dedicated to PostgreSQL to use for caching data.
@param effectiveCacheSize Effective cache size.
@param autovacuum Enable/disable autovacuum. The autovacuum process takes care of several maintenance
chores inside your database that you really need.
@param workMem Memory used for sorting and queries. | [
"Method",
"to",
"validate",
"inputs",
"and",
"consolidate",
"to",
"a",
"map",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-postgres/src/main/java/io/cloudslang/content/postgres/services/ConfigService.java#L45-L95 | train |
CloudSlang/cs-actions | cs-postgres/src/main/java/io/cloudslang/content/postgres/services/ConfigService.java | ConfigService.changeProperty | public static void changeProperty(String filename, Map<String, Object> keyValuePairs) throws IOException {
if (keyValuePairs.size() == 0) {
return;
}
final File file = new File(filename);
final File tmpFile = new File(file + ".tmp");
PrintWriter pw = new PrintWriter(tmpFile);
BufferedReader br = new BufferedReader(new FileReader(file));
Set<String> keys = keyValuePairs.keySet();
List<String> inConfig = new ArrayList<>();
for (String line; (line = br.readLine()) != null; ) {
int keyPos = line.indexOf('=');
if (keyPos > -1) {
String key = line.substring(0, keyPos).trim();
if (!key.trim().startsWith("#") && keys.contains(key) && !inConfig.contains(key)) {
// Check if the line has any comments. Split by '#' to funs all tokens.
String[] keyValuePair = line.split("=");
StringBuilder lineBuilder = new StringBuilder();
lineBuilder.append(keyValuePair[0].trim()).append(" = ").append(keyValuePairs.get(key));
line = lineBuilder.toString();
inConfig.add(key);
}
}
pw.println(line);
}
for (String key : keys) {
if (!inConfig.contains(key)) {
StringBuilder lineBuilder = new StringBuilder();
lineBuilder.append(key).append(" = ").append(keyValuePairs.get(key));
pw.println(lineBuilder.toString());
}
}
br.close();
pw.close();
file.delete();
tmpFile.renameTo(file);
} | java | public static void changeProperty(String filename, Map<String, Object> keyValuePairs) throws IOException {
if (keyValuePairs.size() == 0) {
return;
}
final File file = new File(filename);
final File tmpFile = new File(file + ".tmp");
PrintWriter pw = new PrintWriter(tmpFile);
BufferedReader br = new BufferedReader(new FileReader(file));
Set<String> keys = keyValuePairs.keySet();
List<String> inConfig = new ArrayList<>();
for (String line; (line = br.readLine()) != null; ) {
int keyPos = line.indexOf('=');
if (keyPos > -1) {
String key = line.substring(0, keyPos).trim();
if (!key.trim().startsWith("#") && keys.contains(key) && !inConfig.contains(key)) {
// Check if the line has any comments. Split by '#' to funs all tokens.
String[] keyValuePair = line.split("=");
StringBuilder lineBuilder = new StringBuilder();
lineBuilder.append(keyValuePair[0].trim()).append(" = ").append(keyValuePairs.get(key));
line = lineBuilder.toString();
inConfig.add(key);
}
}
pw.println(line);
}
for (String key : keys) {
if (!inConfig.contains(key)) {
StringBuilder lineBuilder = new StringBuilder();
lineBuilder.append(key).append(" = ").append(keyValuePairs.get(key));
pw.println(lineBuilder.toString());
}
}
br.close();
pw.close();
file.delete();
tmpFile.renameTo(file);
} | [
"public",
"static",
"void",
"changeProperty",
"(",
"String",
"filename",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"keyValuePairs",
")",
"throws",
"IOException",
"{",
"if",
"(",
"keyValuePairs",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"return",
... | Method to modify the Postgres config postgresql.conf based on key-value pairs
@param filename The filename of the config to be updated.
@param keyValuePairs A map of key-value pairs. | [
"Method",
"to",
"modify",
"the",
"Postgres",
"config",
"postgresql",
".",
"conf",
"based",
"on",
"key",
"-",
"value",
"pairs"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-postgres/src/main/java/io/cloudslang/content/postgres/services/ConfigService.java#L103-L148 | train |
CloudSlang/cs-actions | cs-postgres/src/main/java/io/cloudslang/content/postgres/services/ConfigService.java | ConfigService.changeProperty | public static void changeProperty(String filename, String[] allowedHosts, String[] allowedUsers) throws IOException {
if ((allowedHosts == null || allowedHosts.length == 0) && (allowedUsers == null || allowedUsers.length == 0)) {
return;
}
final File file = new File(filename);
final File tmpFile = new File(file + ".tmp");
PrintWriter pw = new PrintWriter(tmpFile);
BufferedReader br = new BufferedReader(new FileReader(file));
Object[] allowedArr = new Object[allowedHosts.length * allowedUsers.length];
boolean[] skip = new boolean[allowedArr.length];
int ctr = 0;
for (int i = 0; i < allowedHosts.length; i++) {
for (int j = 0; j < allowedUsers.length; j++) {
allowedArr[ctr++] = new String[]{allowedHosts[i], allowedUsers[j]};
}
}
for (String line; (line = br.readLine()) != null; ) {
if (line.startsWith("host")) {
for (int x = 0; x < allowedArr.length; x++) {
if (!skip[x]) {
String[] allowedItem = (String[]) allowedArr[x];
if (line.contains(allowedItem[0]) && line.contains(allowedItem[1])) {
skip[x] = true;
break;
}
}
}
}
pw.println(line);
}
StringBuilder addUserHostLineBuilder = new StringBuilder();
for (int x = 0; x < allowedArr.length; x++) {
if (!skip[x]) {
String[] allowedItem = (String[]) allowedArr[x];
addUserHostLineBuilder.append("host").append("\t").append("all").append("\t").append(allowedItem[1])
.append("\t").append(allowedItem[0]).append("\t").append("trust").append("\n");
}
}
pw.write(addUserHostLineBuilder.toString());
br.close();
pw.close();
file.delete();
tmpFile.renameTo(file);
} | java | public static void changeProperty(String filename, String[] allowedHosts, String[] allowedUsers) throws IOException {
if ((allowedHosts == null || allowedHosts.length == 0) && (allowedUsers == null || allowedUsers.length == 0)) {
return;
}
final File file = new File(filename);
final File tmpFile = new File(file + ".tmp");
PrintWriter pw = new PrintWriter(tmpFile);
BufferedReader br = new BufferedReader(new FileReader(file));
Object[] allowedArr = new Object[allowedHosts.length * allowedUsers.length];
boolean[] skip = new boolean[allowedArr.length];
int ctr = 0;
for (int i = 0; i < allowedHosts.length; i++) {
for (int j = 0; j < allowedUsers.length; j++) {
allowedArr[ctr++] = new String[]{allowedHosts[i], allowedUsers[j]};
}
}
for (String line; (line = br.readLine()) != null; ) {
if (line.startsWith("host")) {
for (int x = 0; x < allowedArr.length; x++) {
if (!skip[x]) {
String[] allowedItem = (String[]) allowedArr[x];
if (line.contains(allowedItem[0]) && line.contains(allowedItem[1])) {
skip[x] = true;
break;
}
}
}
}
pw.println(line);
}
StringBuilder addUserHostLineBuilder = new StringBuilder();
for (int x = 0; x < allowedArr.length; x++) {
if (!skip[x]) {
String[] allowedItem = (String[]) allowedArr[x];
addUserHostLineBuilder.append("host").append("\t").append("all").append("\t").append(allowedItem[1])
.append("\t").append(allowedItem[0]).append("\t").append("trust").append("\n");
}
}
pw.write(addUserHostLineBuilder.toString());
br.close();
pw.close();
file.delete();
tmpFile.renameTo(file);
} | [
"public",
"static",
"void",
"changeProperty",
"(",
"String",
"filename",
",",
"String",
"[",
"]",
"allowedHosts",
",",
"String",
"[",
"]",
"allowedUsers",
")",
"throws",
"IOException",
"{",
"if",
"(",
"(",
"allowedHosts",
"==",
"null",
"||",
"allowedHosts",
... | Method to modify the Postgres config pg_hba.config
@param filename The filename of the config to be updated.
@param allowedHosts A wildcard or a comma-separated list of hostnames or IPs (IPv4 or IPv6).
@param allowedUsers A comma-separated list of PostgreSQL users. If no value is specified for this input,
all users will have access to the server. | [
"Method",
"to",
"modify",
"the",
"Postgres",
"config",
"pg_hba",
".",
"config"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-postgres/src/main/java/io/cloudslang/content/postgres/services/ConfigService.java#L158-L209 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/actions/ConvertXmlToJson.java | ConvertXmlToJson.execute | @Action(name = "Convert XML to Json",
outputs = {
@Output(NAMESPACES_PREFIXES),
@Output(NAMESPACES_URIS),
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE)
})
public Map<String, String> execute(
@Param(value = XML, required = true) String xml,
@Param(value = TEXT_ELEMENTS_NAME) String textElementsName,
@Param(value = INCLUDE_ROOT) String includeRootElement,
@Param(value = INCLUDE_ATTRIBUTES) String includeAttributes,
@Param(value = PRETTY_PRINT) String prettyPrint,
@Param(value = PARSING_FEATURES) String parsingFeatures) {
try {
includeRootElement = defaultIfEmpty(includeRootElement, TRUE);
includeAttributes = defaultIfEmpty(includeAttributes, TRUE);
prettyPrint = defaultIfEmpty(prettyPrint, TRUE);
ValidateUtils.validateInputs(includeRootElement, includeAttributes, prettyPrint);
final ConvertXmlToJsonInputs inputs = new ConvertXmlToJsonInputs.ConvertXmlToJsonInputsBuilder()
.withXml(xml)
.withTextElementsName(textElementsName)
.withIncludeRootElement(Boolean.parseBoolean(includeRootElement))
.withIncludeAttributes(Boolean.parseBoolean(includeAttributes))
.withPrettyPrint(Boolean.parseBoolean(prettyPrint))
.withParsingFeatures(parsingFeatures)
.build();
final ConvertXmlToJsonService converter = new ConvertXmlToJsonService();
final String json = converter.convertToJsonString(inputs);
final Map<String, String> result = getSuccessResultsMap(json);
result.put(NAMESPACES_PREFIXES, converter.getNamespacesPrefixes());
result.put(NAMESPACES_URIS, converter.getNamespacesUris());
return result;
} catch (Exception e) {
final Map<String, String> result = getFailureResultsMap(e);
result.put(NAMESPACES_PREFIXES, EMPTY);
result.put(NAMESPACES_URIS, EMPTY);
return result;
}
} | java | @Action(name = "Convert XML to Json",
outputs = {
@Output(NAMESPACES_PREFIXES),
@Output(NAMESPACES_URIS),
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE)
})
public Map<String, String> execute(
@Param(value = XML, required = true) String xml,
@Param(value = TEXT_ELEMENTS_NAME) String textElementsName,
@Param(value = INCLUDE_ROOT) String includeRootElement,
@Param(value = INCLUDE_ATTRIBUTES) String includeAttributes,
@Param(value = PRETTY_PRINT) String prettyPrint,
@Param(value = PARSING_FEATURES) String parsingFeatures) {
try {
includeRootElement = defaultIfEmpty(includeRootElement, TRUE);
includeAttributes = defaultIfEmpty(includeAttributes, TRUE);
prettyPrint = defaultIfEmpty(prettyPrint, TRUE);
ValidateUtils.validateInputs(includeRootElement, includeAttributes, prettyPrint);
final ConvertXmlToJsonInputs inputs = new ConvertXmlToJsonInputs.ConvertXmlToJsonInputsBuilder()
.withXml(xml)
.withTextElementsName(textElementsName)
.withIncludeRootElement(Boolean.parseBoolean(includeRootElement))
.withIncludeAttributes(Boolean.parseBoolean(includeAttributes))
.withPrettyPrint(Boolean.parseBoolean(prettyPrint))
.withParsingFeatures(parsingFeatures)
.build();
final ConvertXmlToJsonService converter = new ConvertXmlToJsonService();
final String json = converter.convertToJsonString(inputs);
final Map<String, String> result = getSuccessResultsMap(json);
result.put(NAMESPACES_PREFIXES, converter.getNamespacesPrefixes());
result.put(NAMESPACES_URIS, converter.getNamespacesUris());
return result;
} catch (Exception e) {
final Map<String, String> result = getFailureResultsMap(e);
result.put(NAMESPACES_PREFIXES, EMPTY);
result.put(NAMESPACES_URIS, EMPTY);
return result;
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Convert XML to Json\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"NAMESPACES_PREFIXES",
")",
",",
"@",
"Output",
"(",
"NAMESPACES_URIS",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
... | Converts a XML document to a JSON array or a JSON object.
@param xml - The XML document (in the form of a String)
@param textElementsName - specify custom property name for text elements. This will be used for elements that have attributes and text content.
Default value: '_text'
@param includeRootElement - The flag for including the xml root in the resulted JSON.
Default value: true
Valid values: true, false
@param includeAttributes - The flag for including XML attributes in the resulted JSON
Default value: true
Valid values: true, false
@param prettyPrint - The flag for formatting the resulted XML. The newline character is '\n'
Default value: true
Valid values: true, false
@param parsingFeatures - The list of XML parsing features separated by new line (CRLF). The feature name - value must be separated by empty space. Setting specific features this field could be used to avoid XML security issues like "XML Entity Expansion injection" and "XML External Entity injection". To avoid aforementioned security issues we strongly recommend to set this input to the following values:
http://apache.org/xml/features/disallow-doctype-decl true
http://xml.org/sax/features/external-general-entities false
http://xml.org/sax/features/external-parameter-entities false
When the "http://apache.org/xml/features/disallow-doctype-decl" feature is set to "true" the parser will throw a FATAL ERROR if the incoming document contains a DOCTYPE declaration.
When the "http://xml.org/sax/features/external-general-entities" feature is set to "false" the parser will not include external general entities.
When the "http://xml.org/sax/features/external-parameter-entities" feature is set to "false" the parser will not include external parameter entities or the external DTD subset.
If any of the validations fails, the operation will fail with an error message describing the problem.
Default value:
http://apache.org/xml/features/disallow-doctype-decl true
http://xml.org/sax/features/external-general-entities false
http://xml.org/sax/features/external-parameter-entities false
@return The converted XML document as a JSON array or object | [
"Converts",
"a",
"XML",
"document",
"to",
"a",
"JSON",
"array",
"or",
"a",
"JSON",
"object",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/actions/ConvertXmlToJson.java#L70-L118 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListTrimAction.java | ListTrimAction.trimList | @Action(name = "Trim List",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)})
public Map<String, String> trimList(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter,
@Param(value = PERCENTAGE, required = true) String percentage) {
Map<String, String> result = new HashMap<>();
try {
int intPct;
try {
intPct = Integer.parseInt(percentage);
} catch (NumberFormatException e) {
throw new NumberFormatException(e.getMessage() + PARSING_PERCENT_EXCEPTION_MSG);
}
String value;
try {
value = trimIntList(list, delimiter, intPct);
} catch (Exception e) {
try {
value = trimDoubleList(list, delimiter, intPct);
} catch (Exception f) {
value = trimStringList(list, delimiter, intPct);
}
}
result.put(RESULT_TEXT, value);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, value);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | java | @Action(name = "Trim List",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)})
public Map<String, String> trimList(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter,
@Param(value = PERCENTAGE, required = true) String percentage) {
Map<String, String> result = new HashMap<>();
try {
int intPct;
try {
intPct = Integer.parseInt(percentage);
} catch (NumberFormatException e) {
throw new NumberFormatException(e.getMessage() + PARSING_PERCENT_EXCEPTION_MSG);
}
String value;
try {
value = trimIntList(list, delimiter, intPct);
} catch (Exception e) {
try {
value = trimDoubleList(list, delimiter, intPct);
} catch (Exception f) {
value = trimStringList(list, delimiter, intPct);
}
}
result.put(RESULT_TEXT, value);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, value);
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Trim List\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESULT_TEXT",
")",
",",
"@",
"Output",
"(",
"RESPONSE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
... | This method trims values from a list. The values trimmed are equally distributed from the high and low ends
of the list. The list is sorted before trimming. The number of elements trimmed is dictated by the percentage
that is passed in. If the percentage would indicate an odd number of elements the number trimmed is lowered
by one so that the same number are taken from both ends.
@param list A list of numbers.
@param delimiter The list delimiter.
@param percentage The percentage of elements to trim.
@return The trimmed list separated by the same delimiter. | [
"This",
"method",
"trims",
"values",
"from",
"a",
"list",
".",
"The",
"values",
"trimmed",
"are",
"equally",
"distributed",
"from",
"the",
"high",
"and",
"low",
"ends",
"of",
"the",
"list",
".",
"The",
"list",
"is",
"sorted",
"before",
"trimming",
".",
"... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListTrimAction.java#L60-L103 | train |
CloudSlang/cs-actions | cs-utilities/src/main/java/io/cloudslang/content/utilities/actions/FindTextInPdf.java | FindTextInPdf.execute | @Action(name = "Find Text in PDF",
description = FIND_TEXT_IN_PDF_OPERATION_DESC,
outputs = {
@Output(value = RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = RETURN_RESULT, description = FIND_TEXT_IN_PDF_RETURN_RESULT_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, isOnFail = true, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = TEXT, required = true, description = INITIAL_VALUE_DESC) String text,
@Param(value = IGNORE_CASE, description = IGNORE_CASE_DESC) String ignoreCase,
@Param(value = PATH_TO_FILE, required = true, description = DEFAULT_VALUE_DESC) String pathToFile,
@Param(value = PASSWORD, description = PASSWORD_DESC, encrypted = true) String password) {
try {
final Path path = Paths.get(pathToFile);
final String pdfPassword = defaultIfEmpty(password, EMPTY);
final String pdfContent = PdfParseService.getPdfContent(path, pdfPassword).trim().replace(System.lineSeparator(), EMPTY);
final boolean validIgnoreCase = BooleanUtilities.isValid(ignoreCase);
if (!validIgnoreCase) {
throw new RuntimeException(format("Invalid boolean value for ignoreCase parameter: %s", ignoreCase));
}
return getSuccessResultsMap(PdfParseService.getOccurrences(pdfContent, text, toBoolean(ignoreCase)));
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | java | @Action(name = "Find Text in PDF",
description = FIND_TEXT_IN_PDF_OPERATION_DESC,
outputs = {
@Output(value = RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = RETURN_RESULT, description = FIND_TEXT_IN_PDF_RETURN_RESULT_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, isOnFail = true, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = TEXT, required = true, description = INITIAL_VALUE_DESC) String text,
@Param(value = IGNORE_CASE, description = IGNORE_CASE_DESC) String ignoreCase,
@Param(value = PATH_TO_FILE, required = true, description = DEFAULT_VALUE_DESC) String pathToFile,
@Param(value = PASSWORD, description = PASSWORD_DESC, encrypted = true) String password) {
try {
final Path path = Paths.get(pathToFile);
final String pdfPassword = defaultIfEmpty(password, EMPTY);
final String pdfContent = PdfParseService.getPdfContent(path, pdfPassword).trim().replace(System.lineSeparator(), EMPTY);
final boolean validIgnoreCase = BooleanUtilities.isValid(ignoreCase);
if (!validIgnoreCase) {
throw new RuntimeException(format("Invalid boolean value for ignoreCase parameter: %s", ignoreCase));
}
return getSuccessResultsMap(PdfParseService.getOccurrences(pdfContent, text, toBoolean(ignoreCase)));
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Find Text in PDF\"",
",",
"description",
"=",
"FIND_TEXT_IN_PDF_OPERATION_DESC",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"value",
"=",
"RETURN_CODE",
",",
"description",
"=",
"RETURN_CODE_DESC",
")",
",",
"@",
"Output",
... | This operation checks if a text input is found in a PDF file.
@param text The text to be searched for in the PDF file.
@param ignoreCase Whether to ignore if characters of the text are lowercase or uppercase.
Valid values: "true", "false".
Default Value: "false"
@param pathToFile The full path to the PDF file.
@param password The password for the PDF file.
@return - a map containing the output of the operation. Keys present in the map are:
returnResult - The number of occurrences of the text in the PDF file.
returnCode - the return code of the operation. 0 if the operation goes to success, -1 if the operation goes to failure.
exception - the exception message if the operation fails. | [
"This",
"operation",
"checks",
"if",
"a",
"text",
"input",
"is",
"found",
"in",
"a",
"PDF",
"file",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-utilities/src/main/java/io/cloudslang/content/utilities/actions/FindTextInPdf.java#L72-L102 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListPrependerAction.java | ListPrependerAction.prependElement | @Action(name = "List Prepender",
outputs = {
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> prependElement(@Param(value = LIST, required = true) String list,
@Param(value = ELEMENT, required = true) String element,
@Param(value = DELIMITER) String delimiter) {
Map<String, String> result = new HashMap<>();
try {
StringBuilder sb = new StringBuilder();
sb = StringUtils.isEmpty(list) ? sb.append(element) : sb.append(element).append(delimiter).append(list);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, sb.toString());
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | java | @Action(name = "List Prepender",
outputs = {
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> prependElement(@Param(value = LIST, required = true) String list,
@Param(value = ELEMENT, required = true) String element,
@Param(value = DELIMITER) String delimiter) {
Map<String, String> result = new HashMap<>();
try {
StringBuilder sb = new StringBuilder();
sb = StringUtils.isEmpty(list) ? sb.append(element) : sb.append(element).append(delimiter).append(list);
result.put(RESPONSE, SUCCESS);
result.put(RETURN_RESULT, sb.toString());
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESPONSE, FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List Prepender\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESPONSE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
"}",
",",
"responses",
"=",
"{",
"@",
"R... | This method pre-pends an element to a list of strings.
@param list The list to pre-pend to.
@param element The element to pre-pend to the list.
@param delimiter The list delimiter. Delimiter can be empty string.
@return The new list. | [
"This",
"method",
"pre",
"-",
"pends",
"an",
"element",
"to",
"a",
"list",
"of",
"strings",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListPrependerAction.java#L55-L81 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/actions/AppendChild.java | AppendChild.execute | @Action(name = "Append Child",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(RESULT_XML),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = XML_DOCUMENT, required = true) String xmlDocument,
@Param(value = XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = XPATH_ELEMENT_QUERY, required = true) String xPathQuery,
@Param(value = XML_ELEMENT, required = true) String xmlElement,
@Param(value = SECURE_PROCESSING) String secureProcessing) {
final CommonInputs inputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withXpathQuery(xPathQuery)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withXmlElement(xmlElement)
.build();
return new AppendChildService().execute(inputs, customInputs);
} | java | @Action(name = "Append Child",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(RESULT_XML),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = XML_DOCUMENT, required = true) String xmlDocument,
@Param(value = XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = XPATH_ELEMENT_QUERY, required = true) String xPathQuery,
@Param(value = XML_ELEMENT, required = true) String xmlElement,
@Param(value = SECURE_PROCESSING) String secureProcessing) {
final CommonInputs inputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withXpathQuery(xPathQuery)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withXmlElement(xmlElement)
.build();
return new AppendChildService().execute(inputs, customInputs);
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Append Child\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RESULT_XML",
")",
",",
"@",
"Output",
"(",
"ERROR_MESSAGE",
... | Appends a child to an XML element.
@param xmlDocument XML string to append a child in
@param xmlDocumentSource The source type of the xml document.
Valid values: xmlString, xmlPath
Default value: xmlString
@param xPathQuery XPATH query that results in an element or element list, where child element will be
appended
@param xmlElement child element to append
@param secureProcessing optional - whether to use secure processing
@return map of results containing success or failure text, a result message, and the modified XML | [
"Appends",
"a",
"child",
"to",
"an",
"XML",
"element",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/actions/AppendChild.java#L46-L74 | train |
CloudSlang/cs-actions | cs-ssh/src/main/java/io/cloudslang/content/ssh/utils/CacheUtils.java | CacheUtils.saveSshSessionAndChannel | public static boolean saveSshSessionAndChannel(Session session, Channel channel, GlobalSessionObject<Map<String, SSHConnection>> sessionParam, String sessionId) {
final SSHConnection sshConnection;
if (channel != null) {
sshConnection = new SSHConnection(session, channel);
} else {
sshConnection = new SSHConnection(session);
}
if (sessionParam != null) {
Map<String, SSHConnection> tempMap = sessionParam.get();
if (tempMap == null) {
tempMap = new HashMap<>();
}
tempMap.put(sessionId, sshConnection);
sessionParam.setResource(new SSHSessionResource(tempMap));
return true;
}
return false;
} | java | public static boolean saveSshSessionAndChannel(Session session, Channel channel, GlobalSessionObject<Map<String, SSHConnection>> sessionParam, String sessionId) {
final SSHConnection sshConnection;
if (channel != null) {
sshConnection = new SSHConnection(session, channel);
} else {
sshConnection = new SSHConnection(session);
}
if (sessionParam != null) {
Map<String, SSHConnection> tempMap = sessionParam.get();
if (tempMap == null) {
tempMap = new HashMap<>();
}
tempMap.put(sessionId, sshConnection);
sessionParam.setResource(new SSHSessionResource(tempMap));
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"saveSshSessionAndChannel",
"(",
"Session",
"session",
",",
"Channel",
"channel",
",",
"GlobalSessionObject",
"<",
"Map",
"<",
"String",
",",
"SSHConnection",
">",
">",
"sessionParam",
",",
"String",
"sessionId",
")",
"{",
"final",
... | Save the SSH session and the channel in the cache.
@param session The SSH session.
@param channel The SSH channel.
@param sessionParam The cache: GlobalSessionObject or SessionObject. | [
"Save",
"the",
"SSH",
"session",
"and",
"the",
"channel",
"in",
"the",
"cache",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-ssh/src/main/java/io/cloudslang/content/ssh/utils/CacheUtils.java#L79-L96 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/entities/EncoderDecoder.java | EncoderDecoder.encodeStringInBase64 | public static String encodeStringInBase64(String str, Charset charset) {
return new String(Base64.encodeBase64(str.getBytes(charset)));
} | java | public static String encodeStringInBase64(String str, Charset charset) {
return new String(Base64.encodeBase64(str.getBytes(charset)));
} | [
"public",
"static",
"String",
"encodeStringInBase64",
"(",
"String",
"str",
",",
"Charset",
"charset",
")",
"{",
"return",
"new",
"String",
"(",
"Base64",
".",
"encodeBase64",
"(",
"str",
".",
"getBytes",
"(",
"charset",
")",
")",
")",
";",
"}"
] | Encodes a string to base64.
@param str The string value to encode.
@param charset The encoding charset used to obtain the byte sequence of the string.
@return The encoded byte sequence using the base64 encoding. | [
"Encodes",
"a",
"string",
"to",
"base64",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/entities/EncoderDecoder.java#L36-L38 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java | ClusterComputeResourceService.createVmOverrideConfiguration | private ClusterDasVmConfigInfo createVmOverrideConfiguration(ManagedObjectReference vmMor, String restartPriority) {
ClusterDasVmConfigInfo clusterDasVmConfigInfo = new ClusterDasVmConfigInfo();
clusterDasVmConfigInfo.setKey(vmMor);
clusterDasVmConfigInfo.setDasSettings(createClusterDasVmSettings(restartPriority));
return clusterDasVmConfigInfo;
} | java | private ClusterDasVmConfigInfo createVmOverrideConfiguration(ManagedObjectReference vmMor, String restartPriority) {
ClusterDasVmConfigInfo clusterDasVmConfigInfo = new ClusterDasVmConfigInfo();
clusterDasVmConfigInfo.setKey(vmMor);
clusterDasVmConfigInfo.setDasSettings(createClusterDasVmSettings(restartPriority));
return clusterDasVmConfigInfo;
} | [
"private",
"ClusterDasVmConfigInfo",
"createVmOverrideConfiguration",
"(",
"ManagedObjectReference",
"vmMor",
",",
"String",
"restartPriority",
")",
"{",
"ClusterDasVmConfigInfo",
"clusterDasVmConfigInfo",
"=",
"new",
"ClusterDasVmConfigInfo",
"(",
")",
";",
"clusterDasVmConfig... | Das method adds a vm override to a HA enabled Cluster.
@param vmMor
@param restartPriority
@return | [
"Das",
"method",
"adds",
"a",
"vm",
"override",
"to",
"a",
"HA",
"enabled",
"Cluster",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java#L423-L428 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java | ClusterComputeResourceService.createClusterDasVmSettings | private ClusterDasVmSettings createClusterDasVmSettings(String restartPriority) {
ClusterDasVmSettings clusterDasVmSettings = new ClusterDasVmSettings();
clusterDasVmSettings.setRestartPriority(restartPriority);
return clusterDasVmSettings;
} | java | private ClusterDasVmSettings createClusterDasVmSettings(String restartPriority) {
ClusterDasVmSettings clusterDasVmSettings = new ClusterDasVmSettings();
clusterDasVmSettings.setRestartPriority(restartPriority);
return clusterDasVmSettings;
} | [
"private",
"ClusterDasVmSettings",
"createClusterDasVmSettings",
"(",
"String",
"restartPriority",
")",
"{",
"ClusterDasVmSettings",
"clusterDasVmSettings",
"=",
"new",
"ClusterDasVmSettings",
"(",
")",
";",
"clusterDasVmSettings",
".",
"setRestartPriority",
"(",
"restartPrio... | Das method creates a cluster vm setting.
@param restartPriority
@return | [
"Das",
"method",
"creates",
"a",
"cluster",
"vm",
"setting",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java#L467-L471 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java | ClusterComputeResourceService.getClusterConfiguration | private ClusterConfigInfoEx getClusterConfiguration(ConnectionResources connectionResources, ManagedObjectReference clusterMor,
String clusterName) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
ObjectContent[] objectContents = GetObjectProperties.getObjectProperties(connectionResources, clusterMor, new String[]{ClusterParameter.CONFIGURATION_EX.getValue()});
if (objectContents != null && objectContents.length == 1) {
List<DynamicProperty> dynamicProperties = objectContents[0].getPropSet();
if (dynamicProperties != null && dynamicProperties.size() == 1 && dynamicProperties.get(0).getVal() instanceof ClusterConfigInfoEx) {
return (ClusterConfigInfoEx) dynamicProperties.get(0).getVal();
}
}
throw new RuntimeException(String.format(ANOTHER_FAILURE_MSG, clusterName));
} | java | private ClusterConfigInfoEx getClusterConfiguration(ConnectionResources connectionResources, ManagedObjectReference clusterMor,
String clusterName) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
ObjectContent[] objectContents = GetObjectProperties.getObjectProperties(connectionResources, clusterMor, new String[]{ClusterParameter.CONFIGURATION_EX.getValue()});
if (objectContents != null && objectContents.length == 1) {
List<DynamicProperty> dynamicProperties = objectContents[0].getPropSet();
if (dynamicProperties != null && dynamicProperties.size() == 1 && dynamicProperties.get(0).getVal() instanceof ClusterConfigInfoEx) {
return (ClusterConfigInfoEx) dynamicProperties.get(0).getVal();
}
}
throw new RuntimeException(String.format(ANOTHER_FAILURE_MSG, clusterName));
} | [
"private",
"ClusterConfigInfoEx",
"getClusterConfiguration",
"(",
"ConnectionResources",
"connectionResources",
",",
"ManagedObjectReference",
"clusterMor",
",",
"String",
"clusterName",
")",
"throws",
"RuntimeFaultFaultMsg",
",",
"InvalidPropertyFaultMsg",
"{",
"ObjectContent",
... | Das method gets the current cluster configurations.
@param connectionResources
@param clusterMor
@param clusterName
@return
@throws RuntimeFaultFaultMsg
@throws InvalidPropertyFaultMsg | [
"Das",
"method",
"gets",
"the",
"current",
"cluster",
"configurations",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java#L483-L493 | train |
CloudSlang/cs-actions | cs-postgres/src/main/java/io/cloudslang/content/postgres/actions/UpdatePostgresConfigAction.java | UpdatePostgresConfigAction.execute | @Action(name = "Update Property Value",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(EXCEPTION),
@Output(STDERR)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS,
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 = FILE_PATH, required = true) String installationPath,
@Param(value = LISTEN_ADDRESSES, required = true) String listenAddresses,
@Param(value = PORT) String port,
@Param(value = SSL) String ssl,
@Param(value = SSL_CA_FILE) String sslCaFile,
@Param(value = SSL_CERT_FILE) String sslCertFile,
@Param(value = SSL_KEY_FILE) String sslKeyFile,
@Param(value = MAX_CONNECTIONS) String maxConnections,
@Param(value = SHARED_BUFFERS) String sharedBuffers,
@Param(value = EFFECTIVE_CACHE_SIZE) String effectiveCacheSize,
@Param(value = AUTOVACUUM) String autovacuum,
@Param(value = WORK_MEM) String workMem
) {
try {
Map<String, Object> keyValues = ConfigService.validateAndBuildKeyValuesMap(
listenAddresses, port, ssl, sslCaFile, sslCertFile, sslKeyFile, maxConnections, sharedBuffers, effectiveCacheSize, autovacuum, workMem);
ConfigService.changeProperty(installationPath, keyValues);
return getSuccessResultsMap("Updated postgresql.conf successfully");
} catch (Exception e) {
return getFailureResultsMap("Failed to update postgresql.conf", e);
}
} | java | @Action(name = "Update Property Value",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(EXCEPTION),
@Output(STDERR)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS,
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 = FILE_PATH, required = true) String installationPath,
@Param(value = LISTEN_ADDRESSES, required = true) String listenAddresses,
@Param(value = PORT) String port,
@Param(value = SSL) String ssl,
@Param(value = SSL_CA_FILE) String sslCaFile,
@Param(value = SSL_CERT_FILE) String sslCertFile,
@Param(value = SSL_KEY_FILE) String sslKeyFile,
@Param(value = MAX_CONNECTIONS) String maxConnections,
@Param(value = SHARED_BUFFERS) String sharedBuffers,
@Param(value = EFFECTIVE_CACHE_SIZE) String effectiveCacheSize,
@Param(value = AUTOVACUUM) String autovacuum,
@Param(value = WORK_MEM) String workMem
) {
try {
Map<String, Object> keyValues = ConfigService.validateAndBuildKeyValuesMap(
listenAddresses, port, ssl, sslCaFile, sslCertFile, sslKeyFile, maxConnections, sharedBuffers, effectiveCacheSize, autovacuum, workMem);
ConfigService.changeProperty(installationPath, keyValues);
return getSuccessResultsMap("Updated postgresql.conf successfully");
} catch (Exception e) {
return getFailureResultsMap("Failed to update postgresql.conf", e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Update Property Value\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"EXCEPTION",
")",
",",
"@",
"Output",
"(",
"STDERR",
... | Updates the Postgres config postgresql.conf
@param installationPath The full path to the PostgreSQL configuration file in the local machine to be updated
@param listenAddresses The list of addresses where the PostgreSQL database listens
@param port The port the PostgreSQL database should listen.
@param ssl Enable SSL connections.
@param sslCaFile Name of the file containing the SSL server certificate authority (CA).
@param sslCertFile Name of the file containing the SSL server certificate.
@param sslKeyFile Name of the file containing the SSL server private key.
@param maxConnections The maximum number of client connections allowed.
@param sharedBuffers Determines how much memory is dedicated to PostgreSQL to use for caching data.
@param effectiveCacheSize Effective cache size.
@param autovacuum Enable/disable autovacuum. The autovacuum process takes care of several maintenance
chores inside your database that you really need.
@param workMem Memory used for sorting and queries.
@return A map with strings as keys and strings as values that contains: outcome of the action (or failure message
and the exception if there is one), returnCode of the operation and the ID of the request | [
"Updates",
"the",
"Postgres",
"config",
"postgresql",
".",
"conf"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-postgres/src/main/java/io/cloudslang/content/postgres/actions/UpdatePostgresConfigAction.java#L58-L97 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/connection/helpers/MoRefHandler.java | MoRefHandler.inContainerByType | public Map<String, ManagedObjectReference> inContainerByType(ManagedObjectReference folder,
String morefType,
RetrieveOptions retrieveOptions)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
RetrieveResult results = containerViewByType(folder, morefType, retrieveOptions);
return toMap(results);
} | java | public Map<String, ManagedObjectReference> inContainerByType(ManagedObjectReference folder,
String morefType,
RetrieveOptions retrieveOptions)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
RetrieveResult results = containerViewByType(folder, morefType, retrieveOptions);
return toMap(results);
} | [
"public",
"Map",
"<",
"String",
",",
"ManagedObjectReference",
">",
"inContainerByType",
"(",
"ManagedObjectReference",
"folder",
",",
"String",
"morefType",
",",
"RetrieveOptions",
"retrieveOptions",
")",
"throws",
"InvalidPropertyFaultMsg",
",",
"RuntimeFaultFaultMsg",
... | Returns all the MOREFs of the specified type that are present under the
container
@param folder {@link ManagedObjectReference} of the container to begin the
search from
@param morefType Type of the managed entity that needs to be searched
@return Map of name and MOREF of the managed objects present. If none
exist then empty Map is returned
@throws InvalidPropertyFaultMsg
@throws RuntimeFaultFaultMsg | [
"Returns",
"all",
"the",
"MOREFs",
"of",
"the",
"specified",
"type",
"that",
"are",
"present",
"under",
"the",
"container"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/connection/helpers/MoRefHandler.java#L98-L105 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/connection/helpers/MoRefHandler.java | MoRefHandler.containerViewByType | private RetrieveResult containerViewByType(final ManagedObjectReference container,
final String morefType,
final RetrieveOptions retrieveOptions,
final String... morefProperties
) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
PropertyFilterSpec[] propertyFilterSpecs = propertyFilterSpecs(container, morefType, morefProperties);
return containerViewByType(retrieveOptions, propertyFilterSpecs);
} | java | private RetrieveResult containerViewByType(final ManagedObjectReference container,
final String morefType,
final RetrieveOptions retrieveOptions,
final String... morefProperties
) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
PropertyFilterSpec[] propertyFilterSpecs = propertyFilterSpecs(container, morefType, morefProperties);
return containerViewByType(retrieveOptions, propertyFilterSpecs);
} | [
"private",
"RetrieveResult",
"containerViewByType",
"(",
"final",
"ManagedObjectReference",
"container",
",",
"final",
"String",
"morefType",
",",
"final",
"RetrieveOptions",
"retrieveOptions",
",",
"final",
"String",
"...",
"morefProperties",
")",
"throws",
"RuntimeFault... | Returns the raw RetrieveResult object for the provided container filtered on properties list
@param container - container to look in
@param morefType - type to filter for
@param morefProperties - properties to include
@return com.vmware.vim25.RetrieveResult for this query
@throws RuntimeFaultFaultMsg
@throws InvalidPropertyFaultMsg | [
"Returns",
"the",
"raw",
"RetrieveResult",
"object",
"for",
"the",
"provided",
"container",
"filtered",
"on",
"properties",
"list"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/connection/helpers/MoRefHandler.java#L141-L149 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/connection/helpers/MoRefHandler.java | MoRefHandler.containerViewByType | private RetrieveResult containerViewByType(final ManagedObjectReference container,
final String morefType,
final RetrieveOptions retrieveOptions
) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
return this.containerViewByType(container, morefType, retrieveOptions, ManagedObjectType.NAME.getValue());
} | java | private RetrieveResult containerViewByType(final ManagedObjectReference container,
final String morefType,
final RetrieveOptions retrieveOptions
) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
return this.containerViewByType(container, morefType, retrieveOptions, ManagedObjectType.NAME.getValue());
} | [
"private",
"RetrieveResult",
"containerViewByType",
"(",
"final",
"ManagedObjectReference",
"container",
",",
"final",
"String",
"morefType",
",",
"final",
"RetrieveOptions",
"retrieveOptions",
")",
"throws",
"RuntimeFaultFaultMsg",
",",
"InvalidPropertyFaultMsg",
"{",
"ret... | Initialize the helper object on the current connection at invocation time. Do not initialize on construction
since the connection may not be ready yet. | [
"Initialize",
"the",
"helper",
"object",
"on",
"the",
"current",
"connection",
"at",
"invocation",
"time",
".",
"Do",
"not",
"initialize",
"on",
"construction",
"since",
"the",
"connection",
"may",
"not",
"be",
"ready",
"yet",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/connection/helpers/MoRefHandler.java#L156-L161 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/utils/InputsProcessor.java | InputsProcessor.init | public static void init(SQLInputs sqlInputs) throws Exception {
if (sqlInputs != null) {
sqlInputs.setStrDelim(",");
sqlInputs.setStrColumns("");
sqlInputs.setLRows(new ArrayList<String>());
sqlInputs.setIUpdateCount(0);
sqlInputs.setSqlCommand(null);
sqlInputs.setDbServer(null);
sqlInputs.setDbName(null);
sqlInputs.setDbType(null);
sqlInputs.setUsername(null);
sqlInputs.setPassword(null);
sqlInputs.setAuthenticationType(null);
sqlInputs.setDbUrl(null);
sqlInputs.setDbClass(null);
sqlInputs.setNetcool(false);
sqlInputs.setLRowsFiles(new ArrayList<List<String>>());
sqlInputs.setLRowsNames(new ArrayList<List<String>>());
sqlInputs.setSkip(0L);
sqlInputs.setInstance(null);
sqlInputs.setTimeout(0);
sqlInputs.setKey(null);
sqlInputs.setIgnoreCase(false);
sqlInputs.setResultSetConcurrency(-1000000);
sqlInputs.setResultSetType(-1000000);
sqlInputs.setTrustAllRoots(false);
sqlInputs.setTrustStore("");
} else throw new Exception("Cannot init null Sql inputs!");
} | java | public static void init(SQLInputs sqlInputs) throws Exception {
if (sqlInputs != null) {
sqlInputs.setStrDelim(",");
sqlInputs.setStrColumns("");
sqlInputs.setLRows(new ArrayList<String>());
sqlInputs.setIUpdateCount(0);
sqlInputs.setSqlCommand(null);
sqlInputs.setDbServer(null);
sqlInputs.setDbName(null);
sqlInputs.setDbType(null);
sqlInputs.setUsername(null);
sqlInputs.setPassword(null);
sqlInputs.setAuthenticationType(null);
sqlInputs.setDbUrl(null);
sqlInputs.setDbClass(null);
sqlInputs.setNetcool(false);
sqlInputs.setLRowsFiles(new ArrayList<List<String>>());
sqlInputs.setLRowsNames(new ArrayList<List<String>>());
sqlInputs.setSkip(0L);
sqlInputs.setInstance(null);
sqlInputs.setTimeout(0);
sqlInputs.setKey(null);
sqlInputs.setIgnoreCase(false);
sqlInputs.setResultSetConcurrency(-1000000);
sqlInputs.setResultSetType(-1000000);
sqlInputs.setTrustAllRoots(false);
sqlInputs.setTrustStore("");
} else throw new Exception("Cannot init null Sql inputs!");
} | [
"public",
"static",
"void",
"init",
"(",
"SQLInputs",
"sqlInputs",
")",
"throws",
"Exception",
"{",
"if",
"(",
"sqlInputs",
"!=",
"null",
")",
"{",
"sqlInputs",
".",
"setStrDelim",
"(",
"\",\"",
")",
";",
"sqlInputs",
".",
"setStrColumns",
"(",
"\"\"",
")"... | init all the non-static variables.
@param sqlInputs | [
"init",
"all",
"the",
"non",
"-",
"static",
"variables",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/utils/InputsProcessor.java#L33-L61 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/PooledDataSourceCleaner.java | PooledDataSourceCleaner.run | public void run() {
// todo if (logger.isDebugEnabled()) {
// logger.debug("start running PooledDataSourceCleaner");
// }
state = STATE_CLEANER.RUNNING;
while (state != STATE_CLEANER.SHUTDOWN) {
try {
Thread.sleep(interval * 1000);
} catch (InterruptedException e) {
// todo if (logger.isDebugEnabled()) {
// logger.debug("Get interrupted, shutdown the PooledDataSourceCleaner");
// }
break;//get out if anyone interrupt
}
this.manager.cleanDataSources();
//if no pool at all, going to stop itself
if (this.manager.getDbmsPoolSize() == 0) {
// todo if (logger.isDebugEnabled()) {
// logger.debug("Empty pools, shutdown the PooledDataSourceCleaner");
// }
state = STATE_CLEANER.SHUTDOWN;//stop spinning
break; //get out
}
}
} | java | public void run() {
// todo if (logger.isDebugEnabled()) {
// logger.debug("start running PooledDataSourceCleaner");
// }
state = STATE_CLEANER.RUNNING;
while (state != STATE_CLEANER.SHUTDOWN) {
try {
Thread.sleep(interval * 1000);
} catch (InterruptedException e) {
// todo if (logger.isDebugEnabled()) {
// logger.debug("Get interrupted, shutdown the PooledDataSourceCleaner");
// }
break;//get out if anyone interrupt
}
this.manager.cleanDataSources();
//if no pool at all, going to stop itself
if (this.manager.getDbmsPoolSize() == 0) {
// todo if (logger.isDebugEnabled()) {
// logger.debug("Empty pools, shutdown the PooledDataSourceCleaner");
// }
state = STATE_CLEANER.SHUTDOWN;//stop spinning
break; //get out
}
}
} | [
"public",
"void",
"run",
"(",
")",
"{",
"// todo if (logger.isDebugEnabled()) {",
"// logger.debug(\"start running PooledDataSourceCleaner\");",
"// }",
"state",
"=",
"STATE_CLEANER",
".",
"RUNNING",
";",
"while",
"(",
"state",
"!=",
"STATE_CLEANER",
"... | wake up and clean the pools if the pool has empty connection table. | [
"wake",
"up",
"and",
"clean",
"the",
"pools",
"if",
"the",
"pool",
"has",
"empty",
"connection",
"table",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/PooledDataSourceCleaner.java#L51-L77 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/utils/ListProcessor.java | ListProcessor.arrayElementsAreNull | public static boolean arrayElementsAreNull(String[] uncontainedArray) {
boolean empty = true;
for (Object ob : uncontainedArray) {
if (ob != null) {
empty = false;
break;
}
}
return empty;
} | java | public static boolean arrayElementsAreNull(String[] uncontainedArray) {
boolean empty = true;
for (Object ob : uncontainedArray) {
if (ob != null) {
empty = false;
break;
}
}
return empty;
} | [
"public",
"static",
"boolean",
"arrayElementsAreNull",
"(",
"String",
"[",
"]",
"uncontainedArray",
")",
"{",
"boolean",
"empty",
"=",
"true",
";",
"for",
"(",
"Object",
"ob",
":",
"uncontainedArray",
")",
"{",
"if",
"(",
"ob",
"!=",
"null",
")",
"{",
"e... | This method check if all elements of an array are null.
@param uncontainedArray element in array
@return any element that is found to be empty | [
"This",
"method",
"check",
"if",
"all",
"elements",
"of",
"an",
"array",
"are",
"null",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/utils/ListProcessor.java#L299-L308 | train |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureHelper.java | AwsSignatureHelper.getSignedHeadersString | public String getSignedHeadersString(Map<String, String> headers) {
List<String> sortedList = new ArrayList<>(headers.keySet());
Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER);
StringBuilder signedHeaderString = new StringBuilder();
for (String header : sortedList) {
if (signedHeaderString.length() > START_INDEX) {
signedHeaderString.append(SEMICOLON);
}
signedHeaderString.append(nullToEmpty(header).toLowerCase());
}
return signedHeaderString.toString();
} | java | public String getSignedHeadersString(Map<String, String> headers) {
List<String> sortedList = new ArrayList<>(headers.keySet());
Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER);
StringBuilder signedHeaderString = new StringBuilder();
for (String header : sortedList) {
if (signedHeaderString.length() > START_INDEX) {
signedHeaderString.append(SEMICOLON);
}
signedHeaderString.append(nullToEmpty(header).toLowerCase());
}
return signedHeaderString.toString();
} | [
"public",
"String",
"getSignedHeadersString",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"{",
"List",
"<",
"String",
">",
"sortedList",
"=",
"new",
"ArrayList",
"<>",
"(",
"headers",
".",
"keySet",
"(",
")",
")",
";",
"Collections",
"... | Creates a comma separated list of headers.
@param headers Headers to be signed.
@return Comma separated list of headers to be signed. | [
"Creates",
"a",
"comma",
"separated",
"list",
"of",
"headers",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureHelper.java#L111-L123 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/utils/TripleDES.java | TripleDES.encryptPassword | public static String encryptPassword(@NotNull final String aPlainPass) throws Exception {
byte[] encBytes = encryptString(aPlainPass.getBytes(DEFAULT_CODEPAGE));
return Base64.encodeBase64String(encBytes);
} | java | public static String encryptPassword(@NotNull final String aPlainPass) throws Exception {
byte[] encBytes = encryptString(aPlainPass.getBytes(DEFAULT_CODEPAGE));
return Base64.encodeBase64String(encBytes);
} | [
"public",
"static",
"String",
"encryptPassword",
"(",
"@",
"NotNull",
"final",
"String",
"aPlainPass",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"encBytes",
"=",
"encryptString",
"(",
"aPlainPass",
".",
"getBytes",
"(",
"DEFAULT_CODEPAGE",
")",
")",
"... | encrypt a plain password
@param aPlainPass a password in plain text
@return an encrypted password
@throws Exception | [
"encrypt",
"a",
"plain",
"password"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/utils/TripleDES.java#L45-L48 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/utils/DocumentUtils.java | DocumentUtils.documentToString | public static String documentToString(Document xmlDocument) throws IOException {
String encoding = (xmlDocument.getXmlEncoding() == null) ? "UTF-8" : xmlDocument.getXmlEncoding();
OutputFormat format = new OutputFormat(xmlDocument);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
format.setEncoding(encoding);
try (Writer out = new StringWriter()) {
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(xmlDocument);
return out.toString();
}
} | java | public static String documentToString(Document xmlDocument) throws IOException {
String encoding = (xmlDocument.getXmlEncoding() == null) ? "UTF-8" : xmlDocument.getXmlEncoding();
OutputFormat format = new OutputFormat(xmlDocument);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
format.setEncoding(encoding);
try (Writer out = new StringWriter()) {
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(xmlDocument);
return out.toString();
}
} | [
"public",
"static",
"String",
"documentToString",
"(",
"Document",
"xmlDocument",
")",
"throws",
"IOException",
"{",
"String",
"encoding",
"=",
"(",
"xmlDocument",
".",
"getXmlEncoding",
"(",
")",
"==",
"null",
")",
"?",
"\"UTF-8\"",
":",
"xmlDocument",
".",
"... | Returns a String representation for the XML Document.
@param xmlDocument the XML Document
@return String representation for the XML Document
@throws IOException | [
"Returns",
"a",
"String",
"representation",
"for",
"the",
"XML",
"Document",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/utils/DocumentUtils.java#L38-L50 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/services/ApplyXslTransformationService.java | ApplyXslTransformationService.readSource | private Source readSource(String xmlDocument, String features) throws Exception {
if (xmlDocument.startsWith(Constants.Inputs.HTTP_PREFIX_STRING) || xmlDocument.startsWith(Constants.Inputs.HTTPS_PREFIX_STRING)) {
URL xmlUrl = new URL(xmlDocument);
InputStream xmlStream = xmlUrl.openStream();
XmlUtils.parseXmlInputStream(xmlStream, features);
return new StreamSource(xmlStream);
} else {
if (new File(xmlDocument).exists()) {
XmlUtils.parseXmlFile(xmlDocument, features);
return new StreamSource(new FileInputStream(xmlDocument));
}
XmlUtils.parseXmlString(xmlDocument, features);
return new StreamSource(new StringReader(xmlDocument));
}
} | java | private Source readSource(String xmlDocument, String features) throws Exception {
if (xmlDocument.startsWith(Constants.Inputs.HTTP_PREFIX_STRING) || xmlDocument.startsWith(Constants.Inputs.HTTPS_PREFIX_STRING)) {
URL xmlUrl = new URL(xmlDocument);
InputStream xmlStream = xmlUrl.openStream();
XmlUtils.parseXmlInputStream(xmlStream, features);
return new StreamSource(xmlStream);
} else {
if (new File(xmlDocument).exists()) {
XmlUtils.parseXmlFile(xmlDocument, features);
return new StreamSource(new FileInputStream(xmlDocument));
}
XmlUtils.parseXmlString(xmlDocument, features);
return new StreamSource(new StringReader(xmlDocument));
}
} | [
"private",
"Source",
"readSource",
"(",
"String",
"xmlDocument",
",",
"String",
"features",
")",
"throws",
"Exception",
"{",
"if",
"(",
"xmlDocument",
".",
"startsWith",
"(",
"Constants",
".",
"Inputs",
".",
"HTTP_PREFIX_STRING",
")",
"||",
"xmlDocument",
".",
... | Reads the xml content from a file, URL or string.
@param xmlDocument xml document as String, path or URL
@return the resulting xml after validation
@throws Exception in case something went wrong | [
"Reads",
"the",
"xml",
"content",
"from",
"a",
"file",
"URL",
"or",
"string",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/services/ApplyXslTransformationService.java#L74-L89 | train |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.isDateValid | public static boolean isDateValid(String date, Locale locale) {
try {
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
format.parse(date);
return true;
} catch (ParseException e) {
return false;
}
} | java | public static boolean isDateValid(String date, Locale locale) {
try {
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
format.parse(date);
return true;
} catch (ParseException e) {
return false;
}
} | [
"public",
"static",
"boolean",
"isDateValid",
"(",
"String",
"date",
",",
"Locale",
"locale",
")",
"{",
"try",
"{",
"DateFormat",
"format",
"=",
"DateFormat",
".",
"getDateTimeInstance",
"(",
"DateFormat",
".",
"DEFAULT",
",",
"DateFormat",
".",
"DEFAULT",
","... | Because the date passed as argument can be in java format, and because not all formats are compatible
with joda-time, this method checks if the date string is valid with java. In this way we can use the
proper DateTime without changing the output.
@param date date passed as argument
@return true if is a java date | [
"Because",
"the",
"date",
"passed",
"as",
"argument",
"can",
"be",
"in",
"java",
"format",
"and",
"because",
"not",
"all",
"formats",
"are",
"compatible",
"with",
"joda",
"-",
"time",
"this",
"method",
"checks",
"if",
"the",
"date",
"string",
"is",
"valid"... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L51-L59 | train |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.getLocaleByCountry | public static Locale getLocaleByCountry(String lang, String country) {
return StringUtils.isNotBlank(country) ? new Locale(lang, country) : new Locale(lang);
} | java | public static Locale getLocaleByCountry(String lang, String country) {
return StringUtils.isNotBlank(country) ? new Locale(lang, country) : new Locale(lang);
} | [
"public",
"static",
"Locale",
"getLocaleByCountry",
"(",
"String",
"lang",
",",
"String",
"country",
")",
"{",
"return",
"StringUtils",
".",
"isNotBlank",
"(",
"country",
")",
"?",
"new",
"Locale",
"(",
"lang",
",",
"country",
")",
":",
"new",
"Locale",
"(... | Generates the locale
@param lang the language
@param country the country
@return the locale | [
"Generates",
"the",
"locale"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L68-L70 | train |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.getJodaOrJavaDate | public static DateTime getJodaOrJavaDate(final DateTimeFormatter dateFormatter, final String date) throws Exception {
if (DateTimeUtils.isDateValid(date, dateFormatter.getLocale())) {
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, dateFormatter.getLocale());
Calendar dateCalendar = GregorianCalendar.getInstance();
dateCalendar.setTime(dateFormat.parse(date));
return new DateTime(dateCalendar.getTime());
}
return new DateTime(date);
} | java | public static DateTime getJodaOrJavaDate(final DateTimeFormatter dateFormatter, final String date) throws Exception {
if (DateTimeUtils.isDateValid(date, dateFormatter.getLocale())) {
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, dateFormatter.getLocale());
Calendar dateCalendar = GregorianCalendar.getInstance();
dateCalendar.setTime(dateFormat.parse(date));
return new DateTime(dateCalendar.getTime());
}
return new DateTime(date);
} | [
"public",
"static",
"DateTime",
"getJodaOrJavaDate",
"(",
"final",
"DateTimeFormatter",
"dateFormatter",
",",
"final",
"String",
"date",
")",
"throws",
"Exception",
"{",
"if",
"(",
"DateTimeUtils",
".",
"isDateValid",
"(",
"date",
",",
"dateFormatter",
".",
"getLo... | Returns a LocalDateTime depending on how the date passes as argument is formatted.
@param date date passed as argument
@return the DateTime if it could parse it | [
"Returns",
"a",
"LocalDateTime",
"depending",
"on",
"how",
"the",
"date",
"passes",
"as",
"argument",
"is",
"formatted",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L78-L89 | train |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.getDateFormatter | public static DateTimeFormatter getDateFormatter(String format, String lang, String country) {
if (StringUtils.isNotBlank(format)) {
DateTimeFormatter dateFormat = DateTimeFormat.forPattern(format);
if (StringUtils.isNotBlank(lang)) {
return dateFormat.withLocale(DateTimeUtils.getLocaleByCountry(lang, country));
}
return dateFormat;
}
return formatWithDefault(lang, country);
} | java | public static DateTimeFormatter getDateFormatter(String format, String lang, String country) {
if (StringUtils.isNotBlank(format)) {
DateTimeFormatter dateFormat = DateTimeFormat.forPattern(format);
if (StringUtils.isNotBlank(lang)) {
return dateFormat.withLocale(DateTimeUtils.getLocaleByCountry(lang, country));
}
return dateFormat;
}
return formatWithDefault(lang, country);
} | [
"public",
"static",
"DateTimeFormatter",
"getDateFormatter",
"(",
"String",
"format",
",",
"String",
"lang",
",",
"String",
"country",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"format",
")",
")",
"{",
"DateTimeFormatter",
"dateFormat",
"=",
... | Generates a DateTimeFormatter using a custom pattern with the default locale or a new one
according to what language and country are provided as params.
@param format the pattern
@param lang the language
@param country the country
@return the DateTimeFormatter generated | [
"Generates",
"a",
"DateTimeFormatter",
"using",
"a",
"custom",
"pattern",
"with",
"the",
"default",
"locale",
"or",
"a",
"new",
"one",
"according",
"to",
"what",
"language",
"and",
"country",
"are",
"provided",
"as",
"params",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L101-L110 | train |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.formatWithDefault | public static DateTimeFormatter formatWithDefault(String lang, String country) {
return (StringUtils.isNotBlank(lang)) ? DateTimeFormat.longDateTime().withLocale(DateTimeUtils.getLocaleByCountry(lang, country)) :
DateTimeFormat.longDateTime().withLocale(Locale.getDefault());
} | java | public static DateTimeFormatter formatWithDefault(String lang, String country) {
return (StringUtils.isNotBlank(lang)) ? DateTimeFormat.longDateTime().withLocale(DateTimeUtils.getLocaleByCountry(lang, country)) :
DateTimeFormat.longDateTime().withLocale(Locale.getDefault());
} | [
"public",
"static",
"DateTimeFormatter",
"formatWithDefault",
"(",
"String",
"lang",
",",
"String",
"country",
")",
"{",
"return",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"lang",
")",
")",
"?",
"DateTimeFormat",
".",
"longDateTime",
"(",
")",
".",
"withLoc... | Generates a DateTimeFormatter using full date pattern with the default locale or a new one
according to what language and country are provided as params.
@param lang the language
@param country the country
@return the DateTimeFormatter generated | [
"Generates",
"a",
"DateTimeFormatter",
"using",
"full",
"date",
"pattern",
"with",
"the",
"default",
"locale",
"or",
"a",
"new",
"one",
"according",
"to",
"what",
"language",
"and",
"country",
"are",
"provided",
"as",
"params",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L120-L123 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/SQLQueryTabularService.java | SQLQueryTabularService.execSqlQueryTabular | public static String execSqlQueryTabular(@NotNull final SQLInputs sqlInputs) throws Exception {
ConnectionService connectionService = new ConnectionService();
try (final Connection connection = connectionService.setUpConnection(sqlInputs)){
connection.setReadOnly(true);
final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
statement.setQueryTimeout(sqlInputs.getTimeout());
final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());
final String resultSetToTable = Format.resultSetToTable(resultSet, sqlInputs.isNetcool());
resultSet.close();
return resultSetToTable;
}
} | java | public static String execSqlQueryTabular(@NotNull final SQLInputs sqlInputs) throws Exception {
ConnectionService connectionService = new ConnectionService();
try (final Connection connection = connectionService.setUpConnection(sqlInputs)){
connection.setReadOnly(true);
final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
statement.setQueryTimeout(sqlInputs.getTimeout());
final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());
final String resultSetToTable = Format.resultSetToTable(resultSet, sqlInputs.isNetcool());
resultSet.close();
return resultSetToTable;
}
} | [
"public",
"static",
"String",
"execSqlQueryTabular",
"(",
"@",
"NotNull",
"final",
"SQLInputs",
"sqlInputs",
")",
"throws",
"Exception",
"{",
"ConnectionService",
"connectionService",
"=",
"new",
"ConnectionService",
"(",
")",
";",
"try",
"(",
"final",
"Connection",... | Run a SQL query with given configuration
@return the formatted result set by colDelimiter and rowDelimiter
@throws ClassNotFoundException
@throws java.sql.SQLException | [
"Run",
"a",
"SQL",
"query",
"with",
"given",
"configuration"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/SQLQueryTabularService.java#L40-L54 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/actions/XpathQuery.java | XpathQuery.execute | @Action(name = "XpathQuery",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(SELECTED_VALUE),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = Constants.Inputs.XML_DOCUMENT, required = true) String xmlDocument,
@Param(Constants.Inputs.XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = Constants.Inputs.XPATH_QUERY, required = true) String xPathQuery,
@Param(value = Constants.Inputs.QUERY_TYPE, required = true) String queryType,
@Param(Constants.Inputs.DELIMITER) String delimiter,
@Param(Constants.Inputs.SECURE_PROCESSING) String secureProcessing) {
final CommonInputs commonInputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withXpathQuery(xPathQuery)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withQueryType(queryType)
.withDelimiter(delimiter)
.build();
return new XpathQueryService().execute(commonInputs, customInputs);
} | java | @Action(name = "XpathQuery",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(SELECTED_VALUE),
@Output(ERROR_MESSAGE)},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS, matchType = COMPARE_EQUAL),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE, matchType = COMPARE_EQUAL, isDefault = true, isOnFail = true)})
public Map<String, String> execute(
@Param(value = Constants.Inputs.XML_DOCUMENT, required = true) String xmlDocument,
@Param(Constants.Inputs.XML_DOCUMENT_SOURCE) String xmlDocumentSource,
@Param(value = Constants.Inputs.XPATH_QUERY, required = true) String xPathQuery,
@Param(value = Constants.Inputs.QUERY_TYPE, required = true) String queryType,
@Param(Constants.Inputs.DELIMITER) String delimiter,
@Param(Constants.Inputs.SECURE_PROCESSING) String secureProcessing) {
final CommonInputs commonInputs = new CommonInputs.CommonInputsBuilder()
.withXmlDocument(xmlDocument)
.withXmlDocumentSource(xmlDocumentSource)
.withXpathQuery(xPathQuery)
.withSecureProcessing(secureProcessing)
.build();
final CustomInputs customInputs = new CustomInputs.CustomInputsBuilder()
.withQueryType(queryType)
.withDelimiter(delimiter)
.build();
return new XpathQueryService().execute(commonInputs, customInputs);
} | [
"@",
"Action",
"(",
"name",
"=",
"\"XpathQuery\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"SELECTED_VALUE",
")",
",",
"@",
"Output",
"(",
"ERROR_MESSAGE",
... | Selects from an XML document using an XPATH query.
@param xmlDocument XML string or path to xml file
@param xmlDocumentSource The source type of the xml document.
Valid values: xmlString, xmlPath
Default value: xmlString
@param xPathQuery XPATH query
@param queryType type of selection result from query attribute value
@param delimiter optional - string to use as delimiter in case query_type is nodelist
@param secureProcessing optional - whether to use secure processing
@return map of results containing success or failure text, a result message, and the value selected | [
"Selects",
"from",
"an",
"XML",
"document",
"using",
"an",
"XPATH",
"query",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/actions/XpathQuery.java#L42-L72 | train |
CloudSlang/cs-actions | cs-xml/src/main/java/io/cloudslang/content/xml/actions/ConvertJsonToXml.java | ConvertJsonToXml.execute | @Action(name = "Convert JSON to XML",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE)
})
public Map<String, String> execute(
@Param(value = JSON, required = true) String json,
@Param(value = PRETTY_PRINT) String prettyPrint,
@Param(value = SHOW_XML_DECLARATION) String showXmlDeclaration,
@Param(value = ROOT_TAG_NAME) String rootTagName,
@Param(value = DEFAULT_JSON_ARRAY_ITEM_NAME) String defaultJsonArrayItemName,
@Param(value = NAMESPACES_PREFIXES) String namespacesPrefixes,
@Param(value = NAMESPACES_URIS) String namespacesUris,
@Param(value = JSON_ARRAYS_NAMES) String jsonArraysNames,
@Param(value = JSON_ARRAYS_ITEM_NAMES) String jsonArraysItemNames,
@Param(value = DELIMITER) String delimiter) {
try {
showXmlDeclaration = StringUtils.defaultIfEmpty(showXmlDeclaration, TRUE);
prettyPrint = StringUtils.defaultIfEmpty(prettyPrint, TRUE);
ValidateUtils.validateInputs(prettyPrint, showXmlDeclaration);
final ConvertJsonToXmlInputs inputs = new ConvertJsonToXmlInputs.ConvertJsonToXmlInputsBuilder()
.withJson(json)
.withPrettyPrint(Boolean.parseBoolean(prettyPrint))
.withShowXmlDeclaration(Boolean.parseBoolean(showXmlDeclaration))
.withRootTagName(rootTagName)
.withDefaultJsonArrayItemName(defaultJsonArrayItemName)
.withNamespaces(namespacesUris, namespacesPrefixes, delimiter)
.withJsonArraysNames(jsonArraysNames, jsonArraysItemNames, delimiter)
.build();
final ConvertJsonToXmlService converter = new ConvertJsonToXmlService();
converter.setNamespaces(inputs.getNamespaces());
converter.setJsonArrayItemNames(inputs.getArraysItemNames());
converter.setJsonArrayItemName(inputs.getDefaultJsonArrayItemName());
final String xml = converter.convertToXmlString(inputs);
return getSuccessResultsMap(xml);
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | java | @Action(name = "Convert JSON to XML",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS),
@Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE)
})
public Map<String, String> execute(
@Param(value = JSON, required = true) String json,
@Param(value = PRETTY_PRINT) String prettyPrint,
@Param(value = SHOW_XML_DECLARATION) String showXmlDeclaration,
@Param(value = ROOT_TAG_NAME) String rootTagName,
@Param(value = DEFAULT_JSON_ARRAY_ITEM_NAME) String defaultJsonArrayItemName,
@Param(value = NAMESPACES_PREFIXES) String namespacesPrefixes,
@Param(value = NAMESPACES_URIS) String namespacesUris,
@Param(value = JSON_ARRAYS_NAMES) String jsonArraysNames,
@Param(value = JSON_ARRAYS_ITEM_NAMES) String jsonArraysItemNames,
@Param(value = DELIMITER) String delimiter) {
try {
showXmlDeclaration = StringUtils.defaultIfEmpty(showXmlDeclaration, TRUE);
prettyPrint = StringUtils.defaultIfEmpty(prettyPrint, TRUE);
ValidateUtils.validateInputs(prettyPrint, showXmlDeclaration);
final ConvertJsonToXmlInputs inputs = new ConvertJsonToXmlInputs.ConvertJsonToXmlInputsBuilder()
.withJson(json)
.withPrettyPrint(Boolean.parseBoolean(prettyPrint))
.withShowXmlDeclaration(Boolean.parseBoolean(showXmlDeclaration))
.withRootTagName(rootTagName)
.withDefaultJsonArrayItemName(defaultJsonArrayItemName)
.withNamespaces(namespacesUris, namespacesPrefixes, delimiter)
.withJsonArraysNames(jsonArraysNames, jsonArraysItemNames, delimiter)
.build();
final ConvertJsonToXmlService converter = new ConvertJsonToXmlService();
converter.setNamespaces(inputs.getNamespaces());
converter.setJsonArrayItemNames(inputs.getArraysItemNames());
converter.setJsonArrayItemName(inputs.getDefaultJsonArrayItemName());
final String xml = converter.convertToXmlString(inputs);
return getSuccessResultsMap(xml);
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Convert JSON to XML\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
"}",
",",
"responses",
"=",
"{",
"@",
"Response",
"(",
"text",
"=",
"ResponseName... | Converts a JSON array or a JSON object to a XML document.
@param json - The JSON array or object (in the form of a String).
@param prettyPrint - The flag for formatting the resulted XML. If it is true the result will contain tabs and newline ('\n') chars.
Default value: true
Valid values: true, false
@param showXmlDeclaration - The flag for showing the xml declaration (<?xml version="1.0" encoding="UTF-8" standalone="yes"?>).
If this is true then rootTagName can't be empty.
Default value: false
Valid values: true, false
@param rootTagName - The XML tag name. If this input is empty you will get a list of XML elements.
@param defaultJsonArrayItemName - Default XML tag name for items in a JSON array if there isn't a pair (array name, array item name) defined in jsonArraysNames and jsonArraysItemNames.
Default value: 'item'
@param jsonArraysNames - The list of array names separated by delimiter.
@param jsonArraysItemNames - The coresponding list of array item names separated by delimiter.
@param namespacesPrefixes - The list of tag prefixes separated by delimiter.
@param namespacesUris - The coresponding list of namespaces uris separated by delimiter.
@param delimiter - The list separator
Default value: ','
@return The converted JSON array or object as an XML document | [
"Converts",
"a",
"JSON",
"array",
"or",
"a",
"JSON",
"object",
"to",
"a",
"XML",
"document",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-xml/src/main/java/io/cloudslang/content/xml/actions/ConvertJsonToXml.java#L62-L108 | train |
CloudSlang/cs-actions | cs-postgres/src/main/java/io/cloudslang/content/postgres/actions/UpdatePgHbaConfigAction.java | UpdatePgHbaConfigAction.execute | @Action(name = "Update pg_hba.config",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(EXCEPTION),
@Output(STDERR)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS,
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 = FILE_PATH, required = true) String installationPath,
@Param(value = ALLOWED_HOSTS) String allowedHosts,
@Param(value = ALLOWED_USERS) String allowedUsers
) {
try {
if (allowedHosts == null && allowedUsers == null) {
return getSuccessResultsMap("No changes in pg_hba.conf");
}
if (allowedHosts == null || allowedHosts.trim().length() == 0) {
allowedHosts = "localhost";
}
allowedHosts = allowedHosts.replace("\'", "").trim();
if (allowedUsers == null || allowedUsers.trim().length() == 0) {
allowedUsers = "all";
} else {
allowedUsers = allowedUsers.replace("\'", "").trim();
}
ConfigService.changeProperty(installationPath, allowedHosts.split(";"), allowedUsers.split(";"));
return getSuccessResultsMap("Updated pg_hba.conf successfully");
} catch (Exception e) {
return getFailureResultsMap("Failed to update pg_hba.conf", e);
}
} | java | @Action(name = "Update pg_hba.config",
outputs = {
@Output(RETURN_CODE),
@Output(RETURN_RESULT),
@Output(EXCEPTION),
@Output(STDERR)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS,
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 = FILE_PATH, required = true) String installationPath,
@Param(value = ALLOWED_HOSTS) String allowedHosts,
@Param(value = ALLOWED_USERS) String allowedUsers
) {
try {
if (allowedHosts == null && allowedUsers == null) {
return getSuccessResultsMap("No changes in pg_hba.conf");
}
if (allowedHosts == null || allowedHosts.trim().length() == 0) {
allowedHosts = "localhost";
}
allowedHosts = allowedHosts.replace("\'", "").trim();
if (allowedUsers == null || allowedUsers.trim().length() == 0) {
allowedUsers = "all";
} else {
allowedUsers = allowedUsers.replace("\'", "").trim();
}
ConfigService.changeProperty(installationPath, allowedHosts.split(";"), allowedUsers.split(";"));
return getSuccessResultsMap("Updated pg_hba.conf successfully");
} catch (Exception e) {
return getFailureResultsMap("Failed to update pg_hba.conf", e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Update pg_hba.config\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"EXCEPTION",
")",
",",
"@",
"Output",
"(",
"STDERR",
... | Updates the Postgres config pg_hba.config
@param installationPath The full path to the PostgreSQL configuration file in the local machine to be updated.
@param allowedHosts A wildcard or a comma-separated list of hostnames or IPs (IPv4 or IPv6).
@param allowedUsers A comma-separated list of PostgreSQL users. If no value is specified for this input,
all users will have access to the server.
@return A map with strings as keys and strings as values that contains: outcome of the action (or failure message
and the exception if there is one), returnCode of the operation and the ID of the request | [
"Updates",
"the",
"Postgres",
"config",
"pg_hba",
".",
"config"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-postgres/src/main/java/io/cloudslang/content/postgres/actions/UpdatePgHbaConfigAction.java#L49-L91 | train |
CloudSlang/cs-actions | cs-tesseract/src/main/java/io/cloudslang/content/tesseract/actions/ExtractTextFromImage.java | ExtractTextFromImage.execute | @Action(name = "Extract text from image",
description = EXTRACT_TEXT_FROM_IMAGE_DESC,
outputs = {
@Output(value = RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC),
@Output(value = TEXT_STRING, description = TEXT_STRING_DESC),
@Output(value = TEXT_JSON, description = TEXT_JSON_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, isOnFail = true, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = FILE_PATH, required = true, description = FILE_PATH_DESC) String filePath,
@Param(value = DATA_PATH, required = true, description = DATA_PATH_DESC) String dataPath,
@Param(value = LANGUAGE, required = true, description = LANGUAGE_DESC) String language,
@Param(value = TEXT_BLOCKS, description = TEXT_BLOCKS_DESC) String textBlocks,
@Param(value = DESKEW, description = DESKEW_DESC) String deskew) {
dataPath = defaultIfEmpty(dataPath, EMPTY);
language = defaultIfEmpty(language, ENG);
textBlocks = defaultIfEmpty(textBlocks, FALSE);
deskew = defaultIfEmpty(deskew, FALSE);
final List<String> exceptionMessages = verifyExtractTextInputs(filePath, dataPath, textBlocks, deskew);
if (!exceptionMessages.isEmpty()) {
return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE));
}
try {
final String resultText = extractTextFromImage(filePath, dataPath, language, textBlocks, deskew);
final Map<String, String> result = getSuccessResultsMap(resultText);
if (Boolean.parseBoolean(textBlocks)) {
result.put(TEXT_JSON, resultText);
} else {
result.put(TEXT_STRING, resultText);
}
return result;
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | java | @Action(name = "Extract text from image",
description = EXTRACT_TEXT_FROM_IMAGE_DESC,
outputs = {
@Output(value = RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC),
@Output(value = TEXT_STRING, description = TEXT_STRING_DESC),
@Output(value = TEXT_JSON, description = TEXT_JSON_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, isOnFail = true, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = FILE_PATH, required = true, description = FILE_PATH_DESC) String filePath,
@Param(value = DATA_PATH, required = true, description = DATA_PATH_DESC) String dataPath,
@Param(value = LANGUAGE, required = true, description = LANGUAGE_DESC) String language,
@Param(value = TEXT_BLOCKS, description = TEXT_BLOCKS_DESC) String textBlocks,
@Param(value = DESKEW, description = DESKEW_DESC) String deskew) {
dataPath = defaultIfEmpty(dataPath, EMPTY);
language = defaultIfEmpty(language, ENG);
textBlocks = defaultIfEmpty(textBlocks, FALSE);
deskew = defaultIfEmpty(deskew, FALSE);
final List<String> exceptionMessages = verifyExtractTextInputs(filePath, dataPath, textBlocks, deskew);
if (!exceptionMessages.isEmpty()) {
return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE));
}
try {
final String resultText = extractTextFromImage(filePath, dataPath, language, textBlocks, deskew);
final Map<String, String> result = getSuccessResultsMap(resultText);
if (Boolean.parseBoolean(textBlocks)) {
result.put(TEXT_JSON, resultText);
} else {
result.put(TEXT_STRING, resultText);
}
return result;
} catch (Exception e) {
return getFailureResultsMap(e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Extract text from image\"",
",",
"description",
"=",
"EXTRACT_TEXT_FROM_IMAGE_DESC",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"value",
"=",
"RETURN_CODE",
",",
"description",
"=",
"RETURN_CODE_DESC",
")",
",",
"@",
"Outpu... | This operation extracts the text from a specified file given as input using Tesseract's OCR library.
@param filePath The path of the file to be extracted. The file must be an image. Most of the common image formats
are supported.
Required
@param dataPath The path to the tessdata folder that contains the tesseract config files.
@param language The language that will be used by the OCR engine. This input is taken into consideration only
when specifying the dataPath input as well.
Default value: 'ENG'
@param textBlocks If set to 'true' operation will return a json containing text blocks
extracted from image.
Valid values: false, true
Default value: false
Optional
@param deskew Improve text recognition if an image does not have a normal text orientation(skewed image).
If set to 'true' the image will be rotated to the correct text orientation.
Valid values: false, true
Default value: false
Optional
@return a map containing the output of the operation. Keys present in the map are:
returnResult - This will contain the extracted text.
exception - 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.
textString - The extracted text from image.
textJson - A json containing extracted blocks of text from image.
returnCode - The returnCode of the operation: 0 for success, -1 for failure. | [
"This",
"operation",
"extracts",
"the",
"text",
"from",
"a",
"specified",
"file",
"given",
"as",
"input",
"using",
"Tesseract",
"s",
"OCR",
"library",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-tesseract/src/main/java/io/cloudslang/content/tesseract/actions/ExtractTextFromImage.java#L81-L124 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java | WSManUtils.isUUID | public static boolean isUUID(String string) {
try {
if (string != null) {
UUID.fromString(string);
return true;
} else {
return false;
}
} catch (IllegalArgumentException ex) {
return false;
}
} | java | public static boolean isUUID(String string) {
try {
if (string != null) {
UUID.fromString(string);
return true;
} else {
return false;
}
} catch (IllegalArgumentException ex) {
return false;
}
} | [
"public",
"static",
"boolean",
"isUUID",
"(",
"String",
"string",
")",
"{",
"try",
"{",
"if",
"(",
"string",
"!=",
"null",
")",
"{",
"UUID",
".",
"fromString",
"(",
"string",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
... | Checks if a string is a valid UUID or not.
@param string The UUID value.
@return true if input is a valid UUID or false if input is empty or an invalid UUID format. | [
"Checks",
"if",
"a",
"string",
"is",
"a",
"valid",
"UUID",
"or",
"not",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java#L98-L109 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java | WSManUtils.validateUUID | public static void validateUUID(String uuid, String uuidValueOf) throws RuntimeException {
if (!WSManUtils.isUUID(uuid)) {
throw new RuntimeException("The returned " + uuidValueOf + " is not a valid UUID value! " + uuidValueOf + ": " + uuid);
}
} | java | public static void validateUUID(String uuid, String uuidValueOf) throws RuntimeException {
if (!WSManUtils.isUUID(uuid)) {
throw new RuntimeException("The returned " + uuidValueOf + " is not a valid UUID value! " + uuidValueOf + ": " + uuid);
}
} | [
"public",
"static",
"void",
"validateUUID",
"(",
"String",
"uuid",
",",
"String",
"uuidValueOf",
")",
"throws",
"RuntimeException",
"{",
"if",
"(",
"!",
"WSManUtils",
".",
"isUUID",
"(",
"uuid",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"The ... | Validates a UUID value and throws a specific exception if UUID is invalid.
@param uuid The UUID value to validate.
@param uuidValueOf The property associated to the given UUID value.
@throws RuntimeException | [
"Validates",
"a",
"UUID",
"value",
"and",
"throws",
"a",
"specific",
"exception",
"if",
"UUID",
"is",
"invalid",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java#L118-L122 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java | WSManUtils.verifyScriptExecutionStatus | public static void verifyScriptExecutionStatus(final Map<String, String> resultMap) {
if (ZERO_SCRIPT_EXIT_CODE.equals(resultMap.get(SCRIPT_EXIT_CODE))) {
resultMap.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} else {
resultMap.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
} | java | public static void verifyScriptExecutionStatus(final Map<String, String> resultMap) {
if (ZERO_SCRIPT_EXIT_CODE.equals(resultMap.get(SCRIPT_EXIT_CODE))) {
resultMap.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} else {
resultMap.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
} | [
"public",
"static",
"void",
"verifyScriptExecutionStatus",
"(",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"resultMap",
")",
"{",
"if",
"(",
"ZERO_SCRIPT_EXIT_CODE",
".",
"equals",
"(",
"resultMap",
".",
"get",
"(",
"SCRIPT_EXIT_CODE",
")",
")",
")",
... | Checks the scriptExitCode value of the script execution and fails the operation if exit code is different than zero.
@param resultMap | [
"Checks",
"the",
"scriptExitCode",
"value",
"of",
"the",
"script",
"execution",
"and",
"fails",
"the",
"operation",
"if",
"exit",
"code",
"is",
"different",
"than",
"zero",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java#L162-L168 | train |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/actions/OffsetTimeBy.java | OffsetTimeBy.execute | @Action(name = "Offset Time By",
description = "Changes the time represented by a date by the specified number of seconds",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, 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 = LOCALE_DATE, required = true) String date,
@Param(value = LOCALE_OFFSET, required = true) String offset,
@Param(value = LOCALE_LANG) String localeLang,
@Param(value = LOCALE_COUNTRY) String localeCountry) {
try {
return OutputUtilities.getSuccessResultsMap(DateTimeService.offsetTimeBy(date, offset, localeLang, localeCountry));
} catch (Exception exception) {
return OutputUtilities.getFailureResultsMap(exception);
}
} | java | @Action(name = "Offset Time By",
description = "Changes the time represented by a date by the specified number of seconds",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(EXCEPTION)
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, 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 = LOCALE_DATE, required = true) String date,
@Param(value = LOCALE_OFFSET, required = true) String offset,
@Param(value = LOCALE_LANG) String localeLang,
@Param(value = LOCALE_COUNTRY) String localeCountry) {
try {
return OutputUtilities.getSuccessResultsMap(DateTimeService.offsetTimeBy(date, offset, localeLang, localeCountry));
} catch (Exception exception) {
return OutputUtilities.getFailureResultsMap(exception);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Offset Time By\"",
",",
"description",
"=",
"\"Changes the time represented by a date by the specified number of seconds\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
... | Changes the time represented by a date by the specified number of seconds.
If locale is specified, it will return the date and time string based on the locale.
Otherwise, default locale will be used.
@param date Current time.
@param offset The offset value specified number of seconds.
@param localeLang The locale language for date and time string. If localeLang is 'unix' the
localeCountry input is ignored and the result will be the current UNIX
timestamp. Examples: en, ja, unix.
@param localeCountry The locale country for date and time string. For example, US or JP.
If localeLang is not specified, this input will be ignored. | [
"Changes",
"the",
"time",
"represented",
"by",
"a",
"date",
"by",
"the",
"specified",
"number",
"of",
"seconds",
".",
"If",
"locale",
"is",
"specified",
"it",
"will",
"return",
"the",
"date",
"and",
"time",
"string",
"based",
"on",
"the",
"locale",
".",
... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/actions/OffsetTimeBy.java#L62-L83 | train |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/cloudformation/ListStacksAction.java | ListStacksAction.execute | @Action(name = "List AWS Cloud Formation stacks",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
}
)
public Map<String, String> execute(
@Param(value = IDENTITY, required = true) String identity,
@Param(value = CREDENTIAL, required = true, encrypted = true) String credential,
@Param(value = REGION, required = true) String region,
@Param(value = PROXY_HOST) String proxyHost,
@Param(value = PROXY_PORT) String proxyPort,
@Param(value = PROXY_USERNAME) String proxyUsername,
@Param(value = PROXY_PASSWORD) String proxyPassword,
@Param(value = CONNECT_TIMEOUT) String connectTimeoutMs,
@Param(value = EXECUTION_TIMEOUT) String execTimeoutMs) {
proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT);
connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
execTimeoutMs = defaultIfEmpty(execTimeoutMs, DefaultValues.EXEC_TIMEOUT);
try {
AmazonCloudFormation stackBuilder = CloudFormationClientBuilder.getCloudFormationClient(identity, credential, proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs, region);
StringBuilder listOfStacksResult = new StringBuilder(EMPTY);
// Show all the stacks for this account along with the resources for each stack
for (Stack stack : stackBuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
listOfStacksResult.append(stack.getStackName() + Constants.Miscellaneous.COMMA_DELIMITER);
}
if (listOfStacksResult.length() > 0) {
listOfStacksResult.deleteCharAt(listOfStacksResult.length() - 1); //remove last comma delimiter
}
return OutputUtilities.getSuccessResultsMap(listOfStacksResult.toString());
} catch (Exception e) {
return OutputUtilities.getFailureResultsMap(e);
}
} | java | @Action(name = "List AWS Cloud Formation stacks",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
}
)
public Map<String, String> execute(
@Param(value = IDENTITY, required = true) String identity,
@Param(value = CREDENTIAL, required = true, encrypted = true) String credential,
@Param(value = REGION, required = true) String region,
@Param(value = PROXY_HOST) String proxyHost,
@Param(value = PROXY_PORT) String proxyPort,
@Param(value = PROXY_USERNAME) String proxyUsername,
@Param(value = PROXY_PASSWORD) String proxyPassword,
@Param(value = CONNECT_TIMEOUT) String connectTimeoutMs,
@Param(value = EXECUTION_TIMEOUT) String execTimeoutMs) {
proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT);
connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT);
execTimeoutMs = defaultIfEmpty(execTimeoutMs, DefaultValues.EXEC_TIMEOUT);
try {
AmazonCloudFormation stackBuilder = CloudFormationClientBuilder.getCloudFormationClient(identity, credential, proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs, region);
StringBuilder listOfStacksResult = new StringBuilder(EMPTY);
// Show all the stacks for this account along with the resources for each stack
for (Stack stack : stackBuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
listOfStacksResult.append(stack.getStackName() + Constants.Miscellaneous.COMMA_DELIMITER);
}
if (listOfStacksResult.length() > 0) {
listOfStacksResult.deleteCharAt(listOfStacksResult.length() - 1); //remove last comma delimiter
}
return OutputUtilities.getSuccessResultsMap(listOfStacksResult.toString());
} catch (Exception e) {
return OutputUtilities.getFailureResultsMap(e);
}
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List AWS Cloud Formation stacks\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"Outputs",
".",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"Outputs",
".",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"Outputs",
"."... | List AWS Cloud Formation Stacks
@param identity Access key associated with your Amazon AWS or IAM account.
Example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
@param credential Secret access key ID associated with your Amazon AWS or IAM account.
@param proxyHost Optional - proxy server used to connect to Amazon API. If empty no proxy will be used.
Default: ""
@param proxyPort Optional - proxy server port. You must either specify values for both proxyHost and
proxyPort inputs or leave them both empty.
Default: ""
@param proxyUsername Optional - proxy server user name.
Default: ""
@param proxyPassword Optional - proxy server password associated with the proxyUsername input value.
Default: ""
@param region AWS region name
Example: "eu-central-1"
@return A map with strings as keys and strings as values that contains: outcome of the action, returnCode of the
operation, or failure message and the exception if there is one | [
"List",
"AWS",
"Cloud",
"Formation",
"Stacks"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/cloudformation/ListStacksAction.java#L61-L106 | train |
CloudSlang/cs-actions | cs-lists/src/main/java/io/cloudslang/content/actions/ListSizeAction.java | ListSizeAction.getListSize | @Action(name = "List Size",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = Constants.ResponseNames.SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = Constants.ResponseNames.FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> getListSize(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter) {
Map<String, String> result = new HashMap<>();
try {
String[] table = ListProcessor.toArray(list, delimiter);
result.put(RESULT_TEXT, String.valueOf(table.length));
result.put(RESPONSE, Constants.ResponseNames.SUCCESS);
result.put(RETURN_RESULT, String.valueOf(table.length));
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, Constants.ResponseNames.FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | java | @Action(name = "List Size",
outputs = {
@Output(RESULT_TEXT),
@Output(RESPONSE),
@Output(RETURN_RESULT),
@Output(RETURN_CODE)
},
responses = {
@Response(text = Constants.ResponseNames.SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL),
@Response(text = Constants.ResponseNames.FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, isOnFail = true, isDefault = true)
})
public Map<String, String> getListSize(@Param(value = LIST, required = true) String list,
@Param(value = DELIMITER, required = true) String delimiter) {
Map<String, String> result = new HashMap<>();
try {
String[] table = ListProcessor.toArray(list, delimiter);
result.put(RESULT_TEXT, String.valueOf(table.length));
result.put(RESPONSE, Constants.ResponseNames.SUCCESS);
result.put(RETURN_RESULT, String.valueOf(table.length));
result.put(RETURN_CODE, RETURN_CODE_SUCCESS);
} catch (Exception e) {
result.put(RESULT_TEXT, e.getMessage());
result.put(RESPONSE, Constants.ResponseNames.FAILURE);
result.put(RETURN_RESULT, e.getMessage());
result.put(RETURN_CODE, RETURN_CODE_FAILURE);
}
return result;
} | [
"@",
"Action",
"(",
"name",
"=",
"\"List Size\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"RESULT_TEXT",
")",
",",
"@",
"Output",
"(",
"RESPONSE",
")",
",",
"@",
"Output",
"(",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"RETURN_CODE",
")",
... | This method returns the length of a list of strings.
@param list The list to be processed.
@param delimiter The list delimiter.
@return The length of the list. | [
"This",
"method",
"returns",
"the",
"length",
"of",
"a",
"list",
"of",
"strings",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-lists/src/main/java/io/cloudslang/content/actions/ListSizeAction.java#L53-L80 | train |
CloudSlang/cs-actions | cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/PooledDataSourceProvider.java | PooledDataSourceProvider.getPropStringValue | protected String getPropStringValue(String aPropName, String aDefaultValue) {
return dbPoolingProperties.getProperty(aPropName,
aDefaultValue);
} | java | protected String getPropStringValue(String aPropName, String aDefaultValue) {
return dbPoolingProperties.getProperty(aPropName,
aDefaultValue);
} | [
"protected",
"String",
"getPropStringValue",
"(",
"String",
"aPropName",
",",
"String",
"aDefaultValue",
")",
"{",
"return",
"dbPoolingProperties",
".",
"getProperty",
"(",
"aPropName",
",",
"aDefaultValue",
")",
";",
"}"
] | get string value based on the property name from property file
the property file is databasePooling.properties
@param aPropName a property name
@param aDefaultValue a default value for that property, if the property is not there.
@return string value of that property | [
"get",
"string",
"value",
"based",
"on",
"the",
"property",
"name",
"from",
"property",
"file",
"the",
"property",
"file",
"is",
"databasePooling",
".",
"properties"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-database/src/main/java/io/cloudslang/content/database/services/dbconnection/PooledDataSourceProvider.java#L171-L174 | train |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java | AwsSignatureV4.getStringToSign | public String getStringToSign(String requestDate, String credentialScope, String canonicalRequest) throws SignatureException {
try {
return AWS4_SIGNING_ALGORITHM + LINE_SEPARATOR + requestDate + LINE_SEPARATOR + credentialScope + LINE_SEPARATOR +
new String(Hex.encode(calculateHash(canonicalRequest)), ENCODING);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new SignatureException(CANONICAL_REQUEST_DIGEST_ERROR + e.getMessage());
}
} | java | public String getStringToSign(String requestDate, String credentialScope, String canonicalRequest) throws SignatureException {
try {
return AWS4_SIGNING_ALGORITHM + LINE_SEPARATOR + requestDate + LINE_SEPARATOR + credentialScope + LINE_SEPARATOR +
new String(Hex.encode(calculateHash(canonicalRequest)), ENCODING);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new SignatureException(CANONICAL_REQUEST_DIGEST_ERROR + e.getMessage());
}
} | [
"public",
"String",
"getStringToSign",
"(",
"String",
"requestDate",
",",
"String",
"credentialScope",
",",
"String",
"canonicalRequest",
")",
"throws",
"SignatureException",
"{",
"try",
"{",
"return",
"AWS4_SIGNING_ALGORITHM",
"+",
"LINE_SEPARATOR",
"+",
"requestDate",... | Combines the inputs into a string with a fixed structure and calculates the canonical request digest.
This string can be used with the derived signing key to create an AWS signature.
@param requestDate Request date in YYYYMMDD'T'HHMMSS'Z' format.
@param credentialScope Request credential scope.
@param canonicalRequest Canonical request.
@return A string that includes meta information about the request. | [
"Combines",
"the",
"inputs",
"into",
"a",
"string",
"with",
"a",
"fixed",
"structure",
"and",
"calculates",
"the",
"canonical",
"request",
"digest",
".",
"This",
"string",
"can",
"be",
"used",
"with",
"the",
"derived",
"signing",
"key",
"to",
"create",
"an",... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java#L81-L88 | train |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java | AwsSignatureV4.getDerivedSigningKey | public byte[] getDerivedSigningKey(String secretAccessKey, String dateStamp, String region, String amazonApi)
throws SignatureException {
try {
byte[] kSecret = (AWS_SIGNATURE_VERSION + secretAccessKey).getBytes(ENCODING);
byte[] kDate = calculateHmacSHA256(dateStamp, kSecret);
byte[] kRegion = calculateHmacSHA256(region, kDate);
byte[] kService = calculateHmacSHA256(amazonApi, kRegion);
return calculateHmacSHA256(AWS_REQUEST_VERSION, kService);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
throw new SignatureException(DERIVED_SIGNING_ERROR + e.getMessage());
}
} | java | public byte[] getDerivedSigningKey(String secretAccessKey, String dateStamp, String region, String amazonApi)
throws SignatureException {
try {
byte[] kSecret = (AWS_SIGNATURE_VERSION + secretAccessKey).getBytes(ENCODING);
byte[] kDate = calculateHmacSHA256(dateStamp, kSecret);
byte[] kRegion = calculateHmacSHA256(region, kDate);
byte[] kService = calculateHmacSHA256(amazonApi, kRegion);
return calculateHmacSHA256(AWS_REQUEST_VERSION, kService);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
throw new SignatureException(DERIVED_SIGNING_ERROR + e.getMessage());
}
} | [
"public",
"byte",
"[",
"]",
"getDerivedSigningKey",
"(",
"String",
"secretAccessKey",
",",
"String",
"dateStamp",
",",
"String",
"region",
",",
"String",
"amazonApi",
")",
"throws",
"SignatureException",
"{",
"try",
"{",
"byte",
"[",
"]",
"kSecret",
"=",
"(",
... | Derives a signing key from the AWS secret access key.
@param secretAccessKey Amazon secret a access key.
@param dateStamp Credential scope date stamp in "yyyyMMdd" format.
@param region Amazon region name.
@param amazonApi Amazon service name.
@return Signing key's bytes. This result is not encoded. | [
"Derives",
"a",
"signing",
"key",
"from",
"the",
"AWS",
"secret",
"access",
"key",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java#L99-L111 | train |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java | AwsSignatureV4.calculateHmacSHA256 | private byte[] calculateHmacSHA256(String data, byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return mac.doFinal(data.getBytes(ENCODING));
} | java | private byte[] calculateHmacSHA256(String data, byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return mac.doFinal(data.getBytes(ENCODING));
} | [
"private",
"byte",
"[",
"]",
"calculateHmacSHA256",
"(",
"String",
"data",
",",
"byte",
"[",
"]",
"key",
")",
"throws",
"NoSuchAlgorithmException",
",",
"InvalidKeyException",
",",
"UnsupportedEncodingException",
"{",
"Mac",
"mac",
"=",
"Mac",
".",
"getInstance",
... | Calculates the keyed-hash message authentication code for the data string.
@param data String for which the HMAC will be calculated.
@param key Key used for HMAC calculation.
@return HMAC's bytes. This result is not encoded. | [
"Calculates",
"the",
"keyed",
"-",
"hash",
"message",
"authentication",
"code",
"for",
"the",
"data",
"string",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java#L147-L152 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.getOsDescriptors | public Map<String, String> getOsDescriptors(HttpInputs httpInputs, VmInputs vmInputs, String delimiter) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference environmentBrowserMor = new MorObjectHandler()
.getEnvironmentBrowser(connectionResources, ManagedObjectType.ENVIRONMENT_BROWSER.getValue());
VirtualMachineConfigOption configOptions = connectionResources.getVimPortType()
.queryConfigOption(environmentBrowserMor, null, connectionResources.getHostMor());
List<GuestOsDescriptor> guestOSDescriptors = configOptions.getGuestOSDescriptor();
return ResponseUtils.getResultsMap(ResponseUtils.getResponseStringFromCollection(guestOSDescriptors, delimiter),
Outputs.RETURN_CODE_SUCCESS);
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> getOsDescriptors(HttpInputs httpInputs, VmInputs vmInputs, String delimiter) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference environmentBrowserMor = new MorObjectHandler()
.getEnvironmentBrowser(connectionResources, ManagedObjectType.ENVIRONMENT_BROWSER.getValue());
VirtualMachineConfigOption configOptions = connectionResources.getVimPortType()
.queryConfigOption(environmentBrowserMor, null, connectionResources.getHostMor());
List<GuestOsDescriptor> guestOSDescriptors = configOptions.getGuestOSDescriptor();
return ResponseUtils.getResultsMap(ResponseUtils.getResponseStringFromCollection(guestOSDescriptors, delimiter),
Outputs.RETURN_CODE_SUCCESS);
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getOsDescriptors",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
",",
"String",
"delimiter",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionRe... | Method used to connect to data center to retrieve a list with all the guest operating system descriptors
supported by the host system.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted host system
@param delimiter String that represents the delimiter needed in the result list
@return Map with String as key and value that contains returnCode of the operation, a list that contains all the
guest operating system descriptors supported by the host system or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"data",
"center",
"to",
"retrieve",
"a",
"list",
"with",
"all",
"the",
"guest",
"operating",
"system",
"descriptors",
"supported",
"by",
"the",
"host",
"system",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L52-L72 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.createVM | public Map<String, String> createVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
VmUtils utils = new VmUtils();
ManagedObjectReference vmFolderMor = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
ManagedObjectReference resourcePoolMor = utils.getMorResourcePool(vmInputs.getResourcePool(), connectionResources);
ManagedObjectReference hostMor = utils.getMorHost(vmInputs.getHostname(), connectionResources, null);
VirtualMachineConfigSpec vmConfigSpec = new VmConfigSpecs().getVmConfigSpec(vmInputs, connectionResources);
ManagedObjectReference task = connectionResources.getVimPortType()
.createVMTask(vmFolderMor, vmConfigSpec, resourcePoolMor, hostMor);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: Created [" +
vmInputs.getVirtualMachineName() + "] VM. The taskId is: " + task.getValue(),
"Failure: Could not create [" + vmInputs.getVirtualMachineName() + "] VM");
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> createVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
VmUtils utils = new VmUtils();
ManagedObjectReference vmFolderMor = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
ManagedObjectReference resourcePoolMor = utils.getMorResourcePool(vmInputs.getResourcePool(), connectionResources);
ManagedObjectReference hostMor = utils.getMorHost(vmInputs.getHostname(), connectionResources, null);
VirtualMachineConfigSpec vmConfigSpec = new VmConfigSpecs().getVmConfigSpec(vmInputs, connectionResources);
ManagedObjectReference task = connectionResources.getVimPortType()
.createVMTask(vmFolderMor, vmConfigSpec, resourcePoolMor, hostMor);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: Created [" +
vmInputs.getVirtualMachineName() + "] VM. The taskId is: " + task.getValue(),
"Failure: Could not create [" + vmInputs.getVirtualMachineName() + "] VM");
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"createVM",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
... | Method used to connect to specified data center and create a virtual machine using the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to create a new virtual machine
@return Map with String as key and value that contains returnCode of the operation, success message with task id
of the execution or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"specified",
"data",
"center",
"and",
"create",
"a",
"virtual",
"machine",
"using",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L83-L107 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.deleteVM | public Map<String, String> deleteVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
ManagedObjectReference task = connectionResources.getVimPortType().destroyTask(vmMor);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was deleted. The taskId is: " + task.getValue(),
"Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be deleted.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> deleteVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
ManagedObjectReference task = connectionResources.getVimPortType().destroyTask(vmMor);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was deleted. The taskId is: " + task.getValue(),
"Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be deleted.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"deleteVM",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
... | Method used to connect to specified data center and delete the virtual machine identified by the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted virtual machine
@return Map with String as key and value that contains returnCode of the operation, success message with task id
of the execution or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"specified",
"data",
"center",
"and",
"delete",
"the",
"virtual",
"machine",
"identified",
"by",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L118-L140 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.listVMsAndTemplates | public Map<String, String> listVMsAndTemplates(HttpInputs httpInputs, VmInputs vmInputs, String delimiter) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
Map<String, ManagedObjectReference> virtualMachinesMorMap = new MorObjectHandler()
.getSpecificObjectsMap(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue());
Set<String> virtualMachineNamesList = virtualMachinesMorMap.keySet();
if (virtualMachineNamesList.size() > 0) {
return ResponseUtils.getResultsMap(ResponseUtils
.getResponseStringFromCollection(virtualMachineNamesList, delimiter), Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getResultsMap("No VM found in datacenter.", Outputs.RETURN_CODE_FAILURE);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> listVMsAndTemplates(HttpInputs httpInputs, VmInputs vmInputs, String delimiter) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
Map<String, ManagedObjectReference> virtualMachinesMorMap = new MorObjectHandler()
.getSpecificObjectsMap(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue());
Set<String> virtualMachineNamesList = virtualMachinesMorMap.keySet();
if (virtualMachineNamesList.size() > 0) {
return ResponseUtils.getResultsMap(ResponseUtils
.getResponseStringFromCollection(virtualMachineNamesList, delimiter), Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getResultsMap("No VM found in datacenter.", Outputs.RETURN_CODE_FAILURE);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"listVMsAndTemplates",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
",",
"String",
"delimiter",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"Connectio... | Method used to connect to data center to retrieve a list with all the virtual machines and templates within.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted data center
@param delimiter String that represents the delimiter needed in the result list
@return Map with String as key and value that contains returnCode of the operation, a list that contains all the
virtual machines and templates within the data center or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"data",
"center",
"to",
"retrieve",
"a",
"list",
"with",
"all",
"the",
"virtual",
"machines",
"and",
"templates",
"within",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L218-L239 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.getVMDetails | public Map<String, String> getVMDetails(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
ObjectContent[] objectContents = GetObjectProperties.getObjectProperties(connectionResources, vmMor,
new String[]{ManagedObjectType.SUMMARY.getValue()});
if (objectContents != null) {
Map<String, String> vmDetails = new HashMap<>();
for (ObjectContent objectItem : objectContents) {
List<DynamicProperty> vmProperties = objectItem.getPropSet();
for (DynamicProperty propertyItem : vmProperties) {
VirtualMachineSummary virtualMachineSummary = (VirtualMachineSummary) propertyItem.getVal();
VirtualMachineConfigSummary virtualMachineConfigSummary = virtualMachineSummary.getConfig();
ResponseUtils.addDataToVmDetailsMap(vmDetails, virtualMachineSummary, virtualMachineConfigSummary);
}
}
String responseJson = ResponseUtils.getJsonString(vmDetails);
return ResponseUtils.getResultsMap(responseJson, Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getResultsMap("Could not retrieve the details for: [" +
vmInputs.getVirtualMachineName() + "] VM.", Outputs.RETURN_CODE_FAILURE);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> getVMDetails(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
ObjectContent[] objectContents = GetObjectProperties.getObjectProperties(connectionResources, vmMor,
new String[]{ManagedObjectType.SUMMARY.getValue()});
if (objectContents != null) {
Map<String, String> vmDetails = new HashMap<>();
for (ObjectContent objectItem : objectContents) {
List<DynamicProperty> vmProperties = objectItem.getPropSet();
for (DynamicProperty propertyItem : vmProperties) {
VirtualMachineSummary virtualMachineSummary = (VirtualMachineSummary) propertyItem.getVal();
VirtualMachineConfigSummary virtualMachineConfigSummary = virtualMachineSummary.getConfig();
ResponseUtils.addDataToVmDetailsMap(vmDetails, virtualMachineSummary, virtualMachineConfigSummary);
}
}
String responseJson = ResponseUtils.getJsonString(vmDetails);
return ResponseUtils.getResultsMap(responseJson, Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getResultsMap("Could not retrieve the details for: [" +
vmInputs.getVirtualMachineName() + "] VM.", Outputs.RETURN_CODE_FAILURE);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getVMDetails",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
","... | Method used to connect to data center to retrieve details of a virtual machine identified by the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted virtual machine
@return Map with String as key and value that contains returnCode of the operation, a JSON formatted string that
contains details of the virtual machine or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"data",
"center",
"to",
"retrieve",
"details",
"of",
"a",
"virtual",
"machine",
"identified",
"by",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L250-L283 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.updateVM | public Map<String, String> updateVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
String device = Device.getValue(vmInputs.getDevice()).toLowerCase();
if (Constants.CPU.equalsIgnoreCase(device) || Constants.MEMORY.equalsIgnoreCase(device)) {
vmConfigSpec = new VmUtils().getUpdateConfigSpec(vmInputs, vmConfigSpec, device);
} else {
vmConfigSpec = new VmUtils().getAddOrRemoveSpecs(connectionResources, vmMor, vmInputs, vmConfigSpec, device);
}
ManagedObjectReference task = connectionResources.getVimPortType().reconfigVMTask(vmMor, vmConfigSpec);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was successfully reconfigured. The taskId is: " +
task.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be reconfigured.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> updateVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
String device = Device.getValue(vmInputs.getDevice()).toLowerCase();
if (Constants.CPU.equalsIgnoreCase(device) || Constants.MEMORY.equalsIgnoreCase(device)) {
vmConfigSpec = new VmUtils().getUpdateConfigSpec(vmInputs, vmConfigSpec, device);
} else {
vmConfigSpec = new VmUtils().getAddOrRemoveSpecs(connectionResources, vmMor, vmInputs, vmConfigSpec, device);
}
ManagedObjectReference task = connectionResources.getVimPortType().reconfigVMTask(vmMor, vmConfigSpec);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was successfully reconfigured. The taskId is: " +
task.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be reconfigured.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"updateVM",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
... | Method used to connect to data center to update existing devices of a virtual machine identified by the inputs
provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted device
@return Map with String as key and value that contains returnCode of the operation, success message with task id
of the execution or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"data",
"center",
"to",
"update",
"existing",
"devices",
"of",
"a",
"virtual",
"machine",
"identified",
"by",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L295-L325 | train |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.cloneVM | public Map<String, String> cloneVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
VmUtils utils = new VmUtils();
ManagedObjectReference folder = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
ManagedObjectReference resourcePool = utils.getMorResourcePool(vmInputs.getCloneResourcePool(), connectionResources);
ManagedObjectReference host = utils.getMorHost(vmInputs.getCloneHost(), connectionResources, vmMor);
ManagedObjectReference dataStore = utils.getMorDataStore(vmInputs.getCloneDataStore(), connectionResources,
vmMor, vmInputs);
VirtualMachineRelocateSpec vmRelocateSpec = utils.getVirtualMachineRelocateSpec(resourcePool, host, dataStore, vmInputs);
VirtualMachineCloneSpec cloneSpec = new VmConfigSpecs().getCloneSpec(vmInputs, vmRelocateSpec);
ManagedObjectReference taskMor = connectionResources.getVimPortType()
.cloneVMTask(vmMor, folder, vmInputs.getCloneName(), cloneSpec);
return new ResponseHelper(connectionResources, taskMor).getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was successfully cloned. The taskId is: " +
taskMor.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be cloned.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> cloneVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());
if (vmMor != null) {
VmUtils utils = new VmUtils();
ManagedObjectReference folder = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
ManagedObjectReference resourcePool = utils.getMorResourcePool(vmInputs.getCloneResourcePool(), connectionResources);
ManagedObjectReference host = utils.getMorHost(vmInputs.getCloneHost(), connectionResources, vmMor);
ManagedObjectReference dataStore = utils.getMorDataStore(vmInputs.getCloneDataStore(), connectionResources,
vmMor, vmInputs);
VirtualMachineRelocateSpec vmRelocateSpec = utils.getVirtualMachineRelocateSpec(resourcePool, host, dataStore, vmInputs);
VirtualMachineCloneSpec cloneSpec = new VmConfigSpecs().getCloneSpec(vmInputs, vmRelocateSpec);
ManagedObjectReference taskMor = connectionResources.getVimPortType()
.cloneVMTask(vmMor, folder, vmInputs.getCloneName(), cloneSpec);
return new ResponseHelper(connectionResources, taskMor).getResultsMap("Success: The [" +
vmInputs.getVirtualMachineName() + "] VM was successfully cloned. The taskId is: " +
taskMor.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be cloned.");
} else {
return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"cloneVM",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
"... | Method used to connect to data center and clone a virtual machine identified by the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the virtual machine that will be
cloned
@return Map with String as key and value that contains returnCode of the operation, success message with task id
of the execution or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"data",
"center",
"and",
"clone",
"a",
"virtual",
"machine",
"identified",
"by",
"the",
"inputs",
"provided",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L337-L372 | train |
CloudSlang/cs-actions | cs-json/src/main/java/io/cloudslang/content/json/actions/MergeArrays.java | MergeArrays.execute | @Action(name = "Merge Arrays",
outputs = {
@Output(OutputNames.RETURN_RESULT),
@Output(OutputNames.RETURN_CODE),
@Output(OutputNames.EXCEPTION)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true)
})
public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array1,
@Param(value = Constants.InputNames.ARRAY, required = true) String array2) {
Map<String, String> returnResult = new HashMap<>();
if (StringUtilities.isBlank(array1)) {
final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE.replaceFirst("=", EMPTY_STRING);
return populateResult(returnResult, exceptionValue, new Exception(exceptionValue));
}
if (StringUtilities.isBlank(array2)) {
final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY2_MESSAGE.replaceFirst("=", EMPTY_STRING);
return populateResult(returnResult, new Exception(exceptionValue));
}
JsonNode jsonNode1;
JsonNode jsonNode2;
ObjectMapper mapper = new ObjectMapper();
try {
jsonNode1 = mapper.readTree(array1);
} catch (IOException exception) {
final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1;
return populateResult(returnResult, value, exception);
}
try {
jsonNode2 = mapper.readTree(array2);
} catch (IOException exception) {
final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2;
return populateResult(returnResult, value, exception);
}
final String result;
if (jsonNode1 instanceof ArrayNode && jsonNode2 instanceof ArrayNode) {
final ArrayNode asJsonArray1 = (ArrayNode) jsonNode1;
final ArrayNode asJsonArray2 = (ArrayNode) jsonNode2;
final ArrayNode asJsonArrayResult = new ArrayNode(mapper.getNodeFactory());
asJsonArrayResult.addAll(asJsonArray1);
asJsonArrayResult.addAll(asJsonArray2);
result = asJsonArrayResult.toString();
} else {
result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2;
return populateResult(returnResult, new Exception(result));
}
return populateResult(returnResult, result, null);
} | java | @Action(name = "Merge Arrays",
outputs = {
@Output(OutputNames.RETURN_RESULT),
@Output(OutputNames.RETURN_CODE),
@Output(OutputNames.EXCEPTION)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true)
})
public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array1,
@Param(value = Constants.InputNames.ARRAY, required = true) String array2) {
Map<String, String> returnResult = new HashMap<>();
if (StringUtilities.isBlank(array1)) {
final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE.replaceFirst("=", EMPTY_STRING);
return populateResult(returnResult, exceptionValue, new Exception(exceptionValue));
}
if (StringUtilities.isBlank(array2)) {
final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY2_MESSAGE.replaceFirst("=", EMPTY_STRING);
return populateResult(returnResult, new Exception(exceptionValue));
}
JsonNode jsonNode1;
JsonNode jsonNode2;
ObjectMapper mapper = new ObjectMapper();
try {
jsonNode1 = mapper.readTree(array1);
} catch (IOException exception) {
final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1;
return populateResult(returnResult, value, exception);
}
try {
jsonNode2 = mapper.readTree(array2);
} catch (IOException exception) {
final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2;
return populateResult(returnResult, value, exception);
}
final String result;
if (jsonNode1 instanceof ArrayNode && jsonNode2 instanceof ArrayNode) {
final ArrayNode asJsonArray1 = (ArrayNode) jsonNode1;
final ArrayNode asJsonArray2 = (ArrayNode) jsonNode2;
final ArrayNode asJsonArrayResult = new ArrayNode(mapper.getNodeFactory());
asJsonArrayResult.addAll(asJsonArray1);
asJsonArrayResult.addAll(asJsonArray2);
result = asJsonArrayResult.toString();
} else {
result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2;
return populateResult(returnResult, new Exception(result));
}
return populateResult(returnResult, result, null);
} | [
"@",
"Action",
"(",
"name",
"=",
"\"Merge Arrays\"",
",",
"outputs",
"=",
"{",
"@",
"Output",
"(",
"OutputNames",
".",
"RETURN_RESULT",
")",
",",
"@",
"Output",
"(",
"OutputNames",
".",
"RETURN_CODE",
")",
",",
"@",
"Output",
"(",
"OutputNames",
".",
"EX... | This operation merge the contents of two JSON arrays. This operation does not modify either of the input arrays.
The result is the contents or array1 and array2, merged into a single array. The merge operation add into the result
the first array and then the second array.
@param array1 The string representation of a JSON array object.
Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ].
Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"]
@param array2 The string representation of a JSON array object.
Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ].
Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"]
@return a map containing the output of the operation. Keys present in the map are:
<p/>
<br><br><b>returnResult</b> - This will contain the string representation of the new JSON array with the contents
of array1 and array2.
<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><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure. | [
"This",
"operation",
"merge",
"the",
"contents",
"of",
"two",
"JSON",
"arrays",
".",
"This",
"operation",
"does",
"not",
"modify",
"either",
"of",
"the",
"input",
"arrays",
".",
"The",
"result",
"is",
"the",
"contents",
"or",
"array1",
"and",
"array2",
"me... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-json/src/main/java/io/cloudslang/content/json/actions/MergeArrays.java#L72-L126 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.runCommand | public Map<String, String> runCommand(WSManRequestInputs wsManRequestInputs) throws RuntimeException, IOException, InterruptedException, ParserConfigurationException, TransformerException, XPathExpressionException, TimeoutException, URISyntaxException, SAXException {
HttpClientService csHttpClient = new HttpClientService();
HttpClientInputs httpClientInputs = new HttpClientInputs();
URL url = buildURL(wsManRequestInputs, WSMAN_RESOURCE_URI);
httpClientInputs = setCommonHttpInputs(httpClientInputs, url, wsManRequestInputs);
String shellId = createShell(csHttpClient, httpClientInputs, wsManRequestInputs);
WSManUtils.validateUUID(shellId, SHELL_ID);
String commandStr = WSManUtils.constructCommand(wsManRequestInputs);
String commandId = executeCommand(csHttpClient, httpClientInputs, shellId, wsManRequestInputs, commandStr);
WSManUtils.validateUUID(commandId, COMMAND_ID);
Map<String, String> scriptResults = receiveCommandResult(csHttpClient, httpClientInputs, shellId, commandId, wsManRequestInputs);
deleteShell(csHttpClient, httpClientInputs, shellId, wsManRequestInputs);
return scriptResults;
} | java | public Map<String, String> runCommand(WSManRequestInputs wsManRequestInputs) throws RuntimeException, IOException, InterruptedException, ParserConfigurationException, TransformerException, XPathExpressionException, TimeoutException, URISyntaxException, SAXException {
HttpClientService csHttpClient = new HttpClientService();
HttpClientInputs httpClientInputs = new HttpClientInputs();
URL url = buildURL(wsManRequestInputs, WSMAN_RESOURCE_URI);
httpClientInputs = setCommonHttpInputs(httpClientInputs, url, wsManRequestInputs);
String shellId = createShell(csHttpClient, httpClientInputs, wsManRequestInputs);
WSManUtils.validateUUID(shellId, SHELL_ID);
String commandStr = WSManUtils.constructCommand(wsManRequestInputs);
String commandId = executeCommand(csHttpClient, httpClientInputs, shellId, wsManRequestInputs, commandStr);
WSManUtils.validateUUID(commandId, COMMAND_ID);
Map<String, String> scriptResults = receiveCommandResult(csHttpClient, httpClientInputs, shellId, commandId, wsManRequestInputs);
deleteShell(csHttpClient, httpClientInputs, shellId, wsManRequestInputs);
return scriptResults;
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"runCommand",
"(",
"WSManRequestInputs",
"wsManRequestInputs",
")",
"throws",
"RuntimeException",
",",
"IOException",
",",
"InterruptedException",
",",
"ParserConfigurationException",
",",
"TransformerException",
",",
... | Executes a command on a remote shell by communicating with the WinRM server from the remote host.
Method creates a shell, runs a command on the shell, waits for the command execution to finnish, retrieves the result then deletes the shell.
@param wsManRequestInputs
@return a map with the result of the command and the exit code of the command execution.
@throws RuntimeException
@throws IOException
@throws InterruptedException
@throws ParserConfigurationException
@throws TransformerException
@throws XPathExpressionException
@throws TimeoutException
@throws URISyntaxException
@throws SAXException | [
"Executes",
"a",
"command",
"on",
"a",
"remote",
"shell",
"by",
"communicating",
"with",
"the",
"WinRM",
"server",
"from",
"the",
"remote",
"host",
".",
"Method",
"creates",
"a",
"shell",
"runs",
"a",
"command",
"on",
"the",
"shell",
"waits",
"for",
"the",... | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L107-L120 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.setCommonHttpInputs | private static HttpClientInputs setCommonHttpInputs(HttpClientInputs httpClientInputs, URL url, WSManRequestInputs wsManRequestInputs) throws MalformedURLException {
httpClientInputs.setUrl(url.toString());
httpClientInputs.setUsername(wsManRequestInputs.getUsername());
httpClientInputs.setPassword(wsManRequestInputs.getPassword());
httpClientInputs.setAuthType(wsManRequestInputs.getAuthType());
httpClientInputs.setKerberosConfFile(wsManRequestInputs.getKerberosConfFile());
httpClientInputs.setKerberosLoginConfFile(wsManRequestInputs.getKerberosLoginConfFile());
httpClientInputs.setKerberosSkipPortCheck(wsManRequestInputs.getKerberosSkipPortForLookup());
httpClientInputs.setTrustAllRoots(wsManRequestInputs.getTrustAllRoots());
httpClientInputs.setX509HostnameVerifier(wsManRequestInputs.getX509HostnameVerifier());
httpClientInputs.setProxyHost(wsManRequestInputs.getProxyHost());
httpClientInputs.setProxyPort(wsManRequestInputs.getProxyPort());
httpClientInputs.setProxyUsername(wsManRequestInputs.getProxyUsername());
httpClientInputs.setProxyPassword(wsManRequestInputs.getProxyPassword());
httpClientInputs.setKeystore(wsManRequestInputs.getKeystore());
httpClientInputs.setKeystorePassword(wsManRequestInputs.getKeystorePassword());
httpClientInputs.setTrustKeystore(wsManRequestInputs.getTrustKeystore());
httpClientInputs.setTrustPassword(wsManRequestInputs.getTrustPassword());
String headers = httpClientInputs.getHeaders();
if (StringUtils.isEmpty(headers)) {
httpClientInputs.setHeaders(CONTENT_TYPE_HEADER);
} else {
httpClientInputs.setHeaders(headers + NEW_LINE_SEPARATOR + CONTENT_TYPE_HEADER);
}
httpClientInputs.setMethod(HttpPost.METHOD_NAME);
return httpClientInputs;
} | java | private static HttpClientInputs setCommonHttpInputs(HttpClientInputs httpClientInputs, URL url, WSManRequestInputs wsManRequestInputs) throws MalformedURLException {
httpClientInputs.setUrl(url.toString());
httpClientInputs.setUsername(wsManRequestInputs.getUsername());
httpClientInputs.setPassword(wsManRequestInputs.getPassword());
httpClientInputs.setAuthType(wsManRequestInputs.getAuthType());
httpClientInputs.setKerberosConfFile(wsManRequestInputs.getKerberosConfFile());
httpClientInputs.setKerberosLoginConfFile(wsManRequestInputs.getKerberosLoginConfFile());
httpClientInputs.setKerberosSkipPortCheck(wsManRequestInputs.getKerberosSkipPortForLookup());
httpClientInputs.setTrustAllRoots(wsManRequestInputs.getTrustAllRoots());
httpClientInputs.setX509HostnameVerifier(wsManRequestInputs.getX509HostnameVerifier());
httpClientInputs.setProxyHost(wsManRequestInputs.getProxyHost());
httpClientInputs.setProxyPort(wsManRequestInputs.getProxyPort());
httpClientInputs.setProxyUsername(wsManRequestInputs.getProxyUsername());
httpClientInputs.setProxyPassword(wsManRequestInputs.getProxyPassword());
httpClientInputs.setKeystore(wsManRequestInputs.getKeystore());
httpClientInputs.setKeystorePassword(wsManRequestInputs.getKeystorePassword());
httpClientInputs.setTrustKeystore(wsManRequestInputs.getTrustKeystore());
httpClientInputs.setTrustPassword(wsManRequestInputs.getTrustPassword());
String headers = httpClientInputs.getHeaders();
if (StringUtils.isEmpty(headers)) {
httpClientInputs.setHeaders(CONTENT_TYPE_HEADER);
} else {
httpClientInputs.setHeaders(headers + NEW_LINE_SEPARATOR + CONTENT_TYPE_HEADER);
}
httpClientInputs.setMethod(HttpPost.METHOD_NAME);
return httpClientInputs;
} | [
"private",
"static",
"HttpClientInputs",
"setCommonHttpInputs",
"(",
"HttpClientInputs",
"httpClientInputs",
",",
"URL",
"url",
",",
"WSManRequestInputs",
"wsManRequestInputs",
")",
"throws",
"MalformedURLException",
"{",
"httpClientInputs",
".",
"setUrl",
"(",
"url",
"."... | Configures the HttpClientInputs object with the most common http parameters.
@param httpClientInputs
@param url
@param wsManRequestInputs
@return the configured HttpClientInputs object.
@throws MalformedURLException | [
"Configures",
"the",
"HttpClientInputs",
"object",
"with",
"the",
"most",
"common",
"http",
"parameters",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L131-L157 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.executeRequestWithBody | private Map<String, String> executeRequestWithBody(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String body) {
httpClientInputs.setBody(body);
Map<String, String> requestResponse = csHttpClient.execute(httpClientInputs);
if (UNAUTHORIZED_STATUS_CODE.equals(requestResponse.get(STATUS_CODE))) {
throw new RuntimeException(UNAUTHORIZED_EXCEPTION_MESSAGE);
}
return requestResponse;
} | java | private Map<String, String> executeRequestWithBody(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String body) {
httpClientInputs.setBody(body);
Map<String, String> requestResponse = csHttpClient.execute(httpClientInputs);
if (UNAUTHORIZED_STATUS_CODE.equals(requestResponse.get(STATUS_CODE))) {
throw new RuntimeException(UNAUTHORIZED_EXCEPTION_MESSAGE);
}
return requestResponse;
} | [
"private",
"Map",
"<",
"String",
",",
"String",
">",
"executeRequestWithBody",
"(",
"HttpClientService",
"csHttpClient",
",",
"HttpClientInputs",
"httpClientInputs",
",",
"String",
"body",
")",
"{",
"httpClientInputs",
".",
"setBody",
"(",
"body",
")",
";",
"Map",... | This method executes a request with the given CSHttpClient, HttpClientInputs and body.
@param csHttpClient
@param httpClientInputs
@param body
@return the result of the request execution. | [
"This",
"method",
"executes",
"a",
"request",
"with",
"the",
"given",
"CSHttpClient",
"HttpClientInputs",
"and",
"body",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L167-L174 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.createShell | private String createShell(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, WSManRequestInputs wsManRequestInputs)
throws RuntimeException, IOException, URISyntaxException,
XPathExpressionException, SAXException, ParserConfigurationException {
String document = ResourceLoader.loadAsString(CREATE_SHELL_REQUEST_XML);
document = createCreateShellRequestBody(document, httpClientInputs.getUrl(), String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()),
wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
Map<String, String> createShellResult = executeRequestWithBody(csHttpClient, httpClientInputs, document);
return getResourceId(createShellResult.get(RETURN_RESULT), CREATE_RESPONSE_ACTION, CREATE_RESPONSE_SHELL_ID_XPATH,
SHELL_ID_NOT_RETRIEVED);
} | java | private String createShell(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, WSManRequestInputs wsManRequestInputs)
throws RuntimeException, IOException, URISyntaxException,
XPathExpressionException, SAXException, ParserConfigurationException {
String document = ResourceLoader.loadAsString(CREATE_SHELL_REQUEST_XML);
document = createCreateShellRequestBody(document, httpClientInputs.getUrl(), String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()),
wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
Map<String, String> createShellResult = executeRequestWithBody(csHttpClient, httpClientInputs, document);
return getResourceId(createShellResult.get(RETURN_RESULT), CREATE_RESPONSE_ACTION, CREATE_RESPONSE_SHELL_ID_XPATH,
SHELL_ID_NOT_RETRIEVED);
} | [
"private",
"String",
"createShell",
"(",
"HttpClientService",
"csHttpClient",
",",
"HttpClientInputs",
"httpClientInputs",
",",
"WSManRequestInputs",
"wsManRequestInputs",
")",
"throws",
"RuntimeException",
",",
"IOException",
",",
"URISyntaxException",
",",
"XPathExpressionE... | Creates a shell on the remote server and returns the shell id.
@param csHttpClient
@param httpClientInputs
@param wsManRequestInputs
@return the id of the created shell.
@throws RuntimeException
@throws IOException
@throws URISyntaxException
@throws TransformerException
@throws XPathExpressionException
@throws SAXException
@throws ParserConfigurationException | [
"Creates",
"a",
"shell",
"on",
"the",
"remote",
"server",
"and",
"returns",
"the",
"shell",
"id",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L191-L200 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.executeCommand | private String executeCommand(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String shellId,
WSManRequestInputs wsManRequestInputs, String command) throws RuntimeException,
IOException, URISyntaxException, TransformerException, XPathExpressionException, SAXException, ParserConfigurationException {
String documentStr = ResourceLoader.loadAsString(EXECUTE_COMMAND_REQUEST_XML);
documentStr = createExecuteCommandRequestBody(documentStr, httpClientInputs.getUrl(), shellId, command, String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()),
wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
commandExecutionStartTime = System.currentTimeMillis() / 1000;
Map<String, String> executeCommandResult = executeRequestWithBody(csHttpClient, httpClientInputs, documentStr);
return getResourceId(executeCommandResult.get(RETURN_RESULT), COMMAND_RESPONSE_ACTION, COMMAND_RESULT_COMMAND_ID_XPATH,
COMMAND_ID_NOT_RETRIEVED);
} | java | private String executeCommand(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String shellId,
WSManRequestInputs wsManRequestInputs, String command) throws RuntimeException,
IOException, URISyntaxException, TransformerException, XPathExpressionException, SAXException, ParserConfigurationException {
String documentStr = ResourceLoader.loadAsString(EXECUTE_COMMAND_REQUEST_XML);
documentStr = createExecuteCommandRequestBody(documentStr, httpClientInputs.getUrl(), shellId, command, String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()),
wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
commandExecutionStartTime = System.currentTimeMillis() / 1000;
Map<String, String> executeCommandResult = executeRequestWithBody(csHttpClient, httpClientInputs, documentStr);
return getResourceId(executeCommandResult.get(RETURN_RESULT), COMMAND_RESPONSE_ACTION, COMMAND_RESULT_COMMAND_ID_XPATH,
COMMAND_ID_NOT_RETRIEVED);
} | [
"private",
"String",
"executeCommand",
"(",
"HttpClientService",
"csHttpClient",
",",
"HttpClientInputs",
"httpClientInputs",
",",
"String",
"shellId",
",",
"WSManRequestInputs",
"wsManRequestInputs",
",",
"String",
"command",
")",
"throws",
"RuntimeException",
",",
"IOEx... | Executes a command on the given shell.
@param csHttpClient
@param httpClientInputs
@param shellId
@param wsManRequestInputs
@return the command id.
@throws RuntimeException
@throws IOException
@throws URISyntaxException
@throws TransformerException
@throws XPathExpressionException
@throws SAXException
@throws ParserConfigurationException | [
"Executes",
"a",
"command",
"on",
"the",
"given",
"shell",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L218-L228 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.receiveCommandResult | private Map<String, String> receiveCommandResult(HttpClientService csHttpClient, HttpClientInputs httpClientInputs,
String shellId, String commandId, WSManRequestInputs wsManRequestInputs) throws RuntimeException,
IOException, URISyntaxException, TransformerException, TimeoutException, XPathExpressionException, SAXException,
ParserConfigurationException, InterruptedException {
String documentStr = ResourceLoader.loadAsString(RECEIVE_REQUEST_XML);
documentStr = createReceiveRequestBody(documentStr, httpClientInputs.getUrl(), shellId, commandId, String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()), wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
Map<String, String> receiveResult;
while (true) {
receiveResult = executeRequestWithBody(csHttpClient, httpClientInputs, documentStr);
if (executionIsTimedOut(commandExecutionStartTime, wsManRequestInputs.getOperationTimeout())) {
throw new TimeoutException(EXECUTION_TIMED_OUT);
} else if (WSManUtils.isSpecificResponseAction(receiveResult.get(RETURN_RESULT), RECEIVE_RESPONSE_ACTION) &&
WSManUtils.commandExecutionIsDone(receiveResult.get(RETURN_RESULT))) {
return processCommandExecutionResponse(receiveResult);
} else if (WSManUtils.isFaultResponse(receiveResult.get(RETURN_RESULT))) {
throw new RuntimeException(WSManUtils.getResponseFault(receiveResult.get(RETURN_RESULT)));
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw e;
}
}
} | java | private Map<String, String> receiveCommandResult(HttpClientService csHttpClient, HttpClientInputs httpClientInputs,
String shellId, String commandId, WSManRequestInputs wsManRequestInputs) throws RuntimeException,
IOException, URISyntaxException, TransformerException, TimeoutException, XPathExpressionException, SAXException,
ParserConfigurationException, InterruptedException {
String documentStr = ResourceLoader.loadAsString(RECEIVE_REQUEST_XML);
documentStr = createReceiveRequestBody(documentStr, httpClientInputs.getUrl(), shellId, commandId, String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()), wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
Map<String, String> receiveResult;
while (true) {
receiveResult = executeRequestWithBody(csHttpClient, httpClientInputs, documentStr);
if (executionIsTimedOut(commandExecutionStartTime, wsManRequestInputs.getOperationTimeout())) {
throw new TimeoutException(EXECUTION_TIMED_OUT);
} else if (WSManUtils.isSpecificResponseAction(receiveResult.get(RETURN_RESULT), RECEIVE_RESPONSE_ACTION) &&
WSManUtils.commandExecutionIsDone(receiveResult.get(RETURN_RESULT))) {
return processCommandExecutionResponse(receiveResult);
} else if (WSManUtils.isFaultResponse(receiveResult.get(RETURN_RESULT))) {
throw new RuntimeException(WSManUtils.getResponseFault(receiveResult.get(RETURN_RESULT)));
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw e;
}
}
} | [
"private",
"Map",
"<",
"String",
",",
"String",
">",
"receiveCommandResult",
"(",
"HttpClientService",
"csHttpClient",
",",
"HttpClientInputs",
"httpClientInputs",
",",
"String",
"shellId",
",",
"String",
"commandId",
",",
"WSManRequestInputs",
"wsManRequestInputs",
")"... | Waits for a specific command that is running on a remote shell to finnish it's execution.
@param csHttpClient
@param httpClientInputs
@param shellId
@param commandId
@param wsManRequestInputs
@return the command execution result and exit code.
@throws RuntimeException
@throws IOException
@throws URISyntaxException
@throws TransformerException
@throws TimeoutException
@throws XPathExpressionException
@throws SAXException
@throws ParserConfigurationException
@throws InterruptedException | [
"Waits",
"for",
"a",
"specific",
"command",
"that",
"is",
"running",
"on",
"a",
"remote",
"shell",
"to",
"finnish",
"it",
"s",
"execution",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L249-L274 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.getResourceId | private String getResourceId(String response, String resourceResponseAction, String resourceIdXpath, String resourceIdExceptionMessage) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
if (WSManUtils.isSpecificResponseAction(response, resourceResponseAction)) {
String shellId = XMLUtils.parseXml(response, resourceIdXpath);
if (StringUtils.isNotBlank(shellId)) {
return shellId;
} else {
throw new RuntimeException(resourceIdExceptionMessage);
}
} else if (WSManUtils.isFaultResponse(response)) {
throw new RuntimeException(WSManUtils.getResponseFault(response));
} else {
throw new RuntimeException(UNEXPECTED_SERVICE_RESPONSE + response);
}
} | java | private String getResourceId(String response, String resourceResponseAction, String resourceIdXpath, String resourceIdExceptionMessage) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
if (WSManUtils.isSpecificResponseAction(response, resourceResponseAction)) {
String shellId = XMLUtils.parseXml(response, resourceIdXpath);
if (StringUtils.isNotBlank(shellId)) {
return shellId;
} else {
throw new RuntimeException(resourceIdExceptionMessage);
}
} else if (WSManUtils.isFaultResponse(response)) {
throw new RuntimeException(WSManUtils.getResponseFault(response));
} else {
throw new RuntimeException(UNEXPECTED_SERVICE_RESPONSE + response);
}
} | [
"private",
"String",
"getResourceId",
"(",
"String",
"response",
",",
"String",
"resourceResponseAction",
",",
"String",
"resourceIdXpath",
",",
"String",
"resourceIdExceptionMessage",
")",
"throws",
"ParserConfigurationException",
",",
"SAXException",
",",
"XPathExpression... | This method retrieves the resource id from the create resource request response and throws the appropriate exceptions in case of failure.
@param response
@param resourceResponseAction
@param resourceIdXpath
@param resourceIdExceptionMessage
@return
@throws ParserConfigurationException
@throws SAXException
@throws XPathExpressionException
@throws IOException | [
"This",
"method",
"retrieves",
"the",
"resource",
"id",
"from",
"the",
"create",
"resource",
"request",
"response",
"and",
"throws",
"the",
"appropriate",
"exceptions",
"in",
"case",
"of",
"failure",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L289-L302 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.deleteShell | private void deleteShell(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String shellId, WSManRequestInputs wsManRequestInputs)
throws RuntimeException, IOException, URISyntaxException, TransformerException, XPathExpressionException, SAXException, ParserConfigurationException {
String documentStr = ResourceLoader.loadAsString(DELETE_SHELL_REQUEST_XML);
documentStr = createDeleteShellRequestBody(documentStr, httpClientInputs.getUrl(), shellId, String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()), wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
Map<String, String> deleteShellResult = executeRequestWithBody(csHttpClient, httpClientInputs, documentStr);
if (WSManUtils.isSpecificResponseAction(deleteShellResult.get(RETURN_RESULT), DELETE_RESPONSE_ACTION)) {
return;
} else if (WSManUtils.isFaultResponse(deleteShellResult.get(RETURN_RESULT))) {
throw new RuntimeException(WSManUtils.getResponseFault(deleteShellResult.get(RETURN_RESULT)));
} else {
throw new RuntimeException(UNEXPECTED_SERVICE_RESPONSE + deleteShellResult.get(RETURN_RESULT));
}
} | java | private void deleteShell(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String shellId, WSManRequestInputs wsManRequestInputs)
throws RuntimeException, IOException, URISyntaxException, TransformerException, XPathExpressionException, SAXException, ParserConfigurationException {
String documentStr = ResourceLoader.loadAsString(DELETE_SHELL_REQUEST_XML);
documentStr = createDeleteShellRequestBody(documentStr, httpClientInputs.getUrl(), shellId, String.valueOf(wsManRequestInputs.getMaxEnvelopeSize()), wsManRequestInputs.getWinrmLocale(), String.valueOf(wsManRequestInputs.getOperationTimeout()));
Map<String, String> deleteShellResult = executeRequestWithBody(csHttpClient, httpClientInputs, documentStr);
if (WSManUtils.isSpecificResponseAction(deleteShellResult.get(RETURN_RESULT), DELETE_RESPONSE_ACTION)) {
return;
} else if (WSManUtils.isFaultResponse(deleteShellResult.get(RETURN_RESULT))) {
throw new RuntimeException(WSManUtils.getResponseFault(deleteShellResult.get(RETURN_RESULT)));
} else {
throw new RuntimeException(UNEXPECTED_SERVICE_RESPONSE + deleteShellResult.get(RETURN_RESULT));
}
} | [
"private",
"void",
"deleteShell",
"(",
"HttpClientService",
"csHttpClient",
",",
"HttpClientInputs",
"httpClientInputs",
",",
"String",
"shellId",
",",
"WSManRequestInputs",
"wsManRequestInputs",
")",
"throws",
"RuntimeException",
",",
"IOException",
",",
"URISyntaxExceptio... | Deletes the remote shell.
@param csHttpClient
@param httpClientInputs
@param shellId
@param wsManRequestInputs
@throws RuntimeException
@throws IOException
@throws URISyntaxException
@throws TransformerException
@throws XPathExpressionException
@throws SAXException
@throws ParserConfigurationException | [
"Deletes",
"the",
"remote",
"shell",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L319-L331 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.processCommandExecutionResponse | private Map<String, String> processCommandExecutionResponse(Map<String, String> receiveResult) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
Map<String, String> scriptResults = new HashMap<>();
scriptResults.put(RETURN_RESULT, buildResultFromResponseStreams(receiveResult.get(RETURN_RESULT), OutputStream.STDOUT));
scriptResults.put(Constants.OutputNames.STDERR, buildResultFromResponseStreams(receiveResult.get(RETURN_RESULT), OutputStream.STDERR));
scriptResults.put(Constants.OutputNames.SCRIPT_EXIT_CODE, WSManUtils.getScriptExitCode(receiveResult.get(RETURN_RESULT)));
return scriptResults;
} | java | private Map<String, String> processCommandExecutionResponse(Map<String, String> receiveResult) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
Map<String, String> scriptResults = new HashMap<>();
scriptResults.put(RETURN_RESULT, buildResultFromResponseStreams(receiveResult.get(RETURN_RESULT), OutputStream.STDOUT));
scriptResults.put(Constants.OutputNames.STDERR, buildResultFromResponseStreams(receiveResult.get(RETURN_RESULT), OutputStream.STDERR));
scriptResults.put(Constants.OutputNames.SCRIPT_EXIT_CODE, WSManUtils.getScriptExitCode(receiveResult.get(RETURN_RESULT)));
return scriptResults;
} | [
"private",
"Map",
"<",
"String",
",",
"String",
">",
"processCommandExecutionResponse",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"receiveResult",
")",
"throws",
"ParserConfigurationException",
",",
"SAXException",
",",
"XPathExpressionException",
",",
"IOExcepti... | This method separates the stdout and stderr response streams from the received execution response.
@param receiveResult A map containing the response from the service.
@return a map containing the stdout, stderr streams and the script exit code.
@throws ParserConfigurationException
@throws SAXException
@throws XPathExpressionException
@throws IOException | [
"This",
"method",
"separates",
"the",
"stdout",
"and",
"stderr",
"response",
"streams",
"from",
"the",
"received",
"execution",
"response",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L343-L349 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.buildResultFromResponseStreams | private String buildResultFromResponseStreams(String response, OutputStream outputStream) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
StringBuilder commandResult = new StringBuilder();
int noOfStreams = WSManUtils.countStreamElements(response);
for (int streamNo = 0; streamNo < noOfStreams; streamNo++) {
String stream = XMLUtils.parseXml(response, String.format(RECEIVE_RESPONSE_XPATH, outputStream.getValue(), streamNo));
if (!"DQo=".equals(stream)) {
commandResult.append(EncoderDecoder.decodeBase64String(stream));
}
}
return commandResult.toString();
} | java | private String buildResultFromResponseStreams(String response, OutputStream outputStream) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
StringBuilder commandResult = new StringBuilder();
int noOfStreams = WSManUtils.countStreamElements(response);
for (int streamNo = 0; streamNo < noOfStreams; streamNo++) {
String stream = XMLUtils.parseXml(response, String.format(RECEIVE_RESPONSE_XPATH, outputStream.getValue(), streamNo));
if (!"DQo=".equals(stream)) {
commandResult.append(EncoderDecoder.decodeBase64String(stream));
}
}
return commandResult.toString();
} | [
"private",
"String",
"buildResultFromResponseStreams",
"(",
"String",
"response",
",",
"OutputStream",
"outputStream",
")",
"throws",
"ParserConfigurationException",
",",
"SAXException",
",",
"XPathExpressionException",
",",
"IOException",
"{",
"StringBuilder",
"commandResult... | Constructs the executed command response from multiple streams of data containing the encoded result of the execution.
@param response
@param outputStream
@return the decoded result of the command in a string.
@throws ParserConfigurationException
@throws SAXException
@throws XPathExpressionException
@throws IOException | [
"Constructs",
"the",
"executed",
"command",
"response",
"from",
"multiple",
"streams",
"of",
"data",
"containing",
"the",
"encoded",
"result",
"of",
"the",
"execution",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L362-L372 | train |
CloudSlang/cs-actions | cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java | WSManRemoteShellService.executionIsTimedOut | private boolean executionIsTimedOut(long aStartTime, int aTimeout) {
if (aTimeout != 0) {
long now = System.currentTimeMillis() / 1000;
if ((now - aStartTime) >= aTimeout) {
return true;
}
}
return false;
} | java | private boolean executionIsTimedOut(long aStartTime, int aTimeout) {
if (aTimeout != 0) {
long now = System.currentTimeMillis() / 1000;
if ((now - aStartTime) >= aTimeout) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"executionIsTimedOut",
"(",
"long",
"aStartTime",
",",
"int",
"aTimeout",
")",
"{",
"if",
"(",
"aTimeout",
"!=",
"0",
")",
"{",
"long",
"now",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"/",
"1000",
";",
"if",
"(",
"(",
"n... | Check whether or not the command execution reach the timeout value.
@param aStartTime A start time in seconds.
@param aTimeout A timeout value in seconds.
@return true if it reaches timeout. | [
"Check",
"whether",
"or",
"not",
"the",
"command",
"execution",
"reach",
"the",
"timeout",
"value",
"."
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/services/WSManRemoteShellService.java#L381-L389 | train |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java | CollectionUtilities.toArrayWithEscaped | @NotNull
public static String[] toArrayWithEscaped(@Nullable final String stringArray, @NotNull final String delimiter) {
if (StringUtils.isEmpty(stringArray)) {
return new String[0];
}
return StringUtils.splitByWholeSeparatorPreserveAllTokens(stringArray, delimiter);
} | java | @NotNull
public static String[] toArrayWithEscaped(@Nullable final String stringArray, @NotNull final String delimiter) {
if (StringUtils.isEmpty(stringArray)) {
return new String[0];
}
return StringUtils.splitByWholeSeparatorPreserveAllTokens(stringArray, delimiter);
} | [
"@",
"NotNull",
"public",
"static",
"String",
"[",
"]",
"toArrayWithEscaped",
"(",
"@",
"Nullable",
"final",
"String",
"stringArray",
",",
"@",
"NotNull",
"final",
"String",
"delimiter",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"stringArray",
... | Splits the stringArray by the delimiter into an array of strings without ignoring the escaped delimiters
@param stringArray the string to be split
@param delimiter the delimiter by which to split the stringArray
@return an array of Strings | [
"Splits",
"the",
"stringArray",
"by",
"the",
"delimiter",
"into",
"an",
"array",
"of",
"strings",
"without",
"ignoring",
"the",
"escaped",
"delimiters"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java#L48-L54 | train |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java | CollectionUtilities.toArray | @NotNull
public static String[] toArray(@Nullable final String stringArray, @NotNull final String delimiter) {
if (StringUtils.isEmpty(stringArray)) {
return new String[0];
}
final String regex = "(?<!\\\\)" + Pattern.quote(delimiter);
return stringArray.split(regex);
} | java | @NotNull
public static String[] toArray(@Nullable final String stringArray, @NotNull final String delimiter) {
if (StringUtils.isEmpty(stringArray)) {
return new String[0];
}
final String regex = "(?<!\\\\)" + Pattern.quote(delimiter);
return stringArray.split(regex);
} | [
"@",
"NotNull",
"public",
"static",
"String",
"[",
"]",
"toArray",
"(",
"@",
"Nullable",
"final",
"String",
"stringArray",
",",
"@",
"NotNull",
"final",
"String",
"delimiter",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"stringArray",
")",
")"... | Splits the stringArray by the delimiter into an array of strings ignoring the escaped delimiters
@param stringArray the string to be split
@param delimiter the delimiter by which to split the stringArray
@return an array of Strings | [
"Splits",
"the",
"stringArray",
"by",
"the",
"delimiter",
"into",
"an",
"array",
"of",
"strings",
"ignoring",
"the",
"escaped",
"delimiters"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java#L63-L70 | train |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java | CollectionUtilities.toListWithEscaped | @NotNull
public static List<String> toListWithEscaped(@Nullable final String stringList, @NotNull final String delimiter) {
return new ArrayList<>(Arrays.asList(toArrayWithEscaped(stringList, delimiter)));
} | java | @NotNull
public static List<String> toListWithEscaped(@Nullable final String stringList, @NotNull final String delimiter) {
return new ArrayList<>(Arrays.asList(toArrayWithEscaped(stringList, delimiter)));
} | [
"@",
"NotNull",
"public",
"static",
"List",
"<",
"String",
">",
"toListWithEscaped",
"(",
"@",
"Nullable",
"final",
"String",
"stringList",
",",
"@",
"NotNull",
"final",
"String",
"delimiter",
")",
"{",
"return",
"new",
"ArrayList",
"<>",
"(",
"Arrays",
".",... | Splits the stringList by the delimiter into a List of strings without ignoring the escaped delimiters
@param stringList the string to be split
@param delimiter the delimiter by which to split the stringArray
@return a list of Strings | [
"Splits",
"the",
"stringList",
"by",
"the",
"delimiter",
"into",
"a",
"List",
"of",
"strings",
"without",
"ignoring",
"the",
"escaped",
"delimiters"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java#L79-L82 | train |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java | CollectionUtilities.toList | @NotNull
public static List<String> toList(@Nullable final String stringList, @NotNull final String delimiter) {
return new ArrayList<>(Arrays.asList(toArray(stringList, delimiter)));
} | java | @NotNull
public static List<String> toList(@Nullable final String stringList, @NotNull final String delimiter) {
return new ArrayList<>(Arrays.asList(toArray(stringList, delimiter)));
} | [
"@",
"NotNull",
"public",
"static",
"List",
"<",
"String",
">",
"toList",
"(",
"@",
"Nullable",
"final",
"String",
"stringList",
",",
"@",
"NotNull",
"final",
"String",
"delimiter",
")",
"{",
"return",
"new",
"ArrayList",
"<>",
"(",
"Arrays",
".",
"asList"... | Splits the stringList by the delimiter into a List of strings ignoring the escaped delimiters
@param stringList the string to be split
@param delimiter the delimiter by which to split the stringArray
@return a list of Strings | [
"Splits",
"the",
"stringList",
"by",
"the",
"delimiter",
"into",
"a",
"List",
"of",
"strings",
"ignoring",
"the",
"escaped",
"delimiters"
] | 9a1be1e99ad88286a6c153d5f2275df6ae1a57a1 | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/CollectionUtilities.java#L91-L94 | train |
ist-dresden/composum | sling/core/commons/src/main/java/com/composum/sling/core/RequestBundle.java | RequestBundle.get | public static synchronized RequestBundle get(SlingHttpServletRequest request) {
RequestBundle instance = (RequestBundle) request.getAttribute(ATTRIBUTE_KEY);
if (instance == null) {
instance = new RequestBundle(request);
request.setAttribute(ATTRIBUTE_KEY, instance);
}
return instance;
} | java | public static synchronized RequestBundle get(SlingHttpServletRequest request) {
RequestBundle instance = (RequestBundle) request.getAttribute(ATTRIBUTE_KEY);
if (instance == null) {
instance = new RequestBundle(request);
request.setAttribute(ATTRIBUTE_KEY, instance);
}
return instance;
} | [
"public",
"static",
"synchronized",
"RequestBundle",
"get",
"(",
"SlingHttpServletRequest",
"request",
")",
"{",
"RequestBundle",
"instance",
"=",
"(",
"RequestBundle",
")",
"request",
".",
"getAttribute",
"(",
"ATTRIBUTE_KEY",
")",
";",
"if",
"(",
"instance",
"==... | returns the requests instance | [
"returns",
"the",
"requests",
"instance"
] | ebc79f559f6022c935240c19102539bdfb1bd1e2 | https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/RequestBundle.java#L19-L26 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.