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

下面列出了怎么用 com.sun.codemodel.JConditional 的API类实例代码及写法,或者点击链接到github查看源代码。


private void addParameter(ParameterDetails details) {
  JBlock b = details.methodBody;
  if (Boolean.TRUE.equals(details.nullCheck)) {
    JConditional ifClause = details.methodBody._if(JExpr.ref(details.valueName).ne(JExpr._null()));
    b = ifClause._then();
  }
  b.invoke(details.queryParams, APPEND).arg(JExpr.lit(details.valueName + "="));
  switch (details.op) {
    case ENCODE:
      encodeParameter(b, details);
      break;
    case FORMAT_DATE:
      formatDateParameter(b, details);
      break;
    case PROCESS_LIST:
      processListParameter(b, details);
      break;
    case NONE:
      b.invoke(details.queryParams, APPEND).arg(JExpr.ref(details.valueName));
      break;
  }
  b.invoke(details.queryParams, APPEND).arg(JExpr.lit("&"));
}
 
源代码2 项目: apicurio-studio   文件: JaxRsEnumRule.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(_enum, fromValue);
}
 
源代码3 项目: 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;
	}
}
 

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;
}
 

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;
}
 
源代码6 项目: immutable-xjc   文件: PluginImpl.java

private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, JFieldVar field, JMethod unconditionalWithMethod, boolean inherit) {
    if (field.type().isPrimitive())
        return null;
    String fieldName = StringUtils.capitalize(field.name());
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull");
    JVar param = generateMethodParameter(method, field);
    JBlock block = method.body();
    if (inherit) {
        generateSuperCall(method);
        method.body()._return(JExpr._this());
    } else {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then()._return(JExpr._this());
        conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param));
    }
    return method;
}
 
源代码7 项目: immutable-xjc   文件: PluginImpl.java

private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) {
    // remove the old getter
    ownerClass.methods().remove(getter);
    // and create a new one
    JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name());
    JBlock block = newGetter.body();

    JVar ret = block.decl(getJavaType(field), "ret");
    JCodeModel codeModel = field.type().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.");
}
 
源代码8 项目: Bats   文件: 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));
}
 
源代码9 项目: Bats   文件: 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));
}
 
源代码10 项目: Bats   文件: 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));
}
 
源代码11 项目: Bats   文件: 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;
    }
 
源代码12 项目: avro-util   文件: FastSerializerGenerator.java

private void processString(final Schema primitiveSchema, JExpression primitiveValueExpression, JBlock body) {
  String writeFunction = "writeString";
  JExpression encodeVar = JExpr.direct(ENCODER);
  if (!useGenericTypes && SchemaAssistant.isStringable(primitiveSchema)) {
    body.invoke(encodeVar, writeFunction).arg(primitiveValueExpression.invoke("toString"));
  } else {
    JConditional stringTypeCheck = body._if(primitiveValueExpression._instanceof(codeModel.ref(Utf8.class)));
    stringTypeCheck._then()
        .invoke(encodeVar, writeFunction)
        .arg(JExpr.cast(codeModel.ref(Utf8.class), primitiveValueExpression));
    stringTypeCheck._else().invoke(encodeVar, writeFunction).arg(primitiveValueExpression.invoke("toString"));
  }
}
 

private void processArray(final Schema arraySchema, JExpression arrayExpr, JBlock body) {
    final JClass arrayClass = schemaAssistant.classFromSchema(arraySchema);
    body.invoke(JExpr.direct(ENCODER), "writeArrayStart");

    final JExpression emptyArrayCondition = arrayExpr.eq(JExpr._null())
            .cor(JExpr.invoke(arrayExpr, "isEmpty"));

    final JConditional emptyArrayIf = body._if(emptyArrayCondition);
    final JBlock emptyArrayBlock = emptyArrayIf._then();
    emptyArrayBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));

    final JBlock nonEmptyArrayBlock = emptyArrayIf._else();
    nonEmptyArrayBlock.invoke(JExpr.direct(ENCODER), "setItemCount")
            .arg(JExpr.invoke(arrayExpr, "size"));
    final JForLoop forLoop = nonEmptyArrayBlock._for();
    final JVar counter = forLoop.init(codeModel.INT, getVariableName("counter"), JExpr.lit(0));
    forLoop.test(counter.lt(JExpr.invoke(JExpr.cast(arrayClass, arrayExpr), "size")));
    forLoop.update(counter.incr());
    final JBlock forBody = forLoop.body();
    forBody.invoke(JExpr.direct(ENCODER), "startItem");

    final Schema elementSchema = arraySchema.getElementType();
    if (SchemaAssistant.isComplexType(elementSchema)) {
        JVar containerVar = declareValueVar(elementSchema.getName(), elementSchema, forBody);
        forBody.assign(containerVar, JExpr.invoke(JExpr.cast(arrayClass, arrayExpr), "get").arg(counter));
        processComplexType(elementSchema, containerVar, forBody);
    } else {
        processSimpleType(elementSchema, arrayExpr.invoke("get").arg(counter), forBody);
    }

    body.invoke(JExpr.direct(ENCODER), "writeArrayEnd");
}
 

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));
}
 
源代码15 项目: 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));
  }
 
源代码16 项目: 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;
}
 

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));
	}

}
 

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);
		}
	}
}
 

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);
	}
}
 
源代码20 项目: 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;");
}
 
源代码21 项目: immutable-xjc   文件: PluginImpl.java

private void generatePropertyAssignment(final JMethod method, JFieldVar field, boolean wrapUnmodifiable) {
    JBlock block = method.body();
    JCodeModel codeModel = field.type().owner();
    String fieldName = field.name();
    JVar param = generateMethodParameter(method, field);
    if (isCollection(field) && !leaveCollectionsMutable && 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(field), param));
    } else {
        block.assign(JExpr.refthis(fieldName), JExpr.ref(fieldName));
    }
}
 
源代码22 项目: Bats   文件: TopNBatch.java

public static PriorityQueue createNewPriorityQueue(
  MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping,
  List<Ordering> orderings, VectorAccessible batch, boolean unionTypeEnabled, boolean codegenDump,
  int limit, BufferAllocator allocator, SelectionVectorMode mode, FragmentContext context)
        throws ClassTransformationException, IOException, SchemaChangeException {
  OptionSet optionSet = context.getOptions();
  FunctionLookupContext functionLookupContext = context.getFunctionRegistry();
  CodeGenerator<PriorityQueue> cg = CodeGenerator.get(PriorityQueue.TEMPLATE_DEFINITION, optionSet);
  cg.plainJavaCapable(true);
  // Uncomment out this line to debug the generated code.
  cg.saveCodeForDebugging(codegenDump);
  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, functionLookupContext, unionTypeEnabled);
    if (collector.hasErrors()) {
      throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
    }
    g.setMappingSet(leftMapping);
    HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(rightMapping);
    HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.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, functionLookupContext);
    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));

  PriorityQueue q = context.getImplementationClass(cg);
  q.init(limit, allocator, mode == BatchSchema.SelectionVectorMode.TWO_BYTE);
  return q;
}
 
源代码23 项目: Bats   文件: 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.getOptions());
  // This operator may be deprecated. No tests exercise it.
  // There is no way, at present, to verify if the generated code
  // works with Plain-old Java.
  // cg.plainOldJavaCapable(true);
  // Uncomment out this line to debug the generated code.
  // cg.saveCodeForDebugging(true);
  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, ClassGenerator.BlkCreateMode.FALSE);
    g.setMappingSet(rightMapping);
    HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.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, 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.getEvalBlock()._return(JExpr.lit(0));

  return context.getImplementationClass(cg);
}
 
源代码24 项目: Bats   文件: ChainedHashTable.java

private void setupIsKeyMatchInternal(ClassGenerator<HashTable> cg, MappingSet incomingMapping, MappingSet htableMapping,
    LogicalExpression[] keyExprs, List<Comparator> comparators, TypedFieldId[] htKeyFieldIds, SetupWork work) {

  boolean checkIfBothNulls = work == SetupWork.CHECK_BOTH_NULLS;

  // Regular key matching may return false in the middle (i.e., some pair of columns did not match), and true only if all matched;
  // but "both nulls" check returns the opposite logic (i.e., true when one pair of nulls is found, need check no more)
  JExpression midPointResult = checkIfBothNulls ? JExpr.TRUE : JExpr.FALSE;
  JExpression finalResult = checkIfBothNulls ? JExpr.FALSE : JExpr.TRUE;

  cg.setMappingSet(incomingMapping);

  if (keyExprs == null || keyExprs.length == 0 ||
      checkIfBothNulls && ! comparators.contains(Comparator.EQUALS)) { // e.g. for Hash-Aggr, or non-equi join
    cg.getEvalBlock()._return(JExpr.FALSE);
    return;
  }

  for (int i = 0; i < keyExprs.length; i++) {
    final LogicalExpression expr = keyExprs[i];
    cg.setMappingSet(incomingMapping);
    HoldingContainer left = cg.addExpr(expr, ClassGenerator.BlkCreateMode.TRUE_IF_BOUND);

    cg.setMappingSet(htableMapping);
    ValueVectorReadExpression vvrExpr = new ValueVectorReadExpression(htKeyFieldIds[i]);
    HoldingContainer right = cg.addExpr(vvrExpr, ClassGenerator.BlkCreateMode.FALSE);

    JConditional jc;

    if ( work != SetupWork.DO_BUILD ) {  // BUILD runs this logic in a separate method - areBothKeysNull()
      // codegen for the special case when both columns are null (i.e., return early with midPointResult)
      if (comparators.get(i) == Comparator.EQUALS
          && left.isOptional() && right.isOptional()) {
        jc = cg.getEvalBlock()._if(left.getIsSet().eq(JExpr.lit(0)).
          cand(right.getIsSet().eq(JExpr.lit(0))));
        jc._then()._return(midPointResult);
      }
    }
    if ( ! checkIfBothNulls ) { // generate comparison code (at least one of the two columns' values is non-null)
      final LogicalExpression f = FunctionGenerationHelper.getOrderingComparatorNullsHigh(left, right, context.getFunctionRegistry());

      HoldingContainer out = cg.addExpr(f, ClassGenerator.BlkCreateMode.FALSE);

      // check if two values are not equal (comparator result != 0)
      jc = cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      jc._then()._return(midPointResult);
    }
  }

  // All key expressions compared the same way, so return the appropriate final result
  cg.getEvalBlock()._return(finalResult);
}
 
源代码25 项目: Bats   文件: OrderedPartitionRecordBatch.java

/**
   * Sets up projection that will transfer all of the columns in batch, and also populate the partition column based on
   * which partition a record falls into in the partition table
   *
   * @param batch
   * @throws SchemaChangeException
   */
  protected void setupNewSchema(VectorAccessible batch) throws SchemaChangeException {
    container.clear();
    final ErrorCollector collector = new ErrorCollectorImpl();
    final List<TransferPair> transfers = Lists.newArrayList();

    final ClassGenerator<OrderedPartitionProjector> cg = CodeGenerator.getRoot(
        OrderedPartitionProjector.TEMPLATE_DEFINITION, context.getOptions());
    // Note: disabled for now. This may require some debugging:
    // no tests are available for this operator.
//    cg.getCodeGenerator().plainOldJavaCapable(true);
    // Uncomment out this line to debug the generated code.
//    cg.getCodeGenerator().saveCodeForDebugging(true);

    for (VectorWrapper<?> vw : batch) {
      TransferPair tp = vw.getValueVector().getTransferPair(oContext.getAllocator());
      transfers.add(tp);
      container.add(tp.getTo());
    }

    cg.setMappingSet(mainMapping);

    int count = 0;
    for (Ordering od : popConfig.getOrderings()) {
      final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector, context.getFunctionRegistry());
      if (collector.hasErrors()) {
        throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
      }
      cg.setMappingSet(incomingMapping);
      ClassGenerator.HoldingContainer left = cg.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
      cg.setMappingSet(partitionMapping);
      ClassGenerator.HoldingContainer right = cg.addExpr(
          new ValueVectorReadExpression(new TypedFieldId(expr.getMajorType(), count++)), ClassGenerator.BlkCreateMode.FALSE);
      cg.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());
      ClassGenerator.HoldingContainer out = cg.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
      JConditional jc = cg.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());
      }
    }

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

    container.add(this.partitionKeyVector);
    container.buildSchema(batch.getSchema().getSelectionVectorMode());

    try {
      this.projector = context.getImplementationClass(cg);
      projector.setup(context, batch, this, transfers, partitionVectors, partitions, popConfig.getRef());
    } catch (ClassTransformationException | IOException e) {
      throw new SchemaChangeException("Failure while attempting to load generated class", e);
    }
  }
 
源代码26 项目: Bats   文件: ExternalSortBatch.java

private MSorter createNewMSorter(FragmentContext context, List<Ordering> orderings, VectorAccessible batch, MappingSet mainMapping, MappingSet leftMapping, MappingSet
    rightMapping)
          throws ClassTransformationException, IOException, SchemaChangeException {
    CodeGenerator<MSorter> cg = CodeGenerator.get(MSorter.TEMPLATE_DEFINITION, context.getOptions());
    ClassGenerator<MSorter> 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, ClassGenerator.BlkCreateMode.FALSE);
      g.setMappingSet(rightMapping);
      HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.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, 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));

    cg.plainJavaCapable(true); // This class can generate plain-old Java.
    // Uncomment out this line to debug the generated code.
//    cg.saveCodeForDebugging(true);
    return context.getImplementationClass(cg);
  }
 
源代码27 项目: Bats   文件: MergeSortWrapper.java

private MSorter createNewMSorter(List<Ordering> orderings, MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping) {
    CodeGenerator<MSorter> cg = CodeGenerator.get(MSorter.TEMPLATE_DEFINITION, context.getFragmentContext().getOptions());
    cg.plainJavaCapable(true);

    // Uncomment out this line to debug the generated code.
//    cg.saveCodeForDebugging(true);
    ClassGenerator<MSorter> 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(), destContainer, collector,
          context.getFragmentContext().getFunctionRegistry());
      if (collector.hasErrors()) {
        throw UserException.unsupportedError()
              .message("Failure while materializing expression. " + collector.toErrorString())
              .build(logger);
      }
      g.setMappingSet(leftMapping);
      HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
      g.setMappingSet(rightMapping);
      HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.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.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));

    return getInstance(cg, logger);
  }
 
源代码28 项目: Bats   文件: EvaluationVisitor.java

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;
}
 
源代码29 项目: Bats   文件: EvaluationVisitor.java

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;
}
 
源代码30 项目: Bats   文件: DrillSimpleFuncHolder.java

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);

  List<String> holderFields = ValueHolderHelper.getHolderParams(returnValueType);
  for (String holderField : holderFields) {
    sub.assign(out.f(holderField), internalOutput.ref(holderField));
  }

  if (sub != topSub) {
    sub.assign(out.f("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;
}
 
 类所在包
 类方法
 同包方法