Search in sources :

Example 1 with ErrorItem

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

the class OAS3Parser method validateAPIDefinition.

/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param host OpenAPI Definition url
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String host, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, options);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        validationResponse.setValid(false);
        for (String message : parseAttemptForV3.getMessages()) {
            OASParserUtil.addErrorToValidationResponse(validationResponse, message);
            if (message.contains(APIConstants.OPENAPI_IS_MISSING_MSG)) {
                ErrorItem errorItem = new ErrorItem();
                errorItem.setErrorCode(ExceptionCodes.INVALID_OAS3_FOUND.getErrorCode());
                errorItem.setMessage(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                errorItem.setDescription(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                validationResponse.getErrorItems().add(errorItem);
            }
        }
    } else {
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        io.swagger.v3.oas.models.info.Info info = openAPI.getInfo();
        List<String> endpoints;
        String endpointWithHost = "";
        if (openAPI.getServers() == null || openAPI.getServers().isEmpty()) {
            endpoints = null;
        } else {
            endpoints = openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList());
            for (String endpoint : endpoints) {
                if (endpoint.startsWith("/")) {
                    if (StringUtils.isEmpty(host)) {
                        endpointWithHost = "http://api.yourdomain.com" + endpoint;
                    } else {
                        endpointWithHost = host + endpoint;
                    }
                    endpoints.set(endpoints.indexOf(endpoint), endpointWithHost);
                }
            }
        }
        String title = null;
        String context = null;
        if (!StringUtils.isBlank(info.getTitle())) {
            title = info.getTitle();
            context = info.getTitle().replaceAll("\\s", "").toLowerCase();
        }
        OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, openAPI.getOpenapi(), title, info.getVersion(), context, info.getDescription(), endpoints);
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) {
                // not a json (it is yaml)
                JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition);
                validationResponse.setJsonContent(jsonNode.toString());
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
Also used : Info(io.swagger.v3.oas.models.info.Info) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) JsonNode(com.fasterxml.jackson.databind.JsonNode) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 2 with ErrorItem

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

the class OAS2Parser method validateAPIDefinition.

/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(apiDefinition);
    boolean swaggerErrorFound = false;
    for (String message : parseAttemptForV2.getMessages()) {
        OASParserUtil.addErrorToValidationResponse(validationResponse, message);
        if (message.contains(APIConstants.SWAGGER_IS_MISSING_MSG)) {
            ErrorItem errorItem = new ErrorItem();
            errorItem.setErrorCode(ExceptionCodes.INVALID_OAS2_FOUND.getErrorCode());
            errorItem.setMessage(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
            errorItem.setDescription(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
            validationResponse.getErrorItems().add(errorItem);
            swaggerErrorFound = true;
        }
    }
    if (parseAttemptForV2.getSwagger() == null || swaggerErrorFound) {
        validationResponse.setValid(false);
    } else {
        Swagger swagger = parseAttemptForV2.getSwagger();
        Info info = swagger.getInfo();
        OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, swagger.getSwagger(), info.getTitle(), info.getVersion(), swagger.getBasePath(), info.getDescription(), (swagger.getHost() == null || swagger.getHost().isEmpty()) ? null : new ArrayList<String>(Arrays.asList(swagger.getHost())));
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) {
                // not a json (it is yaml)
                try {
                    JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition, new SwaggerDeserializationResult());
                    validationResponse.setJsonContent(jsonNode.toString());
                } catch (IOException e) {
                    throw new APIManagementException("Error while reading API definition yaml", e);
                }
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) Info(io.swagger.models.Info) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 3 with ErrorItem

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

the class WSDL11ProcessorImpl method init.

@Override
public boolean init(byte[] wsdlContent) throws APIMgtWSDLException {
    setMode(Mode.SINGLE);
    WSDLReader wsdlReader = getWsdlFactoryInstance().newWSDLReader();
    // switch off the verbose mode
    wsdlReader.setFeature(JAVAX_WSDL_VERBOSE_MODE, false);
    wsdlReader.setFeature(JAVAX_WSDL_IMPORT_DOCUMENTS, false);
    try {
        wsdlDefinition = wsdlReader.readWSDL(null, getSecuredParsedDocumentFromContent(wsdlContent));
        if (log.isDebugEnabled()) {
            log.debug("Successfully initialized an instance of " + this.getClass().getSimpleName() + " with a single WSDL.");
        }
    } catch (WSDLException | APIManagementException e) {
        // This implementation class cannot process the WSDL.
        log.debug("Cannot process the WSDL by " + this.getClass().getName(), e);
        setError(new ErrorItem(ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getErrorMessage(), e.getMessage(), ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getErrorCode(), ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getHttpStatusCode()));
    }
    return !hasError;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) WSDLException(javax.wsdl.WSDLException) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) WSDLReader(javax.wsdl.xml.WSDLReader) APIMWSDLReader(org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader)

Example 4 with ErrorItem

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

the class WSDL11ProcessorImpl method initPath.

@Override
public boolean initPath(String path) throws APIMgtWSDLException {
    setMode(Mode.ARCHIVE);
    pathToDefinitionMap = new HashMap<>();
    wsdlArchiveExtractedPath = path;
    WSDLReader wsdlReader = getWsdlFactoryInstance().newWSDLReader();
    try {
        // switch off the verbose mode
        wsdlReader.setFeature(JAVAX_WSDL_VERBOSE_MODE, false);
        wsdlReader.setFeature(JAVAX_WSDL_IMPORT_DOCUMENTS, false);
        File folderToImport = new File(path);
        Collection<File> foundWSDLFiles = APIFileUtil.searchFilesWithMatchingExtension(folderToImport, "wsdl");
        if (log.isDebugEnabled()) {
            log.debug("Found " + foundWSDLFiles.size() + " WSDL file(s) in path " + path);
        }
        for (File file : foundWSDLFiles) {
            String absWSDLPath = file.getAbsolutePath();
            if (log.isDebugEnabled()) {
                log.debug("Processing WSDL file: " + absWSDLPath);
            }
            Definition definition = wsdlReader.readWSDL(path, getSecuredParsedDocumentFromPath(absWSDLPath));
            pathToDefinitionMap.put(absWSDLPath, definition);
            // set the first found WSDL as wsdlDefinition variable assuming that it is the root WSDL
            if (wsdlDefinition == null) {
                wsdlDefinition = definition;
            }
        }
        if (foundWSDLFiles.isEmpty()) {
            setError(ExceptionCodes.NO_WSDL_FOUND_IN_WSDL_ARCHIVE);
        }
        if (log.isDebugEnabled()) {
            log.debug("Successfully processed all WSDL files in path " + path);
        }
    } catch (WSDLException | APIManagementException e) {
        // This implementation class cannot process the WSDL. Continuing after setting canProcess = false
        log.debug(this.getClass().getName() + " was unable to process the WSDL Files for the path: " + path, e);
        setError(new ErrorItem(ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getErrorMessage(), e.getMessage(), ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getErrorCode(), ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getHttpStatusCode()));
    }
    return !hasError;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) WSDLException(javax.wsdl.WSDLException) Definition(javax.wsdl.Definition) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) File(java.io.File) WSDLReader(javax.wsdl.xml.WSDLReader) APIMWSDLReader(org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader)

Example 5 with ErrorItem

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

the class WSDL20ProcessorImpl method initPath.

@Override
public boolean initPath(String path) throws APIMgtWSDLException {
    setMode(Mode.ARCHIVE);
    pathToDescriptionMap = new HashMap<>();
    wsdlArchiveExtractedPath = path;
    WSDLReader reader;
    try {
        reader = getWsdlFactoryInstance().newWSDLReader();
    } catch (WSDLException e) {
        throw new APIMgtWSDLException("Error while initializing the WSDL reader", e);
    }
    reader.setFeature(WSDLReader.FEATURE_VALIDATION, false);
    File folderToImport = new File(path);
    Collection<File> foundWSDLFiles = APIFileUtil.searchFilesWithMatchingExtension(folderToImport, "wsdl");
    if (log.isDebugEnabled()) {
        log.debug("Found " + foundWSDLFiles.size() + " WSDL file(s) in path " + path);
    }
    try {
        for (File file : foundWSDLFiles) {
            if (log.isDebugEnabled()) {
                log.debug("Processing WSDL file: " + file.getAbsolutePath());
            }
            Document document = getSecuredParsedDocumentFromPath(file.getAbsolutePath());
            WSDLSource wsdlSource = getWSDLSourceFromDocument(document, reader);
            Description description = reader.readWSDL(wsdlSource);
            pathToDescriptionMap.put(file.getAbsolutePath(), description);
        }
        if (foundWSDLFiles.isEmpty()) {
            setError(ExceptionCodes.NO_WSDL_FOUND_IN_WSDL_ARCHIVE);
        }
        if (log.isDebugEnabled()) {
            log.debug("Successfully processed all WSDL files in path " + path);
        }
    } catch (WSDLException e) {
        // This implementation class cannot process the WSDL. Continuing after setting canProcess = false
        log.debug(this.getClass().getName() + " was unable to process the WSDL Files for the path: " + path, e);
        setError(new ErrorItem(ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getErrorMessage(), e.getMessage(), ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getErrorCode(), ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT.getHttpStatusCode()));
    }
    return !hasError;
}
Also used : Description(org.apache.woden.wsdl20.Description) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) WSDLException(org.apache.woden.WSDLException) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) WSDLSource(org.apache.woden.WSDLSource) Document(org.w3c.dom.Document) File(java.io.File) WSDLReader(org.apache.woden.WSDLReader) APIMWSDLReader(org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader)

Aggregations

ErrorItem (org.wso2.carbon.apimgt.api.ErrorItem)10 APIMWSDLReader (org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader)6 APIMgtWSDLException (org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 WSDLException (javax.wsdl.WSDLException)3 WSDLReader (javax.wsdl.xml.WSDLReader)3 WSDLException (org.apache.woden.WSDLException)3 WSDLReader (org.apache.woden.WSDLReader)3 WSDLSource (org.apache.woden.WSDLSource)3 Document (org.w3c.dom.Document)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 File (java.io.File)2 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)2 Info (io.swagger.models.Info)1 Swagger (io.swagger.models.Swagger)1 SwaggerParser (io.swagger.parser.SwaggerParser)1 SwaggerDeserializationResult (io.swagger.parser.util.SwaggerDeserializationResult)1 OpenAPI (io.swagger.v3.oas.models.OpenAPI)1 Info (io.swagger.v3.oas.models.info.Info)1 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)1