Example usage for com.fasterxml.jackson.databind ObjectMapper acceptJsonFormatVisitor

List of usage examples for com.fasterxml.jackson.databind ObjectMapper acceptJsonFormatVisitor

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper acceptJsonFormatVisitor.

Prototype

public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor)
        throws JsonMappingException 

Source Link

Document

Method for visiting type hierarchy for given type, using specified visitor.

Usage

From source file:org.force66.json.tools.JSonSchemaGenerator.java

public static void main(String[] args) throws Exception {
    Validate.isTrue(args != null && args.length >= 2, "Usage arguments: className fileTarget");

    String className = args[0];// w w  w .j  av  a  2 s .com
    String outputFileName = args[1];

    HyperSchemaFactoryWrapper schemaVisitor = new HyperSchemaFactoryWrapper();
    ObjectMapper mapper = new ObjectMapper();
    mapper.acceptJsonFormatVisitor(ClassUtils.getClass(className), schemaVisitor);
    JsonSchema jsonSchema = schemaVisitor.finalSchema();

    File outputFile = new File(outputFileName);
    FileUtils.write(outputFile, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
}

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  ww  .  j  av  a 2  s  . c om
}

From source file:com.cuubez.visualizer.util.CuubezUtil.java

public static String generateJsonSchema(Class<?> clazz) {

    ObjectMapper mapper = new ObjectMapper();
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
    try {// w  ww .j a v  a2  s.c o  m
        mapper.acceptJsonFormatVisitor(clazz, visitor);

        JsonSchema schema = visitor.finalSchema();
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);

    } catch (JsonMappingException e) {
        log.error("Error occurred while generating JSON schema for the class [" + clazz + "]", e);
    } catch (JsonProcessingException e) {
        log.error("Error occurred while generating JSON schema for the class [" + clazz + "]", e);
    }

    return null;
}

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 {//  www .  j a v a 2 s  . c o m
            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:io.neocdtv.jarxrs.server.ResourceExample.java

@GET
@Path("schema-jackson-plugin")
public Response generateSchemaJacksonPlugin() throws JsonMappingException, IOException {
    ValidationSchemaFactoryWrapper visitor = new ValidationSchemaFactoryWrapper();
    ObjectMapper mapper = ServerObjectMapper.INSTANCE;
    mapper.acceptJsonFormatVisitor(Object1.class, visitor);
    JsonSchema jsonSchema = visitor.finalSchema();
    return Response.ok(jsonSchema.asContainerTypeSchema()).build();
}

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 {/*from w ww  . j av a2s  .co  m*/
        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/*from  w  w  w  .  java 2  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.//  w w w.j  a va  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: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 .ja  va 2  s .  co  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());
    }
}