Java Code Examples for com.sun.codemodel.JBlock.directStatement()

The following are Jave code examples for showing how to use directStatement() of the com.sun.codemodel.JBlock class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: raml-module-builder   File: ClientGenerator.java   Source Code and License Vote up 6 votes
private void addParameter(JBlock methodBody, JVar queryParams, String valueName, Boolean encode, Boolean simple, boolean isList) {
  JBlock b = methodBody;
  if (!simple) {
    JConditional _if = methodBody._if(JExpr.ref(valueName).ne(JExpr._null()));
    b = _if._then();
  }
  b.invoke(queryParams, "append").arg(JExpr.lit(valueName + "="));
  if (encode) {
      JExpression expr = jCodeModel.ref(java.net.URLEncoder.class).staticInvoke("encode").arg(JExpr.ref(valueName)).arg("UTF-8");
      b.invoke(queryParams, "append").arg(expr);
  } else {
    if(isList){
      b.directStatement("if("+valueName+".getClass().isArray())"
          +"{queryParams.append(String.join(\"&"+valueName+"=\"," +valueName+"));}");
    } else{
      b.invoke(queryParams, "append").arg(JExpr.ref(valueName));
    }
  }
  b.invoke(queryParams, "append").arg(JExpr.lit("&"));
}
 
Example 2
Project: rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 6 votes
private void renderBuilderCreateContract(JDefinedClass builderClass, JClass literalBuilderClass, List<FieldModel> fields, Class<?> contractInterface) {
	JMethod createContractMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JVar contractParam = createContractMethod.param(contractInterface, "contract");
	JBlock body = createContractMethod.body();
	JConditional nullContractCheck = body._if(contractParam.eq(JExpr._null()));
	nullContractCheck._then().directStatement("throw new IllegalArgumentException(\"contract was null\");");
	body.directStatement("// TODO if create() is modified to accept required parameters, this will need to be modified");
	body.directStatement("Builder builder = create();");
	for (FieldModel fieldModel : fields) {
		String fieldName = fieldModel.fieldName;
		body.directStatement("builder." + Util.generateSetter(fieldName, "contract." + Util.generateGetter(fieldName, isBoolean(fieldModel.fieldType))) + ";");
	}
	body.directStatement("return builder;");
}
 
Example 3
Project: QDrill   File: DrillAggFuncHolder.java   Source Code and License Vote up 5 votes
private JBlock generateInitWorkspaceBlockHA(ClassGenerator<?> g, BlockType bt, String body, JVar[] workspaceJVars, JExpression wsIndexVariable){
  JBlock initBlock = new JBlock(true, true);
  if(!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()){
    JBlock sub = new JBlock(true, true);
    addProtectedBlockHA(g, sub, body, null, workspaceJVars, wsIndexVariable);
    initBlock.directStatement(String.format("/** start %s for function %s **/ ", bt.name(), registeredNames[0]));
    initBlock.add(sub);
    initBlock.directStatement(String.format("/** end %s for function %s **/ ", bt.name(), registeredNames[0]));
  }
  return initBlock;
}
 
Example 4
Project: QDrill   File: DrillFuncHolder.java   Source Code and License Vote up 5 votes
protected void addProtectedBlock(ClassGenerator<?> g, JBlock sub, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstInputOnly) {
  if (inputVariables != null) {
    for (int i = 0; i < inputVariables.length; i++) {
      if (decConstInputOnly && !inputVariables[i].isConstant()) {
        continue;
      }

      ValueReference parameter = parameters[i];
      HoldingContainer inputVariable = inputVariables[i];
      if (parameter.isFieldReader && ! inputVariable.isReader() && ! Types.isComplex(inputVariable.getMajorType())) {
        JType singularReaderClass = g.getModel()._ref(TypeHelper.getHolderReaderImpl(inputVariable.getMajorType().getMinorType(),
            inputVariable.getMajorType().getMode()));
        JType fieldReadClass = g.getModel()._ref(FieldReader.class);
        sub.decl(fieldReadClass, parameter.name, JExpr._new(singularReaderClass).arg(inputVariable.getHolder()));
      } else {
        sub.decl(inputVariable.getHolder().type(), parameter.name, inputVariable.getHolder());
      }
    }
  }

  JVar[] internalVars = new JVar[workspaceJVars.length];
  for (int i = 0; i < workspaceJVars.length; i++) {
    if (decConstInputOnly) {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    } else {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    }

  }

  Preconditions.checkNotNull(body);
  sub.directStatement(body);

  // reassign workspace variables back to global space.
  for (int i = 0; i < workspaceJVars.length; i++) {
    sub.assign(workspaceJVars[i], internalVars[i]);
  }
}
 
Example 5
Project: dremio-oss   File: AggrFunctionHolder.java   Source Code and License Vote up 5 votes
private JBlock generateInitWorkspaceBlockHA(ClassGenerator<?> g, BlockType bt, String body, JVar[] workspaceJVars, JExpression wsIndexVariable){
  JBlock initBlock = new JBlock(true, true);
  if(!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()){
    JBlock sub = new JBlock(true, true);
    addProtectedBlockHA(g, sub, body, null, workspaceJVars, wsIndexVariable);
    initBlock.directStatement(String.format("/** start %s for function %s **/ ", bt.name(), registeredNames[0]));
    initBlock.add(sub);
    initBlock.directStatement(String.format("/** end %s for function %s **/ ", bt.name(), registeredNames[0]));
  }
  return initBlock;
}
 
Example 6
Project: dremio-oss   File: BaseFunctionHolder.java   Source Code and License Vote up 5 votes
protected void addProtectedBlock(ClassGenerator<?> g, JBlock sub, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstInputOnly) {
  if (inputVariables != null) {
    for (int i = 0; i < inputVariables.length; i++) {
      if (decConstInputOnly && !inputVariables[i].isConstant()) {
        continue;
      }

      ValueReference parameter = parameters[i];
      HoldingContainer inputVariable = inputVariables[i];
      if (parameter.isFieldReader && !inputVariable.isReader() && inputVariable.getCompleteType().isScalar()) {
        JType singularReaderClass = g.getModel()._ref(TypeHelper.getHolderReaderImpl(getArrowMinorType(inputVariable.getCompleteType().toMinorType())));
        JType fieldReadClass = g.getModel()._ref(FieldReader.class);
        sub.decl(fieldReadClass, parameter.name, JExpr._new(singularReaderClass).arg(inputVariable.getHolder()));
      } else {
        sub.decl(inputVariable.getHolder().type(), parameter.name, inputVariable.getHolder());
      }
    }
  }

  JVar[] internalVars = new JVar[workspaceJVars.length];
  for (int i = 0; i < workspaceJVars.length; i++) {
    if (decConstInputOnly) {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    } else {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    }

  }

  Preconditions.checkNotNull(body);
  sub.directStatement(body);

  // reassign workspace variables back to global space.
  for (int i = 0; i < workspaceJVars.length; i++) {
    sub.assign(workspaceJVars[i], internalVars[i]);
  }
}
 
Example 7
Project: drill   File: DrillAggFuncHolder.java   Source Code and License Vote up 5 votes
private JBlock generateInitWorkspaceBlockHA(ClassGenerator<?> g, BlockType bt, String body, JVar[] workspaceJVars, JExpression wsIndexVariable){
  JBlock initBlock = new JBlock(true, true);
  if(!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()){
    JBlock sub = new JBlock(true, true);
    addProtectedBlockHA(g, sub, body, null, workspaceJVars, wsIndexVariable);
    initBlock.directStatement(String.format("/** start %s for function %s **/ ", bt.name(), getRegisteredNames()[0]));
    initBlock.add(sub);
    initBlock.directStatement(String.format("/** end %s for function %s **/ ", bt.name(), getRegisteredNames()[0]));
  }
  return initBlock;
}
 
Example 8
Project: drill   File: DrillFuncHolder.java   Source Code and License Vote up 5 votes
protected void addProtectedBlock(ClassGenerator<?> g, JBlock sub, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstInputOnly) {
  if (inputVariables != null) {
    for (int i = 0; i < inputVariables.length; i++) {
      if (decConstInputOnly && !inputVariables[i].isConstant()) {
        continue;
      }

      ValueReference parameter = attributes.getParameters()[i];
      HoldingContainer inputVariable = inputVariables[i];
      if (parameter.isFieldReader() && ! inputVariable.isReader() && ! Types.isComplex(inputVariable.getMajorType()) && inputVariable.getMinorType() != MinorType.UNION) {
        JType singularReaderClass = g.getModel()._ref(TypeHelper.getHolderReaderImpl(inputVariable.getMajorType().getMinorType(),
            inputVariable.getMajorType().getMode()));
        JType fieldReadClass = g.getModel()._ref(FieldReader.class);
        sub.decl(fieldReadClass, parameter.getName(), JExpr._new(singularReaderClass).arg(inputVariable.getHolder()));
      } else {
        sub.decl(inputVariable.getHolder().type(), parameter.getName(), inputVariable.getHolder());
      }
    }
  }

  JVar[] internalVars = new JVar[workspaceJVars.length];
  for (int i = 0; i < workspaceJVars.length; i++) {
    if (decConstInputOnly) {
      internalVars[i] = sub.decl(g.getModel()._ref(attributes.getWorkspaceVars()[i].getType()), attributes.getWorkspaceVars()[i].getName(), workspaceJVars[i]);
    } else {
      internalVars[i] = sub.decl(g.getModel()._ref(attributes.getWorkspaceVars()[i].getType()), attributes.getWorkspaceVars()[i].getName(), workspaceJVars[i]);
    }

  }

  Preconditions.checkNotNull(body);
  sub.directStatement(body);

  // reassign workspace variables back to global space.
  for (int i = 0; i < workspaceJVars.length; i++) {
    sub.assign(workspaceJVars[i], internalVars[i]);
  }
}
 
Example 9
Project: raml-module-builder   File: ClientGenerator.java   Source Code and License Vote up 5 votes
public void generateCloseClient(){
  JMethod jmCreate = method(JMod.PUBLIC, void.class, "close");
  jmCreate.javadoc().add("Close the client. Closing will close down any "
      + "pooled connections. Clients should always be closed after use.");
  JBlock body = jmCreate.body();

  body.directStatement("httpClient.close();");
}
 
Example 10
Project: kc-rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderPrivateJaxbConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = " + getInitString(fieldModel.fieldType) + ";");
	}
	method.javadoc().add("Private constructor used only by JAXB.");
}
 
Example 11
Project: kc-rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderBuilderConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	method.param(codeModel.ref("Builder"), "builder");
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = builder." + Util.generateGetter(fieldModel.fieldName, isBoolean(fieldModel.fieldType)) + ";");
	}
}
 
Example 12
Project: kc-rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderGetters(JDefinedClass classModel, List<FieldModel> fields) {
          for (FieldModel fieldModel : fields) {
              JMethod getterMethod = classModel.method(JMod.PUBLIC, fieldModel.fieldType, Util.generateGetterName(fieldModel.fieldName, isBoolean(fieldModel.fieldType)));
		JBlock methodBody = getterMethod.body();
		methodBody.directStatement("return this." + fieldModel.fieldName + ";");
		getterMethod.annotate(Override.class);
	}
}
 
Example 13
Project: kc-rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderBuilderCreateContract(JDefinedClass builderClass, JClass literalBuilderClass, List<FieldModel> fields, Class<?> contractInterface) {
	JMethod createContractMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JVar contractParam = createContractMethod.param(contractInterface, "contract");
	JBlock body = createContractMethod.body();
	JConditional nullContractCheck = body._if(contractParam.eq(JExpr._null()));
	nullContractCheck._then().directStatement("throw new IllegalArgumentException(\"contract was null\");");
	body.directStatement("// TODO if create() is modified to accept required parameters, this will need to be modified");
	body.directStatement("Builder builder = create();");
	for (FieldModel fieldModel : fields) {
		String fieldName = fieldModel.fieldName;
		body.directStatement("builder." + Util.generateSetter(fieldName, "contract." + Util.generateGetter(fieldName, isBoolean(fieldModel.fieldType))) + ";");
	}
	body.directStatement("return builder;");
}
 
Example 14
Project: jsignalml   File: JavaClassGen.java   Source Code and License Vote up 5 votes
private void comment(JBlock body, String fmt, Object...args)
{
	if (!this._comments)
		return;

	final String out = format(fmt, args);
	body.directStatement("// " + out);
}
 
Example 15
Project: jsignalml   File: JavaClassGen.java   Source Code and License Vote up 5 votes
private void comment(JBlock body, String fmt, Object...args)
{
	if (!this._comments)
		return;

	final String out = format(fmt, args);
	body.directStatement("// " + out);
}
 
Example 16
Project: rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderPrivateJaxbConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = " + getInitString(fieldModel.fieldType) + ";");
	}
	method.javadoc().add("Private constructor used only by JAXB.");
}
 
Example 17
Project: rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderBuilderConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	method.param(codeModel.ref("Builder"), "builder");
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = builder." + Util.generateGetter(fieldModel.fieldName, isBoolean(fieldModel.fieldType)) + ";");
	}
}
 
Example 18
Project: rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 5 votes
private void renderGetters(JDefinedClass classModel, List<FieldModel> fields) {
          for (FieldModel fieldModel : fields) {
              JMethod getterMethod = classModel.method(JMod.PUBLIC, fieldModel.fieldType, Util.generateGetterName(fieldModel.fieldName, isBoolean(fieldModel.fieldType)));
		JBlock methodBody = getterMethod.body();
		methodBody.directStatement("return this." + fieldModel.fieldName + ";");
		getterMethod.annotate(Override.class);
	}
}
 
Example 19
Project: QDrill   File: HiveFuncHolder.java   Source Code and License Vote up 4 votes
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()))));
  }

  // 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+")" : "")));
}
 
Example 20
Project: QDrill   File: HiveFuncHolder.java   Source Code and License Vote up 4 votes
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;
  }
 
Example 21
Project: dremio-oss   File: HiveFuncHolder.java   Source Code and License Vote up 4 votes
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(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("getObjectInspector")
        .arg(mode.staticInvoke("valueOf").arg(JExpr.lit("OPTIONAL")))
        .arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].toMinorType().name())))
        .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(DeferredObject.class), argTypes.length));

  for(int i=0; i<argTypes.length; i++) {
    sub.assign(
      workspaceJVars[2].component(JExpr.lit(i)),
      JExpr._new(m.directClass(DeferredObject.class.getCanonicalName())));
  }

  // declare empty array for argument deferred objects
  sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DeferredObject.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.toMinorType()));

  // 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+")" : "")));
}
 
Example 22
Project: dremio-oss   File: HiveFuncHolder.java   Source Code and License Vote up 4 votes
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++) {
      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);
    }

    // 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.getObject(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;
  }
 
Example 23
Project: drill   File: HiveFuncHolder.java   Source Code and License Vote up 4 votes
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+")" : "")));
}
 
Example 24
Project: drill   File: HiveFuncHolder.java   Source Code and License Vote up 4 votes
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;
  }
 
Example 25
Project: kc-rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 4 votes
private void renderBuilderDefaultCreate(JDefinedClass builderClass, JClass literalBuilderClass) {
	JMethod createMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JBlock createMethodBody = createMethod.body();
	createMethodBody.directStatement("// TODO modify as needed to pass any required values and add them to the signature of the 'create' method");
	createMethodBody.directStatement("return new Builder();");
}
 
Example 26
Project: rice   File: ImmutableJaxbGenerator.java   Source Code and License Vote up 4 votes
private void renderBuilderDefaultCreate(JDefinedClass builderClass, JClass literalBuilderClass) {
	JMethod createMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JBlock createMethodBody = createMethod.body();
	createMethodBody.directStatement("// TODO modify as needed to pass any required values and add them to the signature of the 'create' method");
	createMethodBody.directStatement("return new Builder();");
}