Search in sources :

Example 6 with JCodeModel

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

the class HiveFuncHolder method generateSetup.

private void generateSetup(ClassGenerator<?> g, JVar[] workspaceJVars) {
    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);
    // declare and instantiate argument ObjectInspector's
    JVar oiArray = sub.decl(m._ref(ObjectInspector[].class), "argOIs", JExpr.newArray(m._ref(ObjectInspector.class), argTypes.length));
    JClass oih = m.directClass(ObjectInspectorHelper.class.getCanonicalName());
    JClass mt = m.directClass(TypeProtos.MinorType.class.getCanonicalName());
    JClass mode = m.directClass(DataMode.class.getCanonicalName());
    for (int i = 0; i < argTypes.length; i++) {
        sub.assign(oiArray.component(JExpr.lit(i)), oih.staticInvoke("getDrillObjectInspector").arg(mode.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMode().getNumber()))).arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMinorType().getNumber()))).arg((((PrimitiveObjectInspector) returnOI).getPrimitiveCategory() == PrimitiveObjectInspector.PrimitiveCategory.STRING) ? JExpr.lit(true) : JExpr.lit(false)));
    }
    // declare and instantiate DeferredObject array
    sub.assign(workspaceJVars[2], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length));
    for (int i = 0; i < argTypes.length; i++) {
        sub.assign(workspaceJVars[2].component(JExpr.lit(i)), JExpr._new(m.directClass(DrillDeferredObject.class.getCanonicalName())));
    }
    // declare empty array for argument deferred objects
    sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length));
    // create new instance of the UDF class
    sub.assign(workspaceJVars[1], getUDFInstance(m));
    // create try..catch block to initialize the UDF instance with argument OIs
    JTryBlock udfInitTry = sub._try();
    udfInitTry.body().assign(workspaceJVars[0], workspaceJVars[1].invoke("initialize").arg(oiArray));
    JCatchBlock udfInitCatch = udfInitTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfInitCatch.param("ex");
    udfInitCatch.body()._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName())).arg(JExpr.lit(String.format("Failed to initialize GenericUDF"))).arg(exVar));
    sub.add(ObjectInspectorHelper.initReturnValueHolder(g, m, workspaceJVars[4], returnOI, returnType.getMinorType()));
    // now add it to the doSetup block in Generated class
    JBlock setup = g.getBlock(ClassGenerator.BlockType.SETUP);
    setup.directStatement(String.format("/** start %s for function %s **/ ", ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
    setup.add(sub);
    setup.directStatement(String.format("/** end %s for function %s **/ ", ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
}
Also used : JClass(com.sun.codemodel.JClass) DataMode(org.apache.drill.common.types.TypeProtos.DataMode) JBlock(com.sun.codemodel.JBlock) 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) ObjectInspectorHelper(org.apache.drill.exec.expr.fn.impl.hive.ObjectInspectorHelper)

Example 7 with JCodeModel

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

the class HiveFuncHolder method generateSetup.

private void generateSetup(ClassGenerator<?> g, JVar[] workspaceJVars) {
    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);
    // declare and instantiate argument ObjectInspector's
    JVar oiArray = sub.decl(m._ref(ObjectInspector[].class), "argOIs", JExpr.newArray(m._ref(ObjectInspector.class), argTypes.length));
    JClass oih = m.directClass(ObjectInspectorHelper.class.getCanonicalName());
    JClass mt = m.directClass(TypeProtos.MinorType.class.getCanonicalName());
    JClass mode = m.directClass(DataMode.class.getCanonicalName());
    for (int i = 0; i < argTypes.length; i++) {
        sub.assign(oiArray.component(JExpr.lit(i)), oih.staticInvoke("getDrillObjectInspector").arg(mode.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMode().getNumber()))).arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMinorType().getNumber()))).arg((((PrimitiveObjectInspector) returnOI).getPrimitiveCategory() == PrimitiveObjectInspector.PrimitiveCategory.STRING) ? JExpr.lit(true) : JExpr.lit(false)));
    }
    // declare and instantiate DeferredObject array
    sub.assign(workspaceJVars[2], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length));
    for (int i = 0; i < argTypes.length; i++) {
        sub.assign(workspaceJVars[2].component(JExpr.lit(i)), JExpr._new(m.directClass(DrillDeferredObject.class.getCanonicalName())));
    }
    // declare empty array for argument deferred objects
    sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length));
    // create new instance of the UDF class
    sub.assign(workspaceJVars[1], getUDFInstance(m));
    // create try..catch block to initialize the UDF instance with argument OIs
    JTryBlock udfInitTry = sub._try();
    udfInitTry.body().assign(workspaceJVars[0], workspaceJVars[1].invoke("initialize").arg(oiArray));
    JCatchBlock udfInitCatch = udfInitTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfInitCatch.param("ex");
    udfInitCatch.body()._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName())).arg(JExpr.lit(String.format("Failed to initialize GenericUDF"))).arg(exVar));
    sub.add(ObjectInspectorHelper.initReturnValueHolder(g, m, workspaceJVars[4], returnOI, returnType.getMinorType()));
    // now add it to the doSetup block in Generated class
    JBlock setup = g.getBlock(ClassGenerator.BlockType.SETUP);
    setup.directStatement(String.format("/** start %s for function %s **/ ", ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
    setup.add(sub);
    setup.directStatement(String.format("/** end %s for function %s **/ ", ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
}
Also used : JClass(com.sun.codemodel.JClass) DataMode(org.apache.drill.common.types.TypeProtos.DataMode) JBlock(com.sun.codemodel.JBlock) 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) ObjectInspectorHelper(org.apache.drill.exec.expr.fn.impl.hive.ObjectInspectorHelper)

Example 8 with JCodeModel

use of com.sun.codemodel.JCodeModel in project useful-java-links by Vedenin.

the class JsonSchema2HelloWorld method main.

public static void main(String[] args) throws Exception {
    // Init json
    String source = "{\n" + "  \"type\":\"object\",\n" + "  \"properties\": {\n" + "    \"messageHiWorld\": {\n" + "      \"type\": \"string\"\n" + "    },\n" + "    \"bar\": {\n" + "      \"type\": \"integer\"\n" + "    },\n" + "    \"baz\": {\n" + "      \"type\": \"boolean\"\n" + "    }\n" + "  }\n" + "}";
    // Init config
    JCodeModel codeModel = new JCodeModel();
    GenerationConfig config = new DefaultGenerationConfig() {

        @Override
        public boolean isGenerateBuilders() {
            // set config option by overriding method
            return true;
        }
    };
    // Generate Java POJO from json
    SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(), new SchemaStore()), new SchemaGenerator());
    mapper.generate(codeModel, "HelloWorldClass", "com.github.vedenin", source);
    // Save generated class to file
    File directory = new File("helloworlds/3.8-json/jsonschema2pojo/output");
    directory.mkdirs();
    codeModel.build(directory);
    // Show generated class
    File cls = new File("helloworlds/3.8-json/jsonschema2pojo/output/com/github/vedenin/HelloWorldClass.java");
    String codeHelloWorld = Files.toString(cls, Charsets.UTF_8);
    System.out.println(codeHelloWorld);
}
Also used : RuleFactory(org.jsonschema2pojo.rules.RuleFactory) JCodeModel(com.sun.codemodel.JCodeModel) File(java.io.File)

Example 9 with JCodeModel

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

the class Example method main.

public static void main(String[] args) throws IOException {
    // BEGIN EXAMPLE
    JCodeModel codeModel = new JCodeModel();
    URL source = Example.class.getResource("/schema/required.json");
    GenerationConfig config = new DefaultGenerationConfig() {

        @Override
        public boolean isGenerateBuilders() {
            // set config option by overriding method
            return true;
        }
    };
    SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
    mapper.generate(codeModel, "ClassName", "com.example", source);
    codeModel.build(Files.createTempDirectory("required").toFile());
// END EXAMPLE
}
Also used : DefaultGenerationConfig(org.jsonschema2pojo.DefaultGenerationConfig) RuleFactory(org.jsonschema2pojo.rules.RuleFactory) SchemaStore(org.jsonschema2pojo.SchemaStore) Jackson2Annotator(org.jsonschema2pojo.Jackson2Annotator) SchemaGenerator(org.jsonschema2pojo.SchemaGenerator) JCodeModel(com.sun.codemodel.JCodeModel) URL(java.net.URL) GenerationConfig(org.jsonschema2pojo.GenerationConfig) DefaultGenerationConfig(org.jsonschema2pojo.DefaultGenerationConfig) SchemaMapper(org.jsonschema2pojo.SchemaMapper)

Example 10 with JCodeModel

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

the class DefaultRuleTest method whenIsInitializeCollections_true_applyInitializesField.

@Test
public void whenIsInitializeCollections_true_applyInitializesField() throws JClassAlreadyExistsException {
    when(config.isInitializeCollections()).thenReturn(true);
    JDefinedClass jclass = new JCodeModel()._class("org.jsonschema2pojo.rules.ExampleClass");
    JFieldVar field = jclass.field(JMod.NONE, jclass.owner().ref(fieldTypeClass).narrow(Object.class), "value");
    ArrayNode node = new ObjectMapper().createArrayNode().add(1);
    StringWriter sw = new StringWriter();
    rule.apply("fooBar", node, null, field, null).bind(new JFormatter(sw));
    assertThat(sw.toString(), startsWith(String.format("%s<%s> value = ", fieldTypeClass.getName(), Object.class.getName())));
}
Also used : StringWriter(java.io.StringWriter) JDefinedClass(com.sun.codemodel.JDefinedClass) JFieldVar(com.sun.codemodel.JFieldVar) JFormatter(com.sun.codemodel.JFormatter) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) JCodeModel(com.sun.codemodel.JCodeModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

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