Search in sources :

Example 16 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-business-process by wso2.

the class OpenJPAVendorAdapter method getJpaPropertyMap.

@Override
public Map<String, ?> getJpaPropertyMap(TransactionManager transactionManager) {
    // TODO: Inorder to support external transaction manager, need to fix these property map
    // properly.
    Map<String, Object> jpaProperties = new HashMap<String, Object>();
    if (getDataSource() != null) {
        jpaProperties.put("openjpa.ConnectionFactory", getDataSource());
        String dbDictionary = determineDbDictionary();
        if (dbDictionary != null) {
            log.info("[Attachment-Mgt OpenJPA] DB Dictionary: " + dbDictionary);
            jpaProperties.put("openjpa.jdbc.DBDictionary", dbDictionary);
        }
    // jpaProperties.put("openjpa.jdbc.TransactionIsolation", "read-committed");
    }
    if (isGenerateDDL()) {
        log.info("[Attachment-Mgt OpenJPA] Generate DDL Enabled.");
        jpaProperties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
    }
    if (isShowSQL()) {
        log.info("[Attachment-Mgt OpenJPA] Show SQL enabled.");
        jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE");
        jpaProperties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72");
    }
    if (transactionManager != null) {
        // Using managed transactions
        jpaProperties.put("openjpa.ConnectionFactoryMode", "managed");
        jpaProperties.put("openjpa.ManagedRuntime", new TransactionManagerProvider(transactionManager));
    }
    jpaProperties.put("openjpa.Id", "Attachment-Mgt-PU");
    jpaProperties.put("openjpa.QueryCache", "false");
    jpaProperties.put("openjpa.DataCache", "false");
    jpaProperties.put("openjpa.jdbc.QuerySQLCache", "false");
    return jpaProperties;
}
Also used : HashMap(java.util.HashMap) TransactionManagerProvider(org.wso2.carbon.attachment.mgt.core.dao.impl.TransactionManagerProvider)

Example 17 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-business-process by wso2.

the class HistoricDetailService method getHistoricDetailInfo.

@GET
@Path("/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getHistoricDetailInfo() {
    Map<String, String> allRequestParams = new HashMap<>();
    for (String property : allPropertiesList) {
        String value = uriInfo.getQueryParameters().getFirst(property);
        if (value != null) {
            allRequestParams.put(property, value);
        }
    }
    // Populate query based on request
    HistoricDetailQueryRequest queryRequest = new HistoricDetailQueryRequest();
    if (allRequestParams.get("id") != null) {
        queryRequest.setId(allRequestParams.get("id"));
    }
    if (allRequestParams.get("processInstanceId") != null) {
        queryRequest.setProcessInstanceId(allRequestParams.get("processInstanceId"));
    }
    if (allRequestParams.get("executionId") != null) {
        queryRequest.setExecutionId(allRequestParams.get("executionId"));
    }
    if (allRequestParams.get("activityInstanceId") != null) {
        queryRequest.setActivityInstanceId(allRequestParams.get("activityInstanceId"));
    }
    if (allRequestParams.get("taskId") != null) {
        queryRequest.setTaskId(allRequestParams.get("taskId"));
    }
    if (allRequestParams.get("selectOnlyFormProperties") != null) {
        queryRequest.setSelectOnlyFormProperties(Boolean.valueOf(allRequestParams.get("selectOnlyFormProperties")));
    }
    if (allRequestParams.get("selectOnlyVariableUpdates") != null) {
        queryRequest.setSelectOnlyVariableUpdates(Boolean.valueOf(allRequestParams.get("selectOnlyVariableUpdates")));
    }
    DataResponse dataResponse = getQueryResponse(queryRequest, allRequestParams, uriInfo);
    return Response.ok().entity(dataResponse).build();
}
Also used : HashMap(java.util.HashMap) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) HistoricDetailQueryRequest(org.wso2.carbon.bpmn.rest.model.history.HistoricDetailQueryRequest) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 18 with Property

use of org.wso2.carbon.event.output.adapter.core.Property 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);
    }
}
Also used : BPMNJsonException(org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) XMLDocument(org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument) SAXException(org.xml.sax.SAXException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Resource(org.wso2.carbon.registry.api.Resource) Registry(org.wso2.carbon.registry.api.Registry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.api.RegistryException) Header(org.apache.http.Header) XMLStreamException(javax.xml.stream.XMLStreamException) RealmService(org.wso2.carbon.user.core.service.RealmService) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) BPMNXmlException(org.wso2.carbon.bpmn.core.types.datatypes.xml.BPMNXmlException)

Example 19 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-business-process by wso2.

the class FormDataService method submitForm.

@POST
@Path("/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response submitForm(SubmitFormRequest submitRequest) {
    if (submitRequest == null) {
        throw new ActivitiException("A request body was expected when executing the form submit.");
    }
    if (submitRequest.getTaskId() == null && submitRequest.getProcessDefinitionId() == null) {
        throw new ActivitiIllegalArgumentException("The taskId or processDefinitionId property has to be provided");
    }
    Map<String, String> propertyMap = new HashMap<String, String>();
    if (submitRequest.getProperties() != null) {
        for (RestFormProperty formProperty : submitRequest.getProperties()) {
            propertyMap.put(formProperty.getId(), formProperty.getValue());
        }
    }
    FormService formService = BPMNOSGIService.getFormService();
    Response.ResponseBuilder response = Response.ok();
    if (submitRequest.getTaskId() != null) {
        formService.submitTaskFormData(submitRequest.getTaskId(), propertyMap);
        response.status(Response.Status.NO_CONTENT);
        return response.build();
    } else {
        ProcessInstance processInstance = null;
        if (submitRequest.getBusinessKey() != null) {
            processInstance = formService.submitStartFormData(submitRequest.getProcessDefinitionId(), submitRequest.getBusinessKey(), propertyMap);
        } else {
            processInstance = formService.submitStartFormData(submitRequest.getProcessDefinitionId(), propertyMap);
        }
        ProcessInstanceResponse processInstanceResponse = new RestResponseFactory().createProcessInstanceResponse(processInstance, uriInfo.getBaseUri().toString());
        return response.entity(processInstanceResponse).build();
    }
}
Also used : ProcessInstanceResponse(org.wso2.carbon.bpmn.rest.model.runtime.ProcessInstanceResponse) Response(javax.ws.rs.core.Response) ActivitiException(org.activiti.engine.ActivitiException) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) HashMap(java.util.HashMap) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) FormService(org.activiti.engine.FormService) ProcessInstanceResponse(org.wso2.carbon.bpmn.rest.model.runtime.ProcessInstanceResponse) RestFormProperty(org.wso2.carbon.bpmn.rest.model.form.RestFormProperty) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 20 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticatorTest method testGetConfigurationProperties.

@Test
public void testGetConfigurationProperties() {
    List<Property> configProperties = new ArrayList<Property>();
    Property smsUrl = new Property();
    configProperties.add(smsUrl);
    Property httpMethod = new Property();
    configProperties.add(httpMethod);
    Property headers = new Property();
    configProperties.add(headers);
    Property payload = new Property();
    configProperties.add(payload);
    Property httpResponse = new Property();
    configProperties.add(httpResponse);
    Assert.assertEquals(configProperties.size(), smsotpAuthenticator.getConfigurationProperties().size());
}
Also used : ArrayList(java.util.ArrayList) Property(org.wso2.carbon.identity.application.common.model.Property) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)32 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 Resource (org.wso2.carbon.registry.core.Resource)23 Map (java.util.Map)21 Test (org.junit.Test)21 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 DataResponse (org.wso2.carbon.bpmn.rest.model.common.DataResponse)17 API (org.wso2.carbon.apimgt.api.model.API)16 UserStoreException (org.wso2.carbon.user.api.UserStoreException)16 Path (javax.ws.rs.Path)14 Produces (javax.ws.rs.Produces)14 JSONObject (org.json.simple.JSONObject)14 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)14 List (java.util.List)13 IOException (java.io.IOException)11 QName (javax.xml.namespace.QName)11 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)11 Properties (java.util.Properties)10 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)10