Search in sources :

Example 16 with GatewayException

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

the class APIPublisherImpl method updateAPI.

/**
 * Updates design and implementation of an existing API. This method must not be used to change API status.
 * Implementations should throw an exceptions when such attempts are made. All life cycle state changes
 * should be carried out using the changeAPIStatus method of this interface.
 *
 * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
 * @throws APIManagementException if failed to update API
 */
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    apiBuilder.updatedBy(getUsername());
    try {
        API originalAPI = getAPIbyUUID(apiBuilder.getId());
        if (originalAPI != null) {
            // Checks whether the logged in user has the "UPDATE" permission for the API
            verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
            apiBuilder.createdTime(originalAPI.getCreatedTime());
            // workflow status is an internal property and shouldn't be allowed to update externally
            apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
            if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
                if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                    apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
                    Map<String, Integer> roleNamePermissionList;
                    roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                    apiBuilder.permissionMap(roleNamePermissionList);
                }
                Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
                validateEndpoints(apiEndpointMap, true);
                validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
                createUriTemplateList(apiBuilder, true);
                validateApiPolicy(apiBuilder.getApiPolicy());
                validateSubscriptionPolicies(apiBuilder);
                String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
                String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
                GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
                APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
                gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
                String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
                API api = apiBuilder.build();
                // Add API to gateway
                gateway.updateAPI(api);
                if (log.isDebugEnabled()) {
                    log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
                }
                if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
                    if (!checkIfAPIContextExists(api.getContext())) {
                        // if the API has public visibility, update the API without any role checking
                        if (API.Visibility.PUBLIC == api.getVisibility()) {
                            getApiDAO().updateAPI(api.getId(), api);
                        } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                            // get all the roles in the system
                            Set<String> availableRoles = APIUtils.getAllAvailableRoles();
                            // get the roles needed to be associated with the API
                            Set<String> apiRoleList = api.getVisibleRoles();
                            // if the API has role based visibility, update the API with role checking
                            if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
                                getApiDAO().updateAPI(api.getId(), api);
                            }
                        }
                        getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                        getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                    } else {
                        throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
                    }
                } else {
                    // if the API has public visibility, update the API without any role checking
                    if (API.Visibility.PUBLIC == api.getVisibility()) {
                        getApiDAO().updateAPI(api.getId(), api);
                    } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                        // get all the roles in the system
                        Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                        // get the roles needed to be associated with the API
                        Set<String> apiRoleList = api.getVisibleRoles();
                        // if the API has role based visibility, update the API with role checking
                        if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                            getApiDAO().updateAPI(api.getId(), api);
                        }
                    }
                    getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                    getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                }
                if (log.isDebugEnabled()) {
                    log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
                    // '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_DESCRIPTION, api.getDescription());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
                    // This will notify all the EventObservers(Asynchronous)
                    ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
                    ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
                }
            } else {
                APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
            }
        } else {
            log.error("Couldn't found API with ID " + apiBuilder.getId());
            throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) 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) ParseException(org.json.simple.parser.ParseException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 17 with GatewayException

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

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

the class APIStoreImpl method deleteCompositeApi.

/**
 * {@inheritDoc}
 */
@Override
public void deleteCompositeApi(String apiId) throws APIManagementException {
    try {
        CompositeAPI api = getApiDAO().getCompositeAPI(apiId);
        // Delete API in gateway
        gateway.deleteCompositeAPI(api);
        getApiDAO().deleteCompositeApi(apiId);
    } catch (GatewayException e) {
        String message = "Error occurred while deleting Composite API with id - " + apiId + " from gateway";
        throw new APIManagementException(message, e, ExceptionCodes.GATEWAY_EXCEPTION);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while deleting the Composite API with id " + apiId;
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI)

Example 19 with GatewayException

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

the class APIGatewayPublisherImplTestCase method testDeleteAPIWhenLabelsAreNull.

@Test
public void testDeleteAPIWhenLabelsAreNull() throws GatewayException, ContainerBasedGatewayException {
    APIGatewayPublisherImpl apiGatewayPublisher = new APIGatewayPublisherImpl();
    Broker broker = Mockito.mock(BrokerImpl.class, Mockito.RETURNS_DEEP_STUBS);
    BrokerUtil.initialize(broker);
    ContainerBasedGatewayGenerator containerBasedGatewayGenerator = Mockito.mock(ContainerBasedGatewayGenerator.class);
    apiGatewayPublisher.setContainerBasedGatewayGenerator(containerBasedGatewayGenerator);
    API api = SampleTestObjectCreator.createDefaultAPI().lifeCycleStatus(APIStatus.PUBLISHED.getStatus()).hasOwnGateway(true).labels(null).build();
    apiGatewayPublisher.deleteAPI(api);
    Mockito.verify(containerBasedGatewayGenerator, Mockito.times(0)).removeContainerBasedGateway("label", api);
}
Also used : Broker(org.wso2.carbon.apimgt.core.api.Broker) API(org.wso2.carbon.apimgt.core.models.API) Test(org.junit.Test)

Example 20 with GatewayException

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

the class APIGatewayPublisherImplTestCase method testDeleteAPIWhenAPIDoesNotHaveOwnGateway.

@Test
public void testDeleteAPIWhenAPIDoesNotHaveOwnGateway() throws GatewayException, ContainerBasedGatewayException {
    APIGatewayPublisherImpl apiGatewayPublisher = new APIGatewayPublisherImpl();
    Broker broker = Mockito.mock(BrokerImpl.class, Mockito.RETURNS_DEEP_STUBS);
    BrokerUtil.initialize(broker);
    ContainerBasedGatewayGenerator containerBasedGatewayGenerator = Mockito.mock(ContainerBasedGatewayGenerator.class);
    apiGatewayPublisher.setContainerBasedGatewayGenerator(containerBasedGatewayGenerator);
    List<String> labels = new ArrayList<>();
    labels.add("label");
    API api = SampleTestObjectCreator.createDefaultAPI().lifeCycleStatus(APIStatus.PUBLISHED.getStatus()).hasOwnGateway(false).labels(labels).build();
    apiGatewayPublisher.deleteAPI(api);
    Mockito.verify(containerBasedGatewayGenerator, Mockito.times(0)).removeContainerBasedGateway("label", api);
}
Also used : Broker(org.wso2.carbon.apimgt.core.api.Broker) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.core.models.API) Test(org.junit.Test)

Aggregations

GatewayException (org.wso2.carbon.apimgt.core.exception.GatewayException)14 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)13 API (org.wso2.carbon.apimgt.core.models.API)12 HashMap (java.util.HashMap)7 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)7 ArrayList (java.util.ArrayList)6 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)6 APIEvent (org.wso2.carbon.apimgt.core.models.events.APIEvent)6 Test (org.junit.Test)5 Broker (org.wso2.carbon.apimgt.core.api.Broker)5 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)4 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)4 Subscription (org.wso2.carbon.apimgt.core.models.Subscription)4 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)4 Test (org.testng.annotations.Test)3 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)3 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)3 ApplicationEvent (org.wso2.carbon.apimgt.core.models.events.ApplicationEvent)3 PolicyEvent (org.wso2.carbon.apimgt.core.models.events.PolicyEvent)3 ThreatProtectionEvent (org.wso2.carbon.apimgt.core.models.events.ThreatProtectionEvent)3