Search in sources :

Example 41 with SubscribedAPI

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

the class ApiProductsApiServiceImpl method deleteAPIProduct.

@Override
public Response deleteAPIProduct(String apiProductId, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProductIdentifier apiProductIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        if (log.isDebugEnabled()) {
            log.debug("Delete API Product request: Id " + apiProductId + " by " + username);
        }
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, organization);
        if (apiProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }
        boolean isAPIPublishedOrDeprecated = APIStatus.PUBLISHED.getStatus().equals(apiProduct.getState()) || APIStatus.DEPRECATED.getStatus().equals(apiProduct.getState());
        List<SubscribedAPI> apiUsages = apiProvider.getAPIProductUsageByAPIProductId(apiProductIdentifier);
        if (isAPIPublishedOrDeprecated && (apiUsages != null && apiUsages.size() > 0)) {
            RestApiUtil.handleConflict("Cannot remove the API " + apiProductIdentifier + " as active subscriptions exist", log);
        }
        apiProduct.setOrganization(organization);
        apiProvider.deleteAPIProduct(apiProduct);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting API Product : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 42 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
 * @return SubscriptionListDTO object containing SubscriptionDTOs
 */
public static SubscriptionListDTO fromSubscriptionListToDTO(List<SubscribedAPI> subscriptions, Integer limit, Integer offset) 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++) {
        SubscribedAPI subscription = subscriptions.get(i);
        subscriptionDTOs.add(fromSubscriptionToDTO(subscription));
    }
    subscriptionListDTO.setCount(subscriptionDTOs.size());
    return subscriptionListDTO;
}
Also used : SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.SubscriptionDTO) SubscriptionListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.SubscriptionListDTO)

Example 43 with SubscribedAPI

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

the class ExportUtils method createApplicationDTOToExport.

/**
 * Create an aggregated Application DTO to be exported.
 *
 * @param application Application{@link Application} to be exported
 * @param apiConsumer API Consumer
 * @param withKeys    Export the Application with keys or not
 * @return Exported application
 * @throws APIManagementException If an error occurs while retrieving subscribed APIs
 */
private static ExportedApplication createApplicationDTOToExport(Application application, APIConsumer apiConsumer, Boolean withKeys) throws APIManagementException {
    ApplicationDTO applicationDto = ApplicationMappingUtil.fromApplicationtoDTO(application);
    // Set keys if withKeys is true
    if (withKeys == null || !withKeys) {
        application.clearOAuthApps();
    } else {
        List<ApplicationKeyDTO> applicationKeyDTOs = new ArrayList<>();
        for (APIKey apiKey : application.getKeys()) {
            // Encode the consumer secret and set it
            apiKey.setConsumerSecret(new String(Base64.encodeBase64(apiKey.getConsumerSecret().getBytes(Charset.defaultCharset()))));
            ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(apiKey);
            applicationKeyDTOs.add(applicationKeyDTO);
        }
        applicationDto.setKeys(applicationKeyDTOs);
    }
    // Get the subscribed API details and add it to a set
    Set<SubscribedAPI> subscribedAPIs = apiConsumer.getSubscribedAPIs(application.getSubscriber(), application.getName(), application.getGroupId());
    Set<ExportedSubscribedAPI> exportedSubscribedAPIs = new HashSet<>();
    for (SubscribedAPI subscribedAPI : subscribedAPIs) {
        ExportedSubscribedAPI exportedSubscribedAPI = new ExportedSubscribedAPI(subscribedAPI.getApiId(), subscribedAPI.getSubscriber(), subscribedAPI.getTier().getName());
        exportedSubscribedAPIs.add(exportedSubscribedAPI);
    }
    // Set the subscription count by counting the number of subscribed APIs
    applicationDto.setSubscriptionCount(exportedSubscribedAPIs.size());
    // Set the application
    ExportedApplication exportedApplication = new ExportedApplication(applicationDto);
    // Set the subscribed APIs
    exportedApplication.setSubscribedAPIs(exportedSubscribedAPIs);
    return exportedApplication;
}
Also used : ExportedSubscribedAPI(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedSubscribedAPI) ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO) APIKey(org.wso2.carbon.apimgt.api.model.APIKey) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ExportedSubscribedAPI(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedSubscribedAPI) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) HashSet(java.util.HashSet)

Example 44 with SubscribedAPI

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

the class ApisApiServiceImpl method deleteAPI.

/**
 * Delete API
 *
 * @param apiId   API Id
 * @param ifMatch If-Match header value
 * @return Status of API Deletion
 */
@Override
public Response deleteAPI(String apiId, String ifMatch, MessageContext messageContext) {
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        boolean isAPIExistDB = false;
        APIManagementException error = null;
        APIInfo apiInfo = null;
        try {
            // validate if api exists
            apiInfo = validateAPIExistence(apiId);
            isAPIExistDB = true;
        } catch (APIManagementException e) {
            log.error("Error while validating API existence for deleting API " + apiId + " on organization " + organization);
            error = e;
        }
        if (isAPIExistDB) {
            // validate API update operation permitted based on the LC state
            validateAPIOperationsPerLC(apiInfo.getStatus().toString());
            try {
                // check if the API has subscriptions
                // Todo : need to optimize this check. This method seems too costly to check if subscription exists
                List<SubscribedAPI> apiUsages = apiProvider.getAPIUsageByAPIId(apiId, organization);
                if (apiUsages != null && apiUsages.size() > 0) {
                    RestApiUtil.handleConflict("Cannot remove the API " + apiId + " as active subscriptions exist", log);
                }
            } catch (APIManagementException e) {
                log.error("Error while checking active subscriptions for deleting API " + apiId + " on organization " + organization);
                error = e;
            }
            try {
                List<APIResource> usedProductResources = apiProvider.getUsedProductResources(apiId);
                if (!usedProductResources.isEmpty()) {
                    RestApiUtil.handleConflict("Cannot remove the API because following resource paths " + usedProductResources.toString() + " are used by one or more API Products", log);
                }
            } catch (APIManagementException e) {
                log.error("Error while checking API products using same resources for deleting API " + apiId + " on organization " + organization);
                error = e;
            }
        }
        // Delete the API
        boolean isDeleted = false;
        try {
            apiProvider.deleteAPI(apiId, organization);
            isDeleted = true;
        } catch (APIManagementException e) {
            log.error("Error while deleting API " + apiId + "on organization " + organization, e);
        }
        if (error != null) {
            throw error;
        } else if (!isDeleted) {
            RestApiUtil.handleInternalServerError("Error while deleting API : " + apiId + " on organization " + organization, log);
            return null;
        }
        return Response.ok().build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while deleting API : " + apiId, e, log);
        } else {
            String errorMessage = "Error while deleting API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 45 with SubscribedAPI

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

the class SubscriptionsApiServiceImpl method blockSubscription.

/**
 * Blocks a subscription
 *
 * @param subscriptionId Subscription identifier
 * @param blockState block state; either BLOCKED or PROD_ONLY_BLOCKED
 * @param ifMatch If-Match header value
 * @return 200 response and the updated subscription if subscription block is successful
 */
public Response blockSubscription(String subscriptionId, String blockState, String ifMatch, MessageContext messageContext) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        // validates the subscriptionId if it exists
        SubscribedAPI currentSubscription = apiProvider.getSubscriptionByUUID(subscriptionId);
        if (currentSubscription == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_SUBSCRIPTION, subscriptionId, log);
        }
        SubscribedAPI subscribedAPI = new SubscribedAPI(subscriptionId);
        subscribedAPI.setSubStatus(blockState);
        apiProvider.updateSubscription(subscribedAPI);
        SubscribedAPI updatedSubscription = apiProvider.getSubscriptionByUUID(subscriptionId);
        SubscriptionDTO subscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(updatedSubscription);
        return Response.ok().entity(subscriptionDTO).build();
    } catch (APIManagementException e) {
        String msg = "Error while blocking the subscription " + subscriptionId;
        RestApiUtil.handleInternalServerError(msg, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.SubscriptionDTO)

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