Java 类com.sun.codemodel.JConditional 实例源码

项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) {
    JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME);
    JTypeVar returnType = method.generify("T");
    method.type(returnType);
    Models.suppressWarnings(method, "unchecked");
    JVar nameParam = method.param(String.class, "name");
    JBlock body = method.body();
    JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value",
            invoke(internalGetMethod).arg(nameParam).arg(notFoundValue));
    JConditional found = method.body()._if(notFoundValue.ne(valueVar));
    found._then()._return(cast(returnType, valueVar));
    JBlock notFound = found._else();

    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam)));
    } else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }

    return method;
}
项目:GitHub    文件:EnumRule.java   
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);
}
项目:raml-module-builder    文件:ClientGenerator.java   
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("&"));
}
项目:thrift-java-compiler    文件:StructCodeGeneratorHelper.java   
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);

    }
项目:jaxb2-basics    文件:EqualsArguments.java   
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;
    }
}
项目:hyperjaxb3    文件:AbstractWrappingField.java   
protected JMethod createSetter() {
    final JMethod setter;

    final MethodWriter writer = outline.createMethodWriter();
    setter = writer.declareMethod(codeModel.VOID, getSetterName());
    final JVar target = writer.addParameter(exposedType, "target");

    final JExpression wrapCondition = wrapCondifiton(target);
    if (wrapCondition == null) {
        setCore(setter.body(), wrap(target));
    } else {
        final JConditional _if = setter.body()._if(wrapCondition);
        setCore(_if._then(), wrap(target));
    }
    return setter;
}
项目:hyperjaxb3    文件:AbstractWrappingField.java   
protected JMethod createGetter() {
    final MethodWriter writer = outline.createMethodWriter();
    final JMethod getter = writer.declareMethod(exposedType,
            getGetterName());
    JExpression source = getCore();
    final JExpression unwrapCondition = unwrapCondifiton(source);
    if (unwrapCondition == null) {
        getter.body()._return(unwrap(source));
    } else {
        final JConditional _if = getter.body()._if(unwrapCondition);
        _if._then()._return(unwrap(source));
        _if._else()._return(JExpr._null());
    }
    return getter;
}
项目:jaxb2-rich-contract-plugin    文件:BuilderGenerator.java   
JMethod generateBuildMethod(final JMethod initMethod) {
    final JMethod buildMethod = this.builderClass.raw.method(JMod.PUBLIC, this.definedClass, this.settings.getBuildMethodName());
    if (!(this.builderClass.type._extends() == null || this.builderClass.type._extends().name().equals("java.lang.Object"))) {
        buildMethod.annotate(Override.class);
    }
    if (this.implement) {
        final JExpression buildExpression = JExpr._this().invoke(initMethod).arg(JExpr._new(this.definedClass));
        if (this.settings.isCopyAlways()) {
            buildMethod.body()._return(buildExpression);
        } else if (this.definedClass.isAbstract()) {
            buildMethod.body()._return(JExpr.cast(this.definedClass, this.storedValueField));
        } else {
            final JConditional jConditional = buildMethod.body()._if(this.storedValueField.eq(JExpr._null()));
            jConditional._then()._return(buildExpression);
            jConditional._else()._return(JExpr.cast(this.definedClass, this.storedValueField));
        }
    }
    return buildMethod;
}
项目:rice    文件:ImmutableJaxbGenerator.java   
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;");
}
项目:immutable-xjc    文件:PluginImpl.java   
private void replaceCollectionGetter(FieldOutline field, final JMethod getter) {
    JDefinedClass clazz = field.parent().implClass;
    // remove the old getter
    clazz.methods().remove(getter);
    // and create a new one
    JMethod newGetter = field.parent().implClass.method(getter.mods().getValue(), getter.type(), getter.name());
    JBlock block = newGetter.body();

    JVar ret = block.decl(getJavaType(field), "ret");
    JCodeModel codeModel = field.parent().implClass.owner();
    JVar param = generateMethodParameter(getter, field);
    JConditional conditional = block._if(param.eq(JExpr._null()));
    conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param));
    conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param));
    block._return(ret);

    getter.javadoc().append("Returns unmodifiable collection.");
}
项目:immutable-xjc    文件:PluginImpl.java   
private void generatePropertyAssignment(final JMethod method, FieldOutline fieldOutline, boolean wrapUnmodifiable) {
    JBlock block = method.body();
    JCodeModel codeModel = fieldOutline.parent().implClass.owner();
    String fieldName = fieldOutline.getPropertyInfo().getName(false);
    JVar param = generateMethodParameter(method, fieldOutline);
    if (fieldOutline.getPropertyInfo().isCollection()) {
        if (wrapUnmodifiable) {
            JConditional conditional = block._if(param.eq(JExpr._null()));
            conditional._then().assign(JExpr.refthis(fieldName), JExpr._null());
            conditional._else().assign(JExpr.refthis(fieldName), getDefensiveCopyExpression(codeModel, getJavaType(fieldOutline), param));
        } else {
            block.assign(JExpr.refthis(fieldName), JExpr.ref(fieldName));
        }

        replaceCollectionGetter(fieldOutline, getGetterProperty(fieldOutline));
    } else {
        block.assign(JExpr.refthis(fieldName), JExpr.ref(fieldName));
    }
}
项目:podio-java-codegen    文件:CodeGenerator.java   
/**
 * Adds a equals method, containing all non-static field variables.
 * 
 * @param jclass
 * @param jCodeModel
 * @param includeSuperEquals
 *            if {@code true} super.equals() is incorporated.
 */
public static void addEquals(JDefinedClass jclass, JCodeModel jCodeModel, boolean includeSuperEquals) {
    JMethod equals = jclass.method(JMod.PUBLIC, jCodeModel.BOOLEAN, "equals");
    JVar _obj = equals.param(jCodeModel.ref(Object.class), "obj");
    if (includeSuperEquals) {
        equals.body()._if(JExpr.FALSE.eq(JExpr._super().invoke("equals").arg(_obj)))._then()._return(JExpr.FALSE);
    }
    equals.body().directStatement("\tif (this == obj)\n\t\treturn true;\n\tif (obj == null)\n\t\treturn false;\n\tif (getClass() != obj.getClass())\treturn false;");
    JVar _other = equals.body().decl(jclass, "other", JExpr.cast(jclass, _obj));
    for (JFieldVar jvar : jclass.fields().values()) {
        if ((jvar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }

        JConditional _outerIf = equals.body()._if(jvar.eq(JExpr._null()));
        _outerIf._then()._if(_other.ref(jvar.name()).ne(JExpr._null()))._then()._return(JExpr.FALSE);
        _outerIf._else()._if((jvar.invoke("equals").arg(_other.ref(jvar.name())).not()))._then()._return(JExpr.FALSE);
    }
    equals.body()._return(JExpr.TRUE);
}
项目:jsonschema2pojo    文件:EnumRule.java   
private void addFactoryMethod(JsonNode node, JDefinedClass _enum) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum);

    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(String.class, "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));
    illegalArgumentException.arg(valueParam);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(fromValue);
}
项目:GitHub    文件:DynamicPropertiesRule.java   
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;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
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;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
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));
}
项目:QDrill    文件:MergingRecordBatch.java   
private void generateComparisons(final ClassGenerator g, final VectorAccessible batch) throws SchemaChangeException {
  g.setMappingSet(MAIN_MAPPING);

  for (final Ordering od : popConfig.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    final ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(LEFT_MAPPING);
    final HoldingContainer left = g.addExpr(expr, false);
    g.setMappingSet(RIGHT_MAPPING);
    final HoldingContainer right = g.addExpr(expr, false);
    g.setMappingSet(MAIN_MAPPING);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    final LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getFunctionRegistry());
    final HoldingContainer out = g.addExpr(fh, false);
    final JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    } else {
      jc._then()._return(out.getValue().minus());
    }
  }

  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:QDrill    文件:SortBatch.java   
public static Sorter createNewSorter(FragmentContext context, List<Ordering> orderings, VectorAccessible batch, MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping)
        throws ClassTransformationException, IOException, SchemaChangeException{
  CodeGenerator<Sorter> cg = CodeGenerator.get(Sorter.TEMPLATE_DEFINITION, context.getFunctionRegistry());
  ClassGenerator<Sorter> g = cg.getRoot();
  g.setMappingSet(mainMapping);

  for(Ordering od : orderings) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(leftMapping);
    HoldingContainer left = g.addExpr(expr, false);
    g.setMappingSet(rightMapping);
    HoldingContainer right = g.addExpr(expr, false);
    g.setMappingSet(mainMapping);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    LogicalExpression fh =
      FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                     context.getFunctionRegistry());
    HoldingContainer out = g.addExpr(fh, false);
    JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    }else{
      jc._then()._return(out.getValue().minus());
    }
  }

  g.getEvalBlock()._return(JExpr.lit(0));

  return context.getImplementationClass(cg);
}
项目:QDrill    文件:ExternalSortBatch.java   
private void generateComparisons(ClassGenerator<?> g, VectorAccessible batch) throws SchemaChangeException {
  g.setMappingSet(MAIN_MAPPING);

  for (Ordering od : popConfig.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(LEFT_MAPPING);
    HoldingContainer left = g.addExpr(expr, false);
    g.setMappingSet(RIGHT_MAPPING);
    HoldingContainer right = g.addExpr(expr, false);
    g.setMappingSet(MAIN_MAPPING);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getFunctionRegistry());
    HoldingContainer out = g.addExpr(fh, false);
    JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    }else{
      jc._then()._return(out.getValue().minus());
    }
    g.rotateBlock();
  }

  g.rotateBlock();
  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:QDrill    文件:EvaluationVisitor.java   
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;
    }
项目:dremio-oss    文件:EvaluationVisitor.java   
@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;
    }
项目:dremio-oss    文件:EvaluationVisitor.java   
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;
    }
项目:dremio-oss    文件:MergingReceiverOperator.java   
private void generateComparisons(final ClassGenerator<?> g, final VectorAccessible batch) throws SchemaChangeException {
  g.setMappingSet(mainMapping);

  for (final Ordering od : config.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    final LogicalExpression expr = context.getClassProducer().materialize(od.getExpr(), batch);
    g.setMappingSet(leftMapping);
    final HoldingContainer left = g.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE);
    g.setMappingSet(rightMapping);
    final HoldingContainer right = g.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE);
    g.setMappingSet(mainMapping);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    final LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getClassProducer());
    final HoldingContainer out = g.addExpr(fh, ClassGenerator.BlockCreateMode.MERGE);
    final JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    } else {
      jc._then()._return(out.getValue().minus());
    }
  }

  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:dremio-oss    文件:ExternalSortOperator.java   
static void generateComparisons(ClassGenerator<?> g, VectorAccessible batch, Iterable<Ordering> orderings, ClassProducer producer) throws SchemaChangeException {

    final MappingSet mainMappingSet = new MappingSet( (String) null, null, ClassGenerator.DEFAULT_SCALAR_MAP, ClassGenerator.DEFAULT_SCALAR_MAP);
    final MappingSet leftMappingSet = new MappingSet("leftIndex", null, ClassGenerator.DEFAULT_SCALAR_MAP, ClassGenerator.DEFAULT_SCALAR_MAP);
    final MappingSet rightMappingSet = new MappingSet("rightIndex", null, ClassGenerator.DEFAULT_SCALAR_MAP, ClassGenerator.DEFAULT_SCALAR_MAP);
    g.setMappingSet(mainMappingSet);

    for (Ordering od : orderings) {
      // first, we rewrite the evaluation stack for each side of the comparison.
      final LogicalExpression expr = producer.materialize(od.getExpr(), batch);
      g.setMappingSet(leftMappingSet);
      HoldingContainer left = g.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE);
      g.setMappingSet(rightMappingSet);
      HoldingContainer right = g.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE);
      g.setMappingSet(mainMappingSet);

      // next we wrap the two comparison sides and add the expression block for the comparison.
      LogicalExpression fh = FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right, producer);
      HoldingContainer out = g.addExpr(fh, ClassGenerator.BlockCreateMode.MERGE);
      JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      if (od.getDirection() == Direction.ASCENDING) {
        jc._then()._return(out.getValue());
      }else{
        jc._then()._return(out.getValue().minus());
      }
      g.rotateBlock();
    }

    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));
  }
项目:drill    文件:MergingRecordBatch.java   
private void generateComparisons(final ClassGenerator<?> g, final VectorAccessible batch) throws SchemaChangeException {
  g.setMappingSet(MAIN_MAPPING);

  for (final Ordering od : popConfig.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    final ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(LEFT_MAPPING);
    final HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(RIGHT_MAPPING);
    final HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(MAIN_MAPPING);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    final LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getFunctionRegistry());
    final HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
    final JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    } else {
      jc._then()._return(out.getValue().minus());
    }
  }

  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:drill    文件:ExternalSortBatch.java   
private void generateComparisons(ClassGenerator<?> g, VectorAccessible batch) throws SchemaChangeException {
  g.setMappingSet(MAIN_MAPPING);

  for (Ordering od : popConfig.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(LEFT_MAPPING);
    HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(RIGHT_MAPPING);
    HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(MAIN_MAPPING);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getFunctionRegistry());
    HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
    JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    }else{
      jc._then()._return(out.getValue().minus());
    }
    g.rotateBlock();
  }

  g.rotateBlock();
  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:drill    文件:BaseSortWrapper.java   
protected void generateComparisons(ClassGenerator<?> g, VectorAccessible batch, org.slf4j.Logger logger)  {
  g.setMappingSet(MAIN_MAPPING);

  Sort popConfig = context.getOperatorDefn();
  for (Ordering od : popConfig.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector,
        context.getFragmentContext().getFunctionRegistry());
    if (collector.hasErrors()) {
      throw UserException.unsupportedError()
            .message("Failure while materializing expression. " + collector.toErrorString())
            .build(logger);
    }
    g.setMappingSet(LEFT_MAPPING);
    HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(RIGHT_MAPPING);
    HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(MAIN_MAPPING);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getFragmentContext().getFunctionRegistry());
    HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
    JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    }else{
      jc._then()._return(out.getValue().minus());
    }
    g.rotateBlock();
  }

  g.rotateBlock();
  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:drill    文件:OperatorCodeGenerator.java   
protected void generateComparisons(ClassGenerator<?> g, VectorAccessible batch)  {
  g.setMappingSet(MAIN_MAPPING);

  for (Ordering od : popConfig.getOrderings()) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector, context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw UserException.unsupportedError()
            .message("Failure while materializing expression. " + collector.toErrorString())
            .build(logger);
    }
    g.setMappingSet(LEFT_MAPPING);
    HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(RIGHT_MAPPING);
    HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(MAIN_MAPPING);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    LogicalExpression fh =
        FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                       context.getFunctionRegistry());
    HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
    JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    }else{
      jc._then()._return(out.getValue().minus());
    }
    g.rotateBlock();
  }

  g.rotateBlock();
  g.getEvalBlock()._return(JExpr.lit(0));
}
项目:drill    文件:EvaluationVisitor.java   
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;
    }
项目:kc-rice    文件:ImmutableJaxbGenerator.java   
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;");
}
项目:android-modules    文件:BusHandler.java   
private void registerAll(EComponentHolder holder, Element element, String methodName, JClass eventOrRequestClass) {
    JMethod method = getMethodForRegistering(holder);
    final JClass moduleProviderClass = refClass(ModuleObjectsShare.class);
    final JInvocation modulesNames = moduleProviderClass.staticInvoke("modulesNames");
    final JConditional isEmpty = method.body()._if(modulesNames.invoke("isEmpty"));
    register(holder, element, methodName, eventOrRequestClass, lit(""), isEmpty._then());
    final JForEach forEach = isEmpty._else().forEach(refClass(String.class), "moduleName", modulesNames);
    forEach.body().directStatement("// we need to store module name in some final variable to use it in the listener");
    final JVar moduleNameToPass = forEach.body().decl(JMod.FINAL, refClass(String.class), "moduleNameToPass", forEach.var());
    register(holder, element, methodName, eventOrRequestClass, moduleNameToPass, forEach.body());
}
项目:kola    文件:StatementAdapter.java   
@Override
public void caseAIfThenStatement(AIfThenStatement node) {
    ExpressionAdapter ea = new ExpressionAdapter(new JExprParent(), context);
    node.getCond().apply(ea);
    JConditional cond = parent._if(ea.expr);
    JBlock tmpBlock = new JBlock();
    StatementAdapter sa = new StatementAdapter(new JBlockParent(tmpBlock, context), context);
    node.getThen().apply(sa);
    JStatement stmt = (JStatement) tmpBlock.getContents().get(0);
    if (stmt instanceof JBlock) {
        JBlock stmtBlock = (JBlock) stmt;
        stmtBlock.setNewlineRequired(false);
    }
    cond.setThen(stmt);
}
项目:jaxb2-rich-contract-plugin    文件:ModifierGenerator.java   
private ModifierGenerator(final PluginContext pluginContext, final DefinedTypeOutline classOutline, final String modifierClassName, final String modifierInterfaceName, final Collection<TypeOutline> interfaces, final String modifierMethodName, final boolean implement) throws JClassAlreadyExistsException {
    this.classOutline = classOutline;
    final JDefinedClass definedClass = classOutline.getImplClass();
    this.implement = implement;
    this.modifierClass = definedClass._class(JMod.PUBLIC, modifierClassName, classOutline.getImplClass().getClassType());
    if(interfaces != null) {
        for (final TypeOutline interfaceOutline : interfaces) {
            this.modifierClass._implements( pluginContext.ref(interfaceOutline.getImplClass(), modifierInterfaceName, true));
        }
    }
    final JFieldRef cachedModifierField;
    if(!"java.lang.Object".equals(definedClass._extends().fullName())) {
        this.modifierClass._extends(pluginContext.ref(definedClass._extends(), modifierClassName, false));
        cachedModifierField = JExpr.refthis(ModifierGenerator.MODIFIER_CACHE_FIELD_NAME);
    } else {
        if(implement) {
            cachedModifierField = JExpr._this().ref(definedClass.field(JMod.PROTECTED | JMod.TRANSIENT, this.modifierClass, ModifierGenerator.MODIFIER_CACHE_FIELD_NAME));
        } else {
            cachedModifierField = null;
        }
    }

    final JDefinedClass typeDefinition = classOutline.isInterface() && ((DefinedInterfaceOutline)classOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)classOutline).getSupportInterface() : definedClass;
    final JMethod modifierMethod = typeDefinition.method(JMod.PUBLIC, this.modifierClass, modifierMethodName);
    if(this.implement) {
        final JConditional ifCacheNull = modifierMethod.body()._if(JExpr._null().eq(cachedModifierField));
        ifCacheNull._then().assign(cachedModifierField, JExpr._new(this.modifierClass));
        modifierMethod.body()._return(JExpr.cast(this.modifierClass, cachedModifierField));
    }

}
项目:jaxb2-rich-contract-plugin    文件:ModifierGenerator.java   
private void generateCollectionAccessor(final DefinedPropertyOutline fieldOutline) {
    final JFieldVar fieldVar = fieldOutline.getFieldVar();
    if(fieldVar != null) {
        final JMethod modifier = this.modifierClass.method(JMod.PUBLIC, fieldVar.type(), ModifierGenerator.GETTER_PREFIX + fieldOutline.getBaseName());
        if(this.implement) {
            final JFieldRef fieldRef = new NestedThisRef(this.classOutline.getImplClass()).ref(fieldVar);
            final JConditional ifNull = modifier.body()._if(fieldRef.eq(JExpr._null()));
            ifNull._then().assign(fieldRef, JExpr._new(this.classOutline.getImplClass().owner().ref(ArrayList.class).narrow(fieldOutline.getElementType())));
            modifier.body()._return(fieldRef);
        }
    }
}
项目:jaxb2-rich-contract-plugin    文件:MetaPlugin.java   
private void generateAccessors(final FieldOutline fieldOutline, final String propertyName, final JType returnType, final JDefinedClass declaringClass, final F1<JExpression, JVar> getMaker, final F3<JExpression, JBlock, JVar, JVar> setMaker) {
    final String constantName = getConstantName(fieldOutline);
    final JMethod getMethod = declaringClass.method(JMod.PUBLIC, returnType, "get");
    getMethod.annotate(Override.class);
    final JVar instanceParam = getMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
    getMethod.body()._return(JOp.cond(instanceParam.eq(JExpr._null()), JExpr._null(), getMaker.f(instanceParam)));
    final JMethod setMethod = declaringClass.method(JMod.PUBLIC, void.class, "set");
    setMethod.annotate(Override.class);
    final JVar setInstanceParam = setMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
    final JVar valueParam = setMethod.param(JMod.FINAL, returnType, "_value_");
    if (constantName == null) {
        final JConditional ifNotNull = setMethod.body()._if(setInstanceParam.ne(JExpr._null()));
        setMaker.f(ifNotNull._then(), setInstanceParam, valueParam);
    }
}
项目:LRPaGe    文件:EqualsGenerator.java   
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;
}
项目:immutable-xjc    文件:PluginImpl.java   
private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, FieldOutline field, JMethod unconditionalWithMethod) {
    if (field.getRawType().isPrimitive())
      return null;
    String fieldName = field.getPropertyInfo().getName(true);
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull");
    JVar param = generateMethodParameter(method, field);
    JBlock block = method.body();
    JConditional conditional = block._if(param.eq(JExpr._null()));
    conditional._then()._return(JExpr.direct("this"));
    conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param));
    return method;
}
项目:kuali_rice    文件:ImmutableJaxbGenerator.java   
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;");
}
项目:QDrill    文件:TopNBatch.java   
public PriorityQueue createNewPriorityQueue(FragmentContext context, List<Ordering> orderings,
                                                   VectorAccessible batch, MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping)
        throws ClassTransformationException, IOException, SchemaChangeException{
  CodeGenerator<PriorityQueue> cg = CodeGenerator.get(PriorityQueue.TEMPLATE_DEFINITION, context.getFunctionRegistry());
  ClassGenerator<PriorityQueue> g = cg.getRoot();
  g.setMappingSet(mainMapping);

  for (Ordering od : orderings) {
    // first, we rewrite the evaluation stack for each side of the comparison.
    ErrorCollector collector = new ErrorCollectorImpl();
    final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector, context.getFunctionRegistry());
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(leftMapping);
    HoldingContainer left = g.addExpr(expr, false);
    g.setMappingSet(rightMapping);
    HoldingContainer right = g.addExpr(expr, false);
    g.setMappingSet(mainMapping);

    // next we wrap the two comparison sides and add the expression block for the comparison.
    LogicalExpression fh =
      FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right,
                                                     context.getFunctionRegistry());
    HoldingContainer out = g.addExpr(fh, false);
    JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

    if (od.getDirection() == Direction.ASCENDING) {
      jc._then()._return(out.getValue());
    } else {
      jc._then()._return(out.getValue().minus());
    }
    g.rotateBlock();
  }

  g.rotateBlock();
  g.getEvalBlock()._return(JExpr.lit(0));

  PriorityQueue q = context.getImplementationClass(cg);
  q.init(config.getLimit(), context, oContext.getAllocator(), schema.getSelectionVectorMode() == BatchSchema.SelectionVectorMode.TWO_BYTE);
  return q;
}
项目:QDrill    文件:MergeJoinBatch.java   
private void generateDoCompareNextLeft(ClassGenerator<JoinWorker> cg, JVar incomingRecordBatch,
    LogicalExpression[] leftExpression, JVar incomingLeftRecordBatch, JVar joinStatus,
    ErrorCollector collector) throws ClassTransformationException {
  boolean nextLeftIndexDeclared = false;

  cg.setMappingSet(compareLeftMapping);

  for (int i = 0; i < leftExpression.length; i++) {

    // materialize value vector readers from join expression
    final LogicalExpression materializedLeftExpr = leftExpression[i];

    // generate compareNextLeftKey()
    ////////////////////////////////
    cg.setMappingSet(compareLeftMapping);
    cg.getSetupBlock().assign(JExpr._this().ref(incomingRecordBatch), JExpr._this().ref(incomingLeftRecordBatch));

    if (!nextLeftIndexDeclared) {
      // int nextLeftIndex = leftIndex + 1;
      cg.getEvalBlock().decl(JType.parse(cg.getModel(), "int"), "nextLeftIndex", JExpr.direct("leftIndex").plus(JExpr.lit(1)));
      nextLeftIndexDeclared = true;
    }
    // check if the next key is in this batch
    cg.getEvalBlock()._if(joinStatus.invoke("isNextLeftPositionInCurrentBatch").eq(JExpr.lit(false)))
                     ._then()
                       ._return(JExpr.lit(-1));

    // generate VV read expressions
    ClassGenerator.HoldingContainer compareThisLeftExprHolder = cg.addExpr(materializedLeftExpr, false);
    cg.setMappingSet(compareNextLeftMapping); // change mapping from 'leftIndex' to 'nextLeftIndex'
    ClassGenerator.HoldingContainer compareNextLeftExprHolder = cg.addExpr(materializedLeftExpr, false);

    if (compareThisLeftExprHolder.isOptional()) {
      // handle null == null
      cg.getEvalBlock()._if(compareThisLeftExprHolder.getIsSet().eq(JExpr.lit(0))
                            .cand(compareNextLeftExprHolder.getIsSet().eq(JExpr.lit(0))))
                       ._then()
                         ._return(JExpr.lit(0));

      // handle null == !null
      cg.getEvalBlock()._if(compareThisLeftExprHolder.getIsSet().eq(JExpr.lit(0))
                            .cor(compareNextLeftExprHolder.getIsSet().eq(JExpr.lit(0))))
                       ._then()
                         ._return(JExpr.lit(1));
    }

    // check value equality

    LogicalExpression gh =
        FunctionGenerationHelper.getOrderingComparatorNullsHigh(compareThisLeftExprHolder,
                                                                compareNextLeftExprHolder,
                                                                context.getFunctionRegistry());
    HoldingContainer out = cg.addExpr(gh, false);

    // If not 0, it means not equal. We return this out value.
    JConditional jc = cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));
    jc._then()._return(out.getValue());
  }

  //Pass the equality check for all the join conditions. Finally, return 0.
  cg.getEvalBlock()._return(JExpr.lit(0));
}