Search in sources :

Example 36 with FaultGatewaysException

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

the class ImportUtils method updateApiProductSwagger.

/**
 * This method updates the API Product and the swagger with the correct scopes.
 *
 * @param pathToArchive      Path to the extracted folder
 * @param importedApiProduct Imported API Product
 * @param apiProvider        API Provider
 * @throws APIManagementException If an error occurs when retrieving the parser and updating the API Product
 * @throws FaultGatewaysException If an error occurs when updating the API to overwrite
 * @throws IOException            If an error occurs when loading the swagger file
 */
private static APIProduct updateApiProductSwagger(String pathToArchive, String apiProductId, APIProduct importedApiProduct, APIProvider apiProvider, String orgId) throws APIManagementException, FaultGatewaysException, IOException {
    String swaggerContent = loadSwaggerFile(pathToArchive);
    // Load required properties from swagger to the API Product
    APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
    Set<Scope> scopes = apiDefinition.getScopes(swaggerContent);
    importedApiProduct.setScopes(scopes);
    importedApiProduct.setOrganization(orgId);
    // This is required to make scopes get effected
    Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.updateAPIProduct(importedApiProduct);
    apiProvider.updateAPIProductSwagger(apiProductId, apiToProductResourceMapping, importedApiProduct, orgId);
    return importedApiProduct;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList)

Example 37 with FaultGatewaysException

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

the class APIProviderImpl method updateAPIProduct.

@Override
public Map<API, List<APIProductResource>> updateAPIProduct(APIProduct product) throws APIManagementException, FaultGatewaysException {
    Map<API, List<APIProductResource>> apiToProductResourceMapping = new HashMap<>();
    // validate resources and set api identifiers and resource ids to product
    List<APIProductResource> resources = product.getProductResources();
    for (APIProductResource apiProductResource : resources) {
        API api;
        APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
        String apiUUID;
        if (productIdentifier != null) {
            APIIdentifier productAPIIdentifier = apiProductResource.getApiIdentifier();
            String emailReplacedAPIProviderName = APIUtil.replaceEmailDomain(productAPIIdentifier.getProviderName());
            APIIdentifier emailReplacedAPIIdentifier = new APIIdentifier(emailReplacedAPIProviderName, productAPIIdentifier.getApiName(), productAPIIdentifier.getVersion());
            apiUUID = apiMgtDAO.getUUIDFromIdentifier(emailReplacedAPIIdentifier, product.getOrganization());
            api = getAPIbyUUID(apiUUID, tenantDomain);
        } else {
            apiUUID = apiProductResource.getApiId();
            api = getAPIbyUUID(apiUUID, tenantDomain);
        }
        if (api.getSwaggerDefinition() != null) {
            api.setSwaggerDefinition(getOpenAPIDefinition(apiUUID, tenantDomain));
        }
        if (!apiToProductResourceMapping.containsKey(api)) {
            apiToProductResourceMapping.put(api, new ArrayList<>());
        }
        List<APIProductResource> apiProductResources = apiToProductResourceMapping.get(api);
        apiProductResources.add(apiProductResource);
        // if API does not exist, getLightweightAPIByUUID() method throws exception. so no need to handle NULL
        apiProductResource.setApiIdentifier(api.getId());
        apiProductResource.setProductIdentifier(product.getId());
        if (api.isAdvertiseOnly()) {
            apiProductResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
        } else {
            apiProductResource.setEndpointConfig(api.getEndpointConfig());
        }
        apiProductResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        URITemplate uriTemplate = apiProductResource.getUriTemplate();
        Map<String, URITemplate> templateMap = apiMgtDAO.getURITemplatesForAPI(api);
        if (uriTemplate == null) {
        // TODO handle if no resource is defined. either throw an error or add all the resources of that API
        // to the product
        } else {
            String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
            if (templateMap.containsKey(key)) {
                // Since the template ID is not set from the request, we manually set it.
                uriTemplate.setId(templateMap.get(key).getId());
            } else {
                throw new APIManagementException("API with id " + apiProductResource.getApiId() + " does not have a resource " + uriTemplate.getUriTemplate() + " with http method " + uriTemplate.getHTTPVerb());
            }
        }
    }
    APIProduct oldApi = getAPIProductbyUUID(product.getUuid(), CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
    Gson gson = new Gson();
    Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
    if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
        Map<String, String> newMonetizationProperties = gson.fromJson(product.getMonetizationProperties().toString(), HashMap.class);
        if (newMonetizationProperties != null) {
            for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
                String newValue = newMonetizationProperties.get(entry.getKey());
                if (StringUtils.isAllBlank(newValue)) {
                    newMonetizationProperties.put(entry.getKey(), entry.getValue());
                }
            }
            JSONParser parser = new JSONParser();
            try {
                JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
                product.setMonetizationProperties(jsonObj);
            } catch (ParseException e) {
                throw new APIManagementException("Error when parsing monetization properties ", e);
            }
        }
    }
    invalidateResourceCache(product.getContext(), product.getId().getVersion(), Collections.EMPTY_SET);
    // todo : check whether permissions need to be updated and pass it along
    updateApiProductArtifact(product, true, true);
    apiMgtDAO.updateAPIProduct(product, userNameWithoutChange);
    int productId = apiMgtDAO.getAPIProductId(product.getId());
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, product.getId().getName(), productId, product.getId().getUUID(), product.getId().getVersion(), product.getType(), product.getContext(), product.getId().getProviderName(), APIConstants.LC_PUBLISH_LC_STATE);
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    return apiToProductResourceMapping;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) ArrayList(java.util.ArrayList) List(java.util.List) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 38 with FaultGatewaysException

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

the class APIProviderImpl method updateAPIforStateChange.

public boolean updateAPIforStateChange(APIIdentifier identifier, String newStatus, Map<String, String> failedGatewaysMap, API api) throws APIManagementException, FaultGatewaysException {
    boolean isSuccess = false;
    Map<String, Map<String, String>> failedGateways = new ConcurrentHashMap<String, Map<String, String>>();
    String provider = identifier.getProviderName();
    String providerTenantMode = identifier.getProviderName();
    provider = APIUtil.replaceEmailDomain(provider);
    String name = identifier.getApiName();
    String version = identifier.getVersion();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        APIIdentifier apiId = new APIIdentifier(provider, name, version);
        if (api != null) {
            String currentStatus = api.getStatus();
            if (!currentStatus.equals(newStatus)) {
                api.setStatus(newStatus);
                // If API status changed to publish we should add it to recently added APIs list
                // this should happen in store-publisher cluster domain if deployment is distributed
                // IF new API published we will add it to recently added APIs
                Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).removeAll();
                api.setAsPublishedDefaultVersion(api.getId().getVersion().equals(apiMgtDAO.getPublishedDefaultVersion(api.getId())));
                if (failedGatewaysMap != null) {
                    if (APIConstants.PUBLISHED.equals(newStatus) || APIConstants.DEPRECATED.equals(newStatus) || APIConstants.BLOCKED.equals(newStatus) || APIConstants.PROTOTYPED.equals(newStatus)) {
                        Map<String, String> failedToPublishEnvironments = failedGatewaysMap;
                        if (!failedToPublishEnvironments.isEmpty()) {
                            Set<String> publishedEnvironments = new HashSet<String>(api.getEnvironments());
                            publishedEnvironments.removeAll(new ArrayList<String>(failedToPublishEnvironments.keySet()));
                            api.setEnvironments(publishedEnvironments);
                            updateApiArtifact(api, true, false);
                            failedGateways.clear();
                            failedGateways.put("UNPUBLISHED", Collections.<String, String>emptyMap());
                            failedGateways.put("PUBLISHED", failedToPublishEnvironments);
                        }
                    } else {
                        // API Status : RETIRED or CREATED
                        Map<String, String> failedToRemoveEnvironments = failedGatewaysMap;
                        if (!APIConstants.CREATED.equals(newStatus)) {
                            cleanUpPendingSubscriptionCreationProcessesByAPI(api.getUuid());
                            apiMgtDAO.removeAllSubscriptions(api.getUuid());
                        }
                        if (!failedToRemoveEnvironments.isEmpty()) {
                            Set<String> publishedEnvironments = new HashSet<String>(api.getEnvironments());
                            publishedEnvironments.addAll(failedToRemoveEnvironments.keySet());
                            api.setEnvironments(publishedEnvironments);
                            updateApiArtifact(api, true, false);
                            failedGateways.clear();
                            failedGateways.put("UNPUBLISHED", failedToRemoveEnvironments);
                            failedGateways.put("PUBLISHED", Collections.<String, String>emptyMap());
                        }
                    }
                }
                updateApiArtifact(api, false, false);
            }
            isSuccess = true;
        } else {
            handleException("Couldn't find an API with the name-" + name + "version-" + version);
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    if (!failedGateways.isEmpty() && (!failedGateways.get("UNPUBLISHED").isEmpty() || !failedGateways.get("PUBLISHED").isEmpty())) {
        throw new FaultGatewaysException(failedGateways);
    }
    return isSuccess;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 39 with FaultGatewaysException

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

the class APIProviderImpl method changeLifeCycleStatus.

/**
 * This method is to change registry lifecycle states for an API or API Product artifact
 *
 * @param orgId          UUID of the organization
 * @param apiTypeWrapper API Type Wrapper
 * @param action         Action which need to execute from registry lifecycle
 * @param checklist      checklist items
 * @return APIStateChangeResponse API workflow state and WorkflowResponse
 */
@Override
public APIStateChangeResponse changeLifeCycleStatus(String orgId, ApiTypeWrapper apiTypeWrapper, String action, Map<String, Boolean> checklist) throws APIManagementException, FaultGatewaysException {
    APIStateChangeResponse response = new APIStateChangeResponse();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        String targetStatus;
        String providerName;
        String apiName;
        String apiContext;
        String apiType;
        String apiVersion;
        String currentStatus;
        String uuid;
        int apiOrApiProductId;
        boolean isApiProduct = apiTypeWrapper.isAPIProduct();
        String workflowType;
        if (isApiProduct) {
            APIProduct apiProduct = apiTypeWrapper.getApiProduct();
            providerName = apiProduct.getId().getProviderName();
            apiName = apiProduct.getId().getName();
            apiContext = apiProduct.getContext();
            apiType = apiProduct.getType();
            apiVersion = apiProduct.getId().getVersion();
            currentStatus = apiProduct.getState();
            uuid = apiProduct.getUuid();
            apiOrApiProductId = apiMgtDAO.getAPIProductId(apiTypeWrapper.getApiProduct().getId());
            workflowType = WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE;
        } else {
            API api = apiTypeWrapper.getApi();
            providerName = api.getId().getProviderName();
            apiName = api.getId().getApiName();
            apiContext = api.getContext();
            apiType = api.getType();
            apiVersion = api.getId().getVersion();
            currentStatus = api.getStatus();
            uuid = api.getUuid();
            apiOrApiProductId = apiMgtDAO.getAPIID(uuid);
            workflowType = WorkflowConstants.WF_TYPE_AM_API_STATE;
        }
        String gatewayVendor = apiMgtDAO.getGatewayVendorByAPIUUID(uuid);
        WorkflowStatus apiWFState = null;
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiOrApiProductId), workflowType);
        if (wfDTO != null) {
            apiWFState = wfDTO.getStatus();
        }
        // if the workflow has started, then executor should not fire again
        if (!WorkflowStatus.CREATED.equals(apiWFState)) {
            response = executeStateChangeWorkflow(currentStatus, action, apiName, apiContext, apiType, apiVersion, providerName, apiOrApiProductId, uuid, gatewayVendor, workflowType);
            // get the workflow state once the executor is executed.
            wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiOrApiProductId), workflowType);
            if (wfDTO != null) {
                apiWFState = wfDTO.getStatus();
                response.setStateChangeStatus(apiWFState.toString());
            } else {
                response.setStateChangeStatus(WorkflowStatus.APPROVED.toString());
            }
        }
        // apiWFState is null when simple wf executor is used because wf state is not stored in the db.
        if (WorkflowStatus.APPROVED.equals(apiWFState) || apiWFState == null) {
            targetStatus = LCManagerFactory.getInstance().getLCManager().getStateForTransition(action);
            apiPersistenceInstance.changeAPILifeCycle(new Organization(orgId), uuid, targetStatus);
            sendLCStateChangeNotification(apiName, apiType, apiContext, apiVersion, targetStatus, providerName, apiOrApiProductId, uuid);
            if (!isApiProduct) {
                API api = apiTypeWrapper.getApi();
                api.setOrganization(orgId);
                changeLifeCycle(api, currentStatus, targetStatus, checklist);
                // Sending Notifications to existing subscribers
                if (APIConstants.PUBLISHED.equals(targetStatus)) {
                    sendEmailNotification(api);
                }
            } else {
                APIProduct apiProduct = apiTypeWrapper.getApiProduct();
                apiProduct.setOrganization(orgId);
                changeLifecycle(apiProduct, currentStatus, targetStatus);
            }
            addLCStateChangeInDatabase(currentStatus, targetStatus, uuid);
            if (log.isDebugEnabled()) {
                String logMessage = "LC Status changed successfully for artifact with name: " + apiName + ", version " + apiVersion + ", New Status : " + targetStatus;
                log.debug(logMessage);
            }
            extractRecommendationDetails(apiTypeWrapper);
            return response;
        }
    } catch (APIPersistenceException e) {
        handleException("Error while accessing persistence layer", e);
    } catch (PersistenceException e) {
        handleException("Error while accessing lifecycle information ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return response;
}
Also used : PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus)

Example 40 with FaultGatewaysException

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

the class APIProviderImpl method changeLifeCycleStatus.

public APIStateChangeResponse changeLifeCycleStatus(APIIdentifier apiIdentifier, String action, String organization) throws APIManagementException, FaultGatewaysException {
    APIStateChangeResponse response = new APIStateChangeResponse();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        GenericArtifact apiArtifact = getAPIArtifact(apiIdentifier);
        String targetStatus;
        if (apiArtifact != null) {
            String providerName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
            String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
            String apiContext = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT);
            String apiType = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
            String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
            String currentStatus = apiArtifact.getLifecycleState();
            String uuid = apiMgtDAO.getUUIDFromIdentifier(apiIdentifier, organization);
            String gatewayVendor = apiMgtDAO.getGatewayVendorByAPIUUID(uuid);
            int apiId = apiMgtDAO.getAPIID(uuid);
            WorkflowStatus apiWFState = null;
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiId), WorkflowConstants.WF_TYPE_AM_API_STATE);
            if (wfDTO != null) {
                apiWFState = wfDTO.getStatus();
            }
            // if the workflow has started, then executor should not fire again
            if (!WorkflowStatus.CREATED.equals(apiWFState)) {
                try {
                    WorkflowProperties workflowProperties = getAPIManagerConfiguration().getWorkflowProperties();
                    WorkflowExecutor apiStateWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE);
                    APIStateWorkflowDTO apiStateWorkflow = new APIStateWorkflowDTO();
                    apiStateWorkflow.setApiCurrentState(currentStatus);
                    apiStateWorkflow.setApiLCAction(action);
                    apiStateWorkflow.setApiName(apiName);
                    apiStateWorkflow.setApiContext(apiContext);
                    apiStateWorkflow.setApiType(apiType);
                    apiStateWorkflow.setApiVersion(apiVersion);
                    apiStateWorkflow.setApiProvider(providerName);
                    apiStateWorkflow.setGatewayVendor(gatewayVendor);
                    apiStateWorkflow.setCallbackUrl(workflowProperties.getWorkflowCallbackAPI());
                    apiStateWorkflow.setExternalWorkflowReference(apiStateWFExecutor.generateUUID());
                    apiStateWorkflow.setTenantId(tenantId);
                    apiStateWorkflow.setTenantDomain(this.tenantDomain);
                    apiStateWorkflow.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE);
                    apiStateWorkflow.setStatus(WorkflowStatus.CREATED);
                    apiStateWorkflow.setCreatedTime(System.currentTimeMillis());
                    apiStateWorkflow.setWorkflowReference(Integer.toString(apiId));
                    apiStateWorkflow.setInvoker(this.username);
                    apiStateWorkflow.setApiUUID(uuid);
                    String workflowDescription = "Pending lifecycle state change action: " + action;
                    apiStateWorkflow.setWorkflowDescription(workflowDescription);
                    WorkflowResponse workflowResponse = apiStateWFExecutor.execute(apiStateWorkflow);
                    response.setWorkflowResponse(workflowResponse);
                } catch (WorkflowException e) {
                    handleException("Failed to execute workflow for life cycle status change : " + e.getMessage(), e);
                }
                // get the workflow state once the executor is executed.
                wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiId), WorkflowConstants.WF_TYPE_AM_API_STATE);
                if (wfDTO != null) {
                    apiWFState = wfDTO.getStatus();
                    response.setStateChangeStatus(apiWFState.toString());
                } else {
                    response.setStateChangeStatus(WorkflowStatus.APPROVED.toString());
                }
            }
            // apiWFState is null when simple wf executor is used because wf state is not stored in the db.
            if (WorkflowStatus.APPROVED.equals(apiWFState) || apiWFState == null) {
                targetStatus = "";
                apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
                targetStatus = apiArtifact.getLifecycleState();
                if (!currentStatus.equals(targetStatus)) {
                    apiMgtDAO.recordAPILifeCycleEvent(apiId, currentStatus.toUpperCase(), targetStatus.toUpperCase(), this.username, this.tenantId);
                }
                if (log.isDebugEnabled()) {
                    String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
                    log.debug(logMessage);
                }
                APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), tenantId, tenantDomain, apiName, apiId, uuid, apiVersion, apiType, apiContext, providerName, targetStatus);
                APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
                return response;
            }
        }
    } catch (GovernanceException e) {
        String cause = e.getCause().getMessage();
        if (!StringUtils.isEmpty(cause)) {
            if (cause.contains("FaultGatewaysException:")) {
                Map<String, Map<String, String>> faultMap = new HashMap<String, Map<String, String>>();
                String faultJsonString;
                if (!StringUtils.isEmpty(cause) && cause.split("FaultGatewaysException:").length > 1) {
                    faultJsonString = cause.split("FaultGatewaysException:")[1];
                    try {
                        JSONObject faultGatewayJson = (JSONObject) new JSONParser().parse(faultJsonString);
                        faultMap.putAll(faultGatewayJson);
                        throw new FaultGatewaysException(faultMap);
                    } catch (ParseException e1) {
                        log.error("Couldn't parse the Failed Environment json", e);
                        handleException("Couldn't parse the Failed Environment json : " + e.getMessage(), e);
                    }
                }
            } else if (cause.contains("APIManagementException:")) {
                // This exception already logged from APIExecutor class hence this no need to logged again
                handleException("Failed to change the life cycle status : " + cause.split("APIManagementException:")[1], e);
            } else {
                /* This exception already logged from APIExecutor class hence this no need to logged again
                    This block handles the all the exception which not have custom cause message*/
                handleException("Failed to change the life cycle status : " + e.getMessage(), e);
            }
        }
        return response;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return response;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) JSONObject(org.json.simple.JSONObject) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)26 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)25 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)20 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)18 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)18 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)16 HashMap (java.util.HashMap)11 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)11 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)10 Map (java.util.Map)8 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 JSONObject (org.json.simple.JSONObject)6 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)6 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)6 HashSet (java.util.HashSet)5