Search in sources :

Example 56 with APIMgtResourceNotFoundException

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

the class ApisApiServiceImpl method deleteAPILifecycleStatePendingTasks.

@Override
public Response deleteAPILifecycleStatePendingTasks(String apiId, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        APIIdentifier apiIdentifierFromTable = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifierFromTable == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        apiProvider.deleteWorkflowTask(apiIdentifierFromTable);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting task ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 57 with APIMgtResourceNotFoundException

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

the class SubscriptionsApiServiceImpl method subscriptionsSubscriptionIdPut.

/**
 * Update already created subscriptions with the details specified in the body parameter
 *
 * @param body new subscription details
 * @return newly added subscription as a SubscriptionDTO if successful
 */
@Override
public Response subscriptionsSubscriptionIdPut(String subscriptionId, SubscriptionDTO body, String xWSO2Tenant, MessageContext messageContext) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer apiConsumer;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        apiConsumer = RestApiCommonUtil.getConsumer(username);
        String applicationId = body.getApplicationId();
        String currentThrottlingPolicy = body.getThrottlingPolicy();
        String requestedThrottlingPolicy = body.getRequestedThrottlingPolicy();
        SubscribedAPI subscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionId);
        // Check whether the subscription status is not empty and also not blocked
        if (body.getStatus() != null && subscribedAPI != null) {
            if ("BLOCKED".equals(body.getStatus().value()) || "ON_HOLD".equals(body.getStatus().value()) || "REJECTED".equals(body.getStatus().value()) || "BLOCKED".equals(subscribedAPI.getSubStatus()) || "ON_HOLD".equals(subscribedAPI.getSubStatus()) || "REJECTED".equals(subscribedAPI.getSubStatus())) {
                RestApiUtil.handleBadRequest("Cannot update subscriptions with provided or existing status", log);
                return null;
            }
        } else {
            RestApiUtil.handleBadRequest("Request must contain status of the subscription", log);
            return null;
        }
        // this will throw a APIMgtResourceNotFoundException
        if (body.getApiId() != null) {
            if (!RestAPIStoreUtils.isUserAccessAllowedForAPIByUUID(body.getApiId(), organization)) {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, body.getApiId(), log);
            }
        } else {
            RestApiUtil.handleBadRequest("Request must contain either apiIdentifier or apiProductIdentifier and the relevant type", log);
            return null;
        }
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application == null) {
            // required application not found
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            return null;
        }
        if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
            // application access failure occurred
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
        ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(body.getApiId(), organization);
        apiTypeWrapper.setTier(body.getThrottlingPolicy());
        SubscriptionResponse subscriptionResponse = apiConsumer.updateSubscription(apiTypeWrapper, username, application, subscriptionId, currentThrottlingPolicy, requestedThrottlingPolicy);
        SubscribedAPI addedSubscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionResponse.getSubscriptionUUID());
        SubscriptionDTO addedSubscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(addedSubscribedAPI, organization);
        WorkflowResponse workflowResponse = subscriptionResponse.getWorkflowResponse();
        if (workflowResponse instanceof HttpWorkflowResponse) {
            String payload = workflowResponse.getJSONPayload();
            addedSubscriptionDTO.setRedirectionParams(payload);
        }
        return Response.ok(new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTIONS + "/" + addedSubscribedAPI.getUUID())).entity(addedSubscriptionDTO).build();
    } catch (APIMgtAuthorizationFailedException e) {
        // this occurs when the api:application:tier mapping is not allowed. The reason for the message is taken from
        // the message of the exception e
        RestApiUtil.handleAuthorizationFailure(e.getMessage(), e, log);
    } catch (SubscriptionAlreadyExistingException e) {
        RestApiUtil.handleResourceAlreadyExistsError("Specified subscription already exists for API " + body.getApiId() + ", for application " + body.getApplicationId(), e, log);
    } catch (APIManagementException | URISyntaxException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            // this happens when the specified API identifier does not exist
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, body.getApiId(), e, log);
        } else {
            // unhandled exception
            RestApiUtil.handleInternalServerError("Error while adding the subscription API:" + body.getApiId() + ", application:" + body.getApplicationId() + ", tier:" + body.getThrottlingPolicy(), e, log);
        }
    }
    return null;
}
Also used : ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.HttpWorkflowResponse) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) HttpWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.HttpWorkflowResponse) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Application(org.wso2.carbon.apimgt.api.model.Application) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionDTO)

Example 58 with APIMgtResourceNotFoundException

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

the class PolicyDAOImpl method getSimplifiedPolicyByLevelAndName.

@Override
public Policy getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel policyLevel, String policyName) throws APIMgtDAOException, APIMgtResourceNotFoundException {
    Policy policy = null;
    final String apiPolicyQuery = "SELECT UUID,NAME FROM AM_API_POLICY WHERE NAME = ?";
    final String applicationPolicyQuery = "SELECT UUID,NAME FROM AM_APPLICATION_POLICY WHERE NAME = ?";
    final String subscriptionPolicyQuery = "SELECT UUID,NAME FROM AM_SUBSCRIPTION_POLICY WHERE NAME = ?";
    try (Connection connection = DAOUtil.getConnection()) {
        if (policyLevel.equals(APIMgtAdminService.PolicyLevel.api)) {
            try (PreparedStatement statement = connection.prepareStatement(apiPolicyQuery)) {
                statement.setString(1, policyName);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        policy = new APIPolicy(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_UUID), resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
                    }
                }
            }
        } else if (policyLevel.equals(APIMgtAdminService.PolicyLevel.application)) {
            try (PreparedStatement statement = connection.prepareStatement(applicationPolicyQuery)) {
                statement.setString(1, policyName);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        policy = new ApplicationPolicy(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_UUID), resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
                    }
                }
            }
        } else {
            try (PreparedStatement statement = connection.prepareStatement(subscriptionPolicyQuery)) {
                statement.setString(1, policyName);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        policy = new SubscriptionPolicy(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_UUID), resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
                    }
                }
            }
        }
    } catch (SQLException e) {
        String msg = "Error while retrieving policies";
        log.error(msg, e);
        throw new APIMgtDAOException(msg, ExceptionCodes.APIMGT_DAO_EXCEPTION);
    }
    if (policy == null) {
        throw new APIMgtResourceNotFoundException("Policy " + policyLevel + "Couldn't found " + policyName, ExceptionCodes.POLICY_NOT_FOUND);
    }
    return policy;
}
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) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) SQLException(java.sql.SQLException) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)

Example 59 with APIMgtResourceNotFoundException

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

the class GatewaysApiServiceImpl method gatewaysRegisterPost.

/**
 * Register gateway
 *
 * @param body        RegistrationDTO
 * @param contentType Content-Type header value
 * @return Registration summary details
 * @throws NotFoundException If failed to register gateway
 */
@Override
public Response gatewaysRegisterPost(RegistrationDTO body, String contentType, Request request) throws NotFoundException {
    try {
        LabelInfoDTO labelInfoDTO = body.getLabelInfo();
        if (labelInfoDTO != null) {
            APIMgtAdminService adminService = RestApiUtil.getAPIMgtAdminService();
            String overwriteLabels = labelInfoDTO.getOverwriteLabels();
            List<Label> labels = MappingUtil.convertToLabels(labelInfoDTO.getLabelList());
            adminService.registerGatewayLabels(labels, overwriteLabels);
            RegistrationSummary registrationSummary = adminService.getRegistrationSummary();
            return Response.ok().entity(MappingUtil.toRegistrationSummaryDTO(registrationSummary)).build();
        } else {
            String errorMessage = "Label information cannot be null";
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.LABEL_INFORMATION_CANNOT_BE_NULL);
            HashMap<String, String> paramList = new HashMap<String, String>();
            org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while registering the gateway";
        HashMap<String, String> paramList = new HashMap<String, String>();
        org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : HashMap(java.util.HashMap) Label(org.wso2.carbon.apimgt.core.models.Label) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException) LabelInfoDTO(org.wso2.carbon.apimgt.rest.api.core.dto.LabelInfoDTO) APIMgtAdminService(org.wso2.carbon.apimgt.core.api.APIMgtAdminService) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) RegistrationSummary(org.wso2.carbon.apimgt.core.models.RegistrationSummary)

Example 60 with APIMgtResourceNotFoundException

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

the class CompositeApisApiServiceImpl method compositeApisApiIdDedicatedGatewayGet.

/**
 * Retrieve Dedicated Gateway of an API
 *
 * @param apiId             UUID of API
 * @param ifNoneMatch       ifNoneMatch header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request           msf4j request object
 * @return 200 OK if the operation was successful
 * @throws NotFoundException when the particular resource does not exist
 */
@Override
public Response compositeApisApiIdDedicatedGatewayGet(String apiId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        if (!apiStore.isCompositeAPIExist(apiId)) {
            String errorMessage = "API not found : " + apiId;
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.API_NOT_FOUND);
            HashMap<String, String> paramList = new HashMap<String, String>();
            paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
        String existingFingerprint = compositeApisApiIdGetFingerprint(apiId, ifNoneMatch, ifModifiedSince, request);
        if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        DedicatedGateway dedicatedGateway = apiStore.getDedicatedGateway(apiId);
        if (dedicatedGateway != null) {
            DedicatedGatewayDTO dedicatedGatewayDTO = DedicatedGatewayMappingUtil.toDedicatedGatewayDTO(dedicatedGateway);
            return Response.ok().header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").entity(dedicatedGatewayDTO).build();
        } else {
            String msg = "Dedicated Gateway not found for " + apiId;
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(msg, ExceptionCodes.DEDICATED_GATEWAY_DETAILS_NOT_FOUND);
            HashMap<String, String> paramList = new HashMap<String, String>();
            paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(msg, e);
            return Response.status(Response.Status.NOT_FOUND).entity(errorDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving dedicated gateway of the API : " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException) DedicatedGatewayDTO(org.wso2.carbon.apimgt.rest.api.store.dto.DedicatedGatewayDTO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) DedicatedGateway(org.wso2.carbon.apimgt.core.models.DedicatedGateway)

Aggregations

APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)48 API (org.wso2.carbon.apimgt.api.model.API)22 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)22 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)22 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)21 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)21 HashMap (java.util.HashMap)19 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)19 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)17 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)16 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)14 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)14 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)12 APIRevision (org.wso2.carbon.apimgt.api.model.APIRevision)11 DeployedAPIRevision (org.wso2.carbon.apimgt.api.model.DeployedAPIRevision)11 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)10 ParseException (org.json.simple.parser.ParseException)9 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)9 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)8