Java Code Examples for io.swagger.v3.core.util.Json#pretty()
The following examples show how to use
io.swagger.v3.core.util.Json#pretty() .
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: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 6 votes |
@Test public void verifyAdditionalPropertiesWithArray() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oas3_array.yaml"); ApiResponse response = openAPI.getPaths().get("/dictionaryOfArray").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas(), ExampleBuilder.RequestType.READ); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "{\n" + " \"additionalProp1\" : [ {\n" + " \"joel\" : \"string\",\n" + " \"prop2\" : 0\n" + " } ],\n" + " \"additionalProp2\" : [ {\n" + " \"joel\" : \"string\",\n" + " \"prop2\" : 0\n" + " } ],\n" + " \"additionalProp3\" : [ {\n" + " \"joel\" : \"string\",\n" + " \"prop2\" : 0\n" + " } ]\n" + "}"); }
Example 2
Source File: OpenAPIParserTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testParsingPrettifiedExtensions() throws Exception { String json = "{\n" + " \"openapi\": \"3.0.1\",\n" + " \"x-some-extension\": \"some-value\"\n" + "}"; SwaggerParseResult result = new OpenAPIParser().readContents(json, null, null); assertNotNull(result); OpenAPI openAPI = result.getOpenAPI(); assertNotNull(openAPI); assertNotNull(openAPI.getExtensions()); assertEquals(openAPI.getExtensions().get("x-some-extension"), "some-value"); String prettyJson = Json.pretty(openAPI); SwaggerParseResult prettyResult = new OpenAPIParser().readContents(prettyJson, null, null); assertNotNull(prettyResult); OpenAPI prettyOpenAPI = prettyResult.getOpenAPI(); assertNotNull(prettyOpenAPI); assertNotNull(prettyOpenAPI.getExtensions()); assertEquals(prettyOpenAPI.getExtensions().get("x-some-extension"), "some-value"); }
Example 3
Source File: OpenAPIResolverTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void recursiveIssue984() { ParseOptions parseOptions = new ParseOptions(); parseOptions.setResolve(true); parseOptions.setResolveFully(true); OpenAPI openAPI = new OpenAPIV3Parser().read("issue-984-simple.yaml", null, parseOptions); if (openAPI == null) fail("failed parsing issue-984"); try { Json.pretty(openAPI); //System.out.println(Json.pretty(openAPI)); } catch (Exception e) { e.printStackTrace(); fail("Recursive loop found"); } }
Example 4
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 6 votes |
@Test public void testInlinedArrayExample() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/array-example.yaml"); ApiResponse response = openAPI.getPaths().get("/").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas()); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "[ {\n" + " \"id\" : 1,\n" + " \"name\" : \"Arthur Dent\"\n" + "}, {\n" + " \"id\" : 2,\n" + " \"name\" : \"Ford Prefect\"\n" + "} ]"); }
Example 5
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void verifyGetMapResponse() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oas3.yaml"); ApiResponse response = openAPI.getPaths().get("/mockResponses/primitiveMapResponse").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(),null,ExampleBuilder.RequestType.READ); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "{\n" + " \"additionalProp1\" : \"string\",\n" + " \"additionalProp2\" : \"string\",\n" + " \"additionalProp3\" : \"string\"\n" + "}"); }
Example 6
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void verifyAdditionalPropertiesWithPasswords() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oas3_password.yaml"); ApiResponse response = openAPI.getPaths().get("/dictionaryOfPassword").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), null, ExampleBuilder.RequestType.READ); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "{\n" + " \"additionalProp1\" : \"string\",\n" + " \"additionalProp2\" : \"string\",\n" + " \"additionalProp3\" : \"string\"\n" + "}"); }
Example 7
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void verifyAdditionalPropertyResponse() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oas3.yaml"); ApiResponse response = openAPI.getPaths().get("/mockResponses/additionalPropertiesTest").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(),null,ExampleBuilder.RequestType.READ); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "{\n" + " \"foo\" : 0,\n" + " \"additionalProp1\" : \"string\",\n" + " \"additionalProp2\" : \"string\",\n" + " \"additionalProp3\" : \"string\"\n" + "}"); }
Example 8
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void writeOnlyParametersShouldNotBeIncluded() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/write-only.yaml"); ApiResponse response = openAPI.getPaths().get("/user").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), null, ExampleBuilder.RequestType.READ); String output = Json.pretty(example); // Password shouldn't be included assertEqualsIgnoreLineEnding(output, "{\n" + " \"username\" : \"bob\"\n" + "}"); }
Example 9
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void testIssue1263SchemaExampleNestedObjects() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/issue-1263.yaml"); ApiResponse response = openAPI.getPaths().get("/nested_object").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas()); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "{\n" + " \"nested_object\" : {\n" + " \"foo\" : \"bar\"\n" + " }\n" + "}"); }
Example 10
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
@Override public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException { OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser(); SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(oasDefinition, null, null); if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) { log.debug("Errors found when parsing OAS definition"); } OpenAPI swagger = parseAttemptForV3.getOpenAPI(); // check if API Level tier is content aware. if so, we set a extension as a global property if (contentAwareTiersList.contains(apiLevelTier)) { swagger.addExtension(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, PathItem> entry : swagger.getPaths().entrySet()) { String path = entry.getKey(); List<Operation> operations = swagger.getPaths().get(path).readOperations(); for (Operation op : operations) { if (contentAwareTiersList .contains(op.getExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) { if (log.isDebugEnabled()) { log.debug( "API resource Level policy is content aware for operation " + op.getOperationId()); } op.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true); } } } return Json.pretty(swagger); } }
Example 11
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void verifyBooleanAdditionalPropertyTrue() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oas3.yaml"); ApiResponse response = openAPI.getPaths().get("/mockResponses/booleanAdditionalPropertiesTrue").getGet().getResponses().get("200"); Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), null, ExampleBuilder.RequestType.READ); String output = Json.pretty(example); assertEqualsIgnoreLineEnding(output, "{ }"); }
Example 12
Source File: InlineModelResolver.java From swagger-parser with Apache License 2.0 | 5 votes |
public String matchGenerated(Schema model) { if (skipMatches) { return null; } String json = Json.pretty(model); if (generatedSignature.containsKey(json)) { return generatedSignature.get(json); } return null; }
Example 13
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test(description = "JSON example with xml name on array item") public void testIssue300() throws Exception { OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/issue-300.yaml"); Schema schema = openAPI.getComponents().getSchemas().get("Pet"); Example example = ExampleBuilder.fromSchema(schema, openAPI.getComponents().getSchemas()); String jsonExample = Json.pretty(example); assertEqualsIgnoreLineEnding(jsonExample, "{\n \"name\" : \"doggie\",\n \"shots\" : [ \"rabies\" ]\n}"); String xmlExample = new XmlExampleSerializer().serialize(example); assertEquals(xmlExample, "<?xml version='1.1' encoding='UTF-8'?><Pet><name>doggie</name><shots><shot>rabies</shot></shots></Pet>"); }
Example 14
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Update OAS definition with authorization endpoints. * * @param openAPI OpenAPI * @param swaggerData SwaggerData * @param hostsWithSchemes GW hosts with protocols * @return updated OAS definition */ private String updateSwaggerSecurityDefinitionForStore(OpenAPI openAPI, SwaggerData swaggerData, Map<String,String> hostsWithSchemes) { String authUrl; // By Default, add the GW host with HTTPS protocol if present. if (hostsWithSchemes.containsKey(APIConstants.HTTPS_PROTOCOL)) { authUrl = (hostsWithSchemes.get(APIConstants.HTTPS_PROTOCOL)).concat("/authorize"); } else { authUrl = (hostsWithSchemes.get(APIConstants.HTTP_PROTOCOL)).concat("/authorize"); } updateSwaggerSecurityDefinition(openAPI, swaggerData, authUrl); return Json.pretty(openAPI); }
Example 15
Source File: ExampleBuilderTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void testComplexArray() throws Exception { Map<String, Schema> definitions = new HashMap<>(); Schema address = new Schema() .xml(new XML().name("address")); Schema propertyDefinition1 = new StringSchema(); propertyDefinition1.setName("street"); propertyDefinition1.setExample("12345 El Monte Blvd"); Schema propertyDefinition2 = new StringSchema(); propertyDefinition2.setName("city"); propertyDefinition2.setExample("Los Altos Hills"); Schema propertyDefinition3 = new StringSchema(); propertyDefinition3.setName("state"); propertyDefinition3.setExample("CA"); propertyDefinition3.setMinLength(2); propertyDefinition3.setMaxLength(2); Schema propertyDefinition4 = new StringSchema(); propertyDefinition4.setName("zip"); propertyDefinition4.setExample("94022"); address.addProperties("street",propertyDefinition1); address.addProperties("city",propertyDefinition2); address.addProperties("state",propertyDefinition3); address.addProperties("zip",propertyDefinition4); definitions.put("Address", address); Example rep = (Example) ExampleBuilder.fromSchema(new ArraySchema().$ref("Address"), definitions); String json = Json.pretty(rep); assertEqualsIgnoreLineEnding(json,"{\n \"street\" : \"12345 El Monte Blvd\",\n \"city\" : \"Los Altos Hills\",\n \"state\" : \"CA\",\n \"zip\" : \"94022\"\n}"); }
Example 16
Source File: InlineModelResolver.java From openapi-generator with Apache License 2.0 | 5 votes |
private String matchGenerated(Schema model) { String json = Json.pretty(model); if (generatedSignature.containsKey(json)) { return generatedSignature.get(json); } return null; }
Example 17
Source File: AbstractFSharpCodegen.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override public void setParameterExampleValue(CodegenParameter codegenParameter) { // set the example value // if not specified in x-example, generate a default value // TODO need to revise how to obtain the example value if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); } else if (Boolean.TRUE.equals(codegenParameter.isBoolean)) { codegenParameter.example = "true"; } else if (Boolean.TRUE.equals(codegenParameter.isLong)) { codegenParameter.example = "789"; } else if (Boolean.TRUE.equals(codegenParameter.isInteger)) { codegenParameter.example = "56"; } else if (Boolean.TRUE.equals(codegenParameter.isFloat)) { codegenParameter.example = "3.4F"; } else if (Boolean.TRUE.equals(codegenParameter.isDouble)) { codegenParameter.example = "1.2D"; } else if (Boolean.TRUE.equals(codegenParameter.isNumber)) { codegenParameter.example = "8.14"; } else if (Boolean.TRUE.equals(codegenParameter.isBinary)) { codegenParameter.example = "BINARY_DATA_HERE"; } else if (Boolean.TRUE.equals(codegenParameter.isByteArray)) { codegenParameter.example = "BYTE_ARRAY_DATA_HERE"; } else if (Boolean.TRUE.equals(codegenParameter.isFile)) { codegenParameter.example = "/path/to/file.txt"; } else if (Boolean.TRUE.equals(codegenParameter.isDate)) { codegenParameter.example = "2013-10-20"; } else if (Boolean.TRUE.equals(codegenParameter.isDateTime)) { codegenParameter.example = "2013-10-20T19:20:30+01:00"; } else if (Boolean.TRUE.equals(codegenParameter.isUuid)) { codegenParameter.example = "38400000-8cf0-11bd-b23e-10b96e4ef00d"; } else if (Boolean.TRUE.equals(codegenParameter.isString)) { codegenParameter.example = codegenParameter.paramName + "_example"; } }
Example 18
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method generates API definition to the given api * * @param swaggerData api * @return API definition in string format * @throws APIManagementException */ @Override public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException { OpenAPI openAPI = new OpenAPI(); // create path if null if (openAPI.getPaths() == null) { openAPI.setPaths(new Paths()); } //Create info object Info info = new Info(); info.setTitle(swaggerData.getTitle()); if (swaggerData.getDescription() != null) { info.setDescription(swaggerData.getDescription()); } Contact contact = new Contact(); //Create contact object and map business owner info if (swaggerData.getContactName() != null) { contact.setName(swaggerData.getContactName()); } if (swaggerData.getContactEmail() != null) { contact.setEmail(swaggerData.getContactEmail()); } if (swaggerData.getContactName() != null || swaggerData.getContactEmail() != null) { //put contact object to info object info.setContact(contact); } info.setVersion(swaggerData.getVersion()); openAPI.setInfo(info); updateSwaggerSecurityDefinition(openAPI, swaggerData, "https://test.com"); updateLegacyScopesFromSwagger(openAPI, swaggerData); if (APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) { modifyGraphQLSwagger(openAPI); } else { for (SwaggerData.Resource resource : swaggerData.getResources()) { addOrUpdatePathToSwagger(openAPI, resource); } } return Json.pretty(openAPI); }
Example 19
Source File: SwaggerCreator.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method returns the swagger definition of an api * which suits for k8s_apim_operator * * @param api API * @param oasDefinition Open API definition * @return OAS definition * @throws APIManagementException throws if an error occurred * @throws ParseException throws if the oasDefinition is not in json format */ public String getOASDefinitionForPrivateJetMode(API api, String oasDefinition) throws APIManagementException, ParseException { APIDefinition oasParser = OASParserUtil.getOASParser(oasDefinition); String apiDefinition = oasParser.getOASDefinitionForPublisher(api, oasDefinition); OASParserUtil.SwaggerVersion swaggerVersion = OASParserUtil.getSwaggerVersion(apiDefinition); if (swaggerVersion == OASParserUtil.SwaggerVersion.SWAGGER) { //parsing swagger 2.0 to openAPI 3.0.1 OpenAPIParser openAPIParser = new OpenAPIParser(); SwaggerParseResult swaggerParseResult = openAPIParser.readContents(apiDefinition, null, null); if (CollectionUtils.isNotEmpty(swaggerParseResult.getMessages())) { log.debug("Errors found when parsing OAS definition"); } OpenAPI openAPI = swaggerParseResult.getOpenAPI(); apiDefinition = Json.pretty(openAPI); } //get Json object from parsed openAPI definition JSONParser jsonParser = new JSONParser(); JSONObject apiDefinitionJsonObject = (JSONObject) jsonParser.parse(apiDefinition); /** * Removing the "security" key from the JSONObject */ apiDefinitionJsonObject.remove(ContainerBasedConstants.SECURITY); ((JSONObject) ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.COMPONENTS)) .get(ContainerBasedConstants.SECURITY_SCHEMES)).remove(ContainerBasedConstants.DEFAULT); Set<String> paths = ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.PATHS)).keySet(); Iterator iterator = paths.iterator(); /** * Removing the "security" attribute from each RESTAPI verb of each path in the swagger */ while (iterator.hasNext()) { String path = (String) iterator.next(); Set verbs = ((JSONObject) ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.PATHS)) .get(path)).keySet(); Iterator verbIterator = verbs.iterator(); while (verbIterator.hasNext()) { String verb = (String) verbIterator.next(); ((JSONObject) ((JSONObject) ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.PATHS)). get(path)).get(verb)).remove(ContainerBasedConstants.SECURITY); } } String securityType = api.getApiSecurity() .replace(ContainerBasedConstants.OAUTH_BASICAUTH_APIKEY_MANDATORY, ""); Boolean securityTypeOauth2 = isAPISecurityTypeOauth2(securityType); Boolean securityTypeBasicAuth = isAPISecurityBasicAuth(securityType); if (basicSecurityName != null && securityTypeBasicAuth && !securityTypeOauth2 && !"".equals(basicSecurityName)) { SecurityRequirement basicOauthSecurityReq = referBasicAuthInSwagger(basicSecurityName); List<SecurityRequirement> basicAuth = new ArrayList<SecurityRequirement>(); basicAuth.add(basicOauthSecurityReq); apiDefinitionJsonObject.put(ContainerBasedConstants.SECURITY, basicAuth); } else if (securityTypeOauth2 && !securityTypeBasicAuth) { if (oauthSecurityName != null && !"".equals(oauthSecurityName) || jwtSecurityName != null && !"".equals(jwtSecurityName)) { SecurityRequirement oauth2SecurityReq = referOauth2InSwagger(oauthSecurityName, jwtSecurityName); List<SecurityRequirement> oauth2 = new ArrayList<SecurityRequirement>(); oauth2.add(oauth2SecurityReq); apiDefinitionJsonObject.put(ContainerBasedConstants.SECURITY, oauth2); } } else if (securityTypeBasicAuth && securityTypeOauth2) { if (oauthSecurityName != null && !"".equals(oauthSecurityName) || basicSecurityName != null && !"".equals(basicSecurityName) || jwtSecurityName != null && !"".equals(jwtSecurityName)) { List<SecurityRequirement> basicOauthJWT = new ArrayList<SecurityRequirement>(); SecurityRequirement basicOauthJWTSecurityReq = referBasicOAuth2JWTInSwagger(basicSecurityName, oauthSecurityName, jwtSecurityName); basicOauthJWT.add(basicOauthJWTSecurityReq); apiDefinitionJsonObject.put(ContainerBasedConstants.SECURITY, basicOauthJWT); } } return Json.pretty(apiDefinitionJsonObject); }
Example 20
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 3 votes |
/** * This method generates Sample/Mock payloads of Json Examples for operations in the swagger definition * * @param model model * @param definitions definition * @return JsonExample */ private String getJsonExample(Schema model, Map<String, Schema> definitions) { Example example = ExampleBuilder.fromSchema(model, definitions); SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer()); Json.mapper().registerModule(simpleModule); return Json.pretty(example); }