io.swagger.util.Yaml Java Examples
The following examples show how to use
io.swagger.util.Yaml.
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: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 7 votes |
/** * Remove x-examples from all the paths from the OpenAPI definition. * * @param apiDefinition OpenAPI definition as String */ public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException { try { OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser(); SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null); if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) { log.debug("Errors found when parsing OAS definition"); } OpenAPI openAPI = parseAttemptForV3.getOpenAPI(); for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) { String path = entry.getKey(); List<Operation> operations = openAPI.getPaths().get(path).readOperations(); for (Operation operation : operations) { if (operation.getExtensions() != null && operation.getExtensions().keySet() .contains(APIConstants.SWAGGER_X_EXAMPLES)) { operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES); } } } return Yaml.pretty().writeValueAsString(openAPI); } catch (JsonProcessingException e) { throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES); } }
Example #2
Source File: OAS2Parser.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Remove x-wso2-examples from all the paths from the swagger. * * @param swaggerString Swagger as String */ public String removeExamplesFromSwagger(String swaggerString) throws APIManagementException { try { SwaggerParser swaggerParser = new SwaggerParser(); Swagger swagger = swaggerParser.parse(swaggerString); swagger.getPaths().values().forEach(path -> { path.getOperations().forEach(operation -> { if (operation.getVendorExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) { operation.getVendorExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES); } }); }); return Yaml.pretty().writeValueAsString(swagger); } catch (JsonProcessingException e) { throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES); } }
Example #3
Source File: SwaggerBootstrapServlet.java From render with GNU General Public License v2.0 | 6 votes |
@Override public void init(final ServletConfig config) throws ServletException { super.init(config); final BeanConfig beanConfig = loadConfig(new File("resources/swagger.properties")); beanConfig.setVersion("v1"); beanConfig.setSchemes(new String[]{"http"}); beanConfig.setBasePath("/render-ws"); beanConfig.setResourcePackage("org.janelia.render.service"); beanConfig.setScan(true); beanConfig.setPrettyPrint(true); // Needed to register these modules to get Swagger to use JAXB annotations // (see https://github.com/swagger-api/swagger-core/issues/960 for explanation) Json.mapper().registerModule(new JaxbAnnotationModule()); Yaml.mapper().registerModule(new JaxbAnnotationModule()); }
Example #4
Source File: FlaskConnexionCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } for (Map<String, Object> operations : getOperations(objs)) { @SuppressWarnings("unchecked") List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<Map<String, Object>> opsByPathList = sortOperationsByPath(ops); operations.put("operationsByPath", opsByPathList); } return super.postProcessSupportingFileData(objs); }
Example #5
Source File: ParserTest.java From swagger-codegen-tooling with Apache License 2.0 | 6 votes |
/** * Same code as in the parser itself to find out what is wrong with the swagger.yaml file. */ @Test public void yamlParse() throws JsonProcessingException, IOException { JsonNode rootNode = null; ObjectMapper objectMapper = Yaml.mapper(); rootNode = objectMapper.readTree(getClass().getResourceAsStream("/swagger.yaml")); JsonNode swaggerNode = rootNode.get("swagger"); if (swaggerNode == null) { throw new NullPointerException("You failed!"); } swagger = objectMapper.convertValue(rootNode, Swagger.class); Assertions.assertThat(swagger).isNotNull(); }
Example #6
Source File: YamlToJson.java From swagger-codegen-tooling with Apache License 2.0 | 6 votes |
protected String getYamlFileContentAsJson() throws IOException { String data = ""; if (yamlInputPath.startsWith("http") || yamlInputPath.startsWith("https")) { data = new String(Resources.toByteArray(new URL(yamlInputPath))); } else { data = new String(Files.readAllBytes(java.nio.file.Paths.get(new File(yamlInputPath).toURI()))); } ObjectMapper yamlMapper = Yaml.mapper(); JsonNode rootNode = yamlMapper.readTree(data); // must have swagger node set JsonNode swaggerNode = rootNode.get("swagger"); return rootNode.toString(); }
Example #7
Source File: SwaggerUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
public static String swaggerToString(Swagger swagger) { try { return Yaml.mapper().writeValueAsString(swagger); } catch (Throwable e) { throw new ServiceCombException("Convert swagger to string failed, ", e); } }
Example #8
Source File: ServiceCombSwaggerHandlerImpl.java From spring-cloud-huawei with Apache License 2.0 | 5 votes |
@Override public Map<String, String> getSchemasSummaryMap() { return swaggerMap.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> { try { return calcSchemaSummary(Yaml.mapper().writeValueAsString(entry.getValue())); } catch (JsonProcessingException e) { LOGGER.error("error when calcSchemaSummary."); } return null; })); }
Example #9
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void validDefinition_canParseApiTitleWithSpacesTest() throws Exception { //Given swagger.getInfo().setTitle("Sample API Title"); String swaggerString = objectMapper.writeValueAsString(swagger); //When String apiId = definitionParserService.getApiId(Yaml.mapper().readTree(swaggerString)); //Then assertEquals("Sample_API_Title", apiId); }
Example #10
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void validDefinition_canParseApiTitleWithSpecialCharsTest() throws Exception { //Given swagger.getInfo().setTitle("Sample!API%Title**"); String swaggerString = objectMapper.writeValueAsString(swagger); //When String apiId = definitionParserService.getApiId(Yaml.mapper().readTree(swaggerString)); //Then assertEquals("Sample_API_Title", apiId); }
Example #11
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test(expected = DefinitionParsingException.class) public void definition_missingTitle_throwsExceptionWhenParsingForApiIdTest() throws Exception { //Given String swaggerString = objectMapper.writeValueAsString(swagger); JsonNode swaggerNode = Yaml.mapper().readTree(swaggerString); swaggerNode = removeElementFromNode(swaggerNode.get("info"), "title"); //When definitionParserService.getApiId(swaggerNode); //Then fail(); }
Example #12
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test(expected = DefinitionParsingException.class) public void definition_missingInfoSection_throwsExceptionWhenParsingForApiIdTest() throws Exception { //Given String swaggerString = objectMapper.writeValueAsString(swagger); JsonNode swaggerNode = Yaml.mapper().readTree(swaggerString); swaggerNode = removeElementFromNode(swaggerNode, "info"); //When definitionParserService.getApiId(swaggerNode); //Then fail(); }
Example #13
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void validDefinition_canParseVersionTest() throws Exception { //Given String apiVersion = "1.0.0"; swagger.getInfo().setVersion(apiVersion); String swaggerString = objectMapper.writeValueAsString(swagger); //When String parsedApiVersion = definitionParserService.getVersion(Yaml.mapper().readTree(swaggerString)); //Then assertEquals(apiVersion, parsedApiVersion); }
Example #14
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test(expected = DefinitionParsingException.class) public void definition_missingVersion_throwsExceptionWhenParsingForVersionTest() throws Exception { //Given String swaggerString = objectMapper.writeValueAsString(swagger); JsonNode swaggerNode = Yaml.mapper().readTree(swaggerString); swaggerNode = removeElementFromNode(swaggerNode.get("info"), "version"); //When definitionParserService.getVersion(swaggerNode); //Then fail(); }
Example #15
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test(expected = DefinitionParsingException.class) public void definition_missingInfoSection_throwsExceptionWhenParsingForVersionTest() throws Exception { //Given String swaggerString = objectMapper.writeValueAsString(swagger); JsonNode swaggerNode = Yaml.mapper().readTree(swaggerString); swaggerNode = removeElementFromNode(swaggerNode, "info"); //When definitionParserService.getVersion(swaggerNode); //Then fail(); }
Example #16
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void validOAS2Definition_returns2_asOASVersion() throws Exception { //Given swagger.setSwagger("2.0"); String swaggerString = objectMapper.writeValueAsString(swagger); //When String oasVersion = definitionParserService.getOASVersion(Yaml.mapper().readTree(swaggerString)); //Then assertEquals( oasVersion,"2.0"); }
Example #17
Source File: DefinitionParserServiceTest.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
@Test(expected = DefinitionParsingException.class) public void definition_missingOASVersion_throwsExceptionWhenParsingForOASVersionTest() throws Exception { //Given String swaggerString = objectMapper.writeValueAsString(swagger); JsonNode swaggerNode = Yaml.mapper().readTree(swaggerString); swaggerNode = removeElementFromNode(swaggerNode, "swagger"); //When definitionParserService.getOASVersion(swaggerNode); //Then fail(); }
Example #18
Source File: MultiOpenApiParser.java From api-compiler with Apache License 2.0 | 5 votes |
/** * Validates the input Swagger JsonNode against Swagger Specification schema. * * @throws OpenApiConversionException */ private static void validateSwaggerSpec(JsonNode swaggerJsonNode) throws OpenApiConversionException { ProcessingReport report = null; try { URL url = Resources.getResource(SCHEMA_RESOURCE_PATH); String swaggerSchema = Resources.toString(url, StandardCharsets.UTF_8); JsonNode schemaNode = Yaml.mapper().readTree(swaggerSchema); JsonSchema schema = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode); report = schema.validate(swaggerJsonNode); } catch (Exception ex) { throw new OpenApiConversionException("Unable to parse the content. " + ex.getMessage(), ex); } if (!report.isSuccess()) { String message = ""; Iterator itr = report.iterator(); if (itr.hasNext()) { message += ((ProcessingMessage) itr.next()).toString(); } while(itr.hasNext()) { message += "," + ((ProcessingMessage) itr.next()).toString(); } throw new OpenApiConversionException( String.format("Invalid OpenAPI file. Please fix the schema errors:\n%s", message)); } }
Example #19
Source File: YamlToJsonTest.java From swagger-codegen-tooling with Apache License 2.0 | 5 votes |
@Test public void transform() throws JsonProcessingException, IOException { String data = getResourceContent("/kio-api.yaml"); ObjectMapper yamlMapper = Yaml.mapper(); JsonNode rootNode = yamlMapper.readTree(data); // must have swagger node set JsonNode swaggerNode = rootNode.get("swagger"); String rootNodeString = rootNode.toString(); System.out.println(rootNodeString); }
Example #20
Source File: SinatraServerCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); }
Example #21
Source File: ServiceCombSwaggerHandlerImpl.java From spring-cloud-huawei with Apache License 2.0 | 5 votes |
@Override public Map<String, String> getSchemasMap() { return swaggerMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> { try { return Yaml.mapper().writeValueAsString(entry.getValue()); } catch (JsonProcessingException e) { LOGGER.error("error when calcSchemaSummary."); } return null; })); }
Example #22
Source File: SwaggerUtils.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * Get the swagger definition for a given API. * @param api API object. * @param isJSON response needed in JSON / JAML. * @return Swagger as String. * @throws AxisFault Error occurred while fetching the host name for API. */ public static String getAPISwagger(API api, boolean isJSON) throws AxisFault { MIServerConfig serverConfig = new MIServerConfig(); String responseString; responseString = retrieveAPISwaggerFromRegistry(api); org.yaml.snakeyaml.Yaml yamlDefinition = new org.yaml.snakeyaml.Yaml(); if (StringUtils.isNotEmpty(responseString)) { if (!isJSON) { JsonParser jsonParser = new JsonParser(); responseString = yamlDefinition.dumpAsMap(GSONUtils.gsonJsonObjectToMap(jsonParser.parse(responseString))); } } else { if (logger.isDebugEnabled()) { logger.debug("Generating swagger definition for: " + api.getName()); } GenericApiObjectDefinition objectDefinition = new GenericApiObjectDefinition(api, serverConfig); Map<String, Object> definitionMap = objectDefinition.getDefinitionMap(); if (isJSON) { JSONObject jsonDefinition = new JSONObject(definitionMap); responseString = jsonDefinition.toString(); } else { responseString = yamlDefinition.dumpAsMap(definitionMap); } } return responseString; }
Example #23
Source File: JavaInflectorServerCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); }
Example #24
Source File: Rails5ServerCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); }
Example #25
Source File: HaskellHttpClientCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); }
Example #26
Source File: NodeJSServerCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { SimpleModule module = new SimpleModule(); module.addSerializer(Double.class, new JsonSerializer<Double>() { @Override public void serialize(Double val, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeNumber(new BigDecimal(val)); } }); objs.put("swagger-yaml", Yaml.mapper().registerModule(module).writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } for (Map<String, Object> operations : getOperations(objs)) { @SuppressWarnings("unchecked") List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<Map<String, Object>> opsByPathList = sortOperationsByPath(ops); operations.put("operationsByPath", opsByPathList); } return super.postProcessSupportingFileData(objs); }
Example #27
Source File: AbstractGoCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger) objs.get("swagger"); if (swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); }
Example #28
Source File: RustServerCodegen.java From TypeScript-Microservices with MIT License | 5 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } // We previously built a mapping from path to path ID and regular // expression - see fromOperation for details. Sort it and add an // index, and then add it to the objects that we're about to pass to // the templates to process. List<Map.Entry<String, Map<String, String>>> pathSetEntryList = new ArrayList(pathSetMap.entrySet()); Collections.sort(pathSetEntryList, new Comparator<Map.Entry<String, Map<String, String>>>() { public int compare(Map.Entry<String, Map<String, String>> a, Map.Entry<String, Map<String, String>> b) { return a.getValue().get("path").compareTo(b.getValue().get("path")); } }); List pathSet = new ArrayList<Map<String, String>>(); int index = 0; for (Map.Entry<String, Map<String, String>> pathSetEntry : pathSetEntryList) { Map<String, String> pathSetEntryValue = pathSetEntry.getValue(); pathSetEntryValue.put("index", Integer.toString(index)); index++; pathSet.add(pathSetEntryValue); } objs.put("pathSet", pathSet); return super.postProcessSupportingFileData(objs); }
Example #29
Source File: LogSearchDocumentationGenerator.java From ambari-logsearch with Apache License 2.0 | 5 votes |
private static String generateSwaggerYaml() throws Exception { ApiDocConfig apiDocConfig = new ApiDocConfig(); BeanConfig beanConfig = apiDocConfig.swaggerConfig(); Swagger swagger = beanConfig.getSwagger(); swagger.addSecurityDefinition("basicAuth", new BasicAuthDefinition()); beanConfig.configure(swagger); beanConfig.scanAndRead(); return Yaml.mapper().writeValueAsString(swagger); }
Example #30
Source File: ApiDocStorage.java From ambari-logsearch with Apache License 2.0 | 5 votes |
@PostConstruct private void postConstruct() { Thread loadApiDocThread = new Thread("load_swagger_api_doc") { @Override public void run() { logger.info("Start thread to scan REST API doc from endpoints."); Swagger swagger = beanConfig.getSwagger(); swagger.addSecurityDefinition("basicAuth", new BasicAuthDefinition()); beanConfig.configure(swagger); beanConfig.scanAndRead(); setSwagger(swagger); try { String yaml = Yaml.mapper().writeValueAsString(swagger); StringBuilder b = new StringBuilder(); String[] parts = yaml.split("\n"); for (String part : parts) { b.append(part); b.append("\n"); } setSwaggerYaml(b.toString()); } catch (Exception e) { e.printStackTrace(); } logger.info("Scanning REST API endpoints and generating docs has been successful."); } }; loadApiDocThread.setDaemon(true); loadApiDocThread.start(); }