Search in sources :

Example 26 with APIInfo

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

the class ApisApiServiceImpl method updateAPIThumbnail.

@Override
public Response updateAPIThumbnail(String apiId, InputStream fileInputStream, Attachment fileDetail, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String fileName = fileDetail.getDataHandler().getName();
        String extension = FilenameUtils.getExtension(fileName);
        if (!RestApiConstants.ALLOWED_THUMBNAIL_EXTENSIONS.contains(extension.toLowerCase())) {
            RestApiUtil.handleBadRequest("Unsupported Thumbnail File Extension. Supported extensions are .jpg, .png, .jpeg .svg " + "and .gif", log);
        }
        String fileContentType = URLConnection.guessContentTypeFromName(fileName);
        if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
            fileContentType = fileDetail.getContentType().toString();
        }
        PublisherCommonUtils.updateThumbnail(fileInputStream, fileContentType, apiProvider, apiId, organization);
        String uriString = RestApiConstants.RESOURCE_PATH_THUMBNAIL.replace(RestApiConstants.APIID_PARAM, apiId);
        URI uri = new URI(uriString);
        FileInfoDTO infoDTO = new FileInfoDTO();
        infoDTO.setRelativePath(uriString);
        infoDTO.setMediaType(fileContentType);
        return Response.created(uri).entity(infoDTO).build();
    } catch (APIManagementException e) {
        // 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 adding thumbnail for API : " + apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving thumbnail of API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while updating thumbnail of API: " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) FileInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.FileInfoDTO)

Example 27 with APIInfo

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

the class ApisApiServiceImpl method deleteAPIRevision.

/**
 * Delete a revision of an API
 *
 * @param apiId             UUID of the API
 * @param revisionId     Revision ID of the API
 * @param messageContext    message context object
 * @return response with 204 status code and no content
 */
@Override
public Response deleteAPIRevision(String apiId, String revisionId, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    // validate if api exists
    APIInfo apiInfo = validateAPIExistence(apiId);
    // validate API update operation permitted based on the LC state
    validateAPIOperationsPerLC(apiInfo.getStatus().toString());
    apiProvider.deleteAPIRevision(apiId, revisionId, organization);
    List<APIRevision> apiRevisions = apiProvider.getAPIRevisions(apiId);
    APIRevisionListDTO apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiRevisions);
    return Response.ok().entity(apiRevisionListDTO).build();
}
Also used : APIRevisionListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionListDTO) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 28 with APIInfo

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

the class ApisApiServiceImpl method addAPIDocument.

/**
 * Add a documentation to an API
 *
 * @param apiId api identifier
 * @param body  Documentation DTO as request body
 * @return created document DTO as response
 */
@Override
public Response addAPIDocument(String apiId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        Documentation documentation = PublisherCommonUtils.addDocumentationToAPI(body, apiId, organization);
        DocumentDTO newDocumentDTO = DocumentationMappingUtil.fromDocumentationToDTO(documentation);
        String uriString = RestApiConstants.RESOURCE_PATH_DOCUMENTS_DOCUMENT_ID.replace(RestApiConstants.APIID_PARAM, apiId).replace(RestApiConstants.DOCUMENTID_PARAM, documentation.getId());
        URI uri = new URI(uriString);
        return Response.created(uri).entity(newDocumentDTO).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 adding documents of API : " + apiId, e, log);
        } else {
            String errorMessage = "Error while adding the document for API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving location for document " + body.getName() + " of API " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 29 with APIInfo

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

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

the class ApisApiServiceImpl method reimportServiceFromCatalog.

@Override
public Response reimportServiceFromCatalog(String apiId, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String username = RestApiCommonUtil.getLoggedInUsername();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    int tenantId = APIUtil.getTenantId(username);
    try {
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
        API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
        String serviceKey = apiProvider.retrieveServiceKeyByApiId(originalAPI.getId().getId(), tenantId);
        ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
        ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
        JSONObject serviceInfo = new JSONObject();
        serviceInfo.put("name", service.getName());
        serviceInfo.put("version", service.getVersion());
        serviceInfo.put("key", service.getKey());
        serviceInfo.put("md5", service.getMd5());
        api.setServiceInfo(serviceInfo);
        Map validationResponseMap = new HashMap();
        if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
            validationResponseMap = validateOpenAPIDefinition(null, service.getEndpointDef(), null, null, true, true);
        } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
            validationResponseMap = validateAsyncAPISpecification(null, service.getEndpointDef(), null, true, true);
        } else if (!ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot re-import service to " + "API using the service type " + service.getDefinitionType(), log);
        }
        APIDefinitionValidationResponse validationAPIResponse = null;
        if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, service.getEndpointDef(), api, apiProvider, organization);
        } else {
            validationAPIResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
            if (!validationAPIResponse.isValid()) {
                RestApiUtil.handleBadRequest(validationAPIResponse.getErrorItems(), log);
            }
        }
        String protocol = (validationAPIResponse != null ? validationAPIResponse.getProtocol() : "");
        if (!APIConstants.API_TYPE_WEBSUB.equalsIgnoreCase(protocol)) {
            api.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
        }
        API updatedApi = apiProvider.updateAPI(api, originalAPI);
        if (validationAPIResponse != null) {
            PublisherCommonUtils.updateAPIDefinition(apiId, validationAPIResponse, service, organization);
        }
        return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
    } catch (APIManagementException e) {
        if (ExceptionCodes.MISSING_PROTOCOL_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
            RestApiUtil.handleBadRequest("Missing protocol in the Service Definition", log);
        } else if (ExceptionCodes.UNSUPPORTED_PROTOCOL_SPECIFIED_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
            RestApiUtil.handleBadRequest("Unsupported protocol specified in the Service Definition. Protocol " + "should be either sse or websub or ws", log);
        }
        RestApiUtil.handleInternalServerError("Error while retrieving the service key of the service " + "associated with API with id " + apiId, log);
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) JSONObject(org.json.simple.JSONObject) 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) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Aggregations

APIInfo (org.wso2.carbon.apimgt.api.model.APIInfo)20 ArrayList (java.util.ArrayList)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)16 HashMap (java.util.HashMap)7 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)7 APIInfo (org.wso2.carbon.apimgt.core.models.analytics.APIInfo)7 API (org.wso2.carbon.apimgt.core.models.API)5 WSDLValidationResponse (org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse)5 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 Response (javax.ws.rs.core.Response)4 HttpResponse (org.apache.http.HttpResponse)4 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 APIStateChangeResponse (org.wso2.carbon.apimgt.api.model.APIStateChangeResponse)4 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)4 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)4 Tier (org.wso2.carbon.apimgt.api.model.Tier)4 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)4 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3