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: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 av  a2s.  c  o  m*/
}

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 w  w.  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: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.cuubez.visualizer.util.CuubezUtil.java

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

    ObjectMapper mapper = new ObjectMapper();
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
    try {/*w  w w .  j  a v a 2  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:org.zols.datastore.validator.TV4.java

/**
 * Prepares JSON Schema for a given Java Type
 *
 * @param clazz - Class for which we need JSON Schema
 * @return JSON Schema as JSON text/*from www .j  a  va 2  s. c  o  m*/
 * @throws java.io.IOException
 */
public String getJsonSchema(Class clazz) throws IOException {
    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
    mapper.acceptJsonFormatVisitor(mapper.constructType(clazz), visitor);
    JsonSchema jsonSchema = visitor.finalSchema();
    return addIdField(clazz, getValueAsMap(jsonSchema));
}

From source file:things.thing.ThingUtils.java

public Map<String, JsonSchema> getRegisteredTypeSchemata() {

    if (schemaMap == null) {
        Map<String, JsonSchema> temp = Maps.newTreeMap();
        for (String type : tr.getAllTypes()) {
            Class typeClass = tr.getTypeClass(type);

            SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
            try {
                objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(typeClass), visitor);
            } catch (JsonMappingException e) {
                throw new TypeRuntimeException("Can't get schema for type: " + type, type, e);
            }/*from  w w w .j ava 2s.  c om*/
            JsonSchema jsonSchema = visitor.finalSchema();
            temp.put(type, jsonSchema);
        }
        schemaMap = ImmutableMap.copyOf(temp);
    }
    return schemaMap;
}

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;/*ww w. j  a va  2s.c o  m*/
    //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);
    }
}

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 {//w ww.j  a v  a2s. c  om
        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.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 {//from   w  ww  .j av  a  2s . 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:org.datacleaner.monitor.server.controllers.ComponentControllerV1.java

static void setPropertyType(ComponentDescriptor<?> descriptor, ConfiguredPropertyDescriptor propertyDescriptor,
        ComponentList.PropertyInfo propInfo) {
    // TODO: avoid instanceof by extending the basic ComponentDescriptor
    // interface (maybe add getter for property "Type" in addition to
    // "Class" ? )

    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

    if (propertyDescriptor instanceof AbstractPropertyDescriptor) {
        Field f = ((AbstractPropertyDescriptor) propertyDescriptor).getField();
        Type t = f.getGenericType();
        if (t instanceof Class) {
            propInfo.setClassDetails(((Class<?>) t).getCanonicalName());
        } else {/*from w ww  .  j  ava 2s.  c  o  m*/
            propInfo.setClassDetails(f.getGenericType().toString());
        }
        if (!propertyDescriptor.isInputColumn()) {
            try {
                ComponentHandler.mapper.acceptJsonFormatVisitor(
                        ComponentHandler.mapper.constructType(f.getGenericType()), visitor);
            } catch (JsonMappingException e) {
                throw new RuntimeException(e);
            }
        }
    } else {
        propInfo.setClassDetails(propertyDescriptor.getType().getCanonicalName());
        if (!propertyDescriptor.isInputColumn()) {
            try {
                ComponentHandler.mapper.acceptJsonFormatVisitor(
                        ComponentHandler.mapper.constructType(propertyDescriptor.getType()), visitor);
            } catch (JsonMappingException e) {
                throw new RuntimeException(e);
            }
        }
    }
    propInfo.setClassName(propertyDescriptor.getType().getName());
    if (!propertyDescriptor.isInputColumn()) {
        propInfo.setSchema(visitor.finalSchema());
    }
}