Java Code Examples for com.sun.codemodel.JBlock._if

The following are Jave code examples for showing how to use _if 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: GitHub   File: EnumRule.java   Source Code and License Vote up 7 votes
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(backingType, "value");

    JBlock body = fromValue.body();
    JVar constant = body.decl(_enum, "constant");
    constant.init(quickLookupMap.invoke("get").arg(valueParam));

    JConditional _if = body._if(constant.eq(JExpr._null()));

    JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
    JExpression expr = valueParam;

    // if string no need to add ""
    if(!isString(backingType)){
        expr = expr.plus(JExpr.lit(""));
    }

    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(fromValue);
}
 
Example 2
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 3
Project: thrift-java-compiler   File: StructCodeGeneratorHelper.java   Source Code and License Vote up 6 votes
private void createMethodFieldSetFieldValue(JDefinedClass _class, Map<String, JType> fields) {
		JMethod method = _class.method(JMod.PUBLIC, Void.TYPE, "setFieldValue");
		JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD);
		JVar param = method.param(refEnumFields, "field");
		JVar param2 = method.param(codeModel.ref(Object.class), "value");
		JBlock body = method.body();

		JSwitch _switch = body._switch(param);
		for (Map.Entry<String, JType> entry : fields.entrySet()) {
			JBlock bodyCase = _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body();
			JConditional _if = bodyCase._if(param2.eq(JExpr._null()));
			String capitalizeName = JavaGeneratorUtil.getCapitalizeString(entry.getKey());
			_if._then().invoke("unset" + capitalizeName);
			_if._else().invoke("set" + capitalizeName).arg(JExpr.cast(getTypeGetMethodByName(_class, capitalizeName), param2));
			bodyCase._break();
		}

//		JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class));
//		_switch._default().body()._throw(_newException);

	}
 
Example 4
Project: jaxb2-basics   File: EqualsArguments.java   Source Code and License Vote up 6 votes
public JBlock ifHasSetValue(JBlock block, boolean isAlwaysSet,
		boolean checkForNullRequired) {
	if (isAlwaysSet || !checkForNullRequired) {
		return block;
	} else {
		final JConditional ifLeftHasSetValue = block._if(leftHasSetValue());
		final JConditional ifLeftHasSetValueAndRightHasSetValue = ifLeftHasSetValue
				._then()._if(rightHasSetValue());
		final JBlock subBlock = ifLeftHasSetValueAndRightHasSetValue
				._then();
		ifLeftHasSetValueAndRightHasSetValue._else()._return(JExpr.FALSE);
		ifLeftHasSetValue._elseif(rightHasSetValue())._then()
				._return(JExpr.FALSE);
		return subBlock;
	}
}
 
Example 5
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 6
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License Vote up 5 votes
private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
    JBlock body = method.body();
    JConditional propertyConditional = null;

    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
            if (propertyConditional == null) {
                propertyConditional = body._if(condition);
            } else {
                propertyConditional = propertyConditional._elseif(condition);
            }
            JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {});
            propertyConditional._then()._return(invoke(propertyGetter));
        }
    }

    JClass extendsType = jclass._extends();
    JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
    } else {
        lastBlock._return(notFoundParam);
    }

    return method;
}
 
Example 7
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License Vote up 5 votes
private JMethod addInternalSetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JConditional propertyConditional = null;
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();
            JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
            propertyConditional = propertyConditional == null ? propertyConditional = body._if(condition)
                    : propertyConditional._elseif(condition);

            JBlock callSite = propertyConditional._then();
            addSetProperty(jclass, callSite, propertyName, propertyType, valueParam, node);
            callSite._return(TRUE);
        }
    }
    JClass extendsType = jclass._extends();
    JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();

    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
    } else {
        lastBlock._return(FALSE);
    }
    return method;
}
 
Example 8
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License Vote up 5 votes
private void addSetProperty(JDefinedClass jclass, JBlock callSite, String propertyName, JType propertyType, JVar valueVar, JsonNode node) {
    JMethod propertySetter = jclass.getMethod(getSetterName(propertyName, node), new JType[] { propertyType });
    JConditional isInstance = callSite._if(valueVar._instanceof(propertyType.boxify().erasure()));
    isInstance._then()
    .invoke(propertySetter).arg(cast(propertyType.boxify(), valueVar));
    isInstance._else()
    ._throw(illegalArgumentInvocation(jclass, propertyName, propertyType, valueVar));
}
 
Example 9
Project: QDrill   File: EvaluationVisitor.java   Source Code and License Vote up 5 votes
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 10
Project: dremio-oss   File: EvaluationVisitor.java   Source Code and License Vote up 5 votes
@Override
    public HoldingContainer visitIfExpression(IfExpression ifExpr, ClassGenerator<?> generator) throws RuntimeException {
      JBlock local = generator.getEvalBlock();

      HoldingContainer output = generator.declare(ifExpr.getCompleteType());

      JBlock conditionalBlock = new JBlock(false, false);
      IfCondition c = ifExpr.ifCondition;

      HoldingContainer holdingContainer = c.condition.accept(this, generator);
      final JConditional jc = conditionalBlock._if(holdingContainer.getIsSet().eq(JExpr.lit(1)).cand(holdingContainer.getValue().eq(JExpr.lit(1))));

      generator.nestEvalBlock(jc._then());

      HoldingContainer thenExpr = c.expression.accept(this, generator);

      generator.unNestEvalBlock();

      JConditional newCond = jc._then()._if(thenExpr.getIsSet().ne(JExpr.lit(0)));
      JBlock b = newCond._then();
      b.assign(output.getHolder(), thenExpr.getHolder());
//        b.assign(output.getIsSet(), thenExpr.getIsSet());
//        b.assign(output.getValue(), thenExpr.getValue());

      generator.nestEvalBlock(jc._else());

      HoldingContainer elseExpr = ifExpr.elseExpression.accept(this, generator);

      generator.unNestEvalBlock();

      JConditional newCond2 = jc._else()._if(elseExpr.getIsSet().ne(JExpr.lit(0)));
      JBlock b2 = newCond2._then();
      b2.assign(output.getHolder(), elseExpr.getHolder());
      //b.assign(output.getIsSet(), elseExpr.getIsSet());
      local.add(conditionalBlock);
      return output;
    }
 
Example 11
Project: dremio-oss   File: EvaluationVisitor.java   Source Code and License Vote up 5 votes
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));
        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 12
Project: drill   File: EvaluationVisitor.java   Source Code and License Vote up 5 votes
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 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: LRPaGe   File: EqualsGenerator.java   Source Code and License Vote up 5 votes
public JMethod define(JDefinedClass clazz){
	JCodeModel model= clazz.owner();
	JMethod equals= clazz.method(JMod.PUBLIC, boolean.class, "equals");
	equals.annotate(Override.class);
	JVar o = equals.param(Object.class, "o");
	
	JBlock jBlock = equals.body();
	
	//if objects are the same, return true
	JConditional sameObj = jBlock._if(JExpr._this().eq(o));
	//JConditional sameObj= jBlock._if(JExpr._this().eq(o));
	sameObj._then()._return(JExpr.lit(true));
	//if object is null, return false
	JConditional nullObj= jBlock._if(JExpr._null().eq(o));
	nullObj._then()._return(JExpr.lit(false));
	//if object is not instance of same class, return false
	JConditional notInstOf = jBlock._if(o._instanceof(clazz).not());
	notInstOf._then()._return(JExpr.lit(false));
	
	JVar castResult = jBlock.decl(clazz, "castResult", JExpr.cast(clazz, o));
	//compare field values
	for(JVar f:fields){
		JConditional notEq= jBlock._if(JExpr.invoke(JExpr._this().ref(f), "equals").arg(castResult.ref(f)).not());
		notEq._then()._return(JExpr.lit(false));
	}
	
	equals.body()._return(JExpr.lit(true));
	
	return equals;
}
 
Example 15
Project: QDrill   File: EvaluationVisitor.java   Source Code and License Vote up 4 votes
private HoldingContainer visitBooleanAnd(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("AndOP");
  JBlock eval = generator.getEvalBlock().block();  // enter into nested block
  generator.nestEvalBlock(eval);

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "and" when one side is null
  //    p       q     p and q
  //    true    null     null
  //    false   null     false
  //    null    true     null
  //    null    false    false
  //    null    null     null
  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().ne(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(0));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(1));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(1)) ;
  }

  generator.unNestEvalBlock();     // exit from nested block

  return out;
}
 
Example 16
Project: QDrill   File: EvaluationVisitor.java   Source Code and License Vote up 4 votes
private HoldingContainer visitBooleanOr(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("OrOP");
  JBlock eval = generator.getEvalBlock().block();
  generator.nestEvalBlock(eval);   // enter into nested block.

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "or" when one side is null
  //    p       q       p and q
  //    true    null     true
  //    false   null     null
  //    null    true     true
  //    null    false    null
  //    null    null     null

  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().eq(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().eq(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(1));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(0));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(0)) ;
  }

  generator.unNestEvalBlock();   // exit from nested block.

  return out;
}
 
Example 17
Project: QDrill   File: DrillSimpleFuncHolder.java   Source Code and License Vote up 4 votes
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) {

    g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", registeredNames[0]));

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;
    HoldingContainer out = null;
    MajorType returnValueType = returnValue.type;

    // add outside null handling if it is defined.
    if (nullHandling == NullHandling.NULL_IF_NULL) {
      JExpression e = null;
      for (HoldingContainer v : inputVariables) {
        if (v.isOptional()) {
          if (e == null) {
            e = v.getIsSet();
          } else {
            e = e.mul(v.getIsSet());
          }
        }
      }

      if (e != null) {
        // if at least one expression must be checked, set up the conditional.
        returnValueType = returnValue.type.toBuilder().setMode(DataMode.OPTIONAL).build();
        out = g.declare(returnValueType);
        e = e.eq(JExpr.lit(0));
        JConditional jc = sub._if(e);
        jc._then().assign(out.getIsSet(), JExpr.lit(0));
        sub = jc._else();
      }
    }

    if (out == null) {
      out = g.declare(returnValueType);
    }

    // add the subblock after the out declaration.
    g.getEvalBlock().add(topSub);


    JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValueType), returnValue.name, JExpr._new(g.getHolderType(returnValueType)));
    addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);
    if (sub != topSub) {
      sub.assign(internalOutput.ref("isSet"),JExpr.lit(1));// Assign null if NULL_IF_NULL mode
    }
    sub.assign(out.getHolder(), internalOutput);
    if (sub != topSub) {
      sub.assign(internalOutput.ref("isSet"),JExpr.lit(1));// Assign null if NULL_IF_NULL mode
    }

    g.getEvalBlock().directStatement(String.format("//---- end of eval portion of %s function. ----//", registeredNames[0]));

    return out;
  }
 
Example 18
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 19
Project: dremio-oss   File: EvaluationVisitor.java   Source Code and License Vote up 4 votes
private HoldingContainer visitBooleanAnd(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getCompleteType());

  JLabel label = generator.getEvalBlockLabel("AndOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);  // enter into nested block

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "and" when one side is null
  //    p       q     p and q
  //    true    null     null
  //    false   null     false
  //    null    true     null
  //    null    false    false
  //    null    null     null
  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    earlyExit.assign(out.getIsSet(), JExpr.lit(1));

    earlyExit.assign(out.getValue(),  JExpr.lit(0));
    earlyExit._break(label);
  }

  assert (e != null);

  JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
  notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

  JBlock setBlock = notSetJC._else().block();
  setBlock.assign(out.getIsSet(), JExpr.lit(1));
  setBlock.assign(out.getValue(), JExpr.lit(1));

  generator.unNestEvalBlock();     // exit from nested block

  return out;
}
 
Example 20
Project: dremio-oss   File: EvaluationVisitor.java   Source Code and License Vote up 4 votes
private HoldingContainer visitBooleanOr(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getCompleteType());

  JLabel label = generator.getEvalBlockLabel("OrOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);   // enter into nested block.

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "or" when one side is null
  //    p       q       p and q
  //    true    null     true
  //    false   null     null
  //    null    true     true
  //    null    false    null
  //    null    null     null

  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().eq(JExpr.lit(1))))._then();
    if (e == null) {
      e = arg.getIsSet();
    } else {
      e = e.mul(arg.getIsSet());
    }
    earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    earlyExit.assign(out.getValue(),  JExpr.lit(1));
    earlyExit._break(label);
  }

  assert (e != null);

  JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
  notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

  JBlock setBlock = notSetJC._else().block();
  setBlock.assign(out.getIsSet(), JExpr.lit(1));
  setBlock.assign(out.getValue(), JExpr.lit(0));

  generator.unNestEvalBlock();   // exit from nested block.

  return out;
}
 
Example 21
Project: dremio-oss   File: SimpleFunctionHolder.java   Source Code and License Vote up 4 votes
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) {

    g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", registeredNames[0]));

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;
    HoldingContainer out = null;


    // add outside null handling if it is defined.
    if (nullHandling == NullHandling.NULL_IF_NULL) {
      JExpression e = null;
      for (HoldingContainer v : inputVariables) {
        final JExpression isNullExpr;
        if (v.isReader()) {
          isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }

      if (e != null) {
        // if at least one expression must be checked, set up the conditional.
        out = g.declare(resolvedOutput);
        e = e.eq(JExpr.lit(0));
        JConditional jc = sub._if(e);
        jc._then().assign(out.getIsSet(), JExpr.lit(0));
        sub = jc._else();
      }
    }

    if (out == null) {
      out = g.declare(resolvedOutput);
    }

    // add the subblock after the out declaration.
    g.getEvalBlock().add(topSub);


    JVar internalOutput = sub.decl(JMod.FINAL, resolvedOutput.getHolderType(g.getModel()), getReturnName(), JExpr._new(resolvedOutput.getHolderType(g.getModel())));
    addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);

    if (sub != topSub || inputVariables.length == 0) {
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1));// Assign null if NULL_IF_NULL mode
    }
    sub.assign(out.getHolder(), internalOutput);

    g.getEvalBlock().directStatement(String.format("//---- end of eval portion of %s function. ----//", registeredNames[0]));

    return out;
  }
 
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: EvaluationVisitor.java   Source Code and License Vote up 4 votes
private HoldingContainer visitBooleanAnd(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("AndOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);  // enter into nested block

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "and" when one side is null
  //    p       q     p and q
  //    true    null     null
  //    false   null     false
  //    null    true     null
  //    null    false    false
  //    null    null     null
  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().ne(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(0));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(1));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(1)) ;
  }

  generator.unNestEvalBlock();     // exit from nested block

  return out;
}
 
Example 24
Project: drill   File: EvaluationVisitor.java   Source Code and License Vote up 4 votes
private HoldingContainer visitBooleanOr(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("OrOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);   // enter into nested block.

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "or" when one side is null
  //    p       q       p and q
  //    true    null     true
  //    false   null     null
  //    null    true     true
  //    null    false    null
  //    null    null     null

  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().eq(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().eq(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(1));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(0));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(0)) ;
  }

  generator.unNestEvalBlock();   // exit from nested block.

  return out;
}
 
Example 25
Project: drill   File: DrillSimpleFuncHolder.java   Source Code and License Vote up 4 votes
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, HoldingContainer[] inputVariables, String body,
                                            JVar[] workspaceJVars, FieldReference ref) {

  g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", getRegisteredNames()[0]));

  JBlock sub = new JBlock(true, true);
  JBlock topSub = sub;
  HoldingContainer out = null;
  MajorType returnValueType = getReturnType();

  // add outside null handling if it is defined.
  if (getNullHandling() == NullHandling.NULL_IF_NULL) {
    JExpression e = null;
    for (HoldingContainer v : inputVariables) {
      if (v.isOptional()) {
        JExpression isNullExpr;
        if (v.isReader()) {
         isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }
    }

    if (e != null) {
      // if at least one expression must be checked, set up the conditional.
      returnValueType = getReturnType().toBuilder().setMode(DataMode.OPTIONAL).build();
      out = g.declare(returnValueType);
      e = e.eq(JExpr.lit(0));
      JConditional jc = sub._if(e);
      jc._then().assign(out.getIsSet(), JExpr.lit(0));
      sub = jc._else();
    }
  }

  if (out == null) {
    out = g.declare(returnValueType);
  }

  // add the subblock after the out declaration.
  g.getEvalBlock().add(topSub);


  JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValueType), getReturnValue().getName(), JExpr._new(g.getHolderType(returnValueType)));
  addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);
  if (sub != topSub) {
    sub.assign(internalOutput.ref("isSet"),JExpr.lit(1));// Assign null if NULL_IF_NULL mode
  }
  sub.assign(out.getHolder(), internalOutput);
  if (sub != topSub) {
    sub.assign(internalOutput.ref("isSet"),JExpr.lit(1));// Assign null if NULL_IF_NULL mode
  }

  g.getEvalBlock().directStatement(String.format("//---- end of eval portion of %s function. ----//", getRegisteredNames()[0]));

  return out;
}
 
Example 26
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 27
Project: jaxb2-rich-contract-plugin   File: PluginContext.java   Source Code and License Vote up 4 votes
public JForEach loop(final JBlock block, final JExpression source, final JType sourceElementType, final JAssignmentTarget target, final JType targetElementType) {
	final JConditional ifNull = block._if(source.eq(JExpr._null()));
	ifNull._then().assign(target, JExpr._null());
	ifNull._else().assign(target, JExpr._new(this.arrayListClass.narrow(targetElementType)));
	return ifNull._else().forEach(sourceElementType, "_item", source);
}
 
Example 28
Project: jaxb2-rich-contract-plugin   File: BuilderGenerator.java   Source Code and License Vote up 4 votes
private void generateCollectionProperty(final JBlock initBody, final JVar productParam, final PropertyOutline propertyOutline, final JClass elementType) {
	final String fieldName = propertyOutline.getFieldName();
	final String propertyName = propertyOutline.getBaseName();
	final JClass iterableType = this.pluginContext.iterableClass.narrow(elementType.wildcard());
	final JMethod addIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName);
	final JVar addIterableParam = addIterableMethod.param(JMod.FINAL, iterableType, fieldName);
	generateAddMethodJavadoc(addIterableMethod, addIterableParam);
	final JMethod withIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withIterableParam = withIterableMethod.param(JMod.FINAL, iterableType, fieldName);
	generateWithMethodJavadoc(withIterableMethod, withIterableParam);
	final JMethod addVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName);
	final JVar addVarargsParam = addVarargsMethod.varParam(elementType, fieldName);
	generateAddMethodJavadoc(addVarargsMethod, addVarargsParam);
	final JMethod withVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withVarargsParam = withVarargsMethod.varParam(elementType, fieldName);
	generateWithMethodJavadoc(withVarargsMethod, withVarargsParam);
	final BuilderOutline childBuilderOutline = getBuilderDeclaration(elementType);
	final JMethod addMethod;
	if (childBuilderOutline != null && !childBuilderOutline.getClassOutline().getImplClass().isAbstract()) {
		final JClass builderWithMethodReturnType = childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard());
		addMethod = this.builderClass.raw.method(JMod.PUBLIC, builderWithMethodReturnType, PluginContext.ADD_METHOD_PREFIX + propertyName);
		generateBuilderMethodJavadoc(addMethod, "add", propertyName);
	} else {
		addMethod = null;
	}
	if (this.implement) {
		final JClass childBuilderType = childBuilderOutline == null ? this.pluginContext.buildableInterface : childBuilderOutline.getBuilderClass().narrow(this.builderClass.type);
		final JClass builderArrayListClass = this.pluginContext.arrayListClass.narrow(childBuilderType);
		final JClass builderListClass = this.pluginContext.listClass.narrow(childBuilderType);
		final JFieldVar builderField = this.builderClass.raw.field(JMod.PRIVATE, builderListClass, fieldName);
		addVarargsMethod.body().invoke(addIterableMethod).arg(this.pluginContext.asList(addVarargsParam));
		addVarargsMethod.body()._return(JExpr._this());
		withVarargsMethod.body().invoke(withIterableMethod).arg(this.pluginContext.asList(withVarargsParam));
		withVarargsMethod.body()._return(JExpr._this());
		final JConditional addIterableIfParamNull = addIterableMethod.body()._if(addIterableParam.ne(JExpr._null()));
		final JConditional addIterableIfNull = addIterableIfParamNull._then()._if(JExpr._this().ref(builderField).eq(JExpr._null()));
		addIterableIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass));
		final JForEach jForEach = addIterableIfParamNull._then().forEach(elementType, BuilderGenerator.ITEM_VAR_NAME, addIterableParam);
		final JExpression builderCreationExpression = childBuilderOutline == null
				? JExpr._new(this.pluginContext.buildableClass).arg(jForEach.var())
				: JExpr._new(childBuilderType).arg(JExpr._this()).arg(jForEach.var()).arg(this.settings.isCopyAlways() ? JExpr.TRUE : JExpr.FALSE);
		jForEach.body().add(JExpr._this().ref(builderField).invoke("add").arg(builderCreationExpression));
		addIterableMethod.body()._return(JExpr._this());
		final JConditional withIterableIfNull = withIterableMethod.body()._if(JExpr._this().ref(builderField).ne(JExpr._null()));
		withIterableIfNull._then().add(JExpr._this().ref(builderField).invoke("clear"));
		withIterableMethod.body()._return(JExpr.invoke(addIterableMethod).arg(withIterableParam));
		final JConditional ifNull = initBody._if(JExpr._this().ref(builderField).ne(JExpr._null()));
		final JVar collectionVar = ifNull._then().decl(JMod.FINAL, this.pluginContext.listClass.narrow(elementType), fieldName, JExpr._new(this.pluginContext.arrayListClass.narrow(elementType)).arg(JExpr._this().ref(builderField).invoke("size")));
		final JForEach initForEach = ifNull._then().forEach(childBuilderType, BuilderGenerator.ITEM_VAR_NAME, JExpr._this().ref(builderField));
		final JInvocation buildMethodInvocation = initForEach.var().invoke(this.settings.getBuildMethodName());
		final JExpression buildExpression = childBuilderOutline == null ? JExpr.cast(elementType, buildMethodInvocation) : buildMethodInvocation;
		initForEach.body().add(collectionVar.invoke("add").arg(buildExpression));
		ifNull._then().assign(productParam.ref(fieldName), collectionVar);
		if (addMethod != null) {
			final JConditional addIfNull = addMethod.body()._if(JExpr._this().ref(builderField).eq(JExpr._null()));
			addIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass));
			final JVar childBuilderVar = addMethod.body().decl(JMod.FINAL, childBuilderType, fieldName + this.settings.getBuilderFieldSuffix(), JExpr._new(childBuilderType).arg(JExpr._this()).arg(JExpr._null()).arg(JExpr.FALSE));
			addMethod.body().add(JExpr._this().ref(builderField).invoke("add").arg(childBuilderVar));
			addMethod.body()._return(childBuilderVar);
		}
		this.pluginContext.generateImmutableFieldInit(initBody, productParam, propertyOutline);
	}
}
 
Example 29
Project: jaxb2-rich-contract-plugin   File: BuilderGenerator.java   Source Code and License Vote up 4 votes
JForEach loop(final JBlock block, final JExpression source, final JType sourceElementType, final JAssignmentTarget target, final JType targetElementType) {
	final JConditional ifNull = block._if(source.eq(JExpr._null()));
	ifNull._then().assign(target, JExpr._null());
	ifNull._else().assign(target, JExpr._new(this.pluginContext.arrayListClass.narrow(targetElementType)));
	return ifNull._else().forEach(sourceElementType, BuilderGenerator.ITEM_VAR_NAME, source);
}
 
Example 30
Project: jpmml-evaluator   File: OperationProcessor.java   Source Code and License Vote up 3 votes
static
private void createReportingMethod(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JMethod method = clazz.method(JMod.PUBLIC, clazz, String.valueOf(executableElement.getSimpleName()));
	method.annotate(Override.class);

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

	JBlock body = method.body();

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

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

		JBlock trueBlock = ifStatement._then();

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

		JBlock falseBlock = ifStatement._else();

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

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

	body._return(resultVariable);
}