Search in sources :

Example 41 with WorkflowException

use of org.wso2.carbon.apimgt.core.exception.WorkflowException in project carbon-apimgt by wso2.

the class APIConsumerImpl method updateSubscription.

@Override
public SubscriptionResponse updateSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application, String inputSubscriptionId, String currentThrottlingPolicy, String requestedThrottlingPolicy) 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();
        apiId = product.getProductId();
        apiUUId = product.getUuid();
        identifier = product.getId();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = identifier.getId();
        apiUUId = api.getUuid();
        apiContext = api.getContext();
    }
    checkSubscriptionAllowed(apiTypeWrapper);
    WorkflowResponse workflowResponse = null;
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state)) {
        subscriptionId = apiMgtDAO.updateSubscription(apiTypeWrapper, inputSubscriptionId, APIConstants.SubscriptionStatus.TIER_UPDATE_PENDING, requestedThrottlingPolicy);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        try {
            WorkflowExecutor updateSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(updateSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            workflowDTO.setCallbackUrl(updateSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(requestedThrottlingPolicy);
            workflowDTO.setApplicationName(application.getName());
            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 = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.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 = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException 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 updatedSubscription = 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 = updatedSubscription.getSubStatus();
            subscriptionUUID = updatedSubscription.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, application.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            subsLogObject.put(APIConstants.AuditLogConstants.REQUESTED_TIER, requestedThrottlingPolicy);
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, 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_UPDATE);
        // 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())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, 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 " + application.getName();
            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 42 with WorkflowException

use of org.wso2.carbon.apimgt.core.exception.WorkflowException 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 43 with WorkflowException

use of org.wso2.carbon.apimgt.core.exception.WorkflowException in project carbon-apimgt by wso2.

the class APIConsumerImpl method resumeWorkflow.

public JSONObject resumeWorkflow(Object[] args) {
    JSONObject row = new JSONObject();
    if (args != null && APIUtil.isStringArray(args)) {
        String workflowReference = (String) args[0];
        String status = (String) args[1];
        String description = null;
        if (args.length > 2 && args[2] != null) {
            description = (String) args[2];
        }
        boolean isTenantFlowStarted = false;
        try {
            // if (workflowReference != null) {
            WorkflowDTO workflowDTO = apiMgtDAO.retrieveWorkflow(workflowReference);
            if (workflowDTO == null) {
                log.error("Could not find workflow for reference " + workflowReference);
                row.put("error", Boolean.TRUE);
                row.put("statusCode", 500);
                row.put("message", "Could not find workflow for reference " + workflowReference);
                return row;
            }
            String tenantDomain = workflowDTO.getTenantDomain();
            if (tenantDomain != null && !org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
            }
            workflowDTO.setWorkflowDescription(description);
            workflowDTO.setStatus(WorkflowStatus.valueOf(status));
            String workflowType = workflowDTO.getWorkflowType();
            WorkflowExecutor workflowExecutor;
            try {
                workflowExecutor = getWorkflowExecutor(workflowType);
                workflowExecutor.complete(workflowDTO);
                if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
                    WorkflowUtils.sendNotificationAfterWFComplete(workflowDTO, workflowType);
                }
            } catch (WorkflowException e) {
                throw new APIManagementException(e);
            }
            row.put("error", Boolean.FALSE);
            row.put("statusCode", 200);
            row.put("message", "Invoked workflow completion successfully.");
        // }
        } catch (IllegalArgumentException e) {
            String msg = "Illegal argument provided. Valid values for status are APPROVED and REJECTED.";
            log.error(msg, e);
            row.put("error", Boolean.TRUE);
            row.put("statusCode", 500);
            row.put("message", msg);
        } catch (APIManagementException e) {
            String msg = "Error while resuming the workflow. ";
            log.error(msg, e);
            row.put("error", Boolean.TRUE);
            row.put("statusCode", 500);
            row.put("message", msg + e.getMessage());
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
    }
    return row;
}
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) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)

Example 44 with WorkflowException

use of org.wso2.carbon.apimgt.core.exception.WorkflowException in project carbon-apimgt by wso2.

the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowApprovedByAdmin.

@Test
public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setRoles(roleMap);
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
    PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod();
    PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
    Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true);
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true);
    // Set workflow status to be approved
    workflowDTO.setStatus(WorkflowStatus.APPROVED);
    workflowDTO.setTenantDomain(tenantDomain);
    // Set tenant admin credentials
    userRegistrationConfigDTO.setAdminUserName("admin");
    userRegistrationConfigDTO.setAdminPassword("admin");
    // Test failure to complete workflow execution, when error has been occurred while updating user with signup roles
    Mockito.doThrow(UserStoreException.class).when(userStoreManager).updateRoleListOfUser(Mockito.anyString(), Mockito.any(), new String[] { Mockito.anyString() });
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when sign up roles are not existing in user realm
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false);
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when error has been occurred while retrieving signup config
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException("Error occurred while retrieving signup configuration"));
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 45 with WorkflowException

use of org.wso2.carbon.apimgt.core.exception.WorkflowException in project carbon-apimgt by wso2.

the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowRejectedByAdmin.

@Test
public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setAdminUserName("admin");
    userRegistrationConfigDTO.setAdminPassword("admin");
    userRegistrationConfigDTO.setRoles(roleMap);
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
    PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
    // Set workflow status to be approved
    workflowDTO.setStatus(WorkflowStatus.REJECTED);
    Mockito.doThrow(UserStoreException.class).when(userStoreManager).deleteUser(Mockito.anyString());
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when user deletion failed");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while deleting the user");
    }
}
Also used : HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)56 Test (org.junit.Test)49 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)49 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)32 ApplicationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO)25 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)24 SubscriptionWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO)24 Application (org.wso2.carbon.apimgt.api.model.Application)18 WorkflowExecutor (org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)17 WorkflowException (org.wso2.carbon.apimgt.impl.workflow.WorkflowException)15 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)13 HashMap (java.util.HashMap)12 JSONObject (org.json.simple.JSONObject)12 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)12 ServiceReferenceHolderMockCreator (org.wso2.carbon.apimgt.impl.ServiceReferenceHolderMockCreator)10 XMLStreamException (javax.xml.stream.XMLStreamException)9 UserRegistrationConfigDTO (org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO)9 WorkflowResponse (org.wso2.carbon.apimgt.api.WorkflowResponse)8 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)7 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)6