List of usage examples for com.fasterxml.jackson.databind ObjectMapper constructType
public JavaType constructType(Type t)
java.lang.Class
), but without explicit context. From source file:cz.hobrasoft.pdfmu.jackson.SchemaGenerator.java
public static void main(String[] args) throws JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); // nice formatting SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); Map<String, Type> types = new HashMap<>(); types.put("RpcResponse", RpcResponse.class); types.put("result/inspect", Inspect.class); types.put("result/version set", VersionSet.class); types.put("result/signature add", SignatureAdd.class); types.put("result/empty", EmptyResult.class); for (Map.Entry<String, Type> e : types.entrySet()) { String name = e.getKey(); String filename = String.format("schema/%s.json", name); Type type = e.getValue(); mapper.acceptJsonFormatVisitor(mapper.constructType(type), visitor); JsonSchema jsonSchema = visitor.finalSchema(); mapper.writeValue(new File(filename), jsonSchema); }/*from w w w. j a v a2 s . c o m*/ }
From source file:com.phoenixnap.oss.ramlapisync.naming.SchemaHelper.java
private static JsonSchema extractSchemaInternal(Type clazz, Type genericType, String responseDescription, JavaDocStore javaDocStore, ObjectMapper m) throws JsonMappingException { SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); if (genericType != null) { try {/* w ww . j a v a 2 s.com*/ m.acceptJsonFormatVisitor(m.constructType(genericType), visitor); } catch (Exception ex) { logger.error("Unable to add JSON visitor for " + genericType.toString()); } } try { m.acceptJsonFormatVisitor(m.constructType(clazz), visitor); } catch (Exception ex) { logger.error("Unable to add JSON visitor for " + clazz.toString()); } JsonSchema jsonSchema = visitor.finalSchema(); if (jsonSchema instanceof ObjectSchema && javaDocStore != null) { ObjectSchema objectSchema = (ObjectSchema) jsonSchema; if (objectSchema.getProperties() != null) { for (Entry<String, JsonSchema> cSchema : objectSchema.getProperties().entrySet()) { JavaDocEntry javaDocEntry = javaDocStore.getJavaDoc(cSchema.getKey()); if (javaDocEntry != null && StringUtils.hasText(javaDocEntry.getComment())) { cSchema.getValue().setDescription(javaDocEntry.getComment()); } } } } else if (jsonSchema instanceof ValueTypeSchema && StringUtils.hasText(responseDescription)) { ValueTypeSchema valueTypeSchema = (ValueTypeSchema) jsonSchema; valueTypeSchema.setDescription(responseDescription); } else if (jsonSchema instanceof ArraySchema && genericType != null) { ArraySchema arraySchema = (ArraySchema) jsonSchema; arraySchema.setItemsSchema(extractSchemaInternal(genericType, TypeHelper.inferGenericType(genericType), responseDescription, javaDocStore, m)); } return jsonSchema; }
From source file:org.fusesource.restygwt.server.complex.DTOTypeResolverServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DTO1 one = new DTO1(); one.name = "Fred Flintstone"; one.size = 1024;//ww w.j a v a 2 s .c om DTO2 two = new DTO2(); two.name = "Barney Rubble"; two.foo = "schmaltzy"; DTO2 three = new DTO2(); three.name = "BamBam Rubble"; three.foo = "dorky"; resp.setContentType("application/json"); ObjectMapper om = new ObjectMapper(); try { ObjectWriter writer = om.writer() .withType(om.constructType(getClass().getMethod("prototype").getGenericReturnType())); writer.writeValue(resp.getOutputStream(), Lists.newArrayList(one, two, three)); } catch (Exception e) { throw new ServletException(e); } }
From source file:org.raml.parser.tagresolver.JacksonTagResolver.java
@Override public Node resolve(Node node, ResourceLoader resourceLoader, NodeHandler nodeHandler) { String className = ((ScalarNode) node).getValue(); try {//w ww .j a v a2 s. c om Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className); ObjectMapper objectMapper = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(clazz), visitor); JsonSchema jsonSchema = visitor.finalSchema(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); objectMapper.writeValue(baos, jsonSchema); String schema = baos.toString(); return new ScalarNode(Tag.STR, schema, node.getStartMark(), node.getEndMark(), ((ScalarNode) node).getStyle()); } catch (Exception e) { throw new YAMLException(e); } }
From source file:com.github.helenusdriver.driver.tools.Tool.java
/** * Creates all defined Json schemas based on the provided set of package names * and options and add the schemas to the specified map. * * @author paouelle//w w w .j a v a2 s .co m * * @param pkgs the set of packages to create Json schemas for * @param suffixes the map of provided suffix values * @param matching whether or not to only create schemas for keyspaces that * matches the specified set of suffixes * @param schemas the map where to record the Json schema for the pojo classes * found * @throws LinkageError if the linkage fails for one of the specified entity * class * @throws ExceptionInInitializerError if the initialization provoked by one * of the specified entity class fails * @throws IllegalArgumentException if no pojos are found in any of the * specified packages * @throws IOException if an I/O error occurs while generating the Json schemas */ private static void createJsonSchemasFromPackages(String[] pkgs, Map<String, String> suffixes, boolean matching, Map<Class<?>, JsonSchema> schemas) throws IOException { for (final String pkg : pkgs) { if (pkg == null) { continue; } final CreateSchemas cs = (matching ? StatementBuilder.createMatchingSchemas(pkg) : StatementBuilder.createSchemas(pkg)); // pass all suffixes for (final Map.Entry<String, String> e : suffixes.entrySet()) { // register the suffix value with the corresponding suffix type cs.where(StatementBuilder.eq(e.getKey(), e.getValue())); } for (final Class<?> c : cs.getObjectClasses()) { System.out.println(Tool.class.getSimpleName() + ": creating Json schema for " + c.getName()); final ObjectMapper m = new ObjectMapper(); final SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); m.registerModule(new Jdk8Module()); m.enable(SerializationFeature.INDENT_OUTPUT); m.acceptJsonFormatVisitor(m.constructType(c), visitor); schemas.put(c, visitor.finalSchema()); } } }
From source file:io.mandrel.common.schema.SchemaTest.java
@Test public void test() throws JsonProcessingException { ObjectMapper m = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); m.acceptJsonFormatVisitor(m.constructType(Spider.class), visitor); JsonSchema jsonSchema = visitor.finalSchema(); System.err.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema)); }
From source file:com.github.helenusdriver.driver.tools.Tool.java
/** * Creates all defined Json schemas based on the provided set of class names * and options and add the schemas to the specified map. For each class found; * the corresponding array element will be nulled. All others are simply * skipped.//from w w w . j av a 2 s. c o m * * @author paouelle * * @param cnames the set of class names to create Json schemas for * @param suffixes the map of provided suffix values * @param matching whether or not to only create schemas for keyspaces that * matches the specified set of suffixes * @param schemas the map where to record the Json schema for the pojo classes * found * @throws LinkageError if the linkage fails for one of the specified entity * class * @throws ExceptionInInitializerError if the initialization provoked by one * of the specified entity class fails * @throws IOException if an I/O error occurs while generating the Json schemas */ private static void createJsonSchemasFromClasses(String[] cnames, Map<String, String> suffixes, boolean matching, Map<Class<?>, JsonSchema> schemas) throws IOException { next_class: for (int i = 0; i < cnames.length; i++) { try { final Class<?> clazz = Class.forName(cnames[i]); cnames[i] = null; // clear since we found a class final CreateSchema<?> cs = StatementBuilder.createSchema(clazz); // pass all required suffixes for (final Map.Entry<String, String> e : suffixes.entrySet()) { // check if this suffix type is defined final FieldInfo<?> suffix = cs.getClassInfo().getSuffixKeyByType(e.getKey()); if (suffix != null) { // register the suffix value with the corresponding suffix name cs.where(StatementBuilder.eq(suffix.getSuffixKeyName(), e.getValue())); } else if (matching) { // we have one more suffix then defined with this pojo // and we were requested to only do does that match the provided // suffixes so skip the class continue next_class; } } for (final Class<?> c : cs.getObjectClasses()) { System.out.println(Tool.class.getSimpleName() + ": creating Json schema for " + c.getName()); final ObjectMapper m = new ObjectMapper(); final SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); m.registerModule(new Jdk8Module()); m.enable(SerializationFeature.INDENT_OUTPUT); m.acceptJsonFormatVisitor(m.constructType(c), visitor); schemas.put(c, visitor.finalSchema()); } } catch (ClassNotFoundException e) { // ignore and continue } } }
From source file:org.springframework.data.rest.webmvc.json.DomainObjectReader.java
/** * Returns the {@link MappedProperties} for the given {@link PersistentEntity}. * /*from ww w . j a v a 2 s. c om*/ * @param entity must not be {@literal null}. * @param mapper must not be {@literal null}. * @return */ private MappedProperties getJacksonProperties(PersistentEntity<?, ?> entity, ObjectMapper mapper) { BeanDescription description = introspector.forDeserialization(mapper.getDeserializationConfig(), mapper.constructType(entity.getType()), mapper.getDeserializationConfig()); return new MappedProperties(entity, description); }
From source file:demo.jaxrs.server.CustomerServiceImpl.java
public Response getCustomer2(String id) { System.out.println("----invoking getCustomer, Customer id is: " + id); long idNumber = Long.parseLong(id); Customer c = customers.get(idNumber); ObjectMapper m = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); try {/*from ww w. j a va 2 s. c o m*/ m.acceptJsonFormatVisitor(m.constructType(Customer.class), visitor); } catch (JsonMappingException e) { e.printStackTrace(); } JsonSchema jsonSchema = visitor.finalSchema(); // jsonSchema.asStringSchema().toString(); // System.out.println(jsonSchema.); if (c != null) { return Response.ok(c).build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); // builder.type(MediaType.APPLICATION_JSON_TYPE); builder.type(MediaType.APPLICATION_XML); builder.entity("<error>Customer Not Found!</error>"); // return Response.status(Response.Status.BAD_REQUEST).build(); throw new WebApplicationException(builder.build()); } }
From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java
@Override protected Pair<String, RamlMimeType> extractRequestBody(Method method, Map<String, String> parameterComments, String comment, List<ApiParameterMetadata> apiParameters) { RamlMimeType mimeType = RamlModelFactoryOfFactories.createRamlModelFactory().createRamlMimeType(); String type;/*from w w w . j a va 2 s . com*/ //Handle empty body if (apiParameters != null && apiParameters.size() == 0) { // do nothing here return null; } else if (apiParameters != null && apiParameters.size() == 1 && String.class.equals(apiParameters.get(0).getType()) // Handle Plain Text parameters && apiParameters.get(0).isAnnotationPresent(RequestBody.class)) { ApiParameterMetadata apiParameterMetadata = apiParameters.get(0); type = "text/plain"; if (StringUtils.hasText(apiParameterMetadata.getExample())) { mimeType.setExample(apiParameterMetadata.getExample()); } ObjectMapper m = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); try { m.acceptJsonFormatVisitor(m.constructType(String.class), visitor); JsonSchema jsonSchema = visitor.finalSchema(); String description = parameterComments.get(apiParameterMetadata.getJavaName()); if (description == null) { description = apiParameterMetadata.getName(); } jsonSchema.setDescription(description); jsonSchema.setRequired(!apiParameterMetadata.isNullable()); mimeType.setSchema(m.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema)); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } return new Pair<>(type, mimeType); } else if (apiParameters != null && (apiParameters.size() > 1 || (!apiParameters.get(0).isAnnotationPresent(RequestBody.class) && String.class.equals(apiParameters.get(0).getType())))) { type = "application/x-www-form-urlencoded"; for (ApiParameterMetadata param : apiParameters) { RamlFormParameter formParameter = RamlModelFactoryOfFactories.createRamlModelFactory() .createRamlFormParameter(); formParameter.setDisplayName(param.getName()); formParameter.setExample(param.getExample()); RamlParamType simpleType = SchemaHelper.mapSimpleType(param.getType()); formParameter.setType(simpleType == null ? RamlParamType.STRING : simpleType); String description = parameterComments.get(param.getJavaName()); if (description == null) { description = param.getName(); } formParameter.setDescription(description); formParameter.setRequired(!param.isNullable()); Map<String, List<RamlFormParameter>> paramMap; if (mimeType.getFormParameters() == null) { paramMap = new TreeMap<>(); mimeType.setFormParameters(paramMap); } else { paramMap = mimeType.getFormParameters(); } mimeType.addFormParameters(param.getName(), Collections.singletonList(formParameter)); } return new Pair<>(type, mimeType); } else { return super.extractRequestBody(method, parameterComments, comment, apiParameters); } }