io.swagger.util.Json Java Examples
The following examples show how to use
io.swagger.util.Json.
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: ApiGatewaySdkSwaggerApiImporter.java From aws-apigateway-importer with Apache License 2.0 | 6 votes |
private void createIntegration(Method method, Map<String, Object> vendorExtensions) { if (!vendorExtensions.containsKey(EXTENSION_INTEGRATION)) { return; } Map<String, HashMap> integ = Json.mapper().convertValue( vendorExtensions.get(EXTENSION_INTEGRATION), Map.class ); IntegrationType type = IntegrationType.valueOf(getStringValue(integ.get("type")).toUpperCase()); LOG.info("Creating integration with type " + type); PutIntegrationInput input = new PutIntegrationInput() .withType(type) .withUri(getStringValue(integ.get("uri"))) .withCredentials(getStringValue(integ.get("credentials"))) .withHttpMethod((getStringValue(integ.get("httpMethod")))) .withRequestParameters(integ.get("requestParameters")) .withRequestTemplates(integ.get("requestTemplates")) .withCacheNamespace(getStringValue(integ.get("cacheNamespace"))) .withCacheKeyParameters((List<String>) integ.get("cacheKeyParameters")); Integration integration = method.putIntegration(input); createIntegrationResponses(integration, integ); }
Example #2
Source File: SpringMvcTest.java From swagger-maven-plugin with Apache License 2.0 | 6 votes |
@Test public void testGeneratedDocWithJsonExampleValues() throws Exception { List<ApiSource> apisources = (List<ApiSource>) getVariableValueFromObject(mojo, "apiSources"); ApiSource apiSource = apisources.get(0); // Force serialization of example values as json raw values apiSource.setJsonExampleValues(true); // exclude part of the model when not compliant with jev option (e.g. example expressed as plain string) apiSource.setApiModelPropertyExclusions(Collections.singletonList("exclude-when-jev-option-set")); mojo.execute(); // check generated swagger json file ObjectMapper mapper = Json.mapper(); JsonNode actualJson = mapper.readTree(new File(swaggerOutputDir, "swagger.json")); JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/options/jsonExampleValues/expected/swagger-spring.json")); JsonNode actualUserNode = actualJson.path("definitions").path("User"); JsonNode expectUserNode = expectJson.path("definitions").path("User"); assertJsonEquals(expectUserNode, actualUserNode, Configuration.empty().when(IGNORING_ARRAY_ORDER)); }
Example #3
Source File: SpringMvcTest.java From swagger-maven-plugin with Apache License 2.0 | 6 votes |
private void assertGeneratedSwaggerSpecYaml(String description) throws MojoExecutionException, MojoFailureException, IOException { mojo.getApiSources().get(0).setOutputFormats("yaml"); mojo.execute(); DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setPrettyFlow(true); Yaml yaml = new Yaml(options); String actualYaml = yaml.dump(yaml.load(FileUtils.readFileToString(new File(swaggerOutputDir, "swagger.yaml")))); String expectYaml = yaml.dump(yaml.load(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring.yaml"))); ObjectMapper mapper = Json.mapper(); JsonNode actualJson = mapper.readTree(YamlToJson(actualYaml)); JsonNode expectJson = mapper.readTree(YamlToJson(expectYaml)); changeDescription(expectJson, description); assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER)); }
Example #4
Source File: JaxrsReaderTest.java From swagger-maven-plugin with Apache License 2.0 | 6 votes |
@Test public void createCommonParameters() throws Exception { reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class)); Swagger result = reader.read(CommonParametersApi.class); Parameter headerParam = result.getParameter("headerParam"); assertTrue(headerParam instanceof HeaderParameter); Parameter queryParam = result.getParameter("queryParam"); assertTrue(queryParam instanceof QueryParameter); result = reader.read(ReferenceCommonParametersApi.class); Operation get = result.getPath("/apath").getGet(); List<Parameter> parameters = get.getParameters(); for (Parameter parameter : parameters) { assertTrue(parameter instanceof RefParameter); } ObjectMapper mapper = Json.mapper(); ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter()); String json = jsonWriter.writeValueAsString(result); JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-common-parameters.json")); JsonAssert.assertJsonEquals(expectJson, json); }
Example #5
Source File: AbstractAdaCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { objs.put("orderedModels", orderedModels); Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { String host = swagger.getBasePath(); try { swagger.setHost("SWAGGER_HOST"); objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n")); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } swagger.setHost(host); } /** * Collect the scopes to generate unique identifiers for each of them. */ List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods"); postProcessAuthMethod(authMethods); return super.postProcessSupportingFileData(objs); }
Example #6
Source File: DefaultCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
/** * Update property for array(list) container * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { if (innerProperty == null) { LOGGER.warn("skipping invalid array property " + Json.pretty(property)); return; } property.dataFormat = innerProperty.dataFormat; if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { property.complexType = innerProperty.baseType; } else { property.isPrimitiveType = true; } property.items = innerProperty; // inner item is Enum if (isPropertyInnerMostEnum(property)) { // isEnum is set to true when the type is an enum // or the inner type of an array/map is an enum property.isEnum = true; // update datatypeWithEnum and default value for array // e.g. List<string> => List<StatusEnum> updateDataTypeWithEnumForArray(property); // set allowable values to enum values (including array/map of enum) property.allowableValues = getInnerEnumAllowableValues(property); } }
Example #7
Source File: DefaultCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
/** * Update property for map container * @param property Codegen property * @param innerProperty Codegen inner property of map or list */ protected void updatePropertyForMap(CodegenProperty property, CodegenProperty innerProperty) { if (innerProperty == null) { LOGGER.warn("skipping invalid map property " + Json.pretty(property)); return; } if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { property.complexType = innerProperty.baseType; } else { property.isPrimitiveType = true; } property.items = innerProperty; property.dataFormat = innerProperty.dataFormat; // inner item is Enum if (isPropertyInnerMostEnum(property)) { // isEnum is set to true when the type is an enum // or the inner type of an array/map is an enum property.isEnum = true; // update datatypeWithEnum and default value for map // e.g. Dictionary<string, string> => Dictionary<string, StatusEnum> updateDataTypeWithEnumForMap(property); // set allowable values to enum values (including array/map of enum) property.allowableValues = getInnerEnumAllowableValues(property); } }
Example #8
Source File: ServiceCenterDeploy.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
public void ensureReady() throws Throwable { // check if is running // {"version":"1.0.0","buildTag":"20180608145515.1.0.0.b913a2d","runMode":"dev","apiVersion":"3.0.0"} try { String address = "http://localhost:30100/version"; ServiceCenterInfo serviceCenterInfo = new RestTemplate().getForObject(address, ServiceCenterInfo.class); if (serviceCenterInfo != null && serviceCenterInfo.getVersion() != null) { LOGGER.info("{} already started, {}.", deployDefinition.getDisplayName(), Json.pretty(serviceCenterInfo)); return; } } catch (Throwable e) { LOGGER.info("failed to get ServiceCenter version, message={}", e.getMessage()); } initServiceCenterCmd(); LOGGER.info("definition of {} is: {}", deployDefinition.getDeployName(), deployDefinition); deploy(); waitStartComplete(); }
Example #9
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 #10
Source File: SwaggerFilter.java From SciGraph with Apache License 2.0 | 6 votes |
private byte[] writeDynamicResource(InputStream is) throws IOException { String str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8)); Swagger swagger = new SwaggerParser().parse(str); // set the resource listing tag Tag dynamic = new Tag(); dynamic.setName("dynamic"); dynamic.setDescription("Dynamic Cypher resources"); swagger.addTag(dynamic); // add resources to the path Map<String,Path> paths = swagger.getPaths(); paths.putAll(configuration.getCypherResources()); Map<String,Path> sorted = new LinkedHashMap<>(); List<String> keys = new ArrayList<>(); keys.addAll(paths.keySet()); Collections.sort(keys); for (String key : keys) { sorted.put(key, paths.get(key)); } swagger.setPaths(sorted); // return updated swagger JSON return Json.pretty(swagger).getBytes(); }
Example #11
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 6 votes |
public ResponseContext reviewByContent(RequestContext request, JsonNode inputSpec) { if(inputSpec == null) { return new ResponseContext() .status(Response.Status.BAD_REQUEST) .entity( "No specification supplied in either the url or request body. Try again?" ); } String inputAsString = Json.pretty(inputSpec); ValidationResponse validationResponse = null; try { validationResponse = debugByContent(request ,inputAsString); }catch (Exception e){ return new ResponseContext().status(Response.Status.INTERNAL_SERVER_ERROR).entity( "Failed to process specification" ); } return new ResponseContext() .entity(validationResponse); //return processDebugValidationResponse(validationResponse); }
Example #12
Source File: ValidatorController.java From validator-badge with Apache License 2.0 | 6 votes |
public ResponseContext validateByContent(RequestContext request, JsonNode inputSpec) { if(inputSpec == null) { return new ResponseContext() .status(Response.Status.BAD_REQUEST) .entity( "No specification supplied in either the url or request body. Try again?" ); } String inputAsString = Json.pretty(inputSpec); ValidationResponse validationResponse = null; try { validationResponse = debugByContent(request ,inputAsString); }catch (Exception e){ return new ResponseContext().status(Response.Status.INTERNAL_SERVER_ERROR).entity( "Failed to process URL" ); } return processValidationResponse(validationResponse); }
Example #13
Source File: WebServerModule.java From datacollector with Apache License 2.0 | 6 votes |
@Provides(type = Type.SET) ContextConfigurator provideJersey() { return new ContextConfigurator() { @Override public void init(ServletContextHandler context) { // REST API that requires authentication ServletHolder protectedRest = new ServletHolder(new ServletContainer()); protectedRest.setInitParameter( ServerProperties.PROVIDER_PACKAGES, SWAGGER_PACKAGE + "," + RestAPI.class.getPackage().getName() ); protectedRest.setInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, RestAPIResourceConfig.class.getName()); context.addServlet(protectedRest, "/rest/*"); RJson.configureRJsonForSwagger(Json.mapper()); // REST API that it does not require authentication ServletHolder publicRest = new ServletHolder(new ServletContainer()); publicRest.setInitParameter(ServerProperties.PROVIDER_PACKAGES, PublicRestAPI.class.getPackage().getName()); publicRest.setInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, RestAPIResourceConfig.class.getName()); context.addServlet(publicRest, "/public-rest/*"); } }; }
Example #14
Source File: Hello.java From hasor with Apache License 2.0 | 6 votes |
@Any public void execute(HttpServletResponse response) throws IOException { Swagger swagger = new Swagger(); swagger.setBasePath("/127.0.0.1"); // Operation operation = new Operation(); Path apiPath = new Path(); apiPath.setPost(operation); // apiPath.setPost(); swagger.setPaths(new LinkedHashMap<String, Path>() {{ put("/aaa", apiPath); }}); // // String asString = Json.pretty().writeValueAsString(swagger); PrintWriter writer = response.getWriter(); writer.write(asString); writer.flush(); }
Example #15
Source File: OpenAPICodegenUtils.java From product-microgateway with Apache License 2.0 | 6 votes |
/** * Convert the v2 or v3 open API definition in yaml or json format into json format of the respective format. * v2/YAML -> v2/JSON * v3/YAML -> v3/JSON * * @param openAPIContent open API as a string content * @return openAPI definition as a JSON String */ public static String getOpenAPIAsJson(OpenAPI openAPI, String openAPIContent, Path openAPIPath) { String jsonOpenAPI = Json.pretty(openAPI); String openAPIVersion; Path fileName = openAPIPath.getFileName(); if (fileName == null) { throw new CLIRuntimeException("Error: Couldn't resolve OpenAPI file name."); } else if (fileName.toString().endsWith("json")) { openAPIVersion = findSwaggerVersion(openAPIContent, false); } else { openAPIVersion = findSwaggerVersion(jsonOpenAPI, false); } switch (openAPIVersion) { case "2": Swagger swagger = new SwaggerParser().parse(openAPIContent); return Json.pretty(swagger); case "3": return jsonOpenAPI; default: throw new CLIRuntimeException("Error: Swagger version is not identified"); } }
Example #16
Source File: AbstractOperationGenerator.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
protected void extractAggregatedParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap, java.lang.reflect.Parameter methodParameter) { JavaType javaType = TypeFactory.defaultInstance().constructType(methodParameter.getParameterizedType()); BeanDescription beanDescription = Json.mapper().getSerializationConfig().introspect(javaType); for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) { if (!propertyDefinition.couldSerialize()) { continue; } Annotation[] annotations = collectAnnotations(propertyDefinition); ParameterGenerator propertyParameterGenerator = new ParameterGenerator(method, methodAnnotationMap, propertyDefinition.getName(), annotations, propertyDefinition.getPrimaryType().getRawClass()); parameterGenerators.add(propertyParameterGenerator); } }
Example #17
Source File: SwaggerGenerator.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void generateSwaggerJson() throws Exception { Set<Class<?>> classes = new HashSet<>(endpointConfig.getClasses()); classes.add(RedbeamsApi.class); Swagger swagger = new Reader(SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT).configure(new Swagger())) .read(classes); Path path = Paths.get("./build/swagger/redbeams.json"); Files.createDirectories(path.getParent()); Files.writeString(path, Json.pretty(swagger)); }
Example #18
Source File: SwaggerToOpenApiConversionFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException { if (Boolean.TRUE == reqCtx.getProperty(OPEN_API_PROPERTY)) { final Object entity = respCtx.getEntity(); // Right before 1.5.18, the entity was always a String but became a model object // (io.swagger.models.Swagger) after. For now, let us serialize it to JSON manually. String swaggerJson = entity instanceof String ? (String)entity : Json.pretty(entity); String openApiJson = SwaggerToOpenApiConversionUtils.getOpenApiFromSwaggerJson( createMessageContext(), swaggerJson, openApiConfig); respCtx.setEntity(openApiJson); } }
Example #19
Source File: PathOperationComponent.java From swagger2markup with Apache License 2.0 | 5 votes |
/** * Parse a JSON array * * @param raw Object containing a JSON string * @return JsonNode[contentType, example] * @throws RuntimeException when the given JSON string cannot be parsed */ private JsonNode parseExample(Object raw) throws RuntimeException { try { JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); return mapper.readTree(Json.pretty(raw)); } catch (Exception ex) { throw new RuntimeException("Failed to read example", ex); } }
Example #20
Source File: SwaggerGenerator.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void generateSwaggerJson() throws Exception { Set<Class<?>> classes = new HashSet<>(endpointConfig.getClasses()); classes.add(AutoscaleApi.class); Swagger swagger = new Reader(SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT).configure(new Swagger())) .read(classes); Path path = Paths.get("./build/swagger/autoscale.json"); Files.createDirectories(path.getParent()); Files.writeString(path, Json.pretty(swagger)); }
Example #21
Source File: SpringMvcTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
private void assertGeneratedSwaggerSpecJson(String description) throws MojoExecutionException, MojoFailureException, IOException { mojo.execute(); ObjectMapper mapper = Json.mapper(); JsonNode actualJson = mapper.readTree(new File(swaggerOutputDir, "swagger.json")); JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring.json")); changeDescription(expectJson, description); assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER)); }
Example #22
Source File: SwaggerMavenPluginTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void testFeatureIsAccepted() throws Exception { File testPom = new File(getBasedir(), "src/test/resources/plugin-config.xml"); mojo = (ApiDocumentMojo) lookupMojo("generate", testPom); mojo.execute(); assertTrue(Json.mapper().isEnabled(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)); assertTrue(Json.mapper().isEnabled(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS)); }
Example #23
Source File: StringWrapperModelTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void testAssertGeneratedSwaggerSpecJson() throws MojoExecutionException, MojoFailureException, IOException { mojo.execute(); ObjectMapper mapper = Json.mapper(); JsonNode actualJson = mapper.readTree(new File(swaggerOutputDir, "swagger.json")); JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring-string-wrapper-model.json")); assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER)); }
Example #24
Source File: SpringMvcEnhancedOperationIdTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void testAssertGeneratedSwaggerSpecJson() throws MojoExecutionException, MojoFailureException, IOException { mojo.execute(); ObjectMapper mapper = Json.mapper(); JsonNode actualJson = mapper.readTree(new File(swaggerOutputDir, "swagger.json")); JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring-enhanced-operation-id.json")); assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER)); }
Example #25
Source File: VaadinConnectTsGenerator.java From flow with Apache License 2.0 | 5 votes |
private String getTypeDeclarationFromComposedSchema( ComposedSchema composedSchema, String optionalSuffix) { if (composedSchema.getAllOf() != null && composedSchema.getAllOf().size() == 1) { return getTypeDeclaration(composedSchema.getAllOf().get(0)) + optionalSuffix; } else { String unknownComposedSchema = Json.pretty(composedSchema); getLogger().debug("Unknown ComposedSchema: {}", unknownComposedSchema); return "any"; } }
Example #26
Source File: SwaggerSerializers.java From che with Eclipse Public License 2.0 | 5 votes |
@Override public void writeTo( Swagger data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException { out.write(Json.mapper().writeValueAsString(data).getBytes("utf-8")); }
Example #27
Source File: HttpServer.java From netty-rest with Apache License 2.0 | 5 votes |
private void swaggerApiHandle(RakamHttpRequest request) { String content; try { content = Json.mapper().writeValueAsString(swagger); } catch (JsonProcessingException e) { request.response("Error").end(); return; } request.response(content).end(); }
Example #28
Source File: ApiGatewaySdkSwaggerApiImporter.java From aws-apigateway-importer with Apache License 2.0 | 5 votes |
private String getAuthorizationType(Operation op) { String authType = "NONE"; if (op.getVendorExtensions() != null) { Object objectNode = op.getVendorExtensions().get(EXTENSION_AUTH); Map<String, String> authExtension = Json.mapper().convertValue( objectNode, Map.class ); if (authExtension != null) { authType = authExtension.get("type").toUpperCase(); } } return authType; }
Example #29
Source File: ApiDocumentMojo.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
private void configureObjectMapperFeatures(List<String> features, boolean enabled) throws Exception { for (String feature : features) { int i= feature.lastIndexOf("."); Class clazz = Class.forName(feature.substring(0,i)); Enum e = Enum.valueOf(clazz,feature.substring(i+1)); getLog().debug("enabling " + e.getDeclaringClass().toString() + "." + e.name() + ""); Method method = Json.mapper().getClass().getMethod("configure",e.getClass(),boolean.class); method.invoke(Json.mapper(),e,enabled); } }
Example #30
Source File: SpringMvcSkipInheritedTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void testAssertGeneratedSwaggerSpecJson() throws MojoExecutionException, MojoFailureException, IOException { mojo.execute(); ObjectMapper mapper = Json.mapper(); JsonNode actualJson = mapper.readTree(new File(swaggerOutputDir, "swagger.json")); JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring-skip-inherited.json")); assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER)); }