Java Code Examples for io.swagger.parser.SwaggerParser#readWithInfo()

The following examples show how to use io.swagger.parser.SwaggerParser#readWithInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Validate.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void run() {
    System.out.println("Validating spec file (" + spec + ")");

    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult result = parser.readWithInfo(spec, null, true);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<String>(messageList);

    for (String message : messages) {
        System.out.println(message);
    }

    if (messages.size() > 0) {
        throw new ValidateException();
    }
}
 
Example 2
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get parsed Swagger object
 *
 * @param oasDefinition OAS definition
 * @return Swagger
 * @throws APIManagementException
 */
Swagger getSwagger(String oasDefinition) {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    if (CollectionUtils.isNotEmpty(parseAttemptForV2.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    return parseAttemptForV2.getSwagger();
}
 
Example 3
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition,
        List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    Swagger swagger = parseAttemptForV2.getSwagger();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).getOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList
                        .contains(op.getVendorExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }

}
 
Example 4
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 4 votes vote down vote up
private SwaggerDeserializationResult readSwagger(String content) throws IllegalArgumentException {
    SwaggerParser parser = new SwaggerParser();
    return parser.readWithInfo(content);
}
 
Example 5
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method  generates Sample/Mock payloads for Swagger (2.0) definitions
 *
 * @param swaggerDef Swagger Definition
 * @return Swagger Json
 */
@Override
public Map<String, Object> generateExample(String swaggerDef) {
    // create APIResourceMediationPolicy List = policyList
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
    Swagger swagger = parseAttemptForV2.getSwagger();
    //return map
    Map<String, Object> returnMap = new HashMap<>();
    //List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
        int responseCode = 0;
        int minResponseCode = 0;
        String path = entry.getKey();
        //initializing apiResourceMediationPolicyObject
        APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
        //setting path for apiResourceMediationPolicyObject
        apiResourceMediationPolicyObject.setPath(path);
        Map<String, Model> definitions = swagger.getDefinitions();
        //operation map to get verb
        Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
        List<Operation> operations = swagger.getPaths().get(path).getOperations();
        for (Operation op : operations) {
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            //for each HTTP method get the verb
            for (Map.Entry<HttpMethod, Operation> HTTPMethodMap : operationMap.entrySet()) {
                //add verb to apiResourceMediationPolicyObject
                apiResourceMediationPolicyObject.setVerb(String.valueOf(HTTPMethodMap.getKey()));
            }
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            //for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                if (op.getResponses().get(responseEntry).getExamples() != null) {
                    Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
                    Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        String jsonExample = Json.pretty(applicationJson);
                        genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                        respCodeInitialized = true;
                        hasJsonPayload = true;
                    }
                    if (applicationXml != null) {
                        String xmlExample = applicationXml.toString();
                        genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                        hasXmlPayload = true;
                    }
                } else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
                    Model model = op.getResponses().get(responseEntry).getResponseSchema();
                    String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
                    genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
                    hasJsonPayload = true;
                } else if (op.getResponses().get(responseEntry).getExamples() == null
                        && op.getResponses().get(responseEntry).getResponseSchema() == null) {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            //inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            //gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
            //sets script to each resource in the swagger
            op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
        }
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
 
Example 6
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
                    validationResponse.setJsonContent(jsonNode.toString());
                } catch (IOException e) {
                    throw new APIManagementException("Error while reading API definition yaml", e);
                }
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}