Search in sources :

Example 11 with ApplicationWorkflowDTO

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

the class ApplicationCreationWSWorkflowExecutorTest method testWorkflowExecuteWithLimitedParam.

@Test
public void testWorkflowExecuteWithLimitedParam() throws Exception {
    // application without a callback url
    ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO();
    Application application = new Application("TestAPP", new Subscriber(null));
    application.setTier("Gold");
    application.setDescription("Description");
    workflowDTO.setApplication(application);
    workflowDTO.setTenantDomain("wso2");
    workflowDTO.setUserName("admin");
    workflowDTO.setWorkflowReference("1");
    workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString());
    PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED);
    ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234);
    ServiceReferenceHolderMockCreator.initContextService();
    PowerMockito.whenNew(ServiceClient.class).withArguments(Mockito.any(ConfigurationContext.class), Mockito.any(AxisService.class)).thenReturn(serviceClient);
    try {
        Assert.assertNotNull(applicationCreationWSWorkflowExecutor.execute(workflowDTO));
    } catch (WorkflowException e) {
        Assert.fail("Unexpected WorkflowException occurred while executing Application creation ws workflow");
    }
}
Also used : ServiceReferenceHolderMockCreator(org.wso2.carbon.apimgt.impl.ServiceReferenceHolderMockCreator) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) Application(org.wso2.carbon.apimgt.api.model.Application) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 12 with ApplicationWorkflowDTO

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

the class ApplicationCreationWSWorkflowExecutor method execute.

@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing Application creation Workflow.");
    }
    super.execute(workflowDTO);
    try {
        String action = WorkflowConstants.CREATE_APPLICATION_WS_ACTION;
        ServiceClient client = getClient(action);
        String payload = "<wor:ApplicationApprovalWorkFlowProcessRequest xmlns:wor=\"http://workflow.application.apimgt" + ".carbon.wso2.org\">\n" + "        <wor:applicationName>$1</wor:applicationName>\n" + "        <wor:applicationTier>$2</wor:applicationTier>\n" + "        <wor:applicationCallbackUrl>$3</wor:applicationCallbackUrl>\n" + "        <wor:applicationDescription>$4</wor:applicationDescription>\n" + "        <wor:tenantDomain>$5</wor:tenantDomain>\n" + "        <wor:userName>$6</wor:userName>\n" + "        <wor:workflowExternalRef>$7</wor:workflowExternalRef>\n" + "        <wor:callBackURL>$8</wor:callBackURL>\n" + "      </wor:ApplicationApprovalWorkFlowProcessRequest>";
        ApplicationWorkflowDTO appWorkFlowDTO = (ApplicationWorkflowDTO) workflowDTO;
        Application application = appWorkFlowDTO.getApplication();
        String callBackURL = appWorkFlowDTO.getCallbackUrl();
        payload = payload.replace("$1", application.getName());
        payload = payload.replace("$2", application.getTier());
        payload = payload.replace("$3", application.getCallbackUrl() == null ? "" : application.getCallbackUrl());
        payload = payload.replace("$4", application.getDescription() == null ? "" : application.getDescription());
        payload = payload.replace("$5", appWorkFlowDTO.getTenantDomain());
        payload = payload.replace("$6", appWorkFlowDTO.getUserName());
        payload = payload.replace("$7", appWorkFlowDTO.getExternalWorkflowReference());
        payload = payload.replace("$8", callBackURL != null ? callBackURL : "?");
        client.fireAndForget(AXIOMUtil.stringToOM(payload));
    } catch (AxisFault axisFault) {
        log.error("Error sending out message", axisFault);
        throw new WorkflowException("Error sending out message", axisFault);
    } catch (XMLStreamException e) {
        log.error("Error converting String to OMElement", e);
        throw new WorkflowException("Error converting String to OMElement", e);
    }
    return new GeneralWorkflowResponse();
}
Also used : AxisFault(org.apache.axis2.AxisFault) XMLStreamException(javax.xml.stream.XMLStreamException) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) ServiceClient(org.apache.axis2.client.ServiceClient) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 13 with ApplicationWorkflowDTO

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

the class ApplicationCreationApprovalWorkflowExecutor method execute.

/**
 * Execute the Application Creation workflow approval process.
 *
 * @param workflowDTO
 */
@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing Application creation Workflow.");
    }
    ApplicationWorkflowDTO appWorkFlowDTO = (ApplicationWorkflowDTO) workflowDTO;
    Application application = appWorkFlowDTO.getApplication();
    String message = "Approve application " + application.getName() + " creation request from application creator -" + appWorkFlowDTO.getUserName() + " with throttling tier - " + application.getTier();
    workflowDTO.setWorkflowDescription(message);
    workflowDTO.setProperties("applicationName", application.getName());
    workflowDTO.setProperties("userName", appWorkFlowDTO.getUserName());
    workflowDTO.setProperties("applicationTier", application.getTier());
    super.execute(workflowDTO);
    return new GeneralWorkflowResponse();
}
Also used : ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 14 with ApplicationWorkflowDTO

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

the class APIConsumerImpl method removeApplication.

/**
 * Function to remove an Application from the API Store
 *
 * @param application - The Application Object that represents the Application
 * @param username
 * @throws APIManagementException
 */
@Override
public void removeApplication(Application application, String username) throws APIManagementException {
    String uuid = application.getUUID();
    Map<String, Pair<String, String>> consumerKeysOfApplication = null;
    if (application.getId() == 0 && !StringUtils.isEmpty(uuid)) {
        application = apiMgtDAO.getApplicationByUUID(uuid);
    }
    consumerKeysOfApplication = apiMgtDAO.getConsumerKeysForApplication(application.getId());
    boolean isTenantFlowStarted = false;
    int applicationId = application.getId();
    boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
    boolean isUserAppOwner;
    if (isCaseInsensitiveComparisons) {
        isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(username);
    } else {
        isUserAppOwner = application.getSubscriber().getName().equals(username);
    }
    if (!isUserAppOwner) {
        throw new APIManagementException("user: " + username + ", " + "attempted to remove application owned by: " + application.getSubscriber().getName());
    }
    try {
        String workflowExtRef;
        ApplicationWorkflowDTO workflowDTO;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        WorkflowExecutor createApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        WorkflowExecutor createSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        WorkflowExecutor createProductionRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        WorkflowExecutor createSandboxRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        WorkflowExecutor removeApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceByApplicationID(application.getId());
        // in a normal flow workflowExtRef is null when workflows are not enabled
        if (workflowExtRef == null) {
            workflowDTO = new ApplicationWorkflowDTO();
        } else {
            workflowDTO = (ApplicationWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
        }
        workflowDTO.setApplication(application);
        workflowDTO.setCallbackUrl(removeApplicationWFExecutor.getCallbackURL());
        workflowDTO.setUserName(this.username);
        workflowDTO.setTenantDomain(tenantDomain);
        workflowDTO.setTenantId(tenantId);
        // clean up pending subscription tasks
        Set<Integer> pendingSubscriptions = apiMgtDAO.getPendingSubscriptionsByApplicationId(applicationId);
        for (int subscription : pendingSubscriptions) {
            try {
                workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(subscription);
                createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (APIManagementException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to get external workflow reference for subscription " + subscription);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending subscription approval task: " + subscription);
            }
        }
        // cleanup pending application registration tasks
        Map<String, String> keyManagerWiseProductionKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION);
        Map<String, String> keyManagerWiseSandboxKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_SANDBOX);
        keyManagerWiseProductionKeyStatus.forEach((keyManagerName, state) -> {
            if (WorkflowStatus.CREATED.toString().equals(state)) {
                try {
                    String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION, keyManagerName);
                    createProductionRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
                } catch (APIManagementException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to get external workflow reference for production key of application " + applicationId);
                } catch (WorkflowException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to clean pending production key approval task of " + applicationId);
                }
            }
        });
        keyManagerWiseSandboxKeyStatus.forEach((keyManagerName, state) -> {
            if (WorkflowStatus.CREATED.toString().equals(state)) {
                try {
                    String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_SANDBOX, keyManagerName);
                    createSandboxRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
                } catch (APIManagementException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to get external workflow reference for sandbox key of application " + applicationId);
                } catch (WorkflowException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to clean pending sandbox key approval task of " + applicationId);
                }
            }
        });
        if (workflowExtRef != null) {
            try {
                createApplicationWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending application approval task of " + applicationId);
            }
        }
        // update attributes of the new remove workflow to be created
        workflowDTO.setStatus(WorkflowStatus.CREATED);
        workflowDTO.setCreatedTime(System.currentTimeMillis());
        workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowDTO.setExternalWorkflowReference(removeApplicationWFExecutor.generateUUID());
        removeApplicationWFExecutor.execute(workflowDTO);
        JSONObject appLogObject = new JSONObject();
        appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
        appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
        appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
        appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
        appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    } catch (WorkflowException e) {
        String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION + " " + "for applicationID " + application.getId();
        handleException(errorMsg, e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    if (log.isDebugEnabled()) {
        String logMessage = "Application Name: " + application.getName() + " successfully removed";
        log.debug(logMessage);
    }
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(applicationId, username, requestedTenant);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // get the workflow state once the executor is executed.
    WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(applicationId), WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
    // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
    if (wfDTO != null) {
        if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus()) || wfDTO.getStatus() == null) {
            ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
            APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
        }
    } else {
        ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
        APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
    }
    if (consumerKeysOfApplication != null && consumerKeysOfApplication.size() > 0) {
        for (Map.Entry<String, Pair<String, String>> entry : consumerKeysOfApplication.entrySet()) {
            String consumerKey = entry.getKey();
            String keyManagerName = entry.getValue().getKey();
            String keyManagerTenantDomain = entry.getValue().getValue();
            ApplicationRegistrationEvent removeEntryTrigger = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.REMOVE_APPLICATION_KEYMAPPING.name(), APIUtil.getTenantIdFromTenantDomain(keyManagerTenantDomain), keyManagerTenantDomain, application.getId(), application.getUUID(), consumerKey, application.getKeyType(), keyManagerName);
            APIUtil.sendNotification(removeEntryTrigger, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
        }
    }
}
Also used : ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) ApplicationRegistrationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Pair(org.apache.commons.lang3.tuple.Pair)

Example 15 with ApplicationWorkflowDTO

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

the class APIConsumerImpl method addApplication.

/**
 * Add a new Application from the store.
 * @param application - {@link org.wso2.carbon.apimgt.api.model.Application}
 * @param userId - {@link String}
 * @param organization
 * @return {@link String}
 */
@Override
public int addApplication(Application application, String userId, String organization) throws APIManagementException {
    if (APIUtil.isOnPremResolver()) {
        organization = tenantDomain;
    }
    if (application.getName() != null && (application.getName().length() != application.getName().trim().length())) {
        handleApplicationNameContainSpacesException("Application name " + "cannot contain leading or trailing white spaces");
    }
    validateApplicationPolicy(application, organization);
    JSONArray applicationAttributesFromConfig = getAppAttributesFromConfig(userId);
    Map<String, String> applicationAttributes = application.getApplicationAttributes();
    if (applicationAttributes == null) {
        /*
             * This empty Hashmap is set to avoid throwing a null pointer exception, in case no application attributes
             * are set when creating an application
             */
        applicationAttributes = new HashMap<String, String>();
    }
    Set<String> configAttributes = new HashSet<>();
    if (applicationAttributesFromConfig != null) {
        for (Object object : applicationAttributesFromConfig) {
            JSONObject attribute = (JSONObject) object;
            Boolean hidden = (Boolean) attribute.get(APIConstants.ApplicationAttributes.HIDDEN);
            Boolean required = (Boolean) attribute.get(APIConstants.ApplicationAttributes.REQUIRED);
            String attributeName = (String) attribute.get(APIConstants.ApplicationAttributes.ATTRIBUTE);
            String defaultValue = (String) attribute.get(APIConstants.ApplicationAttributes.DEFAULT);
            if (BooleanUtils.isTrue(hidden) && BooleanUtils.isTrue(required) && StringUtils.isEmpty(defaultValue)) {
                /*
                     * In case a default value is not provided for a required hidden attribute, an exception is thrown,
                     * we don't do this validation in server startup to support multi tenancy scenarios
                     */
                handleException("Default value not provided for hidden required attribute. Please check the " + "configuration");
            }
            configAttributes.add(attributeName);
            if (BooleanUtils.isTrue(required)) {
                if (BooleanUtils.isTrue(hidden)) {
                    /*
                         * If a required hidden attribute is attempted to be populated, we replace it with
                         * the default value.
                         */
                    String oldValue = applicationAttributes.put(attributeName, defaultValue);
                    if (StringUtils.isNotEmpty(oldValue)) {
                        log.info("Replaced provided value: " + oldValue + " with default the value" + " for the hidden application attribute: " + attributeName);
                    }
                } else if (!applicationAttributes.keySet().contains(attributeName)) {
                    if (StringUtils.isNotEmpty(defaultValue)) {
                        /*
                             * If a required attribute is not provided and a default value is given, we replace it with
                             * the default value.
                             */
                        applicationAttributes.put(attributeName, defaultValue);
                        log.info("Added default value: " + defaultValue + " as required attribute: " + attributeName + "is not provided");
                    } else {
                        /*
                             * If a required attribute is not provided but a default value not given, we throw a bad
                             * request exception.
                             */
                        handleException("Bad Request. Required application attribute not provided");
                    }
                }
            } else if (BooleanUtils.isTrue(hidden)) {
                /*
                     * If an optional hidden attribute is provided, we remove it and leave it blank, and leave it for
                     * an extension to populate it.
                     */
                applicationAttributes.remove(attributeName);
            }
        }
        application.setApplicationAttributes(validateApplicationAttributes(applicationAttributes, configAttributes));
    } else {
        application.setApplicationAttributes(null);
    }
    application.setUUID(UUID.randomUUID().toString());
    if (APIUtil.isApplicationExist(userId, application.getName(), application.getGroupId(), organization)) {
        handleResourceAlreadyExistsException("A duplicate application already exists by the name - " + application.getName());
    }
    // check whether callback url is empty and set null
    if (StringUtils.isBlank(application.getCallbackUrl())) {
        application.setCallbackUrl(null);
    }
    int applicationId = apiMgtDAO.addApplication(application, userId, organization);
    JSONObject appLogObject = new JSONObject();
    appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
    appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
    appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
    appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
    appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
    boolean isTenantFlowStarted = false;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
    }
    try {
        WorkflowExecutor appCreationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        ApplicationWorkflowDTO appWFDto = new ApplicationWorkflowDTO();
        appWFDto.setApplication(application);
        appWFDto.setExternalWorkflowReference(appCreationWFExecutor.generateUUID());
        appWFDto.setWorkflowReference(String.valueOf(applicationId));
        appWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        appWFDto.setCallbackUrl(appCreationWFExecutor.getCallbackURL());
        appWFDto.setStatus(WorkflowStatus.CREATED);
        appWFDto.setTenantDomain(organization);
        appWFDto.setTenantId(tenantId);
        appWFDto.setUserName(userId);
        appWFDto.setCreatedTime(System.currentTimeMillis());
        appCreationWFExecutor.execute(appWFDto);
    } catch (WorkflowException e) {
        // If the workflow execution fails, roll back transaction by removing the application entry.
        application.setId(applicationId);
        apiMgtDAO.deleteApplication(application);
        log.error("Unable to execute Application Creation Workflow", e);
        handleException("Unable to execute Application Creation Workflow", e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Application Name: " + application.getName() + " added successfully.");
    }
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(application, userId, applicationId, requestedTenant);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // get the workflow state once the executor is executed.
    WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(applicationId), WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
    // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
    if (wfDTO != null) {
        if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
            ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_CREATE.name(), tenantId, organization, applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), application.getApplicationAttributes(), userId);
            APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
        }
    } else {
        ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_CREATE.name(), tenantId, organization, applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), application.getApplicationAttributes(), userId);
        APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
    }
    return applicationId;
}
Also used : ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) JSONArray(org.json.simple.JSONArray) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) JSONObject(org.json.simple.JSONObject) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) JSONObject(org.json.simple.JSONObject) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Aggregations

ApplicationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO)15 Application (org.wso2.carbon.apimgt.api.model.Application)11 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)7 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 ServiceReferenceHolderMockCreator (org.wso2.carbon.apimgt.impl.ServiceReferenceHolderMockCreator)6 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)4 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)4 SubscriptionWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO)4 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)3 ApplicationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent)3 XMLStreamException (javax.xml.stream.XMLStreamException)2 JSONObject (org.json.simple.JSONObject)2 Before (org.junit.Before)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 ApplicationRegistrationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent)2 RecommenderDetailsExtractor (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor)2 RecommenderEventPublisher (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher)2 WorkflowException (org.wso2.carbon.apimgt.impl.workflow.WorkflowException)2 WorkflowExecutor (org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)2