Search in sources :

Example 1 with AsyncAPISpecificationValidationResponseDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method getAsyncAPISpecificationValidationResponseFromModel.

public static AsyncAPISpecificationValidationResponseDTO getAsyncAPISpecificationValidationResponseFromModel(APIDefinitionValidationResponse model, boolean returnContent) throws APIManagementException {
    AsyncAPISpecificationValidationResponseDTO responseDTO = new AsyncAPISpecificationValidationResponseDTO();
    responseDTO.setIsValid(model.isValid());
    if (model.isValid()) {
        APIDefinitionValidationResponse.Info modelInfo = model.getInfo();
        if (modelInfo != null) {
            AsyncAPISpecificationValidationResponseInfoDTO infoDTO = new AsyncAPISpecificationValidationResponseInfoDTO();
            infoDTO.setAsyncAPIVersion(modelInfo.getOpenAPIVersion());
            infoDTO.setName(modelInfo.getName());
            infoDTO.setVersion(modelInfo.getVersion());
            infoDTO.setContext(modelInfo.getContext());
            infoDTO.setDescription(modelInfo.getDescription());
            infoDTO.setEndpoints(modelInfo.getEndpoints());
            infoDTO.setProtocol(model.getProtocol());
            Map<String, APIDefinition> apiDefinitionMap = APIUtil.getApiDefinitionParsersMap();
            apiDefinitionMap.remove(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
            if (!apiDefinitionMap.isEmpty()) {
                for (Map.Entry<String, APIDefinition> apiDefinitionEntry : apiDefinitionMap.entrySet()) {
                    APIDefinition apiParser = apiDefinitionEntry.getValue();
                    String gatewayVendor = apiParser.getVendorFromExtension(model.getContent());
                    if (gatewayVendor != null) {
                        infoDTO.setGatewayVendor(gatewayVendor);
                        break;
                    }
                }
                infoDTO.asyncTransportProtocols(AsyncApiParser.getTransportProtocolsForAsyncAPI(model.getContent()));
            }
            // Set default value
            if (infoDTO.getGatewayVendor() == null) {
                infoDTO.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
            }
            responseDTO.setInfo(infoDTO);
        }
        if (returnContent) {
            responseDTO.setContent(model.getContent());
        }
    } else {
        responseDTO.setErrors(getErrorListItemsDTOsFromErrorHandlers(model.getErrorItems()));
    }
    return responseDTO;
}
Also used : AsyncAPISpecificationValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO) AsyncAPISpecificationValidationResponseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseInfoDTO) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) Map(java.util.Map) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 2 with AsyncAPISpecificationValidationResponseDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method validateAsyncAPISpecification.

/**
 * Validate the provided AsyncAPI specification (via file or url) and return a Map with the validation response
 * information
 *
 * @param url AsyncAPI specification url
 * @param fileInputStream file as input stream
 * @param returnContent whether to return the content of the definition in the response DTO
 * @param isServiceAPI whether the request is to create API from a service in Service Catalog
 * @return Map with the validation response information. A value with key 'dto' will have the response DTO
 *  of type AsyncAPISpecificationValidationResponseDTO for the REST API. A value with the key 'model' will have the
 *  validation response of type APIDefinitionValidationResponse coming from the impl level
 */
private Map validateAsyncAPISpecification(String url, InputStream fileInputStream, Attachment fileDetail, Boolean returnContent, Boolean isServiceAPI) throws APIManagementException {
    // validate inputs
    handleInvalidParams(fileInputStream, fileDetail, url, null, isServiceAPI);
    AsyncAPISpecificationValidationResponseDTO responseDTO;
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    String schemaToBeValidated = null;
    if (url != null) {
        // validate URL
        validationResponse = AsyncApiParserUtil.validateAsyncAPISpecificationByURL(url, returnContent);
    } else if (fileInputStream != null) {
        // validate file
        String fileName = fileDetail != null ? fileDetail.getContentDisposition().getFilename() : StringUtils.EMPTY;
        try {
            if (isServiceAPI || fileName.endsWith(APIConstants.YAML_FILE_EXTENSION) || fileName.endsWith(APIConstants.YML_FILE_EXTENSION)) {
                // convert .yml or .yaml to JSON for validation
                ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
                Object obj = yamlReader.readValue(fileInputStream, Object.class);
                ObjectMapper jsonWriter = new ObjectMapper();
                schemaToBeValidated = jsonWriter.writeValueAsString(obj);
            } else if (fileName.endsWith(APIConstants.JSON_FILE_EXTENSION)) {
                // continue with .json
                JSONTokener jsonDataFile = new JSONTokener(fileInputStream);
                schemaToBeValidated = new org.json.JSONObject(jsonDataFile).toString();
            }
            validationResponse = AsyncApiParserUtil.validateAsyncAPISpecification(schemaToBeValidated, returnContent);
        } catch (IOException e) {
            // error while reading the schemas
            RestApiUtil.handleInternalServerError("Error while reading file content", e, log);
        }
    }
    responseDTO = APIMappingUtil.getAsyncAPISpecificationValidationResponseFromModel(validationResponse, returnContent);
    Map response = new HashMap();
    response.put(RestApiConstants.RETURN_MODEL, validationResponse);
    response.put(RestApiConstants.RETURN_DTO, responseDTO);
    return response;
}
Also used : JSONTokener(org.json.JSONTokener) AsyncAPISpecificationValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO) JSONObject(org.json.simple.JSONObject) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) JSONObject(org.json.simple.JSONObject) IOException(java.io.IOException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 3 with AsyncAPISpecificationValidationResponseDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importAsyncAPISpecification.

private APIDTO importAsyncAPISpecification(InputStream definition, String definitionUrl, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) {
    // validate and retrieve the AsyncAPI specification
    Map validationResponseMap = null;
    boolean isServiceAPI = false;
    try {
        if (service != null) {
            isServiceAPI = true;
        }
        validationResponseMap = validateAsyncAPISpecification(definitionUrl, definition, fileDetail, true, isServiceAPI);
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
    }
    AsyncAPISpecificationValidationResponseDTO validationResponseDTO = (AsyncAPISpecificationValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
    APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
    if (!validationResponseDTO.isIsValid()) {
        ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
        throw RestApiUtil.buildBadRequestException(errorDTO);
    }
    // Import the API and Definition
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String definitionToAdd = validationResponse.getJsonContent();
        String protocol = validationResponse.getProtocol();
        if (isServiceAPI) {
            apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), protocol));
        }
        if (!APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiDTOFromProperties.getGatewayVendor())) {
            apiDTOFromProperties.getPolicies().add(APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED);
            apiDTOFromProperties.setAsyncTransportProtocols(AsyncApiParser.getTransportProtocolsForAsyncAPI(definitionToAdd));
        }
        API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
        if (isServiceAPI) {
            apiToAdd.setServiceInfo("key", service.getKey());
            apiToAdd.setServiceInfo("md5", service.getMd5());
            if (!APIConstants.API_TYPE_WEBSUB.equals(protocol.toUpperCase())) {
                apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
            }
        }
        apiToAdd.setAsyncApiDefinition(definitionToAdd);
        // load topics from AsyncAPI
        apiToAdd.setUriTemplates(new AsyncApiParser().getURITemplates(definitionToAdd, APIConstants.API_TYPE_WS.equals(apiToAdd.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiToAdd.getGatewayVendor())));
        apiToAdd.setOrganization(organization);
        apiToAdd.setAsyncApiDefinition(definitionToAdd);
        apiProvider.addAPI(apiToAdd);
        return APIMappingUtil.fromAPItoDTO(apiProvider.getAPIbyUUID(apiToAdd.getUuid(), organization));
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion() + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AsyncAPISpecificationValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 4 with AsyncAPISpecificationValidationResponseDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method validateAsyncAPISpecification.

/**
 * Validate AsyncAPI Specification and retrieve as the response
 *
 * @param url URL of the AsyncAPI Specification
 * @param fileInputStream InputStream for the provided file
 * @param fileDetail File meta-data
 * @param returnContent Whether to return the definition content
 * @param messageContext CXF message context
 * @return AsyncAPI Specification Validation response
 */
@Override
public Response validateAsyncAPISpecification(Boolean returnContent, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) throws APIManagementException {
    // validate and retrieve the AsyncAPI specification
    Map validationResponseMap = null;
    try {
        validationResponseMap = validateAsyncAPISpecification(url, fileInputStream, fileDetail, returnContent, false);
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
    }
    AsyncAPISpecificationValidationResponseDTO validationResponseDTO = (AsyncAPISpecificationValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
    return Response.ok().entity(validationResponseDTO).build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AsyncAPISpecificationValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Aggregations

HashMap (java.util.HashMap)4 Map (java.util.Map)4 AsyncAPISpecificationValidationResponseDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO)4 LinkedHashMap (java.util.LinkedHashMap)3 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)1 IOException (java.io.IOException)1 JSONTokener (org.json.JSONTokener)1 JSONObject (org.json.simple.JSONObject)1 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)1 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)1 API (org.wso2.carbon.apimgt.api.model.API)1 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)1 AsyncApiParser (org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser)1 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)1 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)1 AsyncAPISpecificationValidationResponseInfoDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseInfoDTO)1