Example usage for com.fasterxml.jackson.module.jsonSchema.factories SchemaFactoryWrapper SchemaFactoryWrapper

List of usage examples for com.fasterxml.jackson.module.jsonSchema.factories SchemaFactoryWrapper SchemaFactoryWrapper

Introduction

In this page you can find the example usage for com.fasterxml.jackson.module.jsonSchema.factories SchemaFactoryWrapper SchemaFactoryWrapper.

Prototype

public SchemaFactoryWrapper() 

Source Link

Usage

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 ww. j av a2s.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.emonocot.portal.controller.SearchController.java

@RequestMapping(method = RequestMethod.OPTIONS, produces = "application/json")
public ResponseEntity<RestDoc> optionsResource() throws JsonMappingException {
    RestDoc restDoc = new RestDoc();
    HashMap<String, Schema> schemas = new HashMap<String, Schema>();
    Schema pagerSchema = new Schema();
    SchemaFactoryWrapper pageVisitor = new SchemaFactoryWrapper();
    objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(Page.class), pageVisitor);
    pagerSchema.setSchema(pageVisitor.finalSchema());
    schemas.put("http://e-monocot.org#page", pagerSchema);
    restDoc.setSchemas(schemas);//from   ww  w . jav  a  2 s.c om

    GlobalHeader headers = new GlobalHeader();
    headers.request("Content-Type", "Must be set to application/json", true);
    headers.request("Authorization", "Supports HTTP Basic. Users may also use their api key", false);

    restDoc.setHeaders(headers);

    ParamValidation integerParam = new ParamValidation();
    integerParam.setType("match");
    integerParam.setPattern("\\d+");
    ParamValidation apikeyParam = new ParamValidation();
    apikeyParam.setType("match");
    apikeyParam.setPattern("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
    ParamValidation stringParam = new ParamValidation();
    stringParam.setType("match");
    stringParam.setPattern("[0-9a-f]+");
    ParamValidation doubleParam = new ParamValidation();
    doubleParam.setType("match");
    doubleParam.setPattern("[0-9]+\\.[0.9]+");

    Set<RestResource> resources = new HashSet<RestResource>();

    RestResource searchForObjects = new RestResource();
    searchForObjects.setId("Search");
    searchForObjects.setPath("/search{?query,x1,y1,x2,y2,facet,limit,start,sort,callback,apikey,fetch}");
    searchForObjects.param("limit", "The maximum number of resources to return", integerParam);
    searchForObjects.param("start",
            "The number of pages (of size _limit_) offset from the beginning of the recordset", integerParam);
    searchForObjects.param("apikey", "The apikey of the user account making the request", apikeyParam);
    searchForObjects.param("callback", "The name of the callback function used to wrap the JSON response",
            stringParam);
    searchForObjects.param("x1",
            "The southerly extent of the bounding box (uses WGS84 Coordinate reference system). Only documents with distributions within the bounding box will be returned",
            doubleParam);
    searchForObjects.param("y1",
            "The westerly extent of the bounding box (uses WGS84 Coordinate reference system). Only documents with distributions within the bounding box will be returned",
            doubleParam);
    searchForObjects.param("x2",
            "The northerly extent of the bounding box (uses WGS84 Coordinate reference system). Only documents with distributions within the bounding box will be returned",
            doubleParam);
    searchForObjects.param("y2",
            "The easterly extent of the bounding box (uses WGS84 Coordinate reference system). Only documents with distributions within the bounding box will be returned",
            doubleParam);
    searchForObjects.param("query",
            "A free-text query string. Only documents matching the query string will be returned", stringParam);
    searchForObjects.param("facet",
            "Only return documents which match a particular filter, in the form {fieldName}:{fieldValue} where fieldName is from the controlled vocabulary defined by org.emonocot.pager.FacetName.",
            stringParam);
    searchForObjects.param("sort",
            "Sort the result set according to the supplied criteria, in the form {fieldName}_(asc|desc) where fieldName is from the controlled vocabulary defined by org.emonocot.pager.FacetName.",
            stringParam);
    searchForObjects.param("fetch",
            "The name of a valid 'fetch-profile' which will load some or all related objects prior to serialization. Try 'object-page' to return most related objects",
            stringParam);

    MethodDefinition searchObjects = new MethodDefinition();
    searchObjects.description("Search for resources");
    ResponseDefinition searchObjectsResponseDefinition = new ResponseDefinition();

    searchObjectsResponseDefinition.type("application/json", "http://e-monocot.org#page");
    searchObjectsResponseDefinition.type("application/javascript", "http://e-monocot.org#page");
    searchObjects.response(searchObjectsResponseDefinition);
    searchObjects.statusCode("200", "Successfully searched for resources");

    searchForObjects.method("GET", searchObjects);
    resources.add(searchForObjects);

    restDoc.setResources(resources);

    return new ResponseEntity<RestDoc>(restDoc, HttpStatus.OK);
}

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  va2s.  c  o 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:org.versly.rest.wsdoc.AnnotationProcessor.java

String jsonSchemaFromTypeMirror(TypeMirror type) {
    String serializedSchema = null;

    if (type.getKind().isPrimitive() || type.getKind() == TypeKind.VOID) {
        return null;
    }//from www  .ja va  2 s.c  o m

    // we need the dto class to generate schema using jackson json-schema module
    // note: Types.erasure() provides canonical names whereas Class.forName() wants a "regular" name,
    // so forName will fail for nested and inner classes as "regular" names use $ between parent and child.
    Class dtoClass = null;
    StringBuffer erasure = new StringBuffer(_typeUtils.erasure(type).toString());
    for (boolean done = false; !done;) {
        try {
            dtoClass = Class.forName(erasure.toString());
            done = true;
        } catch (ClassNotFoundException e) {
            if (erasure.lastIndexOf(".") != -1) {
                erasure.setCharAt(erasure.lastIndexOf("."), '$');
            } else {
                done = true;
            }
        }
    }

    // if we were able to figure out the dto class, use jackson json-schema module to serialize it
    Exception e = null;
    if (dtoClass != null) {
        try {
            ObjectMapper m = new ObjectMapper();
            m.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            m.registerModule(new JodaModule());
            SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
            m.acceptJsonFormatVisitor(m.constructType(dtoClass), visitor);
            serializedSchema = m.writeValueAsString(visitor.finalSchema());
        } catch (Exception ex) {
            e = ex;
        }
    }

    // report warning if we were not able to generate schema for non-primitive type
    if (serializedSchema == null) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "cannot generate json-schema for class " + type.toString() + " (erasure " + erasure + "), "
                        + ((e != null) ? ("exception: " + e.getMessage()) : "class not found"));
    }

    return serializedSchema;
}