Search in sources :

Example 1 with GenerationException

use of org.jsonschema2pojo.exception.GenerationException in project jsonschema2pojo by joelittlejohn.

the class SchemaGenerator method simpleTypeSchema.

private ObjectNode simpleTypeSchema(JsonNode exampleValue) {
    try {
        Object valueAsJavaType = this.objectMapper.treeToValue(exampleValue, Object.class);
        SerializerProvider serializerProvider = new DefaultSerializerProvider.Impl().createInstance(this.objectMapper.getSerializationConfig(), BeanSerializerFactory.instance);
        if (valueAsJavaType == null) {
            SchemaAware valueSerializer = NullSerializer.instance;
            return (ObjectNode) valueSerializer.getSchema(serializerProvider, null);
        } else if (valueAsJavaType instanceof Long) {
            // longs are 'integers' in schema terms
            SchemaAware valueSerializer = (SchemaAware) serializerProvider.findValueSerializer(Integer.class, null);
            ObjectNode schema = (ObjectNode) valueSerializer.getSchema(serializerProvider, null);
            schema.put("minimum", Long.MAX_VALUE);
            return schema;
        } else {
            Class<? extends Object> javaTypeForValue = valueAsJavaType.getClass();
            SchemaAware valueSerializer = (SchemaAware) serializerProvider.findValueSerializer(javaTypeForValue, null);
            return (ObjectNode) valueSerializer.getSchema(serializerProvider, null);
        }
    } catch (JsonProcessingException e) {
        throw new GenerationException("Unable to generate a schema for this json example: " + exampleValue, e);
    }
}
Also used : SchemaAware(com.fasterxml.jackson.databind.jsonschema.SchemaAware) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DefaultSerializerProvider(com.fasterxml.jackson.databind.ser.DefaultSerializerProvider) GenerationException(org.jsonschema2pojo.exception.GenerationException) DefaultSerializerProvider(com.fasterxml.jackson.databind.ser.DefaultSerializerProvider) SerializerProvider(com.fasterxml.jackson.databind.SerializerProvider) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with GenerationException

use of org.jsonschema2pojo.exception.GenerationException in project jsonschema2pojo by joelittlejohn.

the class ObjectRule method createClass.

/**
 * Creates a new Java class that will be generated.
 *
 * @param nodeName
 *            the node name which may be used to dictate the new class name
 * @param node
 *            the node representing the schema that caused the need for a
 *            new class. This node may include a 'javaType' property which
 *            if present will override the fully qualified name of the newly
 *            generated class.
 * @param _package
 *            the package which may contain a new class after this method
 *            call
 * @return a reference to a newly created class
 * @throws ClassAlreadyExistsException
 *             if the given arguments cause an attempt to create a class
 *             that already exists, either on the classpath or in the
 *             current map of classes to be generated.
 */
private JDefinedClass createClass(String nodeName, JsonNode node, JPackage _package) throws ClassAlreadyExistsException {
    JDefinedClass newType;
    Annotator annotator = ruleFactory.getAnnotator();
    try {
        if (node.has("existingJavaType")) {
            String fqn = substringBefore(node.get("existingJavaType").asText(), "<");
            if (isPrimitive(fqn, _package.owner())) {
                throw new ClassAlreadyExistsException(primitiveType(fqn, _package.owner()));
            }
            JClass existingClass = resolveType(_package, fqn + (node.get("existingJavaType").asText().contains("<") ? "<" + substringAfter(node.get("existingJavaType").asText(), "<") : ""));
            throw new ClassAlreadyExistsException(existingClass);
        }
        boolean usePolymorphicDeserialization = annotator.isPolymorphicDeserializationSupported(node);
        if (node.has("javaType")) {
            String fqn = node.path("javaType").asText();
            if (isPrimitive(fqn, _package.owner())) {
                throw new GenerationException("javaType cannot refer to a primitive type (" + fqn + "), did you mean to use existingJavaType?");
            }
            if (fqn.contains("<")) {
                throw new GenerationException("javaType does not support generic args (" + fqn + "), did you mean to use existingJavaType?");
            }
            int index = fqn.lastIndexOf(".") + 1;
            if (index == 0) {
                // Actually not a fully qualified name
                fqn = _package.name() + "." + fqn;
                index = fqn.lastIndexOf(".") + 1;
            }
            if (index >= 0 && index < fqn.length()) {
                fqn = fqn.substring(0, index) + ruleFactory.getGenerationConfig().getClassNamePrefix() + fqn.substring(index) + ruleFactory.getGenerationConfig().getClassNameSuffix();
            }
            if (usePolymorphicDeserialization) {
                newType = _package.owner()._class(JMod.PUBLIC, fqn, ClassType.CLASS);
            } else {
                newType = _package.owner()._class(fqn);
            }
        } else {
            if (usePolymorphicDeserialization) {
                newType = _package._class(JMod.PUBLIC, ruleFactory.getNameHelper().getUniqueClassName(nodeName, node, _package), ClassType.CLASS);
            } else {
                newType = _package._class(ruleFactory.getNameHelper().getUniqueClassName(nodeName, node, _package));
            }
        }
    } catch (JClassAlreadyExistsException e) {
        throw new ClassAlreadyExistsException(e.getExistingClass());
    }
    annotator.typeInfo(newType, node);
    annotator.propertyInclusion(newType, node);
    return newType;
}
Also used : JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) JDefinedClass(com.sun.codemodel.JDefinedClass) Annotator(org.jsonschema2pojo.Annotator) JClass(com.sun.codemodel.JClass) GenerationException(org.jsonschema2pojo.exception.GenerationException) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) ClassAlreadyExistsException(org.jsonschema2pojo.exception.ClassAlreadyExistsException)

Example 3 with GenerationException

use of org.jsonschema2pojo.exception.GenerationException in project jsonschema2pojo by joelittlejohn.

the class SchemaRule method nameFromRef.

private String nameFromRef(String ref) {
    if ("#".equals(ref)) {
        return null;
    }
    String nameFromRef;
    if (!contains(ref, "#")) {
        nameFromRef = Jsonschema2Pojo.getNodeName(ref, ruleFactory.getGenerationConfig());
    } else {
        String[] nameParts = split(ref, "/\\#");
        nameFromRef = nameParts[nameParts.length - 1];
    }
    try {
        return URLDecoder.decode(nameFromRef, "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new GenerationException("Failed to decode ref: " + ref, e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) GenerationException(org.jsonschema2pojo.exception.GenerationException)

Example 4 with GenerationException

use of org.jsonschema2pojo.exception.GenerationException in project jsonschema2pojo by joelittlejohn.

the class Jsonschema2Pojo method generate.

/**
     * Reads the contents of the given source and initiates schema generation.
     *
     * @param config
     *            the configuration options (including source and target paths,
     *            and other behavioural options) that will control code
     *            generation
     * @throws FileNotFoundException
     *             if the source path is not found
     * @throws IOException
     *             if the application is unable to read data from the source
     */
public static void generate(GenerationConfig config) throws IOException {
    Annotator annotator = getAnnotator(config);
    RuleFactory ruleFactory = createRuleFactory(config);
    ruleFactory.setAnnotator(annotator);
    ruleFactory.setGenerationConfig(config);
    SchemaMapper mapper = new SchemaMapper(ruleFactory, new SchemaGenerator());
    JCodeModel codeModel = new JCodeModel();
    if (config.isRemoveOldOutput()) {
        removeOldOutput(config.getTargetDirectory());
    }
    for (Iterator<URL> sources = config.getSource(); sources.hasNext(); ) {
        URL source = sources.next();
        if (URLUtil.parseProtocol(source.toString()) == URLProtocol.FILE && URLUtil.getFileFromURL(source).isDirectory()) {
            generateRecursive(config, mapper, codeModel, defaultString(config.getTargetPackage()), Arrays.asList(URLUtil.getFileFromURL(source).listFiles(config.getFileFilter())));
        } else {
            mapper.generate(codeModel, getNodeName(source, config), defaultString(config.getTargetPackage()), source);
        }
    }
    if (config.getTargetDirectory().exists() || config.getTargetDirectory().mkdirs()) {
        CodeWriter sourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding());
        CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding());
        codeModel.build(sourcesWriter, resourcesWriter);
    } else {
        throw new GenerationException("Could not create or access target directory " + config.getTargetDirectory().getAbsolutePath());
    }
}
Also used : RuleFactory(org.jsonschema2pojo.rules.RuleFactory) GenerationException(org.jsonschema2pojo.exception.GenerationException) JCodeModel(com.sun.codemodel.JCodeModel) CodeWriter(com.sun.codemodel.CodeWriter) URL(java.net.URL)

Example 5 with GenerationException

use of org.jsonschema2pojo.exception.GenerationException in project jsonschema2pojo by joelittlejohn.

the class TypeUtil method resolveType.

public static JClass resolveType(JClassContainer _package, String typeDefinition) {
    try {
        FieldDeclaration fieldDeclaration = (FieldDeclaration) JavaParser.parseBodyDeclaration(typeDefinition + " foo;");
        ClassOrInterfaceType c = (ClassOrInterfaceType) ((ReferenceType) fieldDeclaration.getType()).getType();
        return buildClass(_package, c, 0);
    } catch (ParseException e) {
        throw new GenerationException("Couldn't parse type: " + typeDefinition, e);
    }
}
Also used : GenerationException(org.jsonschema2pojo.exception.GenerationException) ClassOrInterfaceType(japa.parser.ast.type.ClassOrInterfaceType) ParseException(japa.parser.ParseException) FieldDeclaration(japa.parser.ast.body.FieldDeclaration)

Aggregations

GenerationException (org.jsonschema2pojo.exception.GenerationException)7 CodeWriter (com.sun.codemodel.CodeWriter)2 JCodeModel (com.sun.codemodel.JCodeModel)2 URL (java.net.URL)2 RuleFactory (org.jsonschema2pojo.rules.RuleFactory)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 SerializerProvider (com.fasterxml.jackson.databind.SerializerProvider)1 SchemaAware (com.fasterxml.jackson.databind.jsonschema.SchemaAware)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 DefaultSerializerProvider (com.fasterxml.jackson.databind.ser.DefaultSerializerProvider)1 JClass (com.sun.codemodel.JClass)1 JClassAlreadyExistsException (com.sun.codemodel.JClassAlreadyExistsException)1 JDefinedClass (com.sun.codemodel.JDefinedClass)1 JFieldVar (com.sun.codemodel.JFieldVar)1 ParseException (japa.parser.ParseException)1 FieldDeclaration (japa.parser.ast.body.FieldDeclaration)1 ClassOrInterfaceType (japa.parser.ast.type.ClassOrInterfaceType)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 DataOutputStream (java.io.DataOutputStream)1 IOException (java.io.IOException)1