Java Code Examples for com.sun.codemodel.JBlock#add()

The following examples show how to use com.sun.codemodel.JBlock#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JMethod addAddMethod(JDefinedClass builderClass, JFieldVar field, boolean inherit) {
    List<JClass> typeParams = ((JClass) getJavaType(field)).getTypeParameters();
    if (!typeParams.iterator().hasNext()) {
        return null;
    }
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "add" + StringUtils.capitalize(field.name()));
    JBlock block = method.body();
    String fieldName = field.name();
    JVar param = method.param(JMod.FINAL, typeParams.iterator().next(), fieldName);
    if (inherit) {
        generateSuperCall(method);
    } else {
        JInvocation invocation = JExpr.refthis(fieldName).invoke("add").arg(param);
        block.add(invocation);
    }
    block._return(JExpr._this());
    return method;
}
 
Example 2
Source File: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * The code generator creates a method called __DRILL_INIT__ which takes the
 * place of the constructor when the code goes though the byte code merge.
 * For Plain-old Java, we call the method from a constructor created for
 * that purpose. (Generated code, fortunately, never includes a constructor,
 * so we can create one.) Since the init block throws an exception (which
 * should never occur), the generated constructor converts the checked
 * exception into an unchecked one so as to not require changes to the
 * various places that create instances of the generated classes.
 *
 * Example:<code><pre>
 * public StreamingAggregatorGen1() {
 *       try {
 *         __DRILL_INIT__();
 *     } catch (SchemaChangeException e) {
 *         throw new UnsupportedOperationException(e);
 *     }
 * }</pre></code>
 *
 * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's
 * introspection package. But, Drill prefers Java 7 which only provides
 * parameter types.
 */

private void addCtor(Class<?>[] parameters) {
  JMethod ctor = clazz.constructor(JMod.PUBLIC);
  JBlock body = ctor.body();

  // If there are parameters, need to pass them to the super class.
  if (parameters.length > 0) {
    JInvocation superCall = JExpr.invoke("super");

    // This case only occurs for nested classes, and all nested classes
    // in Drill are inner classes. Don't pass along the (hidden)
    // this$0 field.

    for (int i = 1; i < parameters.length; i++) {
      Class<?> p = parameters[i];
      superCall.arg(ctor.param(model._ref(p), "arg" + i));
    }
    body.add(superCall);
  }
  JTryBlock tryBlock = body._try();
  tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD);
  JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class));
  catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e")));
}
 
Example 3
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
final void generateCopyToMethod(final boolean partial) {
	if (this.implement) {
		final JDefinedClass typeDefinition = this.typeOutline.isInterface() && ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() : this.definedClass;
		final JMethod copyToMethod = typeDefinition.method(JMod.PUBLIC, this.pluginContext.voidType, this.settings.getCopyToMethodName());
		final JTypeVar typeVar = copyToMethod.generify(BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
		final JVar otherParam = copyToMethod.param(JMod.FINAL, this.builderClass.raw.narrow(typeVar), BuilderGenerator.OTHER_PARAM_NAME);
		final CopyGenerator cloneGenerator = this.pluginContext.createCopyGenerator(copyToMethod, partial);
		final JBlock body = copyToMethod.body();
		final JVar otherRef;
		if (this.typeOutline.getSuperClass() != null) {
			body.add(cloneGenerator.generatePartialArgs(this.pluginContext.invoke(JExpr._super(), copyToMethod.name()).arg(otherParam)));
		}
		otherRef = otherParam;
		generateFieldCopyExpressions(cloneGenerator, body, otherRef, JExpr._this());
		copyToMethod.javadoc().append(JavadocUtils.hardWrapTextForJavadoc(getMessage("javadoc.method.copyTo")));
		copyToMethod.javadoc().addParam(otherParam).append(JavadocUtils.hardWrapTextForJavadoc(getMessage("javadoc.method.copyTo.param.other")));
	}
}
 
Example 4
Source File: ClassGenerator.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an inner braced and indented block
 * @param type type of the created block
 * @return a newly created inner block
 */
private JBlock createInnerBlock(BlockType type) {
  final JBlock currBlock = getBlock(type);
  final JBlock innerBlock = new JBlock();
  currBlock.add(innerBlock);
  return innerBlock;
}
 
Example 5
Source File: ReadReferenceVisitor.java    From parceler with Apache License 2.0 5 votes vote down vote up
@Override
public Void visit(MethodReference methodReference, ReadContext input) {
    JBlock body = input.getBody();

    body.add(invocationBuilder.buildMethodCall(
            input.getContainer(),
            methodReference.getRoot(),
            methodReference.getMethod(),
            Collections.singletonList(input.getGetExpression().getExpression()),
            input.getWrapped()));
    return null;
}
 
Example 6
Source File: ReadReferenceVisitor.java    From parceler with Apache License 2.0 5 votes vote down vote up
@Override
public Void visit(FieldReference fieldReference, ReadContext input) {
    JBlock body = input.getBody();

    body.add(invocationBuilder.buildFieldSet(
            input.getContainer(),
            fieldReference.getField(),
            input.getWrapped().getType(),
            new TypedExpression(fieldReference.getOwner(), input.getWrapped().getExpression()),
            input.getGetExpression()
    ));
    return null;
}
 
Example 7
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createReportMethod(JDefinedClass clazz){
	JCodeModel codeModel = clazz.owner();

	JMethod method = clazz.method(JMod.PRIVATE, void.class, "report");

	JVar expressionParameter = method.param(String.class, "expression");

	JBlock body = method.body();

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);
		JClass reportEntryClazz = codeModel.ref(Report.Entry.class);

		JVar reportVariable = body.decl(reportClazz, "report", JExpr.invoke("getReport"));
		JVar entryVariable = body.decl(reportEntryClazz, "entry", JExpr._new(reportEntryClazz).arg(expressionParameter).arg(JExpr.invoke("getValue")));

		body.add(reportVariable.invoke("add").arg(entryVariable));
	} else

	if((clazz.name()).endsWith("Vector")){
		body.add(JExpr.invoke("setExpression").arg(expressionParameter));
	} else

	{
		throw new RuntimeException();
	}
}
 
Example 8
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createConstructor(JDefinedClass clazz, ExecutableElement executableElement, boolean hasExpression){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(hasExpression){
		JVar expressionParameter = constructor.param(String.class, "expression");

		body._if(expressionParameter.ne(JExpr._null()))._then().add(JExpr.invoke("report").arg(expressionParameter));
	}
}
 
Example 9
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createReportingConstructor(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(initialOperation != null){
		throw new RuntimeException();
	}

	body.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, constructor.params(), type)));
}
 
Example 10
Source File: AggrFunctionHolder.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
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 11
Source File: ClassGenerator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an inner braced and indented block
 * @param type type of the created block
 * @return a newly created inner block
 */
private JBlock createInnerBlock(BlockType type) {
  final JBlock currBlock = getBlock(type);
  final JBlock innerBlock = new JBlock();
  currBlock.add(innerBlock);
  return innerBlock;
}
 
Example 12
Source File: DrillAggFuncHolder.java    From Bats with Apache License 2.0 5 votes vote down vote up
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 13
Source File: EvaluationVisitor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {

      final LogicalExpression child = e.getChild();
      final HoldingContainer inputContainer = child.accept(this, generator);

      JBlock block = generator.getEvalBlock();
      JExpression outIndex = generator.getMappingSet().getValueWriteIndex();
      JVar vv = generator.declareVectorValueSetupAndMember(generator.getMappingSet().getOutgoing(), e.getFieldId());

      // Only when the input is a reader, use writer interface to copy value.
      // Otherwise, input is a holder and we use vv mutator to set value.
      if (inputContainer.isReader()) {
        JType writerImpl = generator.getModel()._ref(
            TypeHelper.getWriterImpl(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JType writerIFace = generator.getModel()._ref(
            TypeHelper.getWriterInterface(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JVar writer = generator.declareClassField("writer", writerIFace);
        generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv).arg(JExpr._null()));
        generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));
        String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
        generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
        if (e.isSafe()) {
          HoldingContainer outputContainer = generator.declare(Types.REQUIRED_BIT);
          generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
          return outputContainer;
        }
      } else {

        final JInvocation setMeth = GetSetVectorHelper.write(e.getChild().getMajorType(), vv, inputContainer, outIndex, e.isSafe() ? "setSafe" : "set");
          if (inputContainer.isOptional()) {
            JConditional jc = block._if(inputContainer.getIsSet().eq(JExpr.lit(0)).not());
            block = jc._then();
          }
          block.add(setMeth);

      }

      return null;
    }
 
Example 14
Source File: HiveFuncHolder.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
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 15
Source File: HiveFuncHolder.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
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 16
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
private void createReportingMethod(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	String name = String.valueOf(executableElement.getSimpleName());

	JMethod method = clazz.method(JMod.PUBLIC, clazz, name);
	method.annotate(Override.class);

	List<JVar> params = new ArrayList<>();

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		TypeMirror paramType = parameterElement.asType();
		Name paramName = parameterElement.getSimpleName();

		JVar param;

		if((TypeKind.ARRAY).equals(paramType.getKind())){
			ArrayType arrayType = (ArrayType)paramType;

			param = method.varParam(toType(codeModel, arrayType.getComponentType()), String.valueOf(paramName));
		} else

		{
			param = method.param(toType(codeModel, paramType), String.valueOf(paramName));
		}

		params.add(param);
	}

	String valueMethod;

	if((codeModel.DOUBLE).equals(type)){
		valueMethod = "doubleValue";
	} else

	if((codeModel.FLOAT).equals(type)){
		valueMethod = "floatValue";
	} else

	{
		throw new IllegalArgumentException();
	}

	boolean checkChange;

	switch(name){
		case "add":
		case "subtract":
		case "multiply":
		case "divide":
			checkChange = (clazz.name()).endsWith("Value");
			break;
		default:
			checkChange = false;
			break;
	}

	JBlock body = method.body();

	JVar oldValueVar = null;
	if(checkChange){
		oldValueVar = body.decl(type, "oldValue", JExpr.invoke(valueMethod));
	}

	JVar resultVariable = body.decl(clazz, "result", JExpr.cast(clazz, createSuperInvocation(clazz, method)));

	JVar newValueVar = null;
	if(checkChange){
		newValueVar = body.decl(type, "newValue", JExpr.invoke(valueMethod));
	}

	JBlock block = body;
	if(checkChange){
		block = body._if((oldValueVar).ne(newValueVar))._then();
	}

	if(initialOperation != null){
		JConditional ifStatement = block._if(JExpr.invoke("hasExpression"));

		JBlock trueBlock = ifStatement._then();

		trueBlock.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, params, type)));

		JBlock falseBlock = ifStatement._else();

		falseBlock.add(JExpr.invoke("report").arg(createReportInvocation(clazz, initialOperation, params, type)));
	} else

	{
		block.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, params, type)));
	}

	body._return(resultVariable);
}
 
Example 17
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {

      final LogicalExpression child = e.getChild();
      final HoldingContainer inputContainer = child.accept(this, generator);

      JBlock block = generator.getEvalBlock();
      JExpression outIndex = generator.getMappingSet().getValueWriteIndex();
      JVar vv = generator.declareVectorValueSetupAndMember(generator.getMappingSet().getOutgoing(), e.getFieldId());

      // Only when the input is a reader, use writer interface to copy value.
      // Otherwise, input is a holder and we use vv mutator to set value.
      if (inputContainer.isReader()) {
        JType writerImpl = generator.getModel()._ref(
                TypeHelper.getWriterImpl(getArrowMinorType(inputContainer.getCompleteType().toMinorType())));
        JType writerIFace = generator.getModel()._ref(
            TypeHelper.getWriterInterface(getArrowMinorType(inputContainer.getCompleteType().toMinorType())));

        JVar writer = generator.declareClassField("writer", writerIFace);
        generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv));
        generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));

        if (child.getCompleteType().isUnion() || child.getCompleteType().isComplex()) {
          final JClass complexCopierClass = generator.getModel()
              .ref(org.apache.arrow.vector.complex.impl.ComplexCopier.class);
          final JExpression castedWriter = JExpr.cast(generator.getModel().ref(FieldWriter.class), writer);
          generator.getEvalBlock()
              .add(complexCopierClass.staticInvoke("copy")
                  .arg(inputContainer.getHolder())
                  .arg(castedWriter));
        } else {
          String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
          generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
        }

        if (e.isSafe()) {
          HoldingContainer outputContainer = generator.declare(CompleteType.BIT);
          generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
          return outputContainer;
        }
      } else {

        final JInvocation setMeth = GetSetVectorHelper.write(e.getChild().getCompleteType().toMinorType(), vv, inputContainer, outIndex, e.isSafe() ? "setSafe" : "set");
        JConditional jc = block._if(inputContainer.getIsSet().eq(JExpr.lit(0)).not());
        block = jc._then();
        block.add(setMeth);

      }

      return null;
    }
 
Example 18
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
private void createFormatMethod(JDefinedClass clazz, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JClass numberClazz = codeModel.ref(Number.class);
	JClass stringBuilderClazz = codeModel.ref(StringBuilder.class);

	JMethod method = clazz.method(JMod.STATIC | JMod.PRIVATE, String.class, "format");

	JVar valuesParameter = method.varParam(numberClazz, "values");

	JBlock body = method.body();

	JVar sbVariable = body.decl(stringBuilderClazz, "sb", JExpr._new(stringBuilderClazz).arg(valuesParameter.ref("length").mul(JExpr.lit(32))));

	JForEach forStatement = body.forEach(numberClazz, "value", valuesParameter);

	JBlock forBody = forStatement.body();

	forBody.add(createReportInvocation(clazz, sbVariable, "${0}", Collections.singletonList(forStatement.var()), type));

	body._return(sbVariable.invoke("toString"));
}
 
Example 19
Source File: GetSetVectorHelper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static void read(CompleteType ct, JExpression vector, JBlock eval, HoldingContainer out, JCodeModel model,
                        JExpression indexVariable) {

  MinorType type = ct.toMinorType();

    eval.assign(out.getIsSet(), vector.invoke("isSet").arg(indexVariable));
    eval = eval._if(out.getIsSet().eq(JExpr.lit(1)))._then();
    switch (type) {
    case BIGINT:
    case FLOAT4:
    case FLOAT8:
    case INT:
    case MONEY:
    case SMALLINT:
    case TINYINT:
    case UINT1:
    case UINT2:
    case UINT4:
    case UINT8:
    case INTERVALYEAR:
    case DATE:
    case TIME:
    case TIMESTAMP:
    case BIT:
      eval.assign(out.getValue(), vector.invoke("get").arg(indexVariable));
      return;
    case DECIMAL:
      eval.assign(out.getHolder().ref("scale"), JExpr.lit(ct.getType(Decimal.class).getScale()));
      eval.assign(out.getHolder().ref("precision"), JExpr.lit(ct.getType(Decimal.class).getPrecision()));
      eval.assign(out.getHolder().ref("start"), JExpr.lit(TypeHelper.getSize(getArrowMinorType(type))).mul(indexVariable));
      eval.assign(out.getHolder().ref("buffer"), vector.invoke("getDataBuffer"));
      return;
    case INTERVALDAY: {
      JVar start = eval.decl(model.INT, "start", JExpr.lit(TypeHelper.getSize(getArrowMinorType(type))).mul(indexVariable));
      eval.assign(out.getHolder().ref("days"), vector.invoke("getDataBuffer").invoke("getInt").arg(start));
      eval.assign(out.getHolder().ref("milliseconds"), vector.invoke("getDataBuffer").invoke("getInt").arg(start.plus(JExpr.lit(4))));
      return;
    }
    case VARBINARY:
    case VARCHAR:
       eval.assign(out.getHolder().ref("buffer"), vector.invoke("getDataBuffer"));
       JVar se = eval.decl(model.LONG, "startEnd", vector.invoke("getStartEnd").arg(indexVariable));
       eval.assign(out.getHolder().ref("start"), JExpr.cast(model._ref(int.class), se));
       eval.assign(out.getHolder().ref("end"), JExpr.cast(model._ref(int.class), se.shr(JExpr.lit(32))));
      return;

    }

  // fallback.
  eval.add(vector.invoke("get").arg(indexVariable).arg(out.getHolder()));
}