Search in sources :

Example 26 with ApiTypeWrapper

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

the class ApisApiServiceImpl method getCommentOfAPI.

@Override
public Response getCommentOfAPI(String commentId, String apiId, String xWSO2Tenant, String ifNoneMatch, Boolean includeCommenterInfo, Integer replyLimit, Integer replyOffset, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
        Comment comment = apiConsumer.getComment(apiTypeWrapper, commentId, replyLimit, replyOffset);
        if (comment != null) {
            CommentDTO commentDTO;
            if (includeCommenterInfo) {
                Map<String, Map<String, String>> userClaimsMap = CommentMappingUtil.retrieveUserClaims(comment.getUser(), new HashMap<>());
                commentDTO = CommentMappingUtil.fromCommentToDTOWithUserInfo(comment, userClaimsMap);
            } else {
                commentDTO = CommentMappingUtil.fromCommentToDTO(comment);
            }
            String uriString = RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + RestApiConstants.RESOURCE_PATH_COMMENTS + "/" + commentId;
            URI uri = new URI(uriString);
            return Response.ok(uri).entity(commentDTO).build();
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving comment for API : " + apiId + "with comment ID " + commentId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving comment content location : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : Comment(org.wso2.carbon.apimgt.api.model.Comment) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) URISyntaxException(java.net.URISyntaxException) Map(java.util.Map) HashMap(java.util.HashMap) URI(java.net.URI)

Example 27 with ApiTypeWrapper

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

the class ApisApiServiceImpl method getAPIByAPIId.

private APIDTO getAPIByAPIId(String apiId, String organization) {
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        ApiTypeWrapper api = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
        String status = api.getStatus();
        // Extracting clicked API name by the user, for the recommendation system
        String userName = RestApiCommonUtil.getLoggedInUsername();
        apiConsumer.publishClickedAPI(api, userName);
        if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
            return APIMappingUtil.fromAPItoDTO(api, organization);
        } else {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 28 with ApiTypeWrapper

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

the class ApisApiServiceImpl method deleteComment.

@Override
public Response deleteComment(String commentId, String apiId, String ifMatch, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    String username = RestApiCommonUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
        Comment comment = apiConsumer.getComment(apiTypeWrapper, commentId, 0, 0);
        if (comment != null) {
            String[] tokenScopes = (String[]) PhaseInterceptorChain.getCurrentMessage().getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
            if (Arrays.asList(tokenScopes).contains("apim:admin") || comment.getUser().equals(username)) {
                if (apiConsumer.deleteComment(apiTypeWrapper, commentId)) {
                    JSONObject obj = new JSONObject();
                    obj.put("id", commentId);
                    obj.put("message", "The comment has been deleted");
                    return Response.ok(obj).type(MediaType.APPLICATION_JSON).build();
                } else {
                    return Response.status(405, "Method Not Allowed").type(MediaType.APPLICATION_JSON).build();
                }
            } else {
                return Response.status(403, "Forbidden").type(MediaType.APPLICATION_JSON).build();
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            String errorMessage = "Error while deleting comment " + commentId + "for API " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : Comment(org.wso2.carbon.apimgt.api.model.Comment) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 29 with ApiTypeWrapper

use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper 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 30 with ApiTypeWrapper

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

the class SubscriptionMappingUtil method fromSubscriptionToDTO.

/**
 * Converts a SubscribedAPI object into SubscriptionDTO
 *
 * @param subscription SubscribedAPI object
 * @param organization Identifier of the organization
 * @return SubscriptionDTO corresponds to SubscribedAPI object
 */
public static SubscriptionDTO fromSubscriptionToDTO(SubscribedAPI subscription, String organization) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    SubscriptionDTO subscriptionDTO = new SubscriptionDTO();
    subscriptionDTO.setSubscriptionId(subscription.getUUID());
    APIInfoDTO apiInfo;
    Identifier apiId = subscription.getIdentifier();
    ApiTypeWrapper apiTypeWrapper;
    try {
        apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(subscription.getIdentifier().getUUID(), organization);
        subscriptionDTO.setApiId(subscription.getIdentifier().getUUID());
        Set<String> deniedTiers = apiConsumer.getDeniedTiers(organization);
        Map<String, Tier> tierMap = APIUtil.getTiers(organization);
        if (apiTypeWrapper.isAPIProduct()) {
            apiInfo = APIMappingUtil.fromAPIToInfoDTO(apiTypeWrapper.getApiProduct(), organization);
            APIMappingUtil.setThrottlePoliciesAndMonetization(apiTypeWrapper.getApiProduct(), apiInfo, deniedTiers, tierMap);
        } else {
            apiInfo = APIMappingUtil.fromAPIToInfoDTO(apiTypeWrapper.getApi());
            APIMappingUtil.setThrottlePoliciesAndMonetization(apiTypeWrapper.getApi(), apiInfo, deniedTiers, tierMap);
        }
        subscriptionDTO.setApiInfo(apiInfo);
    } catch (APIManagementException e) {
        if (log.isDebugEnabled()) {
            log.debug("User :" + username + " does not have access to the API " + apiId);
        }
        apiInfo = new APIInfoDTO();
        apiInfo.setName(apiId.getName());
        apiInfo.setVersion(apiId.getVersion());
        subscriptionDTO.setApiInfo(apiInfo);
    }
    Application application = subscription.getApplication();
    application = apiConsumer.getLightweightApplicationByUUID(application.getUUID());
    subscriptionDTO.setApplicationId(subscription.getApplication().getUUID());
    subscriptionDTO.setStatus(SubscriptionDTO.StatusEnum.valueOf(subscription.getSubStatus()));
    subscriptionDTO.setThrottlingPolicy(subscription.getTier().getName());
    subscriptionDTO.setRequestedThrottlingPolicy(subscription.getRequestedTier().getName());
    ApplicationInfoDTO applicationInfoDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(application);
    subscriptionDTO.setApplicationInfo(applicationInfoDTO);
    return subscriptionDTO;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) Tier(org.wso2.carbon.apimgt.api.model.Tier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ApplicationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationInfoDTO) APIInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIInfoDTO) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionDTO) Application(org.wso2.carbon.apimgt.api.model.Application)

Aggregations

ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)41 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 API (org.wso2.carbon.apimgt.api.model.API)24 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)24 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)16 URI (java.net.URI)14 URISyntaxException (java.net.URISyntaxException)14 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)14 Application (org.wso2.carbon.apimgt.api.model.Application)14 ArrayList (java.util.ArrayList)13 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)11 Tier (org.wso2.carbon.apimgt.api.model.Tier)10 Comment (org.wso2.carbon.apimgt.api.model.Comment)9 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 SubscriptionAlreadyExistingException (org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException)7 Identifier (org.wso2.carbon.apimgt.api.model.Identifier)7