Search in sources :

Example 1 with WorkflowProperties

use of org.wso2.carbon.apimgt.impl.dto.WorkflowProperties in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method setOAuthApplicationInfo.

/**
 * set information that are needed to invoke callback service
 */
private void setOAuthApplicationInfo(APIStateWorkflowDTO apiStateWorkFlowDTO) throws WorkflowException {
    // if credentials are not defined in the workflow-extension.xml file call dcr endpoint and generate a
    // oauth application and pass the client id and secret
    WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (clientId == null || clientSecret == null) {
        String dcrUsername = workflowProperties.getdCREndpointUser();
        String dcrPassword = workflowProperties.getdCREndpointPassword();
        byte[] encodedAuth = Base64.encodeBase64((dcrUsername + ":" + dcrPassword).getBytes(Charset.forName("ISO-8859-1")));
        JSONObject payload = new JSONObject();
        payload.put(PayloadConstants.KEY_OAUTH_APPNAME, WorkflowConstants.WORKFLOW_OAUTH_APP_NAME);
        payload.put(PayloadConstants.KEY_OAUTH_OWNER, dcrUsername);
        payload.put(PayloadConstants.KEY_OAUTH_SAASAPP, "true");
        payload.put(PayloadConstants.KEY_OAUTH_GRANT_TYPES, WorkflowConstants.WORKFLOW_OAUTH_APP_GRANT_TYPES);
        URL serviceEndpointURL = new URL(workflowProperties.getdCREndPoint());
        HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
        HttpPost httpPost = new HttpPost(workflowProperties.getdCREndPoint());
        String authHeader = "Basic " + new String(encodedAuth);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        StringEntity requestEntity = new StringEntity(payload.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                String responseStr = EntityUtils.toString(entity);
                if (log.isDebugEnabled()) {
                    log.debug("Workflow oauth app created: " + responseStr);
                }
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse(responseStr);
                clientId = (String) obj.get(PayloadConstants.VARIABLE_CLIENTID);
                clientSecret = (String) obj.get(PayloadConstants.VARIABLE_CLIENTSECRET);
            } else {
                String error = "Error while starting the process:  " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
                log.error(error);
                throw new WorkflowException(error);
            }
        } catch (ClientProtocolException e) {
            String errorMsg = "Error while creating the http client";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = "Error while connecting to dcr endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (ParseException e) {
            String errorMsg = "Error while parsing response from DCR endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } finally {
            httpPost.reset();
        }
    }
    apiStateWorkFlowDTO.setClientId(clientId);
    apiStateWorkFlowDTO.setClientSecret(clientSecret);
    apiStateWorkFlowDTO.setScope(WorkflowConstants.API_WF_SCOPE);
    apiStateWorkFlowDTO.setTokenAPI(workflowProperties.getTokenEndPoint());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 2 with WorkflowProperties

use of org.wso2.carbon.apimgt.impl.dto.WorkflowProperties in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method cleanUpPendingTask.

/**
 * Handle cleanup task for api state change workflow ws executor. This queries the BPMN process related to the given
 * workflow reference id and delete that process
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for APIStateChangeWSWorkflowExecutor for :" + workflowExtRef);
    }
    String errorMsg;
    if (serviceEndpoint == null) {
        // set the bps endpoint from the global configurations
        WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
        serviceEndpoint = workflowProperties.getServerUrl();
    }
    URL serviceEndpointURL = new URL(serviceEndpoint);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    // get the basic auth header value to connect to the bpmn process
    String authHeader = getBasicAuthHeader();
    JSONParser parser = new JSONParser();
    HttpGet httpGet = null;
    HttpDelete httpDelete = null;
    try {
        // Get the process instance details related to the given workflow reference id. If there is a process that
        // is already started with the given wf reference as the businesskey, that process needes to be deleted
        httpGet = new HttpGet(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH + "?businessKey=" + workflowExtRef);
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String processId = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // already exists a process related to the given workflow reference
            String responseStr = EntityUtils.toString(entity);
            if (log.isDebugEnabled()) {
                log.debug("Process instance details for ref : " + workflowExtRef + ": " + responseStr);
            }
            JSONObject obj = (JSONObject) parser.parse(responseStr);
            JSONArray data = (JSONArray) obj.get(PayloadConstants.DATA);
            if (data != null) {
                JSONObject instanceDetails = (JSONObject) data.get(0);
                // extract the id related to that process. this id is used to delete the process
                processId = (String) instanceDetails.get(PayloadConstants.ID);
            }
            if (processId != null) {
                // delete the process using the id
                httpDelete = new HttpDelete(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH + "/" + processId);
                httpDelete.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
                response = httpClient.execute(httpDelete);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
                    errorMsg = "Error while deleting process instance details for " + workflowExtRef + " code: " + response.getStatusLine().getStatusCode();
                    log.error(errorMsg);
                    throw new WorkflowException(errorMsg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Successfully deleted process instance for  : " + workflowExtRef);
                }
                // remove entry from the db
                ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
                apiMgtDAO.removeWorkflowEntry(workflowExtRef, WorkflowConstants.WF_TYPE_AM_API_STATE.toString());
            }
        } else {
            errorMsg = "Error while getting process instance details for " + workflowExtRef + " code: " + response.getStatusLine().getStatusCode();
            log.error(errorMsg);
            throw new WorkflowException(errorMsg);
        }
    } catch (ClientProtocolException e) {
        log.error("Error while creating the http client", e);
        throw new WorkflowException("Error while creating the http client", e);
    } catch (IOException e) {
        log.error("Error while connecting to the BPMN process server from the WorkflowExecutor.", e);
        throw new WorkflowException("Error while connecting to the external service", e);
    } catch (ParseException e) {
        log.error("Error while parsing response from BPS server", e);
        throw new WorkflowException("Error while parsing response from BPS server", e);
    } catch (APIManagementException e) {
        log.error("Error removing the workflow entry", e);
        throw new WorkflowException("Error removing the workflow entry", e);
    } finally {
        if (httpGet != null) {
            httpGet.reset();
        }
        if (httpDelete != null) {
            httpDelete.reset();
        }
    }
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.simple.JSONArray) HttpResponse(org.apache.http.HttpResponse) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 3 with WorkflowProperties

use of org.wso2.carbon.apimgt.impl.dto.WorkflowProperties in project carbon-apimgt by wso2.

the class APIProviderImplTest method prepareForChangeLifeCycleStatus.

/**
 * This method can be used when invoking changeLifeCycleStatus()
 */
private void prepareForChangeLifeCycleStatus(APIProviderImplWrapper apiProvider, ApiMgtDAO apimgtDAO, APIIdentifier apiId, GenericArtifact apiArtifact) throws GovernanceException, APIManagementException, FaultGatewaysException, WorkflowException, XMLStreamException {
    Mockito.when(APIUtil.getAPIArtifact(apiId, apiProvider.registry)).thenReturn(apiArtifact);
    Mockito.when(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn("admin");
    Mockito.when(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME)).thenReturn("API1");
    Mockito.when(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION)).thenReturn("1.0.0");
    Mockito.when(apiArtifact.getLifecycleState()).thenReturn("CREATED");
    Mockito.when(apimgtDAO.getAPIID(apiUUID)).thenReturn(1);
    // Workflow has not started, this will trigger the executor
    WorkflowDTO wfDTO1 = Mockito.mock(WorkflowDTO.class);
    Mockito.when(wfDTO1.getStatus()).thenReturn(null);
    WorkflowDTO wfDTO2 = Mockito.mock(WorkflowDTO.class);
    Mockito.when(wfDTO2.getStatus()).thenReturn(WorkflowStatus.APPROVED);
    Mockito.when(apimgtDAO.retrieveWorkflowFromInternalReference("1", WorkflowConstants.WF_TYPE_AM_API_STATE)).thenReturn(wfDTO1, wfDTO2);
    ServiceReferenceHolder sh = TestUtils.getServiceReferenceHolder();
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
    WorkflowProperties workflowProperties = Mockito.mock(WorkflowProperties.class);
    Mockito.when(workflowProperties.getWorkflowCallbackAPI()).thenReturn("");
    Mockito.when(amConfig.getWorkflowProperties()).thenReturn(workflowProperties);
    WorkflowExecutorFactory wfe = PowerMockito.mock(WorkflowExecutorFactory.class);
    Mockito.when(WorkflowExecutorFactory.getInstance()).thenReturn(wfe);
    WorkflowExecutor apiStateWFExecutor = new APIStateChangeSimpleWorkflowExecutor();
    Mockito.when(wfe.getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE)).thenReturn(apiStateWFExecutor);
    Mockito.when(APIUtil.isAnalyticsEnabled()).thenReturn(false);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) WorkflowExecutorFactory(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutorFactory) APIStateChangeSimpleWorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.APIStateChangeSimpleWorkflowExecutor) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) APIStateChangeSimpleWorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.APIStateChangeSimpleWorkflowExecutor) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)

Example 4 with WorkflowProperties

use of org.wso2.carbon.apimgt.impl.dto.WorkflowProperties in project carbon-apimgt by wso2.

the class APIProviderImpl method setAPIStateWorkflowDTOParameters.

/**
 * Set API or API Product state change workflow parameters
 *
 * @param currentStatus Current state of the API or API Product
 * @param action        LC state change action
 * @param name          Name of the API or API Product
 * @param context       Context of the API or API Product
 * @param apiType       API or API Product
 * @param version       Version of API or API Product
 * @param providerName  Owner of the API or API Product
 * @param apiOrApiProductId Unique ID of the API or API Product
 * @param uuid              Unique UUID of the API or API Product
 * @param gatewayVendor     Gateway Vendor
 * @param workflowType      Workflow Type
 * @param apiStateWFExecutor    WorkflowExecutor
 * @return APIStateWorkflowDTO Object
 */
private APIStateWorkflowDTO setAPIStateWorkflowDTOParameters(String currentStatus, String action, String name, String context, String apiType, String version, String providerName, int apiOrApiProductId, String uuid, String gatewayVendor, String workflowType, WorkflowExecutor apiStateWFExecutor) {
    WorkflowProperties workflowProperties = getAPIManagerConfiguration().getWorkflowProperties();
    APIStateWorkflowDTO stateWorkflowDTO = new APIStateWorkflowDTO();
    stateWorkflowDTO.setApiCurrentState(currentStatus);
    stateWorkflowDTO.setApiLCAction(action);
    stateWorkflowDTO.setApiName(name);
    stateWorkflowDTO.setApiContext(context);
    stateWorkflowDTO.setApiType(apiType);
    stateWorkflowDTO.setApiVersion(version);
    stateWorkflowDTO.setApiProvider(providerName);
    stateWorkflowDTO.setGatewayVendor(gatewayVendor);
    stateWorkflowDTO.setCallbackUrl(workflowProperties.getWorkflowCallbackAPI());
    stateWorkflowDTO.setExternalWorkflowReference(apiStateWFExecutor.generateUUID());
    stateWorkflowDTO.setTenantId(tenantId);
    stateWorkflowDTO.setTenantDomain(this.tenantDomain);
    stateWorkflowDTO.setWorkflowType(workflowType);
    stateWorkflowDTO.setStatus(WorkflowStatus.CREATED);
    stateWorkflowDTO.setCreatedTime(System.currentTimeMillis());
    stateWorkflowDTO.setWorkflowReference(Integer.toString(apiOrApiProductId));
    stateWorkflowDTO.setInvoker(this.username);
    stateWorkflowDTO.setApiUUID(uuid);
    String workflowDescription = "Pending lifecycle state change action: " + action;
    stateWorkflowDTO.setWorkflowDescription(workflowDescription);
    return stateWorkflowDTO;
}
Also used : APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)

Example 5 with WorkflowProperties

use of org.wso2.carbon.apimgt.impl.dto.WorkflowProperties in project carbon-apimgt by wso2.

the class APIAdminImpl method getworkflowReferenceByExternalWorkflowReferenceID.

/**
 * The method converts the date into timestamp
 *
 * @param externelWorkflowRef External Workflow Reference of workflow pending request
 * @param status              Workflow status of workflow pending request
 * @param tenantDomain        tenant domain of user
 * @return Workflow pending request
 * @throws APIManagementException
 */
public Workflow getworkflowReferenceByExternalWorkflowReferenceID(String externelWorkflowRef, String status, String tenantDomain) throws APIManagementException {
    Workflow workflow = null;
    WorkflowProperties workflowConfig = org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (workflowConfig.isListTasks()) {
        workflow = apiMgtDAO.getworkflowReferenceByExternalWorkflowReferenceID(externelWorkflowRef, status, tenantDomain);
    }
    if (workflow == null) {
        String msg = "External workflow Reference: " + externelWorkflowRef + " was not found.";
        throw new APIMgtResourceNotFoundException(msg);
    }
    return workflow;
}
Also used : Workflow(org.wso2.carbon.apimgt.api.model.Workflow) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)

Aggregations

WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)8 IOException (java.io.IOException)3 URL (org.apache.axis2.util.URL)3 HttpResponse (org.apache.http.HttpResponse)3 ClientProtocolException (org.apache.http.client.ClientProtocolException)3 HttpClient (org.apache.http.client.HttpClient)3 JSONObject (org.json.simple.JSONObject)3 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 HttpEntity (org.apache.http.HttpEntity)2 HttpPost (org.apache.http.client.methods.HttpPost)2 StringEntity (org.apache.http.entity.StringEntity)2 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)2 APIStateWorkflowDTO (org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO)2 WorkflowExecutor (org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)2 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1