Search in sources :

Example 1 with JCodeModel

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

the class ArrayRuleTest method arrayWithNonUniqueItemsProducesList.

@Test
public void arrayWithNonUniqueItemsProducesList() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "number");
    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.FALSE);
    propertyNode.set("items", itemsNode);
    Schema schema = mock(Schema.class);
    when(schema.getId()).thenReturn(URI.create("http://example/nonUniqueArray"));
    when(config.isUseDoubleNumbers()).thenReturn(true);
    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema);
    assertThat(propertyType, notNullValue());
    assertThat(propertyType.erasure(), is(codeModel.ref(List.class)));
    assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Double.class.getName()));
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Schema(org.jsonschema2pojo.Schema) JClass(com.sun.codemodel.JClass) JPackage(com.sun.codemodel.JPackage) JCodeModel(com.sun.codemodel.JCodeModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 2 with JCodeModel

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

the class ArrayRuleTest method arrayWithUniqueItemsProducesSet.

@Test
public void arrayWithUniqueItemsProducesSet() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "integer");
    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.TRUE);
    propertyNode.set("items", itemsNode);
    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, mock(Schema.class));
    assertThat(propertyType, notNullValue());
    assertThat(propertyType.erasure(), is(codeModel.ref(Set.class)));
    assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Integer.class.getName()));
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JClass(com.sun.codemodel.JClass) Schema(org.jsonschema2pojo.Schema) JPackage(com.sun.codemodel.JPackage) JCodeModel(com.sun.codemodel.JCodeModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 3 with JCodeModel

use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.

the class CurrentBuild method generate.

public void generate(final File rootDirectory) throws IOException {
    try {
        if (resources.size() > 0) {
            ResponseSupport.buildSupportClasses(rootDirectory, getSupportPackage());
        }
        for (TypeGenerator typeGenerator : builtTypes.values()) {
            if (typeGenerator instanceof RamlToPojoTypeGenerator) {
                RamlToPojoTypeGenerator ramlToPojoTypeGenerator = (RamlToPojoTypeGenerator) typeGenerator;
                ramlToPojoTypeGenerator.output(new CodeContainer<ResultingPojos>() {

                    @Override
                    public void into(ResultingPojos g) throws IOException {
                        g.createFoundTypes(rootDirectory.getAbsolutePath());
                    }
                });
            }
            if (typeGenerator instanceof JavaPoetTypeGenerator) {
                buildTypeTree(rootDirectory, (JavaPoetTypeGenerator) typeGenerator);
                continue;
            }
            if (typeGenerator instanceof CodeModelTypeGenerator) {
                CodeModelTypeGenerator b = (CodeModelTypeGenerator) typeGenerator;
                b.output(new CodeContainer<JCodeModel>() {

                    @Override
                    public void into(JCodeModel g) throws IOException {
                        g.build(rootDirectory);
                    }
                });
            }
        }
        for (ResourceGenerator resource : resources) {
            resource.output(new CodeContainer<TypeSpec>() {

                @Override
                public void into(TypeSpec g) throws IOException {
                    JavaFile.Builder file = JavaFile.builder(getResourcePackage(), g).skipJavaLangImports(true);
                    file.build().writeTo(rootDirectory);
                }
            });
        }
        for (JavaPoetTypeGenerator typeGenerator : supportGenerators) {
            typeGenerator.output(new CodeContainer<TypeSpec.Builder>() {

                @Override
                public void into(TypeSpec.Builder g) throws IOException {
                    JavaFile.Builder file = JavaFile.builder(getSupportPackage(), g.build()).skipJavaLangImports(true);
                    file.build().writeTo(rootDirectory);
                }
            });
        }
    } finally {
        if (schemaRepository != null) {
            FileUtils.deleteDirectory(schemaRepository);
        }
    }
}
Also used : ResourceGenerator(org.raml.jaxrs.generator.builders.resources.ResourceGenerator) IOException(java.io.IOException) JCodeModel(com.sun.codemodel.JCodeModel) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 4 with JCodeModel

use of com.sun.codemodel.JCodeModel in project scout.rt by eclipse.

the class HandlerArtifactProcessor method createAndPersistAuthHandler.

/**
 * Generates the AuthHandler.
 */
public String createAndPersistAuthHandler(final JClass portTypeEntryPoint, final EntryPointDefinition entryPointDefinition, final ProcessingEnvironment processingEnv) throws IOException, JClassAlreadyExistsException {
    final JCodeModel model = new JCodeModel();
    final String fullName = entryPointDefinition.getEntryPointQualifiedName() + "_" + AUTH_HANDLER_NAME;
    final JDefinedClass authHandler = model._class(fullName)._extends(model.ref(AuthenticationHandler.class));
    // Add 'Generated' annotation
    final JAnnotationUse generatedAnnotation = authHandler.annotate(Generated.class);
    generatedAnnotation.param("value", JaxWsAnnotationProcessor.class.getName());
    generatedAnnotation.param("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZ").format(new Date()));
    generatedAnnotation.param("comments", format("Authentication Handler for [method=%s, verifier=%s]", AptUtil.toSimpleName(entryPointDefinition.getAuthMethod()), AptUtil.toSimpleName(entryPointDefinition.getAuthVerifier())));
    // Add default constructor with super call to provide authentication annotation.
    final JMethod defaultConstructor = authHandler.constructor(JMod.PUBLIC);
    final JClass entryPointDefinitionClass = model.ref(entryPointDefinition.getQualifiedName());
    defaultConstructor.body().invoke("super").arg(JExpr.dotclass(entryPointDefinitionClass).invoke("getAnnotation").arg(JExpr.dotclass(model.ref(WebServiceEntryPoint.class))).invoke("authentication"));
    AptUtil.addJavaDoc(authHandler, format("This class is auto-generated by APT triggered by Maven build and is based on the authentication configuration declared in {@link %s}.", entryPointDefinition.getSimpleName()));
    AptUtil.buildAndPersist(model, processingEnv.getFiler());
    return authHandler.fullName();
}
Also used : JaxWsAnnotationProcessor(org.eclipse.scout.jaxws.apt.JaxWsAnnotationProcessor) JDefinedClass(com.sun.codemodel.JDefinedClass) JClass(com.sun.codemodel.JClass) JAnnotationUse(com.sun.codemodel.JAnnotationUse) AuthenticationHandler(org.eclipse.scout.rt.server.jaxws.provider.auth.handler.AuthenticationHandler) JMethod(com.sun.codemodel.JMethod) JCodeModel(com.sun.codemodel.JCodeModel) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 5 with JCodeModel

use of com.sun.codemodel.JCodeModel in project drill by axbaretto.

the class HiveFuncHolder method generateEval.

private HoldingContainer generateEval(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) {
    HoldingContainer out = g.declare(returnType);
    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);
    // initialize DeferredObject's. For an optional type, assign the value holder only if it is not null
    for (int i = 0; i < argTypes.length; i++) {
        if (inputVariables[i].isOptional()) {
            sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
            JBlock conditionalBlock = new JBlock(false, false);
            JConditional jc = conditionalBlock._if(inputVariables[i].getIsSet().ne(JExpr.lit(0)));
            jc._then().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
            jc._else().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), JExpr._null());
            sub.add(conditionalBlock);
        } else {
            sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
            sub.assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
        }
    }
    // declare generic object for storing return value from GenericUDF.evaluate
    JVar retVal = sub.decl(m._ref(Object.class), "ret");
    // create try..catch block to call the GenericUDF instance with given input
    JTryBlock udfEvalTry = sub._try();
    udfEvalTry.body().assign(retVal, workspaceJVars[1].invoke("evaluate").arg(workspaceJVars[3]));
    JCatchBlock udfEvalCatch = udfEvalTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfEvalCatch.param("ex");
    udfEvalCatch.body()._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName())).arg(JExpr.lit(String.format("GenericUDF.evaluate method failed"))).arg(exVar));
    // get the ValueHolder from retVal and return ObjectInspector
    sub.add(ObjectInspectorHelper.getDrillObject(m, returnOI, workspaceJVars[0], workspaceJVars[4], retVal));
    sub.assign(out.getHolder(), workspaceJVars[4]);
    // now add it to the doEval block in Generated class
    JBlock setup = g.getBlock(ClassGenerator.BlockType.EVAL);
    setup.directStatement(String.format("/** start %s for function %s **/ ", ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
    setup.add(sub);
    setup.directStatement(String.format("/** end %s for function %s **/ ", ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
    return out;
}
Also used : HoldingContainer(org.apache.drill.exec.expr.ClassGenerator.HoldingContainer) JBlock(com.sun.codemodel.JBlock) JConditional(com.sun.codemodel.JConditional) DrillDeferredObject(org.apache.drill.exec.expr.fn.impl.hive.DrillDeferredObject) JTryBlock(com.sun.codemodel.JTryBlock) JCatchBlock(com.sun.codemodel.JCatchBlock) JCodeModel(com.sun.codemodel.JCodeModel) JVar(com.sun.codemodel.JVar)

Aggregations

JCodeModel (com.sun.codemodel.JCodeModel)89 Test (org.junit.Test)70 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)58 JPackage (com.sun.codemodel.JPackage)50 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)45 JType (com.sun.codemodel.JType)43 JDefinedClass (com.sun.codemodel.JDefinedClass)18 JClass (com.sun.codemodel.JClass)14 RuleFactory (org.jsonschema2pojo.rules.RuleFactory)14 Schema (org.jsonschema2pojo.Schema)13 JsonNode (com.fasterxml.jackson.databind.JsonNode)9 TextNode (com.fasterxml.jackson.databind.node.TextNode)7 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)5 File (java.io.File)5 IOException (java.io.IOException)5 URL (java.net.URL)5 JBlock (com.sun.codemodel.JBlock)4 JCatchBlock (com.sun.codemodel.JCatchBlock)4 JDocComment (com.sun.codemodel.JDocComment)4 JMethod (com.sun.codemodel.JMethod)4