Search in sources :

Example 26 with APIResource

use of org.wso2.carbon.apimgt.api.doc.model.APIResource 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 27 with APIResource

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

the class APIProviderImpl method getUsedProductResources.

@Override
public List<APIResource> getUsedProductResources(String uuid) throws APIManagementException {
    List<APIResource> usedProductResources = new ArrayList<>();
    Map<Integer, URITemplate> uriTemplates = ApiMgtDAO.getInstance().getURITemplatesOfAPIWithProductMapping(uuid);
    for (URITemplate uriTemplate : uriTemplates.values()) {
        // If existing URITemplate is used by any API Products
        if (!uriTemplate.retrieveUsedByProducts().isEmpty()) {
            APIResource apiResource = new APIResource(uriTemplate.getHTTPVerb(), uriTemplate.getUriTemplate());
            usedProductResources.add(apiResource);
        }
    }
    return usedProductResources;
}
Also used : APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 28 with APIResource

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

the class APIUtil method createSwaggerJSONContent.

/**
 * Create API Definition in JSON
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to generate the content and save
 * @deprecated
 */
@Deprecated
public static String createSwaggerJSONContent(API api) throws APIManagementException {
    APIIdentifier identifier = api.getId();
    String organization = api.getOrganization();
    Environment environment = (Environment) getEnvironments(organization).values().toArray()[0];
    String endpoints = environment.getApiGatewayEndpoint();
    String[] endpointsSet = endpoints.split(",");
    String apiContext = api.getContext();
    String version = identifier.getVersion();
    Set<URITemplate> uriTemplates = api.getUriTemplates();
    String description = api.getDescription();
    // With the new context version strategy, the URL prefix is the apiContext. the verison will be embedded in
    // the apiContext.
    String urlPrefix = apiContext;
    if (endpointsSet.length < 1) {
        throw new APIManagementException("Error in creating JSON representation of the API" + identifier.getApiName());
    }
    if (description == null || "".equals(description)) {
        description = "";
    } else {
        description = description.trim();
    }
    Map<String, List<Operation>> uriTemplateDefinitions = new HashMap<String, List<Operation>>();
    List<APIResource> apis = new ArrayList<APIResource>();
    for (URITemplate template : uriTemplates) {
        List<Operation> ops;
        List<Parameter> parameters;
        String path = urlPrefix + APIUtil.removeAnySymbolFromUriTempate(template.getUriTemplate());
        /* path exists in uriTemplateDefinitions */
        if (uriTemplateDefinitions.get(path) != null) {
            ops = uriTemplateDefinitions.get(path);
            parameters = new ArrayList<Parameter>();
            String httpVerb = template.getHTTPVerb();
            /* For GET and DELETE Parameter name - Query Parameters */
            if (Constants.Configuration.HTTP_METHOD_GET.equals(httpVerb) || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpVerb)) {
                Parameter queryParam = new Parameter(APIConstants.OperationParameter.QUERY_PARAM_NAME, APIConstants.OperationParameter.QUERY_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(queryParam);
            } else {
                /* For POST, PUT and PATCH Parameter name - Payload */
                Parameter payLoadParam = new Parameter(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, APIConstants.OperationParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(payLoadParam);
            }
            Parameter authParam = new Parameter(APIConstants.OperationParameter.AUTH_PARAM_NAME, APIConstants.OperationParameter.AUTH_PARAM_DESCRIPTION, APIConstants.OperationParameter.AUTH_PARAM_TYPE, false, false, "String");
            parameters.add(authParam);
            if (!"OPTIONS".equals(httpVerb)) {
                Operation op = new Operation(httpVerb, description, description, parameters);
                ops.add(op);
            }
        } else {
            /* path not exists in uriTemplateDefinitions */
            ops = new ArrayList<Operation>();
            parameters = new ArrayList<Parameter>();
            String httpVerb = template.getHTTPVerb();
            /* For GET and DELETE Parameter name - Query Parameters */
            if (Constants.Configuration.HTTP_METHOD_GET.equals(httpVerb) || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpVerb)) {
                Parameter queryParam = new Parameter(APIConstants.OperationParameter.QUERY_PARAM_NAME, APIConstants.OperationParameter.QUERY_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(queryParam);
            } else {
                /* For POST,PUT and PATCH Parameter name - Payload */
                Parameter payLoadParam = new Parameter(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, APIConstants.OperationParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(payLoadParam);
            }
            Parameter authParam = new Parameter(APIConstants.OperationParameter.AUTH_PARAM_NAME, APIConstants.OperationParameter.AUTH_PARAM_DESCRIPTION, APIConstants.OperationParameter.AUTH_PARAM_TYPE, false, false, "String");
            parameters.add(authParam);
            if (!"OPTIONS".equals(httpVerb)) {
                Operation op = new Operation(httpVerb, description, description, parameters);
                ops.add(op);
            }
            uriTemplateDefinitions.put(path, ops);
        }
    }
    final Set<Entry<String, List<Operation>>> entries = uriTemplateDefinitions.entrySet();
    for (Entry entry : entries) {
        APIResource apiResource = new APIResource((String) entry.getKey(), description, (List<Operation>) entry.getValue());
        apis.add(apiResource);
    }
    APIDefinition apidefinition = new APIDefinition(version, APIConstants.SWAGGER_VERSION, endpointsSet[0], apiContext, apis);
    Gson gson = new Gson();
    return gson.toJson(apidefinition);
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Operation(org.wso2.carbon.apimgt.api.doc.model.Operation) Entry(java.util.Map.Entry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.doc.model.APIDefinition) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) Environment(org.wso2.carbon.apimgt.api.model.Environment) ExternalEnvironment(org.wso2.carbon.apimgt.impl.ExternalEnvironment) Parameter(org.wso2.carbon.apimgt.api.doc.model.Parameter) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SolrDocumentList(org.apache.solr.common.SolrDocumentList) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)14 APIResource (org.wso2.carbon.apimgt.api.doc.model.APIResource)13 ArrayList (java.util.ArrayList)12 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)11 HashMap (java.util.HashMap)10 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)8 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)8 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)7 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)7 Map (java.util.Map)6 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 API (org.wso2.carbon.apimgt.api.model.API)5 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)5 List (java.util.List)4 JSONObject (org.json.simple.JSONObject)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 APIResource (org.wso2.carbon.apimgt.core.models.APIResource)4 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)4 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)4