Search in sources :

Example 41 with Workflow

use of org.wso2.carbon.apimgt.api.model.Workflow in project carbon-apimgt by wso2.

the class APIStoreImplTestCase method testAddApplicationWorkflowReject.

@Test(description = "Test Application workflow rejection")
public void testAddApplicationWorkflowReject() throws APIManagementException {
    ApplicationDAO applicationDAO = Mockito.mock(ApplicationDAO.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    WorkflowDAO workflowDAO = Mockito.mock(WorkflowDAO.class);
    Policy policy = Mockito.mock(Policy.class);
    APIGateway apiGateway = Mockito.mock(APIGateway.class);
    APIStore apiStore = getApiStoreImpl(applicationDAO, policyDAO, workflowDAO, apiGateway);
    Application application = new Application(APP_NAME, USER_NAME);
    application.setPolicy(new ApplicationPolicy(TIER));
    application.setPermissionString("[{\"groupId\": \"testGroup\",\"permission\":[\"READ\",\"UPDATE\",\"DELETE\",\"SUBSCRIPTION\"]}]");
    Mockito.when(applicationDAO.isApplicationNameExists(APP_NAME)).thenReturn(false);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, TIER)).thenReturn(policy);
    apiStore.addApplication(application);
    DefaultWorkflowExecutor executor = Mockito.mock(DefaultWorkflowExecutor.class);
    Workflow workflow = new ApplicationCreationWorkflow(applicationDAO, workflowDAO, apiGateway);
    workflow.setWorkflowReference(application.getId());
    WorkflowResponse response = new GeneralWorkflowResponse();
    response.setWorkflowStatus(WorkflowStatus.REJECTED);
    Mockito.when(executor.complete(workflow)).thenReturn(response);
    apiStore.completeWorkflow(executor, workflow);
    Mockito.verify(applicationDAO, Mockito.times(1)).updateApplicationState(application.getId(), "REJECTED");
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Workflow(org.wso2.carbon.apimgt.core.workflow.Workflow) ApplicationCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationWorkflow) ApplicationUpdateWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationUpdateWorkflow) SubscriptionCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.SubscriptionCreationWorkflow) ApplicationDAO(org.wso2.carbon.apimgt.core.dao.ApplicationDAO) DefaultWorkflowExecutor(org.wso2.carbon.apimgt.core.workflow.DefaultWorkflowExecutor) WorkflowDAO(org.wso2.carbon.apimgt.core.dao.WorkflowDAO) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) ApplicationCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationWorkflow) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) Application(org.wso2.carbon.apimgt.core.models.Application) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 42 with Workflow

use of org.wso2.carbon.apimgt.api.model.Workflow in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateDevPortalAPIInformation.

protected void populateDevPortalAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    // TODO try to use a single query to get info from db
    // Ratings
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    api.setRating(APIUtil.getAverageRating(internalId));
    apiId.setId(internalId);
    // api level tier
    String apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString = null;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    for (URITemplate uriTemplate : uriTemplates) {
        String uTemplate = uriTemplate.getUriTemplate();
        String method = uriTemplate.getHTTPVerb();
        List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
        List<Scope> newTemplateScopes = new ArrayList<>();
        if (!oldTemplateScopes.isEmpty()) {
            for (Scope templateScope : oldTemplateScopes) {
                Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                newTemplateScopes.add(scope);
            }
        }
        uriTemplate.addAllScopes(newTemplateScopes);
        uriTemplate.setResourceURI(api.getUrl());
        uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        // AWS Lambda: set arn & timeout to URI template
        if (paths != null) {
            JSONObject path = (JSONObject) paths.get(uTemplate);
            if (path != null) {
                JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                if (operation != null) {
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
            }
        }
    }
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        for (URITemplate template : uriTemplates) {
            template.setMediationScript(template.getAggregatedMediationScript());
        }
    }
    api.setUriTemplates(uriTemplates);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 43 with Workflow

use of org.wso2.carbon.apimgt.api.model.Workflow in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
    for (APIProductResource resource : resources) {
        List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
        ListIterator it = resourceScopes.listIterator();
        while (it.hasNext()) {
            Scope resourceScope = (Scope) it.next();
            String scopeKey = resourceScope.getKey();
            if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                resourceScope = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 44 with Workflow

use of org.wso2.carbon.apimgt.api.model.Workflow in project carbon-apimgt by wso2.

the class TenantWorkflowConfigHolder method load.

public void load() throws WorkflowException, RegistryException {
    workflowExecutorMap = new ConcurrentHashMap<>();
    InputStream in = null;
    try {
        String workFlowConfig = ServiceReferenceHolder.getInstance().getApimConfigService().getWorkFlowConfig(tenantDomain);
        if (StringUtils.isNotEmpty(workFlowConfig)) {
            in = new ByteArrayInputStream(workFlowConfig.getBytes());
            StAXOMBuilder builder = new StAXOMBuilder(in);
            secretResolver = SecretResolverFactory.create(builder.getDocumentElement(), true);
            OMElement workflowExtensionsElem = builder.getDocument().getFirstChildWithName(new QName(WorkflowConstants.WORKFLOW_EXTENSIONS));
            OMElement workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.APPLICATION_CREATION));
            String executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            Class clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            WorkflowExecutor workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.PRODUCTION_APPLICATION_REGISTRATION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SANDBOX_APPLICATION_REGISTRATION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.USER_SIGN_UP));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_CREATION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_UPDATE));
            if (workflowElem != null) {
                executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
                clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
                workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
                loadProperties(workflowElem, workFlowExecutor);
                workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE, workFlowExecutor);
            } else {
                executorClass = DEFAULT_SUBSCRIPTION_UPDATE_EXECUTOR_CLASS;
                clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
                workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
                workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE, workFlowExecutor);
            }
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_DELETION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.APPLICATION_DELETION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.API_STATE_CHANGE));
            if (workflowElem == null) {
                // TO handle migrated environment, create the default simple workflow executor
                workflowElem = OMAbstractFactory.getOMFactory().createOMElement(new QName(WorkflowConstants.API_STATE_CHANGE));
                executorClass = WorkflowConstants.DEFAULT_EXECUTOR_API_STATE_CHANGE;
                workflowElem.addAttribute(WorkflowConstants.EXECUTOR, executorClass, null);
            } else {
                executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            }
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_API_STATE, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.API_PRODUCT_STATE_CHANGE));
            if (workflowElem == null) {
                // To handle migration, create the default simple workflow executor
                workflowElem = OMAbstractFactory.getOMFactory().createOMElement(new QName(WorkflowConstants.API_PRODUCT_STATE_CHANGE));
                executorClass = WorkflowConstants.DEFAULT_EXECUTOR_API_PRODUCT_STATE_CHANGE;
                workflowElem.addAttribute(WorkflowConstants.EXECUTOR, executorClass, null);
            } else {
                executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            }
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE, workFlowExecutor);
        }
    } catch (XMLStreamException e) {
        log.error("Error building xml", e);
        handleException("Error building xml", e);
    } catch (ClassNotFoundException e) {
        log.error("Unable to find class", e);
        handleException("Unable to find class", e);
    } catch (InstantiationException e) {
        log.error("Unable to instantiate class", e);
        handleException("Unable to instantiate class", e);
    } catch (IllegalAccessException e) {
        log.error("Illegal attempt to invoke class methods", e);
        handleException("Illegal attempt to invoke class methods", e);
    } catch (WorkflowException e) {
        log.error("Unable to load workflow executor class", e);
        handleException("Unable to load workflow executor class", e);
    } catch (APIManagementException e) {
        log.error("Unable to retrieve workflow configurations", e);
        handleException("Unable to retrieve workflow configurations", e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) XMLStreamException(javax.xml.stream.XMLStreamException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) StAXOMBuilder(org.apache.axiom.om.impl.builder.StAXOMBuilder)

Example 45 with Workflow

use of org.wso2.carbon.apimgt.api.model.Workflow 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)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 Test (org.junit.Test)35 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)35 Workflow (org.wso2.carbon.apimgt.core.workflow.Workflow)28 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)26 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)25 Test (org.testng.annotations.Test)24 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)22 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)21 HashMap (java.util.HashMap)20 SubscriptionWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO)20 WorkflowDAO (org.wso2.carbon.apimgt.core.dao.WorkflowDAO)19 JSONObject (org.json.simple.JSONObject)17 ApplicationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO)17 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)16 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)15 WorkflowExecutor (org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)15 Application (org.wso2.carbon.apimgt.api.model.Application)14 ArrayList (java.util.ArrayList)12 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)11