Search in sources :

Example 71 with APIProvider

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

the class ApisApiServiceImpl method getAllAPIs.

@Override
public Response getAllAPIs(Integer limit, Integer offset, String sortBy, String sortOrder, String xWSO2Tenant, String query, String ifNoneMatch, String accept, MessageContext messageContext) {
    List<API> allMatchedApis = new ArrayList<>();
    Object apiListDTO;
    // pre-processing
    // setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    query = query == null ? "" : query;
    sortBy = sortBy != null ? sortBy : RestApiConstants.DEFAULT_SORT_CRITERION;
    sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER;
    try {
        // revert content search back to normal search by name to avoid doc result complexity and to comply with REST api practices
        if (query.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX + ":")) {
            query = query.replace(APIConstants.CONTENT_SEARCH_TYPE_PREFIX + ":", APIConstants.NAME_TYPE_PREFIX + ":");
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // boolean migrationMode = Boolean.getBoolean(RestApiConstants.MIGRATION_MODE);
        /*if (migrationMode) { // migration flow
                if (!StringUtils.isEmpty(targetTenantDomain)) {
                    tenantDomain = targetTenantDomain;
                }
                RestApiUtil.handleMigrationSpecificPermissionViolations(tenantDomain, username);
            }*/
        Map<String, Object> result;
        result = apiProvider.searchPaginatedAPIs(query, organization, offset, limit, sortBy, sortOrder);
        Set<API> apis = (Set<API>) result.get("apis");
        allMatchedApis.addAll(apis);
        apiListDTO = APIMappingUtil.fromAPIListToDTO(allMatchedApis);
        // Add pagination section in the response
        Object totalLength = result.get("length");
        Integer length = 0;
        if (totalLength != null) {
            length = (Integer) totalLength;
        }
        APIMappingUtil.setPaginationParams(apiListDTO, query, offset, limit, length);
        if (APIConstants.APPLICATION_GZIP.equals(accept)) {
            try {
                File zippedResponse = GZIPUtils.constructZippedResponse(apiListDTO);
                return Response.ok().entity(zippedResponse).header("Content-Disposition", "attachment").header("Content-Encoding", "gzip").build();
            } catch (APIManagementException e) {
                RestApiUtil.handleInternalServerError(e.getMessage(), e, log);
            }
        } else {
            return Response.ok().entity(apiListDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving APIs";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : Set(java.util.Set) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) JSONObject(org.json.simple.JSONObject) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 72 with APIProvider

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

the class ApisApiServiceImpl method apisApiIdEnvironmentsEnvIdKeysGet.

@Override
public Response apisApiIdEnvironmentsEnvIdKeysGet(String apiId, String envId, MessageContext messageContext) throws APIManagementException {
    // validate api UUID
    validateAPIExistence(apiId);
    // validate environment UUID
    validateEnvironment(envId);
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    // get properties
    EnvironmentPropertiesDTO properties = apiProvider.getEnvironmentSpecificAPIProperties(apiId, envId);
    // convert to string to remove null values
    String jsonContent = new Gson().toJson(properties);
    return Response.ok().entity(jsonContent).build();
}
Also used : Gson(com.google.gson.Gson) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) EnvironmentPropertiesDTO(org.wso2.carbon.apimgt.api.dto.EnvironmentPropertiesDTO)

Example 73 with APIProvider

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

the class ApisApiServiceImpl method addAPIMonetization.

/**
 * Monetize (enable or disable) for a given API
 *
 * @param apiId API ID
 * @param body request body
 * @param messageContext message context
 * @return monetizationDTO
 */
@Override
public Response addAPIMonetization(String apiId, APIMonetizationInfoDTO body, MessageContext messageContext) {
    try {
        if (StringUtils.isBlank(apiId)) {
            String errorMessage = "API ID cannot be empty or null when configuring monetization.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifier == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        if (!APIConstants.PUBLISHED.equalsIgnoreCase(api.getStatus())) {
            String errorMessage = "API " + apiIdentifier.getApiName() + " should be in published state to configure monetization.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        // set the monetization status
        boolean monetizationEnabled = body.isEnabled();
        api.setMonetizationStatus(monetizationEnabled);
        // clear the existing properties related to monetization
        api.getMonetizationProperties().clear();
        Map<String, String> monetizationProperties = body.getProperties();
        if (MapUtils.isNotEmpty(monetizationProperties)) {
            String errorMessage = RestApiPublisherUtils.validateMonetizationProperties(monetizationProperties);
            if (!errorMessage.isEmpty()) {
                RestApiUtil.handleBadRequest(errorMessage, log);
            }
            for (Map.Entry<String, String> currentEntry : monetizationProperties.entrySet()) {
                api.addMonetizationProperty(currentEntry.getKey(), currentEntry.getValue());
            }
        }
        Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
        HashMap monetizationDataMap = new Gson().fromJson(api.getMonetizationProperties().toString(), HashMap.class);
        boolean isMonetizationStateChangeSuccessful = false;
        if (MapUtils.isEmpty(monetizationDataMap)) {
            String errorMessage = "Monetization is not configured. Monetization data is empty for " + apiIdentifier.getApiName();
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        try {
            if (monetizationEnabled) {
                isMonetizationStateChangeSuccessful = monetizationImplementation.enableMonetization(organization, api, monetizationDataMap);
            } else {
                isMonetizationStateChangeSuccessful = monetizationImplementation.disableMonetization(organization, api, monetizationDataMap);
            }
        } catch (MonetizationException e) {
            String errorMessage = "Error while changing monetization status for API ID : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
        if (isMonetizationStateChangeSuccessful) {
            apiProvider.configureMonetizationInAPIArtifact(api);
            APIMonetizationInfoDTO monetizationInfoDTO = APIMappingUtil.getMonetizationInfoDTO(apiId, organization);
            return Response.ok().entity(monetizationInfoDTO).build();
        } else {
            String errorMessage = "Unable to change monetization status for API : " + apiId;
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while configuring monetization for API ID : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return Response.serverError().build();
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO)

Example 74 with APIProvider

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

the class ApisApiServiceImpl method getGraphQLPolicyComplexityOfAPI.

/**
 * Get complexity details of a given API
 *
 * @param apiId          apiId
 * @param messageContext message context
 * @return Response with complexity details of the GraphQL API
 */
@Override
public Response getGraphQLPolicyComplexityOfAPI(String apiId, MessageContext messageContext) throws APIManagementException {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        if (APIConstants.GRAPHQL_API.equals(api.getType())) {
            GraphqlComplexityInfo graphqlComplexityInfo = apiProvider.getComplexityDetails(apiId);
            GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO = GraphqlQueryAnalysisMappingUtil.fromGraphqlComplexityInfotoDTO(graphqlComplexityInfo);
            return Response.ok().entity(graphQLQueryComplexityInfoDTO).build();
        } else {
            throw new APIManagementException(ExceptionCodes.API_NOT_GRAPHQL);
        }
    } catch (APIManagementException e) {
        // 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 retrieving complexity details of API : " + apiId, e, log);
        } else {
            String msg = "Error while retrieving complexity details of API " + apiId;
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    }
    return null;
}
Also used : GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) GraphQLQueryComplexityInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLQueryComplexityInfoDTO)

Example 75 with APIProvider

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

the class ApisApiServiceImpl method validateEnvironment.

private void validateEnvironment(String envId) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    // if apiProvider.getEnvironment(tenantDomain, envId) return null, it will throw an exception
    apiProvider.getEnvironment(tenantDomain, envId);
}
Also used : APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)207 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)198 API (org.wso2.carbon.apimgt.api.model.API)92 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 Test (org.junit.Test)82 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)82 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)73 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)65 IOException (java.io.IOException)40 ArrayList (java.util.ArrayList)36 URISyntaxException (java.net.URISyntaxException)34 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)32 URI (java.net.URI)31 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)31 JSONObject (org.json.simple.JSONObject)29 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)29 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)29 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)28 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)28 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)23