Java Code Examples for io.swagger.v3.parser.core.models.SwaggerParseResult#getMessages()
The following examples show how to use
io.swagger.v3.parser.core.models.SwaggerParseResult#getMessages() .
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: CheckCompatibilityBase.java From servicecomb-toolkit with Apache License 2.0 | 6 votes |
private OpenAPI loadOpenApi(String filePath) throws IOException { String yaml = loadFileContent(filePath); SwaggerParseResult oldParseResult = CompatibilityCheckParser.parseYaml(yaml); OpenAPI openAPI = oldParseResult.getOpenAPI(); if (openAPI == null) { StringJoiner errors = new StringJoiner("\n", "Parse errors:", ""); if (CollectionUtils.isNotEmpty(oldParseResult.getMessages())) { for (String message : oldParseResult.getMessages()) { errors.add(message); } } throw new RuntimeException(errors.toString()); } return openAPI; }
Example 2
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testIssue161() { String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "paths:\n" + " /users:\n" + " get:\n" + " parameters:\n" + " - in: query\n" + " name: name\n" + " required: false\n" + " schema:\n" + " type: string\n" + " minLength: 10\n" + " maxLength: 100\n" + " responses:\n" + " default:\n" + " description: ok\n"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(yaml, null, null); Set<String> messages = new HashSet<>(result.getMessages()); assertFalse(messages.contains("attribute paths.'/users'(get).[name].maxLength is unexpected")); }
Example 3
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testDeserializeWithMessages() { String yaml = "openapi: '3.0.0'\n" + "info:\n" + " version: 0.0.0\n" + " title:\n" + " - bar"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(yaml,null, null); Set<String> messages = new HashSet<>(result.getMessages()); assertTrue(messages.size() == 2); assertTrue(messages.contains("attribute info.title is not of type `string`")); assertTrue(messages.contains("attribute paths is missing")); }
Example 4
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testAlmostEmpty(@Injectable List<AuthorizationValue> auths) { String yaml = "openapi: '3.0.1'\n" + "new: extra"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = parser.readContents(yaml,auths,options); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); assertTrue(messages.contains("attribute info is missing")); assertTrue(messages.contains("attribute paths is missing")); assertTrue(messages.contains("attribute new is unexpected")); }
Example 5
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testLicense () { String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "info:\n" + " license:\n" + " invalid: true\n" + " x-valid:\n" + " isValid: true\n" + " version: ''\n"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(yaml,null,null); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); assertTrue(messages.contains("attribute info.license.invalid is unexpected")); assertTrue(messages.contains("attribute info.title is missing")); assertTrue(messages.contains("attribute paths is missing")); assertEquals(((Map)result.getOpenAPI().getInfo().getLicense().getExtensions().get("x-valid")).get("isValid"), true); }
Example 6
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testResponses() { String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "info:\n" + " version: ''\n" + " title: ''\n" + "paths: {}\n" + "components:\n" + " responses:\n" + " foo:\n" + " description: description\n" + " bar: baz\n" + " x-foo: bar"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(yaml, null, null); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); assertTrue(messages.contains("attribute components.responses.foo.bar is unexpected")); assertEquals(result.getOpenAPI().getComponents().getResponses().get("foo").getExtensions().get("x-foo").toString(), "bar"); }
Example 7
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testRootInfo() { String json = "{\n" + "\t\"openapi\": \"3.0.0\",\n" + "\t\"foo\": \"bar\",\n" + "\t\"info\": \"invalid\"\n" + "}"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(json, null, null); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); assertTrue(messages.contains("attribute foo is unexpected")); assertTrue(messages.contains("attribute info is not of type `object`")); }
Example 8
Source File: OpenAPIV3Parser.java From swagger-parser with Apache License 2.0 | 6 votes |
public OpenAPI read(String location, List<AuthorizationValue> auths, ParseOptions resolve) { if (location == null) { return null; } final List<SwaggerParserExtension> parserExtensions = getExtensions(); SwaggerParseResult parsed; for (SwaggerParserExtension extension : parserExtensions) { parsed = extension.readLocation(location, auths, resolve); for (String message : parsed.getMessages()) { LOGGER.info("{}: {}", extension, message); } final OpenAPI result = parsed.getOpenAPI(); if (result != null) { return result; } } return null; }
Example 9
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 5 votes |
@Test public void testAnyOfSchema(@Injectable List<AuthorizationValue> auths){ String yaml = "openapi: '3.0'\n" + "components:\n" + " schemas:\n" + " id:\n" + " anyOf: \n" + " - type: string\n" + " - type: number\n" ; OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = parser.readContents(yaml,auths,options); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); Schema idSchema = result.getOpenAPI().getComponents().getSchemas().get("id"); assertTrue(idSchema != null); assertTrue(idSchema instanceof ComposedSchema); ComposedSchema idCompSchema = (ComposedSchema) idSchema; List<Schema> anyOfSchemas = idCompSchema.getAnyOf(); assertTrue(anyOfSchemas != null); assertEquals(anyOfSchemas.size(), 2); Schema stringSchema = anyOfSchemas.get(0); assertTrue(stringSchema != null); assertEquals(stringSchema.getType(), "string"); Schema numberSchema = anyOfSchemas.get(1); assertTrue(numberSchema != null); assertEquals(numberSchema.getType(), "number"); }
Example 10
Source File: OpenAPIV3ParserTest.java From swagger-parser with Apache License 2.0 | 5 votes |
@Test public void testDuplicateHttpStatusCodesJson() { final String location = "src/test/resources/duplicateHttpStatusCodes.json"; final ParseOptions options = new ParseOptions(); options.setResolve(true); final OpenAPIV3Parser parser = new OpenAPIV3Parser(); final SwaggerParseResult result = parser.readLocation(location, null, options); assertNull(result.getOpenAPI()); List<String> messages = result.getMessages(); assertEquals(1, messages.size()); assertEquals(messages.get(0), "Duplicate field '200' in `src/test/resources/duplicateHttpStatusCodes.json`"); }
Example 11
Source File: OpenAPIV3ParserTest.java From swagger-parser with Apache License 2.0 | 5 votes |
@Test public void testIssue1015() { ParseOptions options = new ParseOptions(); options.setResolve(true); options.setResolveCombinators(true); SwaggerParseResult parseResult = new OpenAPIV3Parser().readLocation("issue-1015.json", null, options); if (parseResult.getMessages() != null && !parseResult.getMessages().isEmpty()) { parseResult.getMessages().forEach(s -> System.out.println(s)); fail("Error while loading apispec!"); } OpenAPI apispec = parseResult.getOpenAPI(); assertNotNull(apispec); }
Example 12
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 5 votes |
@Test public void testDefinitions () { String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "info:\n" + " version: ''\n" + " title: ''\n" + "paths: {}\n" + "components:\n" + " schemas:\n" + " invalid: true\n" + " Person:\n" + " required:\n" + " - id\n" + " - name\n" + " properties:\n" + " id:\n" + " type: integer\n" + " format: int64\n" + " name:\n" + " type: string"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(yaml, null, null); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); assertTrue(messages.contains("attribute components.schemas.invalid is not of type `object`")); assertTrue(result.getOpenAPI().getComponents().getSchemas().get("Person") instanceof Schema); List<String> required = ((Schema)result.getOpenAPI().getComponents().getSchemas().get("Person")).getRequired(); Set<String> requiredKeys = new HashSet<String>(required); assertTrue(requiredKeys.contains("id")); assertTrue(requiredKeys.contains("name")); assertTrue(requiredKeys.size() == 2); }
Example 13
Source File: ApiDocV3Service.java From api-layer with Eclipse Public License 2.0 | 5 votes |
public String transformApiDoc(String serviceId, ApiDocInfo apiDocInfo) { SwaggerParseResult parseResult = new OpenAPIV3Parser().readContents(apiDocInfo.getApiDocContent()); OpenAPI openAPI = parseResult.getOpenAPI(); if (openAPI == null) { log.debug("Could not convert response body to an OpenAPI object for service {}. {}", serviceId, parseResult.getMessages()); if (parseResult.getMessages() == null) { throw new UnexpectedTypeException("Response is not an OpenAPI type object."); } else { throw new UnexpectedTypeException(parseResult.getMessages().toString()); } } boolean hidden = isHidden(openAPI.getTags()); updatePaths(openAPI, serviceId, apiDocInfo, hidden); updateServerAndLink(openAPI, serviceId, hidden); updateExternalDoc(openAPI, apiDocInfo); try { return initializeObjectMapper().writeValueAsString(openAPI); } catch (JsonProcessingException e) { log.debug("Could not convert Swagger to JSON", e); throw new ApiDocTransformationException("Could not convert Swagger to JSON"); } }
Example 14
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 5 votes |
@Test public void testDeserializeWithDiscriminator() { String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "info:\n" + " version: ''\n" + " title: ''\n" + "paths: {}\n" + "components:\n" + " schemas:\n" + " Animal:\n" + " type: object\n" + " discriminator:\n" + " propertyName: petType\n" + " description: |\n" + " A basic `Animal` object which can extend to other animal types.\n" + " required:\n" + " - commonName\n" + " - petType\n" + " properties:\n" + " commonName:\n" + " description: the household name of the animal\n" + " type: string\n" + " petType:\n" + " description: |\n" + " The discriminator for the animal type. It _must_\n" + " match one of the concrete schemas by name (i.e. `Cat`)\n" + " for proper deserialization\n" + " type: string"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(yaml, null, null); Set<String> messages = new HashSet<>(result.getMessages()); assertFalse(messages.contains("attribute definitions.Animal.discriminator is unexpected")); }
Example 15
Source File: SyntaxChecker.java From servicecomb-toolkit with Apache License 2.0 | 5 votes |
public static List<String> check(String oasSpecContent) { ParseOptions parseOptions = new ParseOptions(); parseOptions.setResolve(false); parseOptions.setResolveFully(false); parseOptions.setResolveCombinators(false); parseOptions.setFlatten(false); OpenAPIV3Parser parser = new OpenAPIV3Parser(); SwaggerParseResult result = parser.readContents(oasSpecContent, null, parseOptions); return result.getMessages() == null ? emptyList() : result.getMessages(); }
Example 16
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 4 votes |
@Test public void testOneOfSchema(@Injectable List<AuthorizationValue> auths){ String yaml = "openapi: '3.0'\n" + "components:\n" + " schemas:\n" + " Cat:\n" + " type: object\n" + " # all properties specific to a `Cat`\n" + " properties:\n" + " purring:\n" + " type: string\n" + " Dog:\n" + " type: object\n" + " # all properties specific to a `Dog`\n" + " properties:\n" + " bark:\n" + " type: string\n" + " Pet:\n" + " oneOf: \n" + " - $ref: '#/components/schemas/Cat'\n" + " - $ref: '#/components/schemas/Dog'\n" + " - type: object\n" + " # neither a `Cat` nor a `Dog`\n" + " properties:\n" + " name:\n" + " type: string\n" ; OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = parser.readContents(yaml,auths,options); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); Schema petSchema = result.getOpenAPI().getComponents().getSchemas().get("Pet"); assertTrue(petSchema != null); assertTrue(petSchema instanceof ComposedSchema); ComposedSchema petCompSchema = (ComposedSchema) petSchema; List<Schema> oneOfSchemas = petCompSchema.getOneOf(); assertTrue(oneOfSchemas != null); assertEquals(oneOfSchemas.size(), 3); Schema refCatSchema = oneOfSchemas.get(0); assertTrue(refCatSchema != null); assertEquals(refCatSchema.get$ref(), "#/components/schemas/Cat"); Schema refDogSchema = oneOfSchemas.get(1); assertTrue(refDogSchema != null); assertEquals(refDogSchema.get$ref(), "#/components/schemas/Dog"); Schema otherSchema = oneOfSchemas.get(2); assertTrue(otherSchema != null); Schema nameProp = (Schema) otherSchema.getProperties().get("name"); assertTrue(nameProp != null); assertEquals(nameProp.getType(), "string"); }
Example 17
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * 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(); 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(); OASParserUtil.updateValidationResponseAsSuccess( validationResponse, apiDefinition, openAPI.getOpenapi(), info.getTitle(), info.getVersion(), null, info.getDescription(), (openAPI.getServers()==null || openAPI.getServers().isEmpty() ) ? null : openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList()) ); 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; }
Example 18
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 4 votes |
@Test void testDiscriminatorObject(@Injectable List<AuthorizationValue> auths){ String yaml = "openapi: '3.0.1'\n" + "components:\n" + " schemas:\n" + " Pet:\n" + " type: object\n" + " required:\n" + " - pet_type\n" + " properties:\n" + " pet_type:\n" + " type: string\n" + " discriminator:\n" + " propertyName: pet_type\n" + " mapping:\n" + " cachorro: Dog\n" + " Cat:\n" + " allOf:\n" + " - $ref: '#/components/schemas/Pet'\n" + " - type: object\n" + " # all other properties specific to a `Cat`\n" + " properties:\n" + " name:\n" + " type: string\n" + " Dog:\n" + " allOf:\n" + " - $ref: '#/components/schemas/Pet'\n" + " - type: object\n" + " # all other properties specific to a `Dog`\n" + " properties:\n" + " bark:\n" + " type: string\n" + " Lizard:\n" + " allOf:\n" + " - $ref: '#/components/schemas/Pet'\n" + " - type: object\n" + " # all other properties specific to a `Lizard`\n" + " properties:\n" + " lovesRocks:\n" + " type: boolean"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = parser.readContents(yaml,auths,options); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); assertEquals(result.getOpenAPI().getComponents().getSchemas().get("Pet").getDiscriminator().getPropertyName(),"pet_type"); assertEquals(result.getOpenAPI().getComponents().getSchemas().get("Pet").getDiscriminator().getMapping().get("cachorro"),"Dog" ); assertTrue(messages.contains("attribute paths is missing")); assertTrue(messages.contains("attribute info is missing")); }
Example 19
Source File: Validate.java From openapi-generator with Apache License 2.0 | 4 votes |
@Override public void execute() { System.out.println("Validating spec (" + spec + ")"); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = new OpenAPIParser().readLocation(spec, null, options); List<String> messageList = result.getMessages(); Set<String> errors = new HashSet<>(messageList); Set<String> warnings = new HashSet<>(); StringBuilder sb = new StringBuilder(); OpenAPI specification = result.getOpenAPI(); RuleConfiguration ruleConfiguration = new RuleConfiguration(); if (recommend != null) ruleConfiguration.setEnableRecommendations(recommend); else ruleConfiguration.setEnableRecommendations(false); OpenApiEvaluator evaluator = new OpenApiEvaluator(ruleConfiguration); ValidationResult validationResult = evaluator.validate(specification); // TODO: We could also provide description here along with getMessage. getMessage is either a "generic" message or specific (e.g. Model 'Cat' has issues). // This would require that we parse the messageList coming from swagger-parser into a better structure. validationResult.getWarnings().forEach(invalid -> warnings.add(invalid.getMessage())); validationResult.getErrors().forEach(invalid -> errors.add(invalid.getMessage())); if (!errors.isEmpty()) { sb.append("Errors:").append(System.lineSeparator()); errors.forEach(msg -> sb.append("\t- ").append(WordUtils.wrap(msg, 90).replace(System.lineSeparator(), System.lineSeparator() + "\t ")).append(System.lineSeparator()) ); } if (!warnings.isEmpty()) { sb.append("Warnings: ").append(System.lineSeparator()); warnings.forEach(msg -> sb.append("\t- ").append(WordUtils.wrap(msg, 90).replace(System.lineSeparator(), System.lineSeparator() + "\t ")).append(System.lineSeparator()) ); } if (!errors.isEmpty()) { sb.append(System.lineSeparator()); sb.append("[error] Spec has ").append(errors.size()).append(" errors."); System.err.println(sb.toString()); System.exit(1); } else if (!warnings.isEmpty()) { sb.append(System.lineSeparator()); sb.append("[info] Spec has ").append(warnings.size()).append(" recommendation(s)."); } else { // we say "issues" here rather than "errors" to account for both errors and issues. sb.append("No validation issues detected."); } System.out.println(sb.toString()); }
Example 20
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 4 votes |
@Test public void testAllOfSchema(@Injectable List<AuthorizationValue> auths){ String yaml = "openapi: '3.0'\n" + "components:\n" + " schemas:\n" + " Pet:\n" + " type: object\n" + " required:\n" + " - pet_type\n" + " properties:\n" + " pet_type:\n" + " type: string\n" + " Cat:\n" + " allOf:\n" + " - $ref: '#/components/schemas/Pet'\n" + " - type: object\n" + " # all other properties specific to a `Cat`\n" + " properties:\n" + " name:\n" + " type: string\n"; OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = parser.readContents(yaml,auths,options); List<String> messageList = result.getMessages(); Set<String> messages = new HashSet<>(messageList); Schema catSchema = result.getOpenAPI().getComponents().getSchemas().get("Cat"); assertTrue(catSchema != null); assertTrue(catSchema instanceof ComposedSchema); ComposedSchema catCompSchema = (ComposedSchema) catSchema; List<Schema> allOfSchemas = catCompSchema.getAllOf(); assertTrue(allOfSchemas != null); assertEquals(allOfSchemas.size(), 2); Schema refPetSchema = allOfSchemas.get(0); assertTrue(refPetSchema != null); assertEquals(refPetSchema.get$ref(), "#/components/schemas/Pet"); Schema otherSchema = allOfSchemas.get(1); assertTrue(otherSchema != null); assertTrue(otherSchema.getProperties() != null); Schema nameProp = (Schema) otherSchema.getProperties().get("name"); assertTrue(nameProp != null); assertEquals(nameProp.getType(), "string"); }