use of org.wso2.carbon.messaging.Header in project carbon-business-process by wso2.
the class RESTTask method execute.
@Override
public void execute(DelegateExecution execution) {
if (method == null) {
String error = "HTTP method for the REST task not found. Please specify the \"method\" form property.";
throw new RESTClientException(error);
}
if (log.isDebugEnabled()) {
if (serviceURL != null) {
log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceURL.getValue(execution).toString());
} else if (serviceRef != null) {
log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceRef.getValue(execution).toString());
}
}
RESTInvoker restInvoker = BPMNRestExtensionHolder.getInstance().getRestInvoker();
RESTResponse response;
String url = null;
String bUsername = null;
String bPassword = null;
JsonNodeObject jsonHeaders = null;
boolean contentAvailable = false;
try {
if (serviceURL != null) {
url = serviceURL.getValue(execution).toString();
if (basicAuthUsername != null && basicAuthPassword != null) {
bUsername = basicAuthUsername.getValue(execution).toString();
bPassword = basicAuthPassword.getValue(execution).toString();
}
} else if (serviceRef != null) {
String resourcePath = serviceRef.getValue(execution).toString();
String registryPath;
int tenantIdInt = Integer.parseInt(execution.getTenantId());
RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
String domain = realmService.getTenantManager().getDomain(tenantIdInt);
Registry registry;
Resource urlResource;
try {
PrivilegedCarbonContext.startTenantFlow();
if (domain != null) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(domain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
}
if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(tenantIdInt);
} else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(tenantIdInt);
} else {
String msg = "Registry type is not specified for service reference in " + getTaskDetails(execution) + ". serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
throw new RESTClientException(msg);
}
if (log.isDebugEnabled()) {
log.debug("Reading endpoint from registry location: " + registryPath + " for task " + getTaskDetails(execution));
}
urlResource = registry.get(registryPath);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
if (urlResource != null) {
String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
url = uep.getAddress();
bUsername = uep.getAuthorizationUserName();
bPassword = uep.getAuthorizationPassword();
} else {
String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + getTaskDetails(execution);
throw new RESTClientException(errorMsg);
}
} else {
String urlNotFoundErrorMsg = "Service URL is not provided for " + getTaskDetails(execution) + ". serviceURL or serviceRef must be provided.";
throw new RESTClientException(urlNotFoundErrorMsg);
}
if (headers != null) {
String headerContent = headers.getValue(execution).toString();
jsonHeaders = JSONUtils.parse(headerContent);
}
if (POST_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
String inputContent = input.getValue(execution).toString();
response = restInvoker.invokePOST(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
} else if (GET_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
response = restInvoker.invokeGET(new URI(url), jsonHeaders, bUsername, bPassword);
} else if (PUT_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
String inputContent = input.getValue(execution).toString();
response = restInvoker.invokePUT(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
} else if (DELETE_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
response = restInvoker.invokeDELETE(new URI(url), jsonHeaders, bUsername, bPassword);
} else {
String errorMsg = "Unsupported http method. The REST task only supports GET, POST, PUT and DELETE operations";
throw new RESTClientException(errorMsg);
}
Object output = response.getContent();
if (output != null) {
contentAvailable = !response.getContent().equals("");
}
boolean contentTypeAvailable = false;
if (response.getContentType() != null) {
contentTypeAvailable = true;
}
if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_JSON)) {
output = JSONUtils.parse(String.valueOf(output));
} else if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_XML)) {
output = Utils.parse(String.valueOf(output));
} else {
output = StringEscapeUtils.escapeXml(String.valueOf(output));
}
if (outputVariable != null) {
String outVarName = outputVariable.getValue(execution).toString();
execution.setVariable(outVarName, output);
} else if (outputMappings != null) {
String outMappings = outputMappings.getValue(execution).toString();
outMappings = outMappings.trim();
String[] mappings = outMappings.split(",");
for (String mapping : mappings) {
String[] mappingParts = mapping.split(":");
String varName = mappingParts[0];
String expression = mappingParts[1];
Object value;
if (output instanceof JsonNodeObject) {
value = ((JsonNodeObject) output).jsonPath(expression);
} else {
value = ((XMLDocument) output).xPath(expression);
}
execution.setVariable(varName, value);
}
} else {
String outputNotFoundErrorMsg = "An outputVariable or outputMappings is not provided. " + "Either an output variable or output mappings must be provided to save " + "the response.";
throw new RESTClientException(outputNotFoundErrorMsg);
}
if (responseHeaderVariable != null) {
StringBuilder headerJsonStr = new StringBuilder();
headerJsonStr.append("{");
String prefix = "";
for (Header header : response.getHeaders()) {
headerJsonStr.append(prefix);
String name = header.getName().replaceAll("\"", "");
String value = header.getValue().replaceAll("\"", "");
headerJsonStr.append("\"").append(name).append("\":\"").append(value).append("\"");
prefix = ",";
}
headerJsonStr.append("}");
JsonNodeObject headerJson = JSONUtils.parse(headerJsonStr.toString());
execution.setVariable(responseHeaderVariable.getValue(execution).toString(), headerJson);
}
if (httpStatusVariable != null) {
execution.setVariable(httpStatusVariable.getValue(execution).toString(), response.getHttpStatus());
}
} catch (RegistryException | XMLStreamException | URISyntaxException | IOException | SAXException | ParserConfigurationException e) {
String errorMessage = "Failed to execute " + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
log.error(errorMessage, e);
throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
} catch (BPMNJsonException | BPMNXmlException e) {
String errorMessage = "Failed to extract values for output mappings, the response content" + " doesn't support the expression" + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
log.error(errorMessage, e);
throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
} catch (UserStoreException e) {
String errorMessage = "Failed to obtain tenant domain information";
log.error(errorMessage, e);
throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
}
}
use of org.wso2.carbon.messaging.Header in project carbon-business-process by wso2.
the class SOAPTask method execute.
@Override
public void execute(DelegateExecution execution) {
String endpointURL;
String payloadRequest;
String version;
String connection;
String transferEncoding;
String[] transportHeaderList;
String action = "";
String soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
List<Header> headerList = new ArrayList<Header>();
try {
if (serviceURL != null) {
endpointURL = serviceURL.getValue(execution).toString();
} else if (serviceRef != null) {
String resourcePath = serviceRef.getValue(execution).toString();
String registryPath;
String tenantId = execution.getTenantId();
Registry registry;
if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(Integer.parseInt(tenantId));
} else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(Integer.parseInt(tenantId));
} else {
String msg = "Registry type is not specified for service reference in " + " serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, msg);
}
if (log.isDebugEnabled()) {
log.debug("Reading endpoint from registry location: " + registryPath + " for task " + execution.getCurrentActivityName());
}
Resource urlResource = registry.get(registryPath);
if (urlResource != null) {
String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
endpointURL = uep.getAddress();
} else {
String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + execution.getCurrentActivityName();
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, errorMsg);
}
} else {
String urlNotFoundErrorMsg = "Service URL is not provided. serviceURL must be provided.";
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, urlNotFoundErrorMsg);
}
if (payload != null) {
payloadRequest = payload.getValue(execution).toString();
} else {
String payloadNotFoundErrorMsg = "Payload request is not provided. Payload must be provided.";
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, payloadNotFoundErrorMsg);
}
if (soapVersion != null) {
version = soapVersion.getValue(execution).toString();
if (version.equalsIgnoreCase(SOAP12_VERSION)) {
soapVersionURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
} else if (version.equalsIgnoreCase(SOAP11_VERSION)) {
soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
} else {
String invalidVersionErrorMsg = "Invalid soap version string specified";
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, invalidVersionErrorMsg);
}
}
// Adding the connection
Header connectionHeader = new Header();
if (httpConnection != null) {
connection = httpConnection.getValue(execution).toString();
if (connection != null && !connection.trim().equals("Keep-Alive")) {
log.debug("Setting Keep-Alive header ");
connectionHeader.setName("Connection");
connectionHeader.setValue(connection);
headerList.add(connectionHeader);
}
}
// Adding the additional transport headers
if (transportHeaders != null) {
String headerContent = transportHeaders.getValue(execution).toString();
if (headerContent != null) {
transportHeaderList = headerContent.split(",");
for (String transportHeader : transportHeaderList) {
String[] pair = transportHeader.split(":");
Header additionalHeader = new Header();
if (pair.length == 1) {
additionalHeader.setName(pair[0]);
additionalHeader.setValue("");
if (log.isDebugEnabled()) {
log.debug("Adding transport headers " + pair[0]);
}
} else {
additionalHeader.setName(pair[0]);
additionalHeader.setValue(pair[1]);
if (log.isDebugEnabled()) {
log.debug("Adding transport headers " + pair[0] + " " + pair[1]);
}
}
headerList.add(additionalHeader);
}
}
}
// Adding the soap action
if (soapAction != null) {
action = soapAction.getValue(execution).toString();
if (log.isDebugEnabled()) {
log.debug("Setting soap action " + soapAction);
}
}
// Converting the payload to an OMElement
OMElement payLoad = AXIOMUtil.stringToOM(payloadRequest);
// Creating the Service client
ServiceClient sender = new ServiceClient();
OMElement response;
// Creating options to set the headers
Options options = new Options();
options.setTo(new EndpointReference(endpointURL));
options.setAction(action);
options.setSoapVersionURI(soapVersionURI);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
// Adding the soap header block to the SOAP Header block when creating the SOAP Envelope
if (headers != null) {
String headerContent = headers.getValue(execution).toString();
OMElement headerElement = AXIOMUtil.stringToOM(headerContent);
sender.addHeader(headerElement);
if (log.isDebugEnabled()) {
log.debug("Adding soap header " + headerContent);
}
}
// Adding the transfer encoding
if (httpTransferEncoding != null) {
transferEncoding = httpTransferEncoding.getValue(execution).toString();
if (transferEncoding.equalsIgnoreCase("chunked")) {
options.setProperty(HTTPConstants.CHUNKED, Boolean.TRUE);
if (log.isDebugEnabled()) {
log.debug("Enabling transfer encoding chunked ");
}
} else {
options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
if (log.isDebugEnabled()) {
log.debug("Disabling transfer encoding chunked ");
}
}
}
sender.setOptions(options);
// Invoking the endpoint
response = sender.sendReceive(payLoad);
// Getting the response as a string
String responseStr = response.toStringWithConsume();
if (outputVariable != null) {
String outVarName = outputVariable.getValue(execution).toString();
execution.setVariableLocal(outVarName, responseStr);
} else {
String outputNotFoundErrorMsg = "Output variable is not provided. " + "outputVariable must be provided to save " + "the response.";
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, outputNotFoundErrorMsg);
}
} catch (AxisFault axisFault) {
log.error("Axis2 Fault", axisFault);
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception while getting response :" + axisFault.getMessage());
} catch (XMLStreamException | RegistryException e) {
log.error("Exception in processing", e);
throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception in processing :" + e.getMessage());
}
}
use of org.wso2.carbon.messaging.Header in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticator method getConfigurationProperties.
/**
* Get the configuration properties of UI
*/
@Override
public List<Property> getConfigurationProperties() {
List<Property> configProperties = new ArrayList<Property>();
Property smsUrl = new Property();
smsUrl.setName(SMSOTPConstants.SMS_URL);
smsUrl.setDisplayName("SMS URL");
smsUrl.setRequired(true);
smsUrl.setDescription("Enter client sms url value. If the phone number and text message are in URL, " + "specify them as $ctx.num and $ctx.msg");
smsUrl.setDisplayOrder(0);
configProperties.add(smsUrl);
Property httpMethod = new Property();
httpMethod.setName(SMSOTPConstants.HTTP_METHOD);
httpMethod.setDisplayName("HTTP Method");
httpMethod.setRequired(true);
httpMethod.setDescription("Enter the HTTP Method used by the SMS API");
httpMethod.setDisplayOrder(1);
configProperties.add(httpMethod);
Property headers = new Property();
headers.setName(SMSOTPConstants.HEADERS);
headers.setDisplayName("HTTP Headers");
headers.setRequired(false);
headers.setDescription("Enter the headers used by the API separated by comma, with the Header name and value " + "separated by \":\". If the phone number and text message are in Headers, specify them as $ctx.num and $ctx.msg");
headers.setDisplayOrder(2);
configProperties.add(headers);
Property payload = new Property();
payload.setName(SMSOTPConstants.PAYLOAD);
payload.setDisplayName("HTTP Payload");
payload.setRequired(false);
payload.setDescription("Enter the HTTP Payload used by the SMS API. If the phone number and text message are " + "in Payload, specify them as $ctx.num and $ctx.msg");
payload.setDisplayOrder(3);
configProperties.add(payload);
Property httpResponse = new Property();
httpResponse.setName(SMSOTPConstants.HTTP_RESPONSE);
httpResponse.setDisplayName("HTTP Response Code");
httpResponse.setRequired(false);
httpResponse.setDescription("Enter the HTTP response code the API sends upon successful call. Leave empty if unknown");
httpResponse.setDisplayOrder(4);
configProperties.add(httpResponse);
return configProperties;
}
use of org.wso2.carbon.messaging.Header in project identity-outbound-auth-sms-otp by wso2-extensions.
the class SMSOTPAuthenticator method getConnection.
/**
* Get the connection and proceed with SMS API's rest call.
*
* @param httpConnection the connection
* @param context the authenticationContext
* @param headerString the header string
* @param payload the payload
* @param httpResponse the http response
* @param encodedMobileNo the encoded mobileNo
* @param smsMessage the sms message
* @param otpToken the token
* @param httpMethod the http method
* @return true or false
* @throws AuthenticationFailedException
*/
private boolean getConnection(HttpURLConnection httpConnection, AuthenticationContext context, String headerString, String payload, String httpResponse, String encodedMobileNo, String smsMessage, String otpToken, String httpMethod) throws AuthenticationFailedException {
try {
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
String[] headerArray;
if (StringUtils.isNotEmpty(headerString)) {
if (log.isDebugEnabled()) {
log.debug("Processing HTTP headers since header string is available");
}
headerString = headerString.trim().replaceAll("\\$ctx.num", encodedMobileNo).replaceAll("\\$ctx.msg", smsMessage + otpToken);
headerArray = headerString.split(",");
for (String header : headerArray) {
String[] headerElements = header.split(":");
if (headerElements.length > 1) {
httpConnection.setRequestProperty(headerElements[0], headerElements[1]);
} else {
log.info("Either header name or value not found. Hence not adding header which contains " + headerElements[0]);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("No configured headers found. Header string is empty");
}
}
// Processing HTTP Method
if (log.isDebugEnabled()) {
log.debug("Configured http method is " + httpMethod);
}
if (SMSOTPConstants.GET_METHOD.equalsIgnoreCase(httpMethod)) {
httpConnection.setRequestMethod(SMSOTPConstants.GET_METHOD);
} else if (SMSOTPConstants.POST_METHOD.equalsIgnoreCase(httpMethod)) {
httpConnection.setRequestMethod(SMSOTPConstants.POST_METHOD);
if (StringUtils.isNotEmpty(payload)) {
payload = payload.replaceAll("\\$ctx.num", encodedMobileNo).replaceAll("\\$ctx.msg", smsMessage + otpToken);
}
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(httpConnection.getOutputStream(), SMSOTPConstants.CHAR_SET);
writer.write(payload);
} catch (IOException e) {
throw new AuthenticationFailedException("Error while posting payload message ", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
if (StringUtils.isNotEmpty(httpResponse)) {
if (httpResponse.trim().equals(String.valueOf(httpConnection.getResponseCode()))) {
if (log.isDebugEnabled()) {
log.debug("Code is successfully sent to the mobile and recieved expected response code : " + httpResponse);
}
return true;
}
} else {
if (httpConnection.getResponseCode() == 200 || httpConnection.getResponseCode() == 201 || httpConnection.getResponseCode() == 202) {
if (log.isDebugEnabled()) {
log.debug("Code is successfully sent to the mobile. Relieved HTTP response code is : " + httpConnection.getResponseCode());
}
return true;
} else {
context.setProperty(SMSOTPConstants.ERROR_CODE, httpConnection.getResponseCode() + " : " + httpConnection.getResponseMessage());
log.error("Error while sending SMS: error code is " + httpConnection.getResponseCode() + " and error message is " + httpConnection.getResponseMessage());
return false;
}
}
} catch (MalformedURLException e) {
throw new AuthenticationFailedException("Invalid URL ", e);
} catch (ProtocolException e) {
throw new AuthenticationFailedException("Error while setting the HTTP method ", e);
} catch (IOException e) {
throw new AuthenticationFailedException("Error while setting the HTTP response ", e);
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return false;
}
use of org.wso2.carbon.messaging.Header in project carbon-apimgt by wso2.
the class BlacklistApiServiceImpl method blacklistGet.
@Override
public Response blacklistGet(String accept, Request request) throws NotFoundException {
try {
APIMgtAdminService apiMgtAdminService = APIManagerFactory.getInstance().getAPIMgtAdminService();
List<BlockConditions> blockConditionsList = apiMgtAdminService.getBlockConditions();
BlockingConditionListDTO blockingConditionListDTO = MappingUtil.fromBlockConditionListToListDTO(blockConditionsList);
return Response.ok(blockingConditionListDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Error while retrieving block conditions";
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(errorDTO).build();
}
}
Aggregations