Search in sources :

Example 61 with SubscribedAPI

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

the class SolaceBrokerDeployer method undeployWhenRetire.

/**
 * Undeploy API artifact from provided environment in the external gateway when Api is retired
 *
 * @param api         API to be undeployed from the external gateway
 * @param environment Environment needed to be undeployed API from the external gateway
 * @throws DeployerException if error occurs when undeploying APIs from the external gateway
 */
public boolean undeployWhenRetire(API api, Environment environment) throws DeployerException {
    Application application;
    APIProvider apiProvider;
    // Remove subscription
    try {
        apiProvider = APIManagerFactory.getInstance().getAPIProvider(CarbonContext.getThreadLocalCarbonContext().getUsername());
        List<SubscribedAPI> apiUsages = apiProvider.getAPIUsageByAPIId(api.getUuid(), api.getOrganization());
        for (SubscribedAPI usage : apiUsages) {
            application = usage.getApplication();
            // Check whether the subscription is belongs to an API deployed in Solace
            if (SolaceConstants.SOLACE_ENVIRONMENT.equals(api.getGatewayVendor())) {
                SolaceNotifierUtils.unsubscribeAPIProductFromSolaceApplication(api, application);
            }
        }
    } catch (APIManagementException e) {
        throw new DeployerException("Error occurred when removing subscriptions of the API " + api.getUuid() + "to be retired", e);
    }
    // undeploy API from Solace
    boolean deletedFromSolace = undeploy(api.getId().getName(), api.getId().getVersion(), api.getContext(), environment);
    if (!deletedFromSolace) {
        throw new DeployerException("Error while deleting API product of API " + api.getUuid() + "from Solace " + "broker");
    }
    return true;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DeployerException(org.wso2.carbon.apimgt.impl.deployer.exceptions.DeployerException) Application(org.wso2.carbon.apimgt.api.model.Application) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 62 with SubscribedAPI

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

the class APIProviderImpl method getAPIUsageByAPIId.

/**
 * Returns usage details of a particular API
 *
 * @param uuid API uuid
 * @param organization identifier of the organization
 * @return UserApplicationAPIUsages for given provider
 * @throws org.wso2.carbon.apimgt.api.APIManagementException If failed to get UserApplicationAPIUsage
 */
@Override
public List<SubscribedAPI> getAPIUsageByAPIId(String uuid, String organization) throws APIManagementException {
    APIIdentifier identifier = apiMgtDAO.getAPIIdentifierFromUUID(uuid);
    List<SubscribedAPI> subscribedAPIs = new ArrayList<>();
    if (identifier != null) {
        APIIdentifier apiIdEmailReplaced = new APIIdentifier(APIUtil.replaceEmailDomain(identifier.getProviderName()), identifier.getApiName(), identifier.getVersion());
        UserApplicationAPIUsage[] allApiResult = apiMgtDAO.getAllAPIUsageByProviderAndApiId(uuid, organization);
        for (UserApplicationAPIUsage usage : allApiResult) {
            for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) {
                APIIdentifier subsApiId = apiSubscription.getApiId();
                APIIdentifier subsApiIdEmailReplaced = new APIIdentifier(APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), subsApiId.getVersion());
                if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) {
                    subscribedAPIs.add(apiSubscription);
                }
            }
        }
    }
    return subscribedAPIs;
}
Also used : UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 63 with SubscribedAPI

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

the class APIProviderImpl method updateSubscription.

/**
 * This method is used to update the subscription
 *
 * @param subscribedAPI subscribedAPI object that represents the new subscription detals
 * @throws APIManagementException if failed to update subscription
 */
public void updateSubscription(SubscribedAPI subscribedAPI) throws APIManagementException {
    apiMgtDAO.updateSubscription(subscribedAPI);
    subscribedAPI = apiMgtDAO.getSubscriptionByUUID(subscribedAPI.getUUID());
    Identifier identifier = subscribedAPI.getApiId() != null ? subscribedAPI.getApiId() : subscribedAPI.getProductId();
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
    SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscribedAPI.getSubscriptionId(), subscribedAPI.getUUID(), identifier.getId(), identifier.getUUID(), subscribedAPI.getApplication().getId(), subscribedAPI.getApplication().getUUID(), subscribedAPI.getTier().getName(), subscribedAPI.getSubStatus());
    APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier)

Example 64 with SubscribedAPI

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

the class SubscriptionsApiServiceImpl method subscriptionsPost.

/**
 * Creates a new 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 subscriptionsPost(SubscriptionDTO body, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer apiConsumer;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String userOrganization = RestApiUtil.getValidatedSubjectOrganization(messageContext);
        apiConsumer = RestApiCommonUtil.getConsumer(username, userOrganization);
        String applicationId = body.getApplicationId();
        // 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 application creation workflow status is pending or rejected, throw a Bad request exception
        if (application.getStatus().equals(WorkflowStatus.REJECTED.toString()) || application.getStatus().equals(WorkflowStatus.CREATED.toString())) {
            RestApiUtil.handleBadRequest("Workflow status is not Approved", 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.addSubscription(apiTypeWrapper, username, application);
        SubscribedAPI addedSubscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionResponse.getSubscriptionUUID());
        SubscriptionDTO addedSubscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(addedSubscribedAPI, apiTypeWrapper, organization);
        WorkflowResponse workflowResponse = subscriptionResponse.getWorkflowResponse();
        if (workflowResponse instanceof HttpWorkflowResponse) {
            String payload = workflowResponse.getJSONPayload();
            addedSubscriptionDTO.setRedirectionParams(payload);
        }
        return Response.created(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 (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) 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 65 with SubscribedAPI

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

the class SubscriptionsApiServiceImpl method getAdditionalInfoOfAPISubscriptions.

/**
 * Get additional Info details of subscriptions attached with given API
 *
 * @param apiId         apiId
 * @param offset        starting index of the subscription list
 * @param limit         max num of subscriptions returned
 * @param ifNoneMatch   If-None-Match header value
 * @param messageContext message context
 * @return Response with additional Info of the GraphQL API
 */
@Override
public Response getAdditionalInfoOfAPISubscriptions(String apiId, String groupId, String xWSO2Tenant, Integer offset, Integer limit, String ifNoneMatch, MessageContext messageContext) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    Subscriber subscriber = new Subscriber(username);
    Set<SubscribedAPI> subscriptions;
    List<SubscribedAPI> subscribedAPIList = new ArrayList<>();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        AdditionalSubscriptionInfoListDTO additionalSubscriptionInfoListDTO;
        ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
        if (apiTypeWrapper.isAPIProduct()) {
            subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApiProduct().getId(), groupId, organization);
        } else {
            subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApi().getId(), groupId, organization);
        }
        // Sort subscriptions by application name
        subscribedAPIList.addAll(subscriptions);
        subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));
        additionalSubscriptionInfoListDTO = AdditionalSubscriptionInfoMappingUtil.fromAdditionalSubscriptionInfoListToDTO(subscribedAPIList, limit, offset, organization);
        AdditionalSubscriptionInfoMappingUtil.setPaginationParams(additionalSubscriptionInfoListDTO, apiId, "", limit, offset, subscribedAPIList.size());
        return Response.ok().entity(additionalSubscriptionInfoListDTO).build();
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving additional information details of the API : " + apiId, e, log);
        } else {
            String msg = "Error while retrieving additional information details of the API " + apiId;
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    }
    return null;
}
Also used : AdditionalSubscriptionInfoListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoListDTO) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) WorkflowStatus(org.wso2.carbon.apimgt.api.WorkflowStatus) SubscriptionsApiService(org.wso2.carbon.apimgt.rest.api.store.v1.SubscriptionsApiService) SubscriptionMappingUtil(org.wso2.carbon.apimgt.rest.api.store.v1.mappings.SubscriptionMappingUtil) SubscriptionListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionListDTO) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) URISyntaxException(java.net.URISyntaxException) HttpWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.HttpWorkflowResponse) RestAPIStoreUtils(org.wso2.carbon.apimgt.rest.api.util.utils.RestAPIStoreUtils) StringUtils(org.apache.commons.lang3.StringUtils) APIMappingUtil(org.wso2.carbon.apimgt.rest.api.store.v1.mappings.APIMappingUtil) ArrayList(java.util.ArrayList) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionDTO) RestApiCommonUtil(org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil) AdditionalSubscriptionInfoMappingUtil(org.wso2.carbon.apimgt.rest.api.store.v1.mappings.AdditionalSubscriptionInfoMappingUtil) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) Map(java.util.Map) Monetization(org.wso2.carbon.apimgt.api.model.Monetization) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) URI(java.net.URI) Application(org.wso2.carbon.apimgt.api.model.Application) MapUtils(org.apache.commons.collections.MapUtils) APIMonetizationUsageDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationUsageDTO) APIUtil(org.wso2.carbon.apimgt.impl.utils.APIUtil) Set(java.util.Set) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) List(java.util.List) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Response(javax.ws.rs.core.Response) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Comparator(java.util.Comparator) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) AdditionalSubscriptionInfoListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoListDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

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