Search in sources :

Example 6 with APIStateChangeResponse

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

Example 7 with APIStateChangeResponse

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

the class APIProviderImplTest method testChangeLifeCycleStatusOfAPIProduct.

@Test
public void testChangeLifeCycleStatusOfAPIProduct() throws APIManagementException, FaultGatewaysException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    String provider = "admin";
    PrivilegedCarbonContext carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.doNothing().when(carbonContext).setUsername(Mockito.anyString());
    PowerMockito.doNothing().when(carbonContext).setTenantDomain(Mockito.anyString(), Mockito.anyBoolean());
    APIProduct product = createMockAPIProduct(provider);
    Mockito.when(apimgtDAO.getAPIProductId(product.getId())).thenReturn(1);
    WorkflowDTO workflowDTO = Mockito.mock(WorkflowDTO.class);
    Mockito.when(workflowDTO.getStatus()).thenReturn(WorkflowStatus.CREATED);
    Mockito.when(apimgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(1), WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)).thenReturn(workflowDTO);
    APIStateChangeResponse response = apiProvider.changeLifeCycleStatus("carbon.super", new ApiTypeWrapper(product), "Publish", null);
    Assert.assertNotNull(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) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 8 with APIStateChangeResponse

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

the class APIProviderImplTest method testChangeLifeCycleStatus.

@Test
public void testChangeLifeCycleStatus() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, WorkflowException, XMLStreamException {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    prepareForChangeLifeCycleStatus(apiProvider, apimgtDAO, apiId, artifact);
    APIStateChangeResponse response1 = apiProvider.changeLifeCycleStatus(apiId, APIConstants.API_LC_ACTION_DEPRECATE, "org1");
    Assert.assertEquals("APPROVED", response1.getStateChangeStatus());
}
Also used : APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 9 with APIStateChangeResponse

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

the class APIProviderImplTest method testChangeLifeCycleStatus_WFAlreadyStarted.

@Test
public void testChangeLifeCycleStatus_WFAlreadyStarted() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, WorkflowException {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    GenericArtifact apiArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(APIUtil.getAPIArtifact(apiId, apiProvider.registry)).thenReturn(apiArtifact);
    Mockito.when(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn("admin");
    Mockito.when(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME)).thenReturn("API1");
    Mockito.when(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION)).thenReturn("1.0.0");
    Mockito.when(apiArtifact.getLifecycleState()).thenReturn("CREATED");
    Mockito.when(apimgtDAO.getUUIDFromIdentifier(apiId, "org1")).thenReturn(apiUUID);
    Mockito.when(apimgtDAO.getAPIID(apiUUID)).thenReturn(1);
    // Workflow has started already
    WorkflowDTO wfDTO = Mockito.mock(WorkflowDTO.class);
    Mockito.when(wfDTO.getStatus()).thenReturn(WorkflowStatus.CREATED);
    Mockito.when(apimgtDAO.retrieveWorkflowFromInternalReference("1", WorkflowConstants.WF_TYPE_AM_API_STATE)).thenReturn(wfDTO);
    APIStateChangeResponse response = apiProvider.changeLifeCycleStatus(apiId, APIConstants.API_LC_ACTION_DEPRECATE, "org1");
    Assert.assertNotNull(response);
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 10 with APIStateChangeResponse

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

the class APIProviderImpl method executeStateChangeWorkflow.

/**
 * Execute state change workflow
 *
 * @param currentStatus     Current Status of the API or API Product
 * @param action            LC state change action
 * @param apiName           Name of API or API Product
 * @param apiContext        Context of API or API Product
 * @param apiType           API Type
 * @param apiVersion        Version of API or API Product
 * @param providerName      Provider of API or API Product
 * @param apiOrApiProductId Unique ID API or API Product
 * @param uuid              UUID of the API or API Product
 * @param gatewayVendor     Gateway vendor
 * @param workflowType      Workflow Type
 * @return  APIStateChangeResponse
 * @throws APIManagementException Error when executing the state change workflow
 */
private APIStateChangeResponse executeStateChangeWorkflow(String currentStatus, String action, String apiName, String apiContext, String apiType, String apiVersion, String providerName, int apiOrApiProductId, String uuid, String gatewayVendor, String workflowType) throws APIManagementException {
    APIStateChangeResponse response = new APIStateChangeResponse();
    try {
        WorkflowExecutor apiStateWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(workflowType);
        APIStateWorkflowDTO apiStateWorkflow = setAPIStateWorkflowDTOParameters(currentStatus, action, apiName, apiContext, apiType, apiVersion, providerName, apiOrApiProductId, uuid, gatewayVendor, workflowType, apiStateWFExecutor);
        WorkflowResponse workflowResponse = apiStateWFExecutor.execute(apiStateWorkflow);
        response.setWorkflowResponse(workflowResponse);
    } catch (WorkflowException e) {
        handleException("Failed to execute workflow for life cycle status change : " + e.getMessage(), e);
    }
    return response;
}
Also used : APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)

Aggregations

APIStateChangeResponse (org.wso2.carbon.apimgt.api.model.APIStateChangeResponse)8 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)4 Test (org.junit.Test)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)3 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)3 APIStateWorkflowDTO (org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO)3 WorkflowResponseDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WorkflowResponseDTO)3 HashMap (java.util.HashMap)2 JSONObject (org.json.simple.JSONObject)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)2 WorkflowResponse (org.wso2.carbon.apimgt.api.WorkflowResponse)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)2 WorkflowException (org.wso2.carbon.apimgt.impl.workflow.WorkflowException)2 WorkflowExecutor (org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)2 WorkflowStatus (org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus)2 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)2 LifecycleStateDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.LifecycleStateDTO)2