Search in sources :

Example 26 with GeneralWorkflowResponse

use of org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse in project carbon-apimgt by wso2.

the class APIConsumerImpl method addSubscription.

@Override
public SubscriptionResponse addSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application) throws APIManagementException {
    API api = null;
    APIProduct product = null;
    Identifier identifier = null;
    int apiId;
    String apiUUID;
    final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
    String state;
    String apiContext;
    if (isApiProduct) {
        product = apiTypeWrapper.getApiProduct();
        state = product.getState();
        identifier = product.getId();
        apiId = product.getProductId();
        apiUUID = product.getUuid();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = api.getId().getId();
        apiUUID = api.getUuid();
        apiContext = api.getContext();
    }
    WorkflowResponse workflowResponse = null;
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
    checkSubscriptionAllowed(apiTypeWrapper);
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state) || APIConstants.PROTOTYPED.equals(state)) {
        subscriptionId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, tenantAwareUsername);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        String applicationName = application.getName();
        try {
            WorkflowExecutor addSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(addSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            workflowDTO.setCallbackUrl(addSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(identifier.getTier());
            workflowDTO.setApplicationName(applicationName);
            workflowDTO.setApplicationId(application.getId());
            workflowDTO.setSubscriber(userId);
            Tier tier = null;
            Set<Tier> policies = Collections.emptySet();
            if (!isApiProduct) {
                policies = api.getAvailableTiers();
            } else {
                policies = product.getAvailableTiers();
            }
            for (Tier policy : policies) {
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
            boolean isMonetizationEnabled = false;
            if (api != null) {
                isMonetizationEnabled = api.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            } else {
                isMonetizationEnabled = product.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException e) {
            // If the workflow execution fails, roll back transaction by removing the subscription entry.
            apiMgtDAO.removeSubscriptionById(subscriptionId);
            log.error("Could not execute Workflow", e);
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
        // to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
        // the response should have {"Status":"REJECTED"} in the json payload for this to work.
        boolean subscriptionRejected = false;
        String subscriptionStatus = null;
        String subscriptionUUID = "";
        SubscribedAPI addedSubscription = getSubscriptionById(subscriptionId);
        if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
            try {
                JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
                if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
                    subscriptionRejected = true;
                    subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                }
            } catch (ParseException e) {
                log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
            }
        }
        if (!subscriptionRejected) {
            subscriptionStatus = addedSubscription.getSubStatus();
            subscriptionUUID = addedSubscription.getUUID();
            JSONObject subsLogObject = new JSONObject();
            subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
            if (workflowResponse == null) {
                workflowResponse = new GeneralWorkflowResponse();
            }
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        // only send the notification if approved
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + applicationName;
            log.debug(logMessage);
        }
        return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
    } else {
        throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) 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) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 27 with GeneralWorkflowResponse

use of org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse in project carbon-apimgt by wso2.

the class DefaultWorkflowExecutor method complete.

/**
 * Complete the external process status
 * Based on the workflow status we will update the status column of the
 * Application table
 *
 * @param workFlow - Workflow
 */
public WorkflowResponse complete(Workflow workFlow) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing complete() in Workflow for " + workFlow.getWorkflowType());
    }
    WorkflowResponse workflowResponse = new GeneralWorkflowResponse();
    workflowResponse.setWorkflowStatus(workFlow.getStatus());
    return workflowResponse;
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse)

Example 28 with GeneralWorkflowResponse

use of org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse in project carbon-apimgt by wso2.

the class DefaultWorkflowExecutor method execute.

/**
 * {@inheritDoc}
 */
@Override
public WorkflowResponse execute(Workflow workFlow) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing execute() in Workflow for " + workFlow.getWorkflowType());
    }
    WorkflowResponse workflowResponse = new GeneralWorkflowResponse();
    // set the state to approved
    workflowResponse.setWorkflowStatus(WorkflowStatus.APPROVED);
    return workflowResponse;
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse)

Example 29 with GeneralWorkflowResponse

use of org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImplTestCase method testApplicationsPostErrorCase.

@Test
public void testApplicationsPostErrorCase() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String applicationId = UUID.randomUUID().toString();
    String accessToken = UUID.randomUUID().toString();
    String clientID = UUID.randomUUID().toString();
    String clientSecret = UUID.randomUUID().toString();
    ApplicationsApiServiceImpl applicationsApiService = new ApplicationsApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    Application application = getSampleApplication(applicationId);
    WorkflowResponse workflowResponse = new GeneralWorkflowResponse();
    workflowResponse.setWorkflowStatus(WorkflowStatus.APPROVED);
    ApplicationCreationResponse creationResponse = new ApplicationCreationResponse(UUID.randomUUID().toString(), workflowResponse);
    Mockito.when(apiStore.addApplication(application)).thenReturn(creationResponse);
    Mockito.when(apiStore.getApplication(creationResponse.getApplicationUUID(), USER)).thenReturn(application);
    ApplicationTokenDTO applicationTokenDTO = new ApplicationTokenDTO();
    applicationTokenDTO.setAccessToken(accessToken);
    applicationTokenDTO.setTokenScopes("SCOPE1");
    applicationTokenDTO.setValidityTime((long) 100000);
    List<String> grantTypes = new ArrayList<>();
    grantTypes.add("password");
    grantTypes.add("jwt");
    ApplicationKeysDTO applicationKeysDTO = new ApplicationKeysDTO();
    applicationKeysDTO.setConsumerKey(clientID);
    applicationKeysDTO.setConsumerSecret(clientSecret);
    applicationKeysDTO.setKeyType(ApplicationKeysDTO.KeyTypeEnum.PRODUCTION);
    applicationKeysDTO.setCallbackUrl(null);
    applicationKeysDTO.setSupportedGrantTypes(grantTypes);
    List<ApplicationKeysDTO> applicationKeysDTOList = new ArrayList<>();
    applicationKeysDTOList.add(applicationKeysDTO);
    ApplicationDTO applicationDTO = new ApplicationDTO();
    applicationDTO.setApplicationId(applicationId);
    applicationDTO.setDescription("sample application");
    applicationDTO.setName("app1");
    applicationDTO.setSubscriber("subscriber");
    applicationDTO.setPermission("permission");
    applicationDTO.setLifeCycleStatus("APPROVED");
    applicationDTO.setThrottlingTier("UNLIMITED");
    applicationDTO.setToken(applicationTokenDTO);
    applicationDTO.setKeys(applicationKeysDTOList);
    Response response = applicationsApiService.applicationsPost(applicationDTO, request);
    Assert.assertEquals(201, response.getStatus());
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationDTO) ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenDTO) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) Request(org.wso2.msf4j.Request) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) ArrayList(java.util.ArrayList) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) Response(javax.ws.rs.core.Response) ApplicationKeysDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Application(org.wso2.carbon.apimgt.core.models.Application) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 30 with GeneralWorkflowResponse

use of org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImplTestCase method testApplicationsApplicationIdPut.

@Test
public void testApplicationsApplicationIdPut() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String applicationId = UUID.randomUUID().toString();
    String accessToken = UUID.randomUUID().toString();
    String clientID = UUID.randomUUID().toString();
    String clientSecret = UUID.randomUUID().toString();
    ApplicationsApiServiceImpl applicationsApiService = new ApplicationsApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    ApplicationTokenDTO applicationTokenDTO = new ApplicationTokenDTO();
    applicationTokenDTO.setAccessToken(accessToken);
    applicationTokenDTO.setTokenScopes("SCOPE1");
    applicationTokenDTO.setValidityTime((long) 100000);
    List<String> grantTypes = new ArrayList<>();
    grantTypes.add("password");
    grantTypes.add("jwt");
    ApplicationKeysDTO applicationKeysDTO = new ApplicationKeysDTO();
    applicationKeysDTO.setConsumerKey(clientID);
    applicationKeysDTO.setConsumerSecret(clientSecret);
    applicationKeysDTO.setKeyType(ApplicationKeysDTO.KeyTypeEnum.PRODUCTION);
    applicationKeysDTO.setCallbackUrl(null);
    applicationKeysDTO.setSupportedGrantTypes(grantTypes);
    List<ApplicationKeysDTO> applicationKeysDTOList = new ArrayList<>();
    applicationKeysDTOList.add(applicationKeysDTO);
    ApplicationDTO applicationDTO = new ApplicationDTO();
    applicationDTO.setApplicationId(applicationId);
    applicationDTO.setDescription("sample application");
    applicationDTO.setName("app1");
    applicationDTO.setSubscriber("subscriber");
    applicationDTO.setPermission("permission");
    applicationDTO.setLifeCycleStatus("APPROVED");
    applicationDTO.setThrottlingTier("UNLIMITED");
    applicationDTO.setToken(applicationTokenDTO);
    applicationDTO.setKeys(applicationKeysDTOList);
    WorkflowResponse workflowResponse = new GeneralWorkflowResponse();
    workflowResponse.setWorkflowStatus(WorkflowStatus.APPROVED);
    Mockito.when(apiStore.getApplication(applicationId, USER)).thenReturn(getSampleApplication(applicationId));
    Mockito.when(apiStore.updateApplication(applicationId, getSampleApplication(applicationId))).thenReturn(workflowResponse);
    Mockito.when(apiStore.getApplication(applicationId, USER)).thenReturn(getSampleApplication(applicationId));
    Response response = applicationsApiService.applicationsApplicationIdPut(applicationId, applicationDTO, null, null, request);
    Assert.assertEquals(200, response.getStatus());
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationDTO) ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenDTO) Request(org.wso2.msf4j.Request) ArrayList(java.util.ArrayList) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) Response(javax.ws.rs.core.Response) ApplicationKeysDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)19 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)19 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)15 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)14 SubscriptionWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO)9 Response (javax.ws.rs.core.Response)8 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)8 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)7 Test (org.testng.annotations.Test)6 XMLStreamException (javax.xml.stream.XMLStreamException)5 Application (org.wso2.carbon.apimgt.api.model.Application)5 ApplicationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO)5 Request (org.wso2.msf4j.Request)5 HashMap (java.util.HashMap)4 AxisFault (org.apache.axis2.AxisFault)4 ServiceClient (org.apache.axis2.client.ServiceClient)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 Application (org.wso2.carbon.apimgt.core.models.Application)4