Search in sources :

Example 11 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle 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 12 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle 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 13 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIStoreImplTestCase method testGetAPIWithNotAllowedLifecycleStates.

@Test(description = "Test get API with not allowed lifecycle states (Created, Maintenance, Retired)")
public void testGetAPIWithNotAllowedLifecycleStates() throws APIManagementException {
    String exceptionShouldThrowError = "Exception should be thrown when accessing an API in %s state";
    String matchedErrorMessage = "Attempt to access an API which is in a restricted state";
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Policy policy = new SubscriptionPolicy(UUID, TIER);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, TIER)).thenReturn(policy);
    APIStore apiStore = getApiStoreImpl(apiDAO, Mockito.mock(ApplicationDAO.class), Mockito.mock(APISubscriptionDAO.class), Mockito.mock(WorkflowDAO.class), Mockito.mock(APIGateway.class), policyDAO);
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI();
    String apiId = apiBuilder.getId();
    List<String> notAllowedStates = new ArrayList<String>() {

        {
            add(APIStatus.CREATED.getStatus());
            add(APIStatus.MAINTENANCE.getStatus());
            add(APIStatus.RETIRED.getStatus());
        }
    };
    for (String notAllowedState : notAllowedStates) {
        apiBuilder.lifeCycleStatus(notAllowedState);
        API api = apiBuilder.build();
        Mockito.when(apiDAO.getAPI(apiId)).thenReturn(api);
        try {
            apiStore.getAPIbyUUID(apiId);
            Assert.fail(exceptionShouldThrowError);
        } catch (APIManagementException e) {
            Assert.assertTrue(e.getMessage().contains(matchedErrorMessage));
        }
    }
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APISubscriptionDAO(org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) ArrayList(java.util.ArrayList) ApplicationDAO(org.wso2.carbon.apimgt.core.dao.ApplicationDAO) WorkflowDAO(org.wso2.carbon.apimgt.core.dao.WorkflowDAO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 14 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testAddAPILifecycleFailure.

@Test(description = "Test add api with API Lifecycle failed", expectedExceptions = { LifecycleException.class, APIManagementException.class })
public void testAddAPILifecycleFailure() throws LifecycleException, APIManagementException {
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI();
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    LabelDAO labelDao = Mockito.mock(LabelDAO.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenThrow(new LifecycleException("Couldn't add api lifecycle"));
    APIGateway gateway = Mockito.mock(APIGateway.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO, apiLifecycleManager, labelDao, gateway);
    apiPublisher.addAPI(apiBuilder);
    Mockito.verify(apiLifecycleManager, Mockito.times(1)).addLifecycle(APIMgtConstants.API_LIFECYCLE, USER);
    Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
}
Also used : APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) LabelDAO(org.wso2.carbon.apimgt.core.dao.LabelDAO) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Example 15 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisGet.

/**
 * Retrieve a list of APIs with given gateway labels and status.
 *
 * @param labels Gateway labels
 * @param status Lifecycle status
 * @param request msf4j request object
 * @return 200 OK if the opration was successful
 * @throws NotFoundException If failed to retrieve APIs
 */
@Override
public Response apisGet(String labels, String status, Request request) throws NotFoundException {
    APIListDTO apiListDTO;
    try {
        APIMgtAdminService adminService = RestApiUtil.getAPIMgtAdminService();
        if (labels != null && !labels.isEmpty()) {
            String[] gatewayLabels = labels.split(",");
            List<String> labelList = new ArrayList<String>(Arrays.asList(gatewayLabels));
            if (status != null && !status.isEmpty()) {
                apiListDTO = MappingUtil.toAPIListDTO(adminService.getAPIsByStatus(labelList, status));
                return Response.ok().entity(apiListDTO).build();
            } else {
                apiListDTO = MappingUtil.toAPIListDTO(adminService.getAPIsByGatewayLabel(labelList));
                return Response.ok().entity(apiListDTO).build();
            }
        } else {
            apiListDTO = new APIListDTO();
            return Response.ok().entity(apiListDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving APIs";
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIMgtAdminService(org.wso2.carbon.apimgt.core.api.APIMgtAdminService) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) ArrayList(java.util.ArrayList) APIListDTO(org.wso2.carbon.apimgt.rest.api.core.dto.APIListDTO)

Aggregations

Test (org.testng.annotations.Test)20 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)20 API (org.wso2.carbon.apimgt.core.models.API)20 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)19 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)13 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)11 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)10 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)10 LifecycleException (org.wso2.carbon.lcm.core.exception.LifecycleException)10 JSONObject (org.json.simple.JSONObject)8 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)8 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)7 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)7 List (java.util.List)6 IOException (java.io.IOException)5 Map (java.util.Map)5 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)4