Search in sources :

Example 36 with SubscribedAPI

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

use of org.wso2.carbon.apimgt.api.model.SubscribedAPI 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)

Example 38 with SubscribedAPI

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

the class SubscriptionMappingUtil method fromSubscriptionListToDTO.

/**
 * Converts a List object of SubscribedAPIs into a DTO
 *
 * @param subscriptions a list of SubscribedAPI objects
 * @param limit         max number of objects returned
 * @param offset        starting index
 * @param organization  identifier of the organization
 * @return SubscriptionListDTO object containing SubscriptionDTOs
 */
public static SubscriptionListDTO fromSubscriptionListToDTO(List<SubscribedAPI> subscriptions, Integer limit, Integer offset, String organization) throws APIManagementException {
    SubscriptionListDTO subscriptionListDTO = new SubscriptionListDTO();
    List<SubscriptionDTO> subscriptionDTOs = subscriptionListDTO.getList();
    if (subscriptionDTOs == null) {
        subscriptionDTOs = new ArrayList<>();
        subscriptionListDTO.setList(subscriptionDTOs);
    }
    // identifying the proper start and end indexes
    int size = subscriptions.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= size - 1 ? offset + limit - 1 : size - 1;
    for (int i = start; i <= end; i++) {
        try {
            SubscribedAPI subscription = subscriptions.get(i);
            subscriptionDTOs.add(fromSubscriptionToDTO(subscription, organization));
        } catch (APIManagementException e) {
            log.error("Error while obtaining api metadata", e);
        }
    }
    subscriptionListDTO.setCount(subscriptionDTOs.size());
    return subscriptionListDTO;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionDTO) SubscriptionListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionListDTO)

Example 39 with SubscribedAPI

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

the class SubscriptionMappingUtil method fromSubscriptionToDTO.

public static SubscriptionDTO fromSubscriptionToDTO(SubscribedAPI subscription, ApiTypeWrapper apiTypeWrapper, String organization) throws APIManagementException {
    SubscriptionDTO subscriptionDTO = new SubscriptionDTO();
    subscriptionDTO.setSubscriptionId(subscription.getUUID());
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    Set<String> deniedTiers = apiConsumer.getDeniedTiers(organization);
    Map<String, Tier> tierMap = APIUtil.getTiers(organization);
    if (apiTypeWrapper != null && !apiTypeWrapper.isAPIProduct()) {
        API api = apiTypeWrapper.getApi();
        subscriptionDTO.setApiId(api.getUUID());
        APIInfoDTO apiInfo = APIMappingUtil.fromAPIToInfoDTO(api);
        APIMappingUtil.setThrottlePoliciesAndMonetization(api, apiInfo, deniedTiers, tierMap);
        subscriptionDTO.setApiInfo(apiInfo);
    } else {
        APIProduct apiProduct = apiTypeWrapper.getApiProduct();
        subscriptionDTO.setApiId(apiProduct.getUuid());
        APIInfoDTO apiInfo = APIMappingUtil.fromAPIToInfoDTO(apiProduct, organization);
        APIMappingUtil.setThrottlePoliciesAndMonetization(apiProduct, apiInfo, deniedTiers, tierMap);
        subscriptionDTO.setApiInfo(apiInfo);
    }
    Application application = subscription.getApplication();
    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 : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) 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)

Example 40 with SubscribedAPI

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

the class APIConsumerImplTest method testRemoveSubscription.

@Test
public void testRemoveSubscription() throws APIManagementException, WorkflowException, APIPersistenceException {
    String uuid = UUID.randomUUID().toString();
    String apiUUID = UUID.randomUUID().toString();
    Subscriber subscriber = new Subscriber("sub1");
    Application application = new Application("app1", subscriber);
    application.setId(1);
    APIIdentifier identifier = new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION);
    identifier.setUuid(apiUUID);
    SubscribedAPI subscribedAPIOld = new SubscribedAPI(subscriber, identifier);
    subscribedAPIOld.setApplication(application);
    Mockito.when(apiMgtDAO.isAppAllowed(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    Mockito.when(apiMgtDAO.checkAPIUUIDIsARevisionUUID(Mockito.anyString())).thenReturn(null);
    DevPortalAPI devPortalAPI = Mockito.mock(DevPortalAPI.class);
    Mockito.when(apiPersistenceInstance.getDevPortalAPI(any(Organization.class), any(String.class))).thenReturn(devPortalAPI);
    SubscribedAPI subscribedAPINew = new SubscribedAPI(subscriber, identifier);
    subscribedAPINew.setUUID(uuid);
    subscribedAPINew.setApplication(application);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO, apiPersistenceInstance);
    apiConsumer.removeSubscription(subscribedAPINew, "org1");
    Mockito.verify(apiMgtDAO, Mockito.times(1)).getApplicationNameFromId(Mockito.anyInt());
    String workflowExtRef = "test_wf_ref";
    String workflowExtRef1 = "complete_wf_ref";
    Mockito.when(apiMgtDAO.getExternalWorkflowReferenceForSubscription((APIIdentifier) Mockito.any(), Mockito.anyInt(), Mockito.anyString())).thenReturn(workflowExtRef, workflowExtRef1);
    SubscriptionWorkflowDTO subscriptionWorkflowDTO = new SubscriptionWorkflowDTO();
    subscriptionWorkflowDTO.setWorkflowReference("1");
    Mockito.when(apiMgtDAO.retrieveWorkflow(workflowExtRef)).thenReturn(subscriptionWorkflowDTO);
    SubscribedAPI subscribedAPI = new SubscribedAPI("api1");
    subscribedAPI.setTier(new Tier("Gold"));
    Mockito.when(apiMgtDAO.getSubscriptionById(Mockito.anyInt())).thenReturn(subscribedAPI);
    Mockito.when(apiMgtDAO.getSubscriptionStatus(uuid, 1)).thenReturn(APIConstants.SubscriptionStatus.ON_HOLD);
    apiConsumer.removeSubscription(subscribedAPINew, "org1");
    Mockito.when(apiMgtDAO.retrieveWorkflow(workflowExtRef1)).thenReturn(subscriptionWorkflowDTO);
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn("abc.org");
    apiConsumer.removeSubscription(subscribedAPINew, "org1");
    Mockito.verify(apiMgtDAO, Mockito.times(2)).retrieveWorkflow(Mockito.anyString());
}
Also used : DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Matchers.anyString(org.mockito.Matchers.anyString) Application(org.wso2.carbon.apimgt.api.model.Application) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 Application (org.wso2.carbon.apimgt.api.model.Application)28 Tier (org.wso2.carbon.apimgt.api.model.Tier)23 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)16 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)14 ArrayList (java.util.ArrayList)12 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)12 HashSet (java.util.HashSet)11 TreeMap (java.util.TreeMap)11 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)11 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 SQLException (java.sql.SQLException)10 ResultSet (java.sql.ResultSet)9 JSONObject (net.minidev.json.JSONObject)9 API (org.wso2.carbon.apimgt.api.model.API)9