Search in sources :

Example 16 with APIDefinitionValidationResponse

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

the class ApisApiServiceImpl method validateOpenAPIDefinition.

/**
 * Validate the provided OpenAPI definition (via file or url) and return a Map with the validation response
 * information.
 *
 * @param url OpenAPI definition url
 * @param fileInputStream file as input stream
 * @param apiDefinition Swagger API definition String
 * @param returnContent whether to return the content of the definition in the response DTO
 * @return Map with the validation response information. A value with key 'dto' will have the response DTO
 *  of type OpenAPIDefinitionValidationResponseDTO for the REST API. A value with key 'model' will have the
 *  validation response of type APIDefinitionValidationResponse coming from the impl level.
 */
private Map validateOpenAPIDefinition(String url, InputStream fileInputStream, Attachment fileDetail, String apiDefinition, Boolean returnContent, Boolean isServiceAPI) throws APIManagementException {
    // validate inputs
    handleInvalidParams(fileInputStream, fileDetail, url, apiDefinition, isServiceAPI);
    OpenAPIDefinitionValidationResponseDTO responseDTO;
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    if (url != null) {
        validationResponse = OASParserUtil.validateAPIDefinitionByURL(url, returnContent);
    } else if (fileInputStream != null) {
        try {
            if (fileDetail != null) {
                String filename = fileDetail.getContentDisposition().getFilename();
                if (filename.endsWith(".zip")) {
                    validationResponse = OASParserUtil.extractAndValidateOpenAPIArchive(fileInputStream, returnContent);
                } else {
                    String openAPIContent = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
                    validationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
                }
            } else {
                String openAPIContent = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
                validationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
            }
        } catch (IOException e) {
            RestApiUtil.handleInternalServerError("Error while reading file content", e, log);
        }
    } else if (apiDefinition != null) {
        validationResponse = OASParserUtil.validateAPIDefinition(apiDefinition, returnContent);
    }
    responseDTO = APIMappingUtil.getOpenAPIDefinitionValidationResponseFromModel(validationResponse, returnContent);
    Map response = new HashMap();
    response.put(RestApiConstants.RETURN_MODEL, validationResponse);
    response.put(RestApiConstants.RETURN_DTO, responseDTO);
    return response;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) OpenAPIDefinitionValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OpenAPIDefinitionValidationResponseDTO) IOException(java.io.IOException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 17 with APIDefinitionValidationResponse

use of org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse 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)

Example 18 with APIDefinitionValidationResponse

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

the class ApisApiServiceImpl method updateAPISwagger.

/**
 * Updates the swagger definition of an existing API
 *
 * @param apiId             API identifier
 * @param apiDefinition     Swagger definition
 * @param url               Swagger definition URL
 * @param fileInputStream   Swagger definition input file content
 * @param fileDetail        file meta information as Attachment
 * @param ifMatch           If-match header value
 * @return updated swagger document of the API
 */
@Override
public Response updateAPISwagger(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) {
    try {
        String updatedSwagger;
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().getStatus());
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // Handle URL and file based definition imports
        if (url != null || fileInputStream != null) {
            // Validate and retrieve the OpenAPI definition
            Map validationResponseMap = validateOpenAPIDefinition(url, fileInputStream, fileDetail, null, true, false);
            APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
            if (!validationResponse.isValid()) {
                RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
            }
            updatedSwagger = PublisherCommonUtils.updateSwagger(apiId, validationResponse, false, organization);
        } else {
            updatedSwagger = updateSwagger(apiId, apiDefinition, organization);
        }
        return Response.ok().entity(updatedSwagger).build();
    } 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 updating swagger definition of API: " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the swagger definition of the API: " + apiId + " - " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 19 with APIDefinitionValidationResponse

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

the class OASParserUtil method addErrorToValidationResponse.

/**
 * Add error item with the provided message to the provided validation response object
 *
 * @param validationResponse APIDefinitionValidationResponse object
 * @param errMessage         error message
 * @return added ErrorItem object
 */
public static ErrorItem addErrorToValidationResponse(APIDefinitionValidationResponse validationResponse, String errMessage) {
    ErrorItem errorItem = new ErrorItem();
    errorItem.setErrorCode(ExceptionCodes.OPENAPI_PARSE_EXCEPTION.getErrorCode());
    errorItem.setMessage(ExceptionCodes.OPENAPI_PARSE_EXCEPTION.getErrorMessage());
    errorItem.setDescription(errMessage);
    validationResponse.getErrorItems().add(errorItem);
    return errorItem;
}
Also used : ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem)

Example 20 with APIDefinitionValidationResponse

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

the class PublisherCommonUtils method updateAsyncAPIDefinition.

/**
 * update AsyncPI definition of the given api.
 *
 * @param apiId    API Id
 * @param response response of the AsyncAPI definition validation call
 * @param organization identifier of the organization
 * @return updated AsyncAPI definition
 * @throws APIManagementException when error occurred updating AsyncAPI definition
 * @throws FaultGatewaysException when error occurred publishing API to the gateway
 */
public static String updateAsyncAPIDefinition(String apiId, APIDefinitionValidationResponse response, String organization) throws APIManagementException, FaultGatewaysException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    // this will fall if user does not have access to the API or the API does not exist
    API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
    existingAPI.setOrganization(organization);
    String apiDefinition = response.getJsonContent();
    AsyncApiParser asyncApiParser = new AsyncApiParser();
    // Set uri templates
    Set<URITemplate> uriTemplates = asyncApiParser.getURITemplates(apiDefinition, APIConstants.API_TYPE_WS.equals(existingAPI.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(existingAPI.getGatewayVendor()));
    if (uriTemplates == null || uriTemplates.isEmpty()) {
        throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
    }
    existingAPI.setUriTemplates(uriTemplates);
    // Update ws uri mapping
    existingAPI.setWsUriMapping(asyncApiParser.buildWSUriMapping(apiDefinition));
    // updating APi with the new AsyncAPI definition
    existingAPI.setAsyncApiDefinition(apiDefinition);
    apiProvider.saveAsyncApiDefinition(existingAPI, apiDefinition);
    apiProvider.updateAPI(existingAPI);
    // retrieves the updated AsyncAPI definition
    return apiProvider.getAsyncAPIDefinition(existingAPI.getId().getUUID(), organization);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) API(org.wso2.carbon.apimgt.api.model.API) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)24 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)14 API (org.wso2.carbon.apimgt.api.model.API)10 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 LinkedHashMap (java.util.LinkedHashMap)7 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)7 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)5 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)5 ArrayList (java.util.ArrayList)4 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)4 JSONObject (org.json.JSONObject)3 ErrorItem (org.wso2.carbon.apimgt.api.ErrorItem)3 Scope (org.wso2.carbon.apimgt.api.model.Scope)3 AsyncAPISpecificationValidationResponseDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Gson (com.google.gson.Gson)2 JsonObject (com.google.gson.JsonObject)2