Search in sources :

Example 26 with LifecycleException

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

the class APIPublisherImpl method createNewAPIVersion.

/**
 * Create a new version of the <code>api</code>, with version <code>newVersion</code>
 *
 * @param apiId      The API to be copied
 * @param newVersion The version of the new API
 * @return UUID of the newly created version.
 * @throws APIManagementException If an error occurs while trying to create
 *                                the new version of the API
 */
@Override
public String createNewAPIVersion(String apiId, String newVersion) throws APIManagementException {
    String newVersionedId;
    LifecycleState lifecycleState;
    // validate parameters
    if (StringUtils.isEmpty(newVersion)) {
        String errorMsg = "New API version cannot be empty";
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    if (StringUtils.isEmpty(apiId)) {
        String errorMsg = "API ID cannot be empty";
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    try {
        API api = getApiDAO().getAPI(apiId);
        if (api.getVersion().equals(newVersion)) {
            String errMsg = "New API version " + newVersion + " cannot be same as the previous version for " + "API " + api.getName();
            log.error(errMsg);
            throw new APIManagementException(errMsg, ExceptionCodes.API_ALREADY_EXISTS);
        }
        API.APIBuilder apiBuilder = new API.APIBuilder(api);
        apiBuilder.id(UUID.randomUUID().toString());
        apiBuilder.version(newVersion);
        apiBuilder.context(api.getContext().replace(api.getVersion(), newVersion));
        lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
        apiBuilder.associateLifecycle(lifecycleState);
        apiBuilder.copiedFromApiId(api.getId());
        if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
            apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
        }
        getApiDAO().addAPI(apiBuilder.build());
        newVersionedId = apiBuilder.getId();
        sendNotification(apiId, apiBuilder.getName(), newVersion);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Couldn't create new API version from " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Couldn't Associate  new API Lifecycle from " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    }
    return newVersionedId;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) API(org.wso2.carbon.apimgt.core.models.API)

Example 27 with LifecycleException

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

the class APIPublisherImpl method updateAPIStatus.

/**
 * @see org.wso2.carbon.apimgt.core.api.APIPublisher#updateAPIStatus(String, String, Map)
 */
@Override
public WorkflowResponse updateAPIStatus(String apiId, String status, Map<String, Boolean> checkListItemMap) throws APIManagementException {
    WorkflowResponse workflowResponse = null;
    try {
        API api = getApiDAO().getAPI(apiId);
        if (api != null && !APILCWorkflowStatus.PENDING.toString().equals(api.getWorkflowStatus())) {
            API.APIBuilder apiBuilder = new API.APIBuilder(api);
            apiBuilder.lastUpdatedTime(LocalDateTime.now());
            apiBuilder.updatedBy(getUsername());
            LifecycleState currentState = getApiLifecycleManager().getLifecycleDataForState(apiBuilder.getLifecycleInstanceId(), apiBuilder.getLifeCycleStatus());
            apiBuilder.lifecycleState(currentState);
            for (Map.Entry<String, Boolean> checkListItem : checkListItemMap.entrySet()) {
                getApiLifecycleManager().checkListItemEvent(api.getLifecycleInstanceId(), api.getLifeCycleStatus(), checkListItem.getKey(), checkListItem.getValue());
            }
            API originalAPI = apiBuilder.build();
            WorkflowExecutor executor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE);
            APIStateChangeWorkflow workflow = new APIStateChangeWorkflow(getApiDAO(), getApiSubscriptionDAO(), getWorkflowDAO(), getApiLifecycleManager(), getApiGateway(), getLabelDAO());
            workflow.setApiName(originalAPI.getName());
            workflow.setApiProvider(originalAPI.getProvider());
            workflow.setApiVersion(originalAPI.getVersion());
            workflow.setCurrentState(currentState.getState());
            workflow.setTransitionState(status);
            workflow.setWorkflowReference(originalAPI.getId());
            workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
            workflow.setCreatedTime(LocalDateTime.now());
            workflow.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE);
            workflow.setInvoker(getUsername());
            // setting attributes for internal use. These are set to use from outside the executor's method
            // these will be saved in the AM_WORKFLOW table so these can be retrieved later
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_CUR_STATE, currentState.getState());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_TARGET_STATE, status);
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_LC_INVOKER, getUsername());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_NAME, originalAPI.getId());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_HAS_OWN_GATEWAY, String.valueOf(originalAPI.hasOwnGateway()));
            if (originalAPI.hasOwnGateway()) {
                List<String> gwLabels = originalAPI.getLabels();
                for (String label : gwLabels) {
                    if (label.contains(ContainerBasedGatewayConstants.PRIVATE_JET_API_PREFIX)) {
                        workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_AUTOGEN_LABEL, label);
                        break;
                    }
                }
            }
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_HAS_OWN_GATEWAY, String.valueOf(originalAPI.hasOwnGateway()));
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_API_LAST_UPTIME, originalAPI.getLastUpdatedTime().toString());
            String workflowDescription = "API [" + workflow.getApiName() + " - " + workflow.getApiVersion() + "] state change [" + workflow.getCurrentState() + " to " + workflow.getTransitionState() + "] request from " + getUsername();
            workflow.setWorkflowDescription(workflowDescription);
            workflowResponse = executor.execute(workflow);
            workflow.setStatus(workflowResponse.getWorkflowStatus());
            if (WorkflowStatus.CREATED != workflowResponse.getWorkflowStatus()) {
                completeWorkflow(executor, workflow);
            } else {
                // add entry to workflow table if it is only in pending state
                addWorkflowEntries(workflow);
                getApiDAO().updateAPIWorkflowStatus(api.getId(), APILCWorkflowStatus.PENDING);
            }
        } else if (api != null && APILCWorkflowStatus.PENDING.toString().equals(api.getWorkflowStatus())) {
            String message = "Pending state transition for api :" + api.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.WORKFLOW_PENDING);
        } else {
            throw new APIMgtResourceNotFoundException("Requested API " + apiId + " Not Available");
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Couldn't change the status of api ID " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Couldn't change the status of api ID " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    }
    return workflowResponse;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) APIStateChangeWorkflow(org.wso2.carbon.apimgt.core.workflow.APIStateChangeWorkflow) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) API(org.wso2.carbon.apimgt.core.models.API) WorkflowExecutor(org.wso2.carbon.apimgt.core.api.WorkflowExecutor) Map(java.util.Map) HashMap(java.util.HashMap)

Example 28 with LifecycleException

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

the class APIPublisherImpl method deleteAPI.

/**
 * Delete an API
 *
 * @param identifier UUID of the API.
 * @throws APIManagementException if failed to remove the API
 */
@Override
public void deleteAPI(String identifier) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    try {
        if (getAPISubscriptionCountByAPI(identifier) == 0) {
            API api = getAPIbyUUID(identifier);
            // Checks whether the user has required permissions to delete the API
            verifyUserPermissionsToDeleteAPI(getUsername(), api);
            String apiWfStatus = api.getWorkflowStatus();
            API.APIBuilder apiBuilder = new API.APIBuilder(api);
            // Delete API in gateway
            gateway.deleteAPI(api);
            if (log.isDebugEnabled()) {
                log.debug("API : " + api.getName() + " has been successfully removed from the gateway");
            }
            if (!getApiDAO().isAPIVersionsExist(api.getName())) {
                Map<String, String> scopeMap = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(identifier));
                for (String scope : scopeMap.keySet()) {
                    try {
                        getKeyManager().deleteScope(scope);
                    } catch (KeyManagementException e) {
                        // We ignore the error due to if scope get deleted from other end that will affect to delete
                        // api.
                        log.warn("Scope couldn't delete from Key Manager", e);
                    }
                }
            }
            getApiDAO().deleteAPI(identifier);
            // Deleting API specific endpoints
            if (api.getEndpoint() != null) {
                for (Map.Entry<String, Endpoint> entry : api.getEndpoint().entrySet()) {
                    Endpoint endpoint = entry.getValue();
                    if (APIMgtConstants.API_SPECIFIC_ENDPOINT.equals(endpoint.getApplicableLevel())) {
                        deleteEndpoint(endpoint.getId());
                    }
                }
            }
            getApiLifecycleManager().removeLifecycle(apiBuilder.getLifecycleInstanceId());
            APIUtils.logDebug("API with id " + identifier + " was deleted successfully.", log);
            if (APILCWorkflowStatus.PENDING.toString().equals(apiWfStatus)) {
                cleanupPendingTaskForAPIStateChange(identifier);
            }
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PROVIDER, api.getProvider());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_DELETION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            throw new ApiDeleteFailureException("API with " + identifier + " already have subscriptions");
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while deleting the API with id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Error occurred while Disassociating the API with Lifecycle id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while deleting API with id - " + identifier + " from gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) ApiDeleteFailureException(org.wso2.carbon.apimgt.core.exception.ApiDeleteFailureException) HashMap(java.util.HashMap) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) Map(java.util.Map) HashMap(java.util.HashMap)

Example 29 with LifecycleException

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

the class APIPublisherImplTestCase method testUpdateAPIWithRestrictedVisibility.

@Test(description = "Test UpdateAPI with restricted visibility")
public void testUpdateAPIWithRestrictedVisibility() throws APIManagementException, LifecycleException {
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add(ADMIN_ROLE);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    API.APIBuilder api = SampleTestObjectCreator.createDefaultAPI().visibility(API.Visibility.RESTRICTED).visibleRoles(visibleRoles);
    String uuid = api.getId();
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, apiLifecycleManager, gatewaySourceGenerator, gateway, policyDAO);
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.lifeCycleStatus(APIStatus.CREATED.getStatus()).build());
    Mockito.when(apiDAO.isAPIContextExists(api.getContext())).thenReturn(true);
    String configString = SampleTestObjectCreator.createSampleGatewayConfig();
    Mockito.when(apiDAO.getGatewayConfigOfAPI(uuid)).thenReturn(configString);
    Mockito.when(identityProvider.getRoleId(ADMIN_ROLE)).thenReturn(ADMIN_ROLE_ID);
    Mockito.when(apiDAO.getApiSwaggerDefinition(api.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
    Mockito.when(identityProvider.getRoleId(DEVELOPER_ROLE)).thenReturn(DEVELOPER_ROLE_ID);
    apiPublisher.updateAPI(api.lifeCycleStatus(APIStatus.CREATED.getStatus()).id(uuid));
    Mockito.verify(apiDAO, Mockito.times(1)).getAPI(uuid);
    Mockito.verify(apiDAO, Mockito.times(0)).isAPIContextExists(api.getContext());
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(uuid, api.lifeCycleStatus(APIStatus.CREATED.getStatus()).build());
}
Also used : APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 30 with LifecycleException

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

the class APIPublisherImplTestCase method testCreateNewAPIVersionWithInvalidUUID.

@Test(description = "Create new  API version with invalid APIID")
public void testCreateNewAPIVersionWithInvalidUUID() throws APIManagementException, LifecycleException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, gateway);
    Mockito.when(apiDAO.getAPI("xxxxxx")).thenThrow(new APIMgtDAOException("API with ID does not exist", ExceptionCodes.API_NOT_FOUND));
    try {
        apiPublisher.createNewAPIVersion("xxxxxx", "2.0.0");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getErrorHandler(), ExceptionCodes.API_NOT_FOUND);
    }
}
Also used : APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Aggregations

ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)59 Test (org.testng.annotations.Test)58 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)56 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)55 API (org.wso2.carbon.apimgt.core.models.API)54 LifecycleState (org.wso2.carbon.lcm.core.impl.LifecycleState)32 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)31 LabelDAO (org.wso2.carbon.apimgt.core.dao.LabelDAO)21 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)20 HashMap (java.util.HashMap)17 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)15 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)14 LifecycleException (org.wso2.carbon.lcm.core.exception.LifecycleException)14 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)13 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)13 WorkflowDAO (org.wso2.carbon.apimgt.core.dao.WorkflowDAO)11 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)11 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)11 APISubscriptionDAO (org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO)10 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)8