Search in sources :

Example 1 with JClassAlreadyExistsException

use of com.sun.codemodel.JClassAlreadyExistsException 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;
    try {
        boolean usePolymorphicDeserialization = usesPolymorphicDeserialization(node);
        if (node.has("javaType")) {
            String fqn = substringBefore(node.get("javaType").asText(), "<");
            if (isPrimitive(fqn, _package.owner())) {
                throw new ClassAlreadyExistsException(primitiveType(fqn, _package.owner()));
            }
            JClass existingClass;
            try {
                _package.owner().ref(Thread.currentThread().getContextClassLoader().loadClass(fqn));
                existingClass = resolveType(_package, fqn + (node.get("javaType").asText().contains("<") ? "<" + substringAfter(node.get("javaType").asText(), "<") : ""));
                throw new ClassAlreadyExistsException(existingClass);
            } catch (ClassNotFoundException e) {
            }
            int index = fqn.lastIndexOf(".") + 1;
            if (index >= 0 && index < fqn.length()) {
                fqn = fqn.substring(0, index) + ruleFactory.getGenerationConfig().getClassNamePrefix() + fqn.substring(index) + ruleFactory.getGenerationConfig().getClassNameSuffix();
            }
            try {
                _package.owner().ref(Thread.currentThread().getContextClassLoader().loadClass(fqn));
                existingClass = resolveType(_package, fqn + (node.get("javaType").asText().contains("<") ? "<" + substringAfter(node.get("javaType").asText(), "<") : ""));
                throw new ClassAlreadyExistsException(existingClass);
            } catch (ClassNotFoundException e) {
            }
            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, getClassName(nodeName, node, _package), ClassType.CLASS);
            } else {
                newType = _package._class(getClassName(nodeName, node, _package));
            }
        }
    } catch (JClassAlreadyExistsException e) {
        throw new ClassAlreadyExistsException(e.getExistingClass());
    }
    ruleFactory.getAnnotator().propertyInclusion(newType, node);
    return newType;
}
Also used : JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) ClassAlreadyExistsException(org.jsonschema2pojo.exception.ClassAlreadyExistsException)

Example 2 with JClassAlreadyExistsException

use of com.sun.codemodel.JClassAlreadyExistsException in project groovy-cps by cloudbees.

the class Translator method translate.

/**
     * Transforms a single class.
     */
public void translate(String fqcn, String outfqcn, String sourceJarName) throws JClassAlreadyExistsException {
    final JDefinedClass $output = codeModel._class(outfqcn);
    $output.annotate(Generated.class).param("value", Translator.class.getName()).param("date", new Date().toString()).param("comments", "based on " + sourceJarName);
    $output.annotate(SuppressWarnings.class).param("value", "rawtypes");
    $output.constructor(JMod.PRIVATE);
    CompilationUnitTree dgmCut = getDefaultGroovyMethodCompilationUnitTree(parsed, fqcn);
    overloadsResolved.clear();
    ClassSymbol dgm = (ClassSymbol) elements.getTypeElement(fqcn);
    dgm.accept(new ElementScanner7<Void, Void>() {

        @Override
        public Void visitExecutable(ExecutableElement e, Void __) {
            if (translatable.contains(fqcn + "." + e)) {
                overloadsResolved.put(mangledName(e), e);
            }
            // TODO else if it is public and has a Closure argument, translate to a form that just throws UnsupportedOperationException when called in CPS mode
            return null;
        }
    }, null);
    // TODO verify that we actually found everything listed in translatables
    overloadsResolved.forEach((overloadResolved, e) -> {
        try {
            translateMethod(dgmCut, e, $output, fqcn, overloadResolved);
        } catch (Exception x) {
            throw new RuntimeException("Unable to transform " + fqcn + "." + e, x);
        }
    });
    /*
            private static MethodLocation loc(String methodName) {
                return new MethodLocation(CpsDefaultGroovyMethods.class,methodName);
            }
        */
    JClass $MethodLocation = codeModel.ref("com.cloudbees.groovy.cps.MethodLocation");
    $output.method(JMod.PRIVATE | JMod.STATIC, $MethodLocation, "loc").tap(m -> {
        JVar $methodName = m.param(String.class, "methodName");
        m.body()._return(JExpr._new($MethodLocation).arg($output.dotclass()).arg($methodName));
    });
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Generated(javax.annotation.Generated) JDefinedClass(com.sun.codemodel.JDefinedClass) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) ExecutableElement(javax.lang.model.element.ExecutableElement) JClass(com.sun.codemodel.JClass) Date(java.util.Date) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) IOException(java.io.IOException) JVar(com.sun.codemodel.JVar)

Example 3 with JClassAlreadyExistsException

use of com.sun.codemodel.JClassAlreadyExistsException in project jsonschema2pojo by joelittlejohn.

the class ObjectRule method makeUnique.

private String makeUnique(String className, JPackage _package) {
    try {
        JDefinedClass _class = _package._class(className);
        _package.remove(_class);
        return className;
    } catch (JClassAlreadyExistsException e) {
        return makeUnique(className + "_", _package);
    }
}
Also used : JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) JDefinedClass(com.sun.codemodel.JDefinedClass)

Example 4 with JClassAlreadyExistsException

use of com.sun.codemodel.JClassAlreadyExistsException in project rest.li by linkedin.

the class JavaDataTemplateGenerator method generate.

public JClass generate(ClassTemplateSpec classTemplateSpec) {
    final JClass result;
    if (classTemplateSpec == null) {
        result = null;
    } else {
        if (classTemplateSpec.getSchema() == null) {
            // this is for custom class, package override is not applicable.
            result = getCodeModel().directClass(classTemplateSpec.getFullName());
        } else if (PredefinedJavaClasses.containsKey(classTemplateSpec.getSchema())) {
            final Class<?> nativeJavaClass = PredefinedJavaClasses.get(classTemplateSpec.getSchema());
            result = getCodeModel().ref(nativeJavaClass);
        } else if (classTemplateSpec.getSchema().isPrimitive()) {
            result = generatePrimitive((PrimitiveTemplateSpec) classTemplateSpec);
        } else {
            try {
                final JDefinedClass definedClass = defineClass(classTemplateSpec);
                populateClassContent(classTemplateSpec, definedClass);
                result = definedClass;
            } catch (JClassAlreadyExistsException e) {
                throw new IllegalArgumentException(classTemplateSpec.getFullName());
            }
        }
    }
    return result;
}
Also used : JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) PrimitiveTemplateSpec(com.linkedin.pegasus.generator.spec.PrimitiveTemplateSpec) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass)

Example 5 with JClassAlreadyExistsException

use of com.sun.codemodel.JClassAlreadyExistsException in project drill by apache.

the class ClassGenerator method createNestedClass.

/**
   * Creates {@link #innerClassGenerator} with inner class
   * if {@link #hasMaxIndexValue()} returns {@code true}.
   *
   * @return true if splitting happened.
   */
private boolean createNestedClass() {
    if (hasMaxIndexValue()) {
        // all new fields will be declared in the class from innerClassGenerator
        if (innerClassGenerator == null) {
            try {
                JDefinedClass innerClazz = clazz._class(JMod.PRIVATE, clazz.name() + "0");
                innerClassGenerator = new ClassGenerator<>(codeGenerator, mappings, sig, evaluationVisitor, innerClazz, model, optionManager);
            } catch (JClassAlreadyExistsException e) {
                throw new DrillRuntimeException(e);
            }
            oldBlocks = blocks;
            innerClassGenerator.index = index;
            innerClassGenerator.maxIndex += index;
            // blocks from the inner class should be used
            setupInnerClassBlocks();
            return true;
        }
        return innerClassGenerator.createNestedClass();
    }
    return false;
}
Also used : JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) JDefinedClass(com.sun.codemodel.JDefinedClass) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException)

Aggregations

JClassAlreadyExistsException (com.sun.codemodel.JClassAlreadyExistsException)5 JDefinedClass (com.sun.codemodel.JDefinedClass)5 JClass (com.sun.codemodel.JClass)3 PrimitiveTemplateSpec (com.linkedin.pegasus.generator.spec.PrimitiveTemplateSpec)1 JVar (com.sun.codemodel.JVar)1 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)1 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)1 IOException (java.io.IOException)1 Date (java.util.Date)1 Generated (javax.annotation.Generated)1 ExecutableElement (javax.lang.model.element.ExecutableElement)1 DrillRuntimeException (org.apache.drill.common.exceptions.DrillRuntimeException)1 ClassAlreadyExistsException (org.jsonschema2pojo.exception.ClassAlreadyExistsException)1