com.sun.codemodel.JConditional Java Examples
The following examples show how to use
com.sun.codemodel.JConditional.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PluginImpl.java From immutable-xjc with MIT License | 6 votes |
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."); }
Example #2
Source File: PluginImpl.java From immutable-xjc with MIT License | 6 votes |
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; }
Example #3
Source File: BuilderGenerator.java From jaxb2-rich-contract-plugin with MIT License | 6 votes |
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; }
Example #4
Source File: ClientGenerator.java From raml-module-builder with Apache License 2.0 | 6 votes |
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("&")); }
Example #5
Source File: JaxRsEnumRule.java From apicurio-studio with Apache License 2.0 | 6 votes |
private void addFactoryMethod(JDefinedClass _enum, JType backingType) { JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType); JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue"); JVar valueParam = fromValue.param(backingType, "value"); JBlock body = fromValue.body(); JVar constant = body.decl(_enum, "constant"); constant.init(quickLookupMap.invoke("get").arg(valueParam)); JConditional _if = body._if(constant.eq(JExpr._null())); JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class)); JExpression expr = valueParam; // if string no need to add "" if(!isString(backingType)){ expr = expr.plus(JExpr.lit("")); } illegalArgumentException.arg(expr); _if._then()._throw(illegalArgumentException); _if._else()._return(constant); ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue); }
Example #6
Source File: EqualsArguments.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 6 votes |
public JBlock ifHasSetValue(JBlock block, boolean isAlwaysSet, boolean checkForNullRequired) { if (isAlwaysSet || !checkForNullRequired) { return block; } else { final JConditional ifLeftHasSetValue = block._if(leftHasSetValue()); final JConditional ifLeftHasSetValueAndRightHasSetValue = ifLeftHasSetValue ._then()._if(rightHasSetValue()); final JBlock subBlock = ifLeftHasSetValueAndRightHasSetValue ._then(); ifLeftHasSetValueAndRightHasSetValue._else()._return(JExpr.FALSE); ifLeftHasSetValue._elseif(rightHasSetValue())._then() ._return(JExpr.FALSE); return subBlock; } }
Example #7
Source File: AbstractWrappingField.java From hyperjaxb3 with BSD 2-Clause "Simplified" License | 6 votes |
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; }
Example #8
Source File: ModifierGenerator.java From jaxb2-rich-contract-plugin with MIT License | 5 votes |
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)); } }
Example #9
Source File: FastSerializerGenerator.java From avro-fastserde with Apache License 2.0 | 5 votes |
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"); }
Example #10
Source File: MergingReceiverOperator.java From dremio-oss with Apache License 2.0 | 5 votes |
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)); }
Example #11
Source File: ExternalSortOperator.java From dremio-oss with Apache License 2.0 | 5 votes |
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)); }
Example #12
Source File: AbstractWrappingField.java From hyperjaxb3 with BSD 2-Clause "Simplified" License | 5 votes |
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; }
Example #13
Source File: MergingRecordBatch.java From Bats with Apache License 2.0 | 5 votes |
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)); }
Example #14
Source File: ModifierGenerator.java From jaxb2-rich-contract-plugin with MIT License | 5 votes |
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); } } }
Example #15
Source File: MetaPlugin.java From jaxb2-rich-contract-plugin with MIT License | 5 votes |
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); } }
Example #16
Source File: ImmutableJaxbGenerator.java From rice with Educational Community License v2.0 | 5 votes |
private void renderBuilderCreateContract(JDefinedClass builderClass, JClass literalBuilderClass, List<FieldModel> fields, Class<?> contractInterface) { JMethod createContractMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create"); JVar contractParam = createContractMethod.param(contractInterface, "contract"); JBlock body = createContractMethod.body(); JConditional nullContractCheck = body._if(contractParam.eq(JExpr._null())); nullContractCheck._then().directStatement("throw new IllegalArgumentException(\"contract was null\");"); body.directStatement("// TODO if create() is modified to accept required parameters, this will need to be modified"); body.directStatement("Builder builder = create();"); for (FieldModel fieldModel : fields) { String fieldName = fieldModel.fieldName; body.directStatement("builder." + Util.generateSetter(fieldName, "contract." + Util.generateGetter(fieldName, isBoolean(fieldModel.fieldType))) + ";"); } body.directStatement("return builder;"); }
Example #17
Source File: PluginImpl.java From immutable-xjc with MIT License | 5 votes |
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)); } }
Example #18
Source File: FastSerializerGenerator.java From avro-util with BSD 2-Clause "Simplified" License | 5 votes |
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")); } }
Example #19
Source File: EvaluationVisitor.java From Bats with Apache License 2.0 | 5 votes |
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) { final LogicalExpression child = e.getChild(); final HoldingContainer inputContainer = child.accept(this, generator); JBlock block = generator.getEvalBlock(); JExpression outIndex = generator.getMappingSet().getValueWriteIndex(); JVar vv = generator.declareVectorValueSetupAndMember(generator.getMappingSet().getOutgoing(), e.getFieldId()); // Only when the input is a reader, use writer interface to copy value. // Otherwise, input is a holder and we use vv mutator to set value. if (inputContainer.isReader()) { JType writerImpl = generator.getModel()._ref( TypeHelper.getWriterImpl(inputContainer.getMinorType(), inputContainer.getMajorType().getMode())); JType writerIFace = generator.getModel()._ref( TypeHelper.getWriterInterface(inputContainer.getMinorType(), inputContainer.getMajorType().getMode())); JVar writer = generator.declareClassField("writer", writerIFace); generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv).arg(JExpr._null())); generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex)); String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue"; generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer)); if (e.isSafe()) { HoldingContainer outputContainer = generator.declare(Types.REQUIRED_BIT); generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1)); return outputContainer; } } else { final JInvocation setMeth = GetSetVectorHelper.write(e.getChild().getMajorType(), vv, inputContainer, outIndex, e.isSafe() ? "setSafe" : "set"); if (inputContainer.isOptional()) { JConditional jc = block._if(inputContainer.getIsSet().eq(JExpr.lit(0)).not()); block = jc._then(); } block.add(setMeth); } return null; }
Example #20
Source File: ExternalSortBatch.java From Bats with Apache License 2.0 | 5 votes |
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)); }
Example #21
Source File: BaseSortWrapper.java From Bats with Apache License 2.0 | 5 votes |
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)); }
Example #22
Source File: BuilderGenerator.java From jaxb2-rich-contract-plugin with MIT License | 4 votes |
private void generateCollectionProperty(final JBlock initBody, final JVar productParam, final PropertyOutline propertyOutline, final JClass elementType) { final String fieldName = propertyOutline.getFieldName(); final String propertyName = propertyOutline.getBaseName(); final JClass iterableType = this.pluginContext.iterableClass.narrow(elementType.wildcard()); final JMethod addIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName); final JVar addIterableParam = addIterableMethod.param(JMod.FINAL, iterableType, fieldName); generateAddMethodJavadoc(addIterableMethod, addIterableParam, propertyOutline.getSchemaAnnotationText().orElse(null)); final JMethod withIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName); final JVar withIterableParam = withIterableMethod.param(JMod.FINAL, iterableType, fieldName); generateWithMethodJavadoc(withIterableMethod, withIterableParam, propertyOutline.getSchemaAnnotationText().orElse(null)); final JMethod addVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName); final JVar addVarargsParam = addVarargsMethod.varParam(elementType, fieldName); generateAddMethodJavadoc(addVarargsMethod, addVarargsParam, propertyOutline.getSchemaAnnotationText().orElse(null)); final JMethod withVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName); final JVar withVarargsParam = withVarargsMethod.varParam(elementType, fieldName); generateWithMethodJavadoc(withVarargsMethod, withVarargsParam, propertyOutline.getSchemaAnnotationText().orElse(null)); final BuilderOutline childBuilderOutline = getBuilderDeclaration(elementType); final JMethod addMethod; if (childBuilderOutline != null && !childBuilderOutline.getClassOutline().getImplClass().isAbstract()) { final JClass builderWithMethodReturnType = childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard()); addMethod = this.builderClass.raw.method(JMod.PUBLIC, builderWithMethodReturnType, PluginContext.ADD_METHOD_PREFIX + propertyName); generateBuilderMethodJavadoc(addMethod, "add", propertyName, propertyOutline.getSchemaAnnotationText().orElse(null)); } else { addMethod = null; } if (this.implement) { final JClass childBuilderType = childBuilderOutline == null ? this.pluginContext.buildableInterface : childBuilderOutline.getBuilderClass().narrow(this.builderClass.type); final JClass builderArrayListClass = this.pluginContext.arrayListClass.narrow(childBuilderType); final JClass builderListClass = this.pluginContext.listClass.narrow(childBuilderType); final JFieldVar builderField = this.builderClass.raw.field(JMod.PRIVATE, builderListClass, fieldName); addVarargsMethod.body().invoke(addIterableMethod).arg(this.pluginContext.asList(addVarargsParam)); addVarargsMethod.body()._return(JExpr._this()); withVarargsMethod.body().invoke(withIterableMethod).arg(this.pluginContext.asList(withVarargsParam)); withVarargsMethod.body()._return(JExpr._this()); final JConditional addIterableIfParamNull = addIterableMethod.body()._if(addIterableParam.ne(JExpr._null())); final JConditional addIterableIfNull = addIterableIfParamNull._then()._if(JExpr._this().ref(builderField).eq(JExpr._null())); addIterableIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass)); final JForEach jForEach = addIterableIfParamNull._then().forEach(elementType, BuilderGenerator.ITEM_VAR_NAME, addIterableParam); final JExpression builderCreationExpression = childBuilderOutline == null ? JExpr._new(this.pluginContext.buildableClass).arg(jForEach.var()) : JExpr._new(childBuilderType).arg(JExpr._this()).arg(jForEach.var()).arg(this.settings.isCopyAlways() ? JExpr.TRUE : JExpr.FALSE); jForEach.body().add(JExpr._this().ref(builderField).invoke("add").arg(builderCreationExpression)); addIterableMethod.body()._return(JExpr._this()); final JConditional withIterableIfNull = withIterableMethod.body()._if(JExpr._this().ref(builderField).ne(JExpr._null())); withIterableIfNull._then().add(JExpr._this().ref(builderField).invoke("clear")); withIterableMethod.body()._return(JExpr.invoke(addIterableMethod).arg(withIterableParam)); final JConditional ifNull = initBody._if(JExpr._this().ref(builderField).ne(JExpr._null())); final JVar collectionVar = ifNull._then().decl(JMod.FINAL, this.pluginContext.listClass.narrow(elementType), fieldName, JExpr._new(this.pluginContext.arrayListClass.narrow(elementType)).arg(JExpr._this().ref(builderField).invoke("size"))); final JForEach initForEach = ifNull._then().forEach(childBuilderType, BuilderGenerator.ITEM_VAR_NAME, JExpr._this().ref(builderField)); final JInvocation buildMethodInvocation = initForEach.var().invoke(this.settings.getBuildMethodName()); final JExpression buildExpression = childBuilderOutline == null ? JExpr.cast(elementType, buildMethodInvocation) : buildMethodInvocation; initForEach.body().add(collectionVar.invoke("add").arg(buildExpression)); ifNull._then().assign(productParam.ref(fieldName), collectionVar); if (addMethod != null) { final JConditional addIfNull = addMethod.body()._if(JExpr._this().ref(builderField).eq(JExpr._null())); addIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass)); final JVar childBuilderVar = addMethod.body().decl(JMod.FINAL, childBuilderType, fieldName + this.settings.getBuilderFieldSuffix(), JExpr._new(childBuilderType).arg(JExpr._this()).arg(JExpr._null()).arg(JExpr.FALSE)); addMethod.body().add(JExpr._this().ref(builderField).invoke("add").arg(childBuilderVar)); addMethod.body()._return(childBuilderVar); } this.pluginContext.generateImmutableFieldInit(initBody, productParam, propertyOutline); } }
Example #23
Source File: ObjectCodeGenerator.java From jaxb2-basics with BSD 2-Clause "Simplified" License | 4 votes |
@Override public void generate(final JBlock block, JType type, Collection<JType> possibleTypes, boolean isAlwaysSet, A arguments) { if (possibleTypes.size() <= 1) { getImplementor().onObject(arguments, block, isAlwaysSet); } else { final JClass jaxbElementClass = getCodeModel().ref( JAXBElement.class); final Set<JType> arrays = new HashSet<JType>(); final Collection<JClass> jaxbElements = new HashSet<JClass>(); final Set<JType> otherTypes = new HashSet<JType>(); for (final JType possibleType : possibleTypes) { if (possibleType.isArray()) { arrays.add(possibleType); } else if (possibleType instanceof JClass && jaxbElementClass .isAssignableFrom(((JClass) possibleType) .erasure())) { jaxbElements.add((JClass) possibleType); } else { otherTypes.add(possibleType); } } final JConditionable _if = new JConditionable() { private JConditional conditional = null; @Override public JBlock _ifThen(JExpression condition) { if (conditional == null) { conditional = block._if(condition); } else { conditional = conditional._elseif(condition); } return conditional._then(); } @Override public JBlock _else() { if (conditional == null) { return block; } else { return conditional._else(); } } }; if (!jaxbElements.isEmpty()) { final Set<JType> valueTypes = getJAXBElementValueTypes(jaxbElements); final JType valueType = TypeUtil.getCommonBaseType( getCodeModel(), valueTypes); final JClass jaxbElementType = jaxbElementClass .narrow(valueType); final JBlock jaxbElementBlock = _if._ifThen(arguments ._instanceof(jaxbElementClass)); getCodeGenerator().generate( jaxbElementBlock, jaxbElementType, new HashSet<JType>(jaxbElements), true, arguments.cast("JAXBElement", jaxbElementBlock, jaxbElementType, true)); } if (!arrays.isEmpty()) { for (JType arrayType : arrays) { final JBlock arrayBlock = _if._ifThen(arguments ._instanceof(arrayType)); getCodeGenerator().generate( arrayBlock, arrayType, Collections.singleton(arrayType), true, arguments.cast("Array", arrayBlock, arrayType, false)); } } if (!otherTypes.isEmpty()) { getImplementor().onObject(arguments, _if._else(), false); } } }
Example #24
Source File: EvaluationVisitor.java From Bats with Apache License 2.0 | 4 votes |
private HoldingContainer visitBooleanOr(BooleanOperator op, ClassGenerator<?> generator) { HoldingContainer out = generator.declare(op.getMajorType()); JLabel label = generator.getEvalBlockLabel("OrOP"); JBlock eval = generator.createInnerEvalBlock(); generator.nestEvalBlock(eval); // enter into nested block. HoldingContainer arg = null; JExpression e = null; // value of boolean "or" when one side is null // p q p and q // true null true // false null null // null true true // null false null // null null null for (int i = 0; i < op.args.size(); i++) { arg = op.args.get(i).accept(this, generator); JBlock earlyExit = null; if (arg.isOptional()) { earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().eq(JExpr.lit(1))))._then(); if (e == null) { e = arg.getIsSet(); } else { e = e.mul(arg.getIsSet()); } } else { earlyExit = eval._if(arg.getValue().eq(JExpr.lit(1)))._then(); } if (out.isOptional()) { earlyExit.assign(out.getIsSet(), JExpr.lit(1)); } earlyExit.assign(out.getValue(), JExpr.lit(1)); earlyExit._break(label); } if (out.isOptional()) { assert (e != null); JConditional notSetJC = eval._if(e.eq(JExpr.lit(0))); notSetJC._then().assign(out.getIsSet(), JExpr.lit(0)); JBlock setBlock = notSetJC._else().block(); setBlock.assign(out.getIsSet(), JExpr.lit(1)); setBlock.assign(out.getValue(), JExpr.lit(0)); } else { assert (e == null); eval.assign(out.getValue(), JExpr.lit(0)); } generator.unNestEvalBlock(); // exit from nested block. return out; }
Example #25
Source File: EvaluationVisitor.java From Bats with Apache License 2.0 | 4 votes |
private HoldingContainer visitBooleanAnd(BooleanOperator op, ClassGenerator<?> generator) { HoldingContainer out = generator.declare(op.getMajorType()); JLabel label = generator.getEvalBlockLabel("AndOP"); JBlock eval = generator.createInnerEvalBlock(); generator.nestEvalBlock(eval); // enter into nested block HoldingContainer arg = null; JExpression e = null; // value of boolean "and" when one side is null // p q p and q // true null null // false null false // null true null // null false false // null null null for (int i = 0; i < op.args.size(); i++) { arg = op.args.get(i).accept(this, generator); JBlock earlyExit = null; if (arg.isOptional()) { earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then(); if (e == null) { e = arg.getIsSet(); } else { e = e.mul(arg.getIsSet()); } } else { earlyExit = eval._if(arg.getValue().ne(JExpr.lit(1)))._then(); } if (out.isOptional()) { earlyExit.assign(out.getIsSet(), JExpr.lit(1)); } earlyExit.assign(out.getValue(), JExpr.lit(0)); earlyExit._break(label); } if (out.isOptional()) { assert (e != null); JConditional notSetJC = eval._if(e.eq(JExpr.lit(0))); notSetJC._then().assign(out.getIsSet(), JExpr.lit(0)); JBlock setBlock = notSetJC._else().block(); setBlock.assign(out.getIsSet(), JExpr.lit(1)); setBlock.assign(out.getValue(), JExpr.lit(1)); } else { assert (e == null); eval.assign(out.getValue(), JExpr.lit(1)); } generator.unNestEvalBlock(); // exit from nested block return out; }
Example #26
Source File: PluginContext.java From jaxb2-rich-contract-plugin with MIT License | 4 votes |
public JForEach loop(final JBlock block, final JExpression source, final JType sourceElementType, final JAssignmentTarget target, final JType targetElementType) { final JConditional ifNull = block._if(source.eq(JExpr._null())); ifNull._then().assign(target, JExpr._null()); ifNull._else().assign(target, JExpr._new(this.arrayListClass.narrow(targetElementType))); return ifNull._else().forEach(sourceElementType, "_item", source); }
Example #27
Source File: MergeSortWrapper.java From Bats with Apache License 2.0 | 4 votes |
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); }
Example #28
Source File: BuilderGenerator.java From jaxb2-rich-contract-plugin with MIT License | 4 votes |
private void generateAddMethods(final PropertyOutline propertyOutline, final QName elementName, final JType jType, final String schemaAnnotation) { final JClass elementType = jType.boxify(); final JClass iterableType = this.pluginContext.iterableClass.narrow(elementType.wildcard()); final String fieldName = this.pluginContext.toVariableName(elementName.getLocalPart()); final String propertyName = this.pluginContext.toPropertyName(elementName.getLocalPart()); final JMethod addIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName); final JVar addIterableParam = addIterableMethod.param(JMod.FINAL, iterableType, fieldName + "_"); generateAddMethodJavadoc(addIterableMethod, addIterableParam, schemaAnnotation); final JMethod addVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName); final JVar addVarargsParam = addVarargsMethod.varParam(elementType, fieldName + "_"); generateAddMethodJavadoc(addVarargsMethod, addVarargsParam, schemaAnnotation); final BuilderOutline childBuilderOutline = getBuilderDeclaration(elementType); final JMethod addMethod; if (childBuilderOutline != null && !childBuilderOutline.getClassOutline().getImplClass().isAbstract()) { final JClass builderWithMethodReturnType = childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard()); addMethod = this.builderClass.raw.method(JMod.PUBLIC, builderWithMethodReturnType, PluginContext.ADD_METHOD_PREFIX + propertyName); generateBuilderMethodJavadoc(addMethod, "add", fieldName, schemaAnnotation); } else { addMethod = null; } if (this.implement) { final BuilderOutline choiceChildBuilderOutline = getBuilderDeclaration(propertyOutline.getElementType()); final JClass childBuilderType = childBuilderOutline == null ? this.pluginContext.buildableInterface : childBuilderOutline.getBuilderClass().narrow(this.builderClass.type); final JClass builderFieldElementType = choiceChildBuilderOutline == null ? this.pluginContext.buildableInterface : choiceChildBuilderOutline.getBuilderClass().narrow(this.builderClass.type); final JClass builderArrayListClass = this.pluginContext.arrayListClass.narrow(builderFieldElementType); final JFieldVar builderField = this.builderClass.raw.fields().get(propertyOutline.getFieldName()); addVarargsMethod.body()._return(JExpr.invoke(addIterableMethod).arg(this.pluginContext.asList(addVarargsParam))); if (addMethod == null) { addIterableMethod.body()._return(JExpr.invoke(PluginContext.ADD_METHOD_PREFIX + propertyOutline.getBaseName()).arg(addIterableParam)); } else { final JConditional addIterableIfParamNull = addIterableMethod.body()._if(addIterableParam.ne(JExpr._null())); final JConditional addIterableIfNull = addIterableIfParamNull._then()._if(JExpr._this().ref(builderField).eq(JExpr._null())); addIterableIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass)); final JForEach addIterableForEach = addIterableIfParamNull._then().forEach(elementType, BuilderGenerator.ITEM_VAR_NAME, addIterableParam); final JExpression builderCreationExpression = JExpr._new(childBuilderType).arg(JExpr._this()).arg(addIterableForEach.var()).arg(this.settings.isCopyAlways() ? JExpr.TRUE : JExpr.FALSE); addIterableForEach.body().add(JExpr._this().ref(builderField).invoke("add").arg(builderCreationExpression)); addIterableMethod.body()._return(JExpr._this()); final JConditional addIfNull = addMethod.body()._if(JExpr._this().ref(builderField).eq(JExpr._null())); addIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass)); final JVar childBuilderVar = addMethod.body().decl(JMod.FINAL, childBuilderType, fieldName + this.settings.getBuilderFieldSuffix(), JExpr._new(childBuilderType).arg(JExpr._this()).arg(JExpr._null()).arg(JExpr.FALSE)); addMethod.body().add(JExpr._this().ref(builderField).invoke("add").arg(childBuilderVar)); addMethod.body()._return(childBuilderVar); } } }
Example #29
Source File: DrillSimpleFuncHolder.java From Bats with Apache License 2.0 | 4 votes |
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars, FieldReference ref) { g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", getRegisteredNames()[0])); JBlock sub = new JBlock(true, true); JBlock topSub = sub; HoldingContainer out = null; MajorType returnValueType = getReturnType(); // add outside null handling if it is defined. if (getNullHandling() == NullHandling.NULL_IF_NULL) { JExpression e = null; for (HoldingContainer v : inputVariables) { if (v.isOptional()) { JExpression isNullExpr; if (v.isReader()) { isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0)); } else { isNullExpr = v.getIsSet(); } if (e == null) { e = isNullExpr; } else { e = e.mul(isNullExpr); } } } if (e != null) { // if at least one expression must be checked, set up the conditional. returnValueType = getReturnType().toBuilder().setMode(DataMode.OPTIONAL).build(); out = g.declare(returnValueType); e = e.eq(JExpr.lit(0)); JConditional jc = sub._if(e); jc._then().assign(out.getIsSet(), JExpr.lit(0)); sub = jc._else(); } } if (out == null) { out = g.declare(returnValueType); } // add the subblock after the out declaration. g.getEvalBlock().add(topSub); JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValueType), getReturnValue().getName(), JExpr._new(g.getHolderType(returnValueType))); addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false); 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; }
Example #30
Source File: BuilderGenerator.java From jaxb2-rich-contract-plugin with MIT License | 4 votes |
JForEach loop(final JBlock block, final JExpression source, final JType sourceElementType, final JAssignmentTarget target, final JType targetElementType) { final JConditional ifNull = block._if(source.eq(JExpr._null())); ifNull._then().assign(target, JExpr._null()); ifNull._else().assign(target, JExpr._new(this.pluginContext.arrayListClass.narrow(targetElementType))); return ifNull._else().forEach(sourceElementType, BuilderGenerator.ITEM_VAR_NAME, source); }