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); }
private JInvocation getUDFInstance(JCodeModel m) { if (isGenericUDF) { return JExpr._new(m.directClass(genericUdfClazz.getCanonicalName())); } else { return JExpr._new(m.directClass(GenericUDFBridge.class.getCanonicalName())) .arg(JExpr.lit(udfName)) .arg(JExpr.lit(false)) .arg(JExpr.lit(udfClazz.getCanonicalName().toString())); } }
/** * Creates a default value for a list property by: * <ol> * <li>Creating a new {@link ArrayList} with the correct generic type * <li>Using {@link Arrays#asList(Object...)} to initialize the list with * the correct default values * </ol> * * @param fieldType * the java type that applies for this field ({@link List} with * some generic type argument) * @param node * the node containing default values for this list * @return an expression that creates a default value that can be assigned * to this field */ private JExpression getDefaultList(JType fieldType, JsonNode node) { JClass listGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass listImplClass = fieldType.owner().ref(ArrayList.class); listImplClass = listImplClass.narrow(listGenericType); JInvocation newListImpl = JExpr._new(listImplClass); if (node instanceof ArrayNode && node.size() > 0) { JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList"); for (JsonNode defaultValue : node) { invokeAsList.arg(getDefaultValue(listGenericType, defaultValue)); } newListImpl.arg(invokeAsList); } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) { return JExpr._null(); } return newListImpl; }
/** * setup comparison functions isSamePartition and isPeer */ private void setupIsFunction(final ClassGenerator<WindowFramer> cg, final Iterable<LogicalExpression> exprs, final MappingSet leftMapping, final MappingSet rightMapping) { cg.setMappingSet(leftMapping); for (LogicalExpression expr : exprs) { if (expr == null) { continue; } cg.setMappingSet(leftMapping); ClassGenerator.HoldingContainer first = cg.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE); cg.setMappingSet(rightMapping); ClassGenerator.HoldingContainer second = cg.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE); final LogicalExpression fh = FunctionGenerationHelper .getOrderingComparatorNullsHigh(first, second, context.getClassProducer()); final ClassGenerator.HoldingContainer out = cg.addExpr(fh, ClassGenerator.BlockCreateMode.MERGE); cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); } cg.getEvalBlock()._return(JExpr.TRUE); }
private void addToString(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString"); Set<String> excludes = new HashSet<String>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes())); JBlock body = toString.body(); Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class; JClass toStringBuilderClass = jclass.owner().ref(toStringBuilder); JInvocation toStringBuilderInvocation = JExpr._new(toStringBuilderClass).arg(JExpr._this()); if (!jclass._extends().fullName().equals(Object.class.getName())) { toStringBuilderInvocation = toStringBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("toString")); } for (JFieldVar fieldVar : fields.values()) { if (excludes.contains(fieldVar.name()) || (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } toStringBuilderInvocation = toStringBuilderInvocation.invoke("append").arg(fieldVar.name()).arg(fieldVar); } body._return(toStringBuilderInvocation.invoke("toString")); toString.annotate(Override.class); }
/** * @return A list of the class level annotations that the annotator will * use. */ private List<MetaAnnotation> buildClassAnnotations() { List<MetaAnnotation> anns = Lists.newArrayList(); HashMap<String, Object> annotParams; // AlwaysValid JDefinedClass alwaysValid = buildTemplateConstraint("AlwaysValid"); JDefinedClass alwaysValidValidator = buildTemplateConstraintValidator("AlwaysValidValidator", alwaysValid, Object.class); JMethod isValid = getIsValidMethod(alwaysValidValidator); isValid.body()._return(JExpr.TRUE); alwaysValid.annotate(Constraint.class).param("validatedBy", alwaysValidValidator); annotParams = Maps.newHashMap(); anns.add(new MetaAnnotation(alwaysValid, AnnotationType.JSR_303, annotParams)); return anns; }
/** * Recursive method that handles the creation of reference beans at * different depth levels. * * @param mjb * The target bean to create an instance of. * @param body * The current block of code. * @param level * The current depth level. * @return A generated variable referencing the created bean. */ private JVar generateBeanNonStaticInitCode(MetaJavaBean mjb, JBlock body, int level) { JVar beanDecl = body.decl(mjb.getGeneratedClass(), "lvl" + level + mjb.getName() + "_" + Config.CFG.nextUniqueNum()); body.assign(beanDecl, JExpr._new(mjb.getGeneratedClass())); for (AbstractMetaField amf : mjb.getFields()) { if (amf instanceof JavaBeanRefField) { JavaBeanRefField jbrf = (JavaBeanRefField) amf; // Should a nested bean be created? if (Config.CFG.shouldAddNestedBean(level)) { JVar nestedBeanDecl = generateBeanNonStaticInitCode(jbrf.getRefBean(), body, level + 1); jbrf.generateAssignCode(body, beanDecl, nestedBeanDecl); } } } return beanDecl; }
/** * Creates a random MetaField * * @param owner * The class that owns this field. * @param name * The name of the meta field. */ public JavaBeanBasicField(MetaJavaBean owner, String name) { super(owner, name); this.basicType = BasicType.getRandom(); // Generate the field declaration JDefinedClass ownerClass = owner.getGeneratedClass(); this.generatedField = ownerClass.field(JMod.PRIVATE, basicType.getTypeClass(), name); // The getter getter = ownerClass.method(JMod.PUBLIC, basicType.getTypeClass(), "get" + name.substring(0, 1).toUpperCase() + name.substring(1)); getter.body()._return(this.generatedField); // And the setter setter = ownerClass.method(JMod.PUBLIC, void.class, "set" + name.substring(0, 1).toUpperCase() + name.substring(1)); JVar setterParam = setter.param(basicType.getTypeClass(), name); setter.body().assign(JExpr._this().ref(this.generatedField), setterParam); }
public JavaBeanRefField(MetaJavaBean owner, String name, MetaJavaBean refBean) { super(owner, name); this.refBean = refBean; // Generate the field declaration JDefinedClass ownerClass = owner.getGeneratedClass(); this.generatedField = ownerClass.field(JMod.PRIVATE, refBean.getGeneratedClass(), name); // The getter getter = ownerClass.method(JMod.PUBLIC, refBean.getGeneratedClass(), "get"+name.substring(0, 1).toUpperCase()+name.substring(1)); getter.body()._return(this.generatedField); // The setter setter = ownerClass.method(JMod.PUBLIC, void.class, "set"+name.substring(0, 1).toUpperCase()+name.substring(1)); JVar setterParam = setter.param(refBean.getGeneratedClass(), name); setter.body().assign(JExpr._this().ref(this.generatedField), setterParam); }
private void setupIsSame(ClassGenerator<StreamingAggregator> cg, LogicalExpression[] keyExprs) { cg.setMappingSet(IS_SAME_I1); for (final LogicalExpression expr : keyExprs) { // first, we rewrite the evaluation stack for each side of the comparison. cg.setMappingSet(IS_SAME_I1); final HoldingContainer first = cg.addExpr(expr, false); cg.setMappingSet(IS_SAME_I2); final HoldingContainer second = cg.addExpr(expr, false); final LogicalExpression fh = FunctionGenerationHelper .getOrderingComparatorNullsHigh(first, second, context.getFunctionRegistry()); final HoldingContainer out = cg.addExpr(fh, false); cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); } cg.getEvalBlock()._return(JExpr.TRUE); }
private void setupIsSameApart(ClassGenerator<StreamingAggregator> cg, LogicalExpression[] keyExprs) { cg.setMappingSet(ISA_B1); for (final LogicalExpression expr : keyExprs) { // first, we rewrite the evaluation stack for each side of the comparison. cg.setMappingSet(ISA_B1); final HoldingContainer first = cg.addExpr(expr, false); cg.setMappingSet(ISA_B2); final HoldingContainer second = cg.addExpr(expr, false); final LogicalExpression fh = FunctionGenerationHelper .getOrderingComparatorNullsHigh(first, second, context.getFunctionRegistry()); final HoldingContainer out = cg.addExpr(fh, false); cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); } cg.getEvalBlock()._return(JExpr.TRUE); }
@Override void generateCode(ClassGenerator<WindowFramer> cg) { final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup"); final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping); cg.setMappingSet(mappingSet); final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId); final JExpression outIndex = cg.getMappingSet().getValueWriteIndex(); JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex) .arg(JExpr.direct("partition.ntile(" + numTiles + ")")); cg.getEvalBlock().add(setMethod); }
/** * setup comparison functions isSamePartition and isPeer */ private void setupIsFunction(final ClassGenerator<WindowFramer> cg, final List<LogicalExpression> exprs, final MappingSet leftMapping, final MappingSet rightMapping) { cg.setMappingSet(leftMapping); for (LogicalExpression expr : exprs) { if (expr == null) { continue; } cg.setMappingSet(leftMapping); ClassGenerator.HoldingContainer first = cg.addExpr(expr, false); cg.setMappingSet(rightMapping); ClassGenerator.HoldingContainer second = cg.addExpr(expr, false); final LogicalExpression fh = FunctionGenerationHelper .getOrderingComparatorNullsHigh(first, second, context.getFunctionRegistry()); final ClassGenerator.HoldingContainer out = cg.addExpr(fh, false); cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); } cg.getEvalBlock()._return(JExpr.TRUE); }
private void setupGetHash(ClassGenerator<HashTable> cg, MappingSet incomingMapping, VectorAccessible batch, LogicalExpression[] keyExprs, boolean isProbe) throws SchemaChangeException { cg.setMappingSet(incomingMapping); if (keyExprs == null || keyExprs.length == 0) { cg.getEvalBlock()._return(JExpr.lit(0)); return; } /* * We use the same logic to generate run time code for the hash function both for hash join and hash * aggregate. For join we need to hash everything as double (both for distribution and for comparison) but * for aggregation we can avoid the penalty of casting to double */ LogicalExpression hashExpression = HashPrelUtil.getHashExpression(Arrays.asList(keyExprs), incomingProbe != null ? true : false); final LogicalExpression materializedExpr = ExpressionTreeMaterializer.materializeAndCheckErrors(hashExpression, batch, context.getFunctionRegistry()); HoldingContainer hash = cg.addExpr(materializedExpr); cg.getEvalBlock()._return(hash.getValue()); }
private void codeGenGetVectorIndex(ClassGenerator<StreamingAggregator> g) { switch (onDeckInput.getSchema().getSelectionVectorMode()) { case FOUR_BYTE: { throw new UnsupportedOperationException(); } case NONE: { g.getBlock("getVectorIndex")._return(JExpr.direct("recordIndex"));; return; } case TWO_BYTE: { throw new UnsupportedOperationException(); // this does't work since the we would need to move between ondeck and atbat // JVar var = g.declareClassField("sv2_", g.getModel()._ref(SelectionVector2.class)); // g.getBlock("setup").assign(var, JExpr.direct("incoming").invoke("getSelectionVector2")); // g.getBlock("getVectorIndex")._return(var.invoke("getIndex").arg(JExpr.direct("recordIndex")));; // return; } default: throw new IllegalStateException(); } }
@Override public HoldingContainer visitDecimal9Constant(Decimal9Expression e, ClassGenerator<?> generator) throws RuntimeException { MajorType majorType = e.getMajorType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = generator.getHolderType(majorType); JVar var = generator.declareClassField("dec9", holderType); JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal9Holder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, null, null); }
@Override public HoldingContainer visitDecimal18Constant(Decimal18Expression e, ClassGenerator<?> generator) throws RuntimeException { MajorType majorType = e.getMajorType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = generator.getHolderType(majorType); JVar var = generator.declareClassField("dec18", holderType); JExpression valueLiteral = JExpr.lit(e.getLongFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal18Holder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, null, null); }
@Override public HoldingContainer renderEnd(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) { HoldingContainer out = g.declare(returnValue.type, false); JBlock sub = new JBlock(); g.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValue.type), returnValue.name, JExpr._new(g.getHolderType(returnValue.type))); addProtectedBlock(g, sub, output, null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!g.getMappingSet().isHashAggMapping()) { generateBody(g, BlockType.RESET, reset, null, workspaceJVars, false); } generateBody(g, BlockType.CLEANUP, cleanup, null, workspaceJVars, false); return out; }
private void setupGetHash(ClassGenerator<HashTable> cg, MappingSet incomingMapping, VectorAccessible batch, LogicalExpression[] keyExprs, boolean isProbe) throws SchemaChangeException { cg.setMappingSet(incomingMapping); if (keyExprs == null || keyExprs.length == 0) { cg.getEvalBlock()._return(JExpr.lit(0)); return; } /* * We use the same logic to generate run time code for the hash function both for hash join and hash * aggregate. */ LogicalExpression hashExpression = HashPrelUtil.getHashExpression(Arrays.asList(keyExprs)); final LogicalExpression materializedExpr = producer.materialize(hashExpression, batch); HoldingContainer hash = cg.addExpr(materializedExpr); cg.getEvalBlock()._return(hash.getValue()); }
@Override public HoldingContainer visitDecimalConstant(DecimalExpression e, ClassGenerator<?> generator) throws RuntimeException { CompleteType majorType= e.getCompleteType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = majorType.getHolderType(generator.getModel()); JVar var = generator.declareClassField("dec", holderType); JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getNullableDecimalHolder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, var.ref("value"), var.ref("isSet")); }
@Override public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[] workspaceJVars) { HoldingContainer out = g.declare(resolvedOutput, false); JBlock sub = new JBlock(); g.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, resolvedOutput.getHolderType(g.getModel()), getReturnName(), JExpr._new(resolvedOutput.getHolderType(g.getModel()))); addProtectedBlock(g, sub, output(), null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!g.getMappingSet().isHashAggMapping()) { generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false); } generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false); return out; }
private JVar[] declareWorkspaceVectors(ClassGenerator<?> g) { JVar[] workspaceJVars = new JVar[workspaceVars.length]; for(int i =0 ; i < workspaceVars.length; i++){ if (workspaceVars[i].isInject() == true) { workspaceJVars[i] = g.declareClassField("work", g.getModel()._ref(workspaceVars[i].type)); g.getBlock(BlockType.SETUP).assign(workspaceJVars[i], JExpr.direct("context").invoke("getManagedBuffer")); } else { Preconditions.checkState(workspaceVars[i].completeType.isFixedWidthScalar(), "Workspace variable '%s' in aggregation function '%s' is not allowed to have variable length type.", workspaceVars[i].name, registeredNames[0]); //workspaceJVars[i] = g.declareClassField("work", g.getHolderType(workspaceVars[i].majorType), JExpr._new(g.getHolderType(workspaceVars[i].majorType))); workspaceJVars[i] = g.declareClassField("work", workspaceVars[i].completeType.getHolderType(g.getModel())); //Declare a workspace vector for the workspace var. TypedFieldId typedFieldId = new TypedFieldId(workspaceVars[i].completeType, g.getWorkspaceTypes().size()); JVar vv = g.declareVectorValueSetupAndMember(g.getMappingSet().getWorkspace(), typedFieldId); g.getWorkspaceTypes().add(typedFieldId); g.getWorkspaceVectors().put(workspaceVars[i], vv); } } return workspaceJVars; }
private JFieldVar addValueField(JDefinedClass _enum, JType type) { JFieldVar valueField = _enum.field(JMod.PRIVATE | JMod.FINAL, type, VALUE_FIELD_NAME); JMethod constructor = _enum.constructor(JMod.PRIVATE); JVar valueParam = constructor.param(type, VALUE_FIELD_NAME); JBlock body = constructor.body(); body.assign(JExpr._this().ref(valueField), valueParam); return valueField; }
private void addToString(JDefinedClass _enum, JFieldVar valueField) { JMethod toString = _enum.method(JMod.PUBLIC, String.class, "toString"); JBlock body = toString.body(); JExpression toReturn = JExpr._this().ref(valueField); if(!isString(valueField.type())){ toReturn = toReturn.plus(JExpr.lit("")); } body._return(toReturn); toString.annotate(Override.class); }
private void addValueMethod(JDefinedClass _enum, JFieldVar valueField) { JMethod fromValue = _enum.method(JMod.PUBLIC, valueField.type(), "value"); JBlock body = fromValue.body(); body._return(JExpr._this().ref(valueField)); ruleFactory.getAnnotator().enumValueMethod(fromValue); }
private void codeGenAtBat(ClassGenerator<StreamingAggregator> cg, LogicalExpression[] keyExprs, LogicalExpression[] valueExprs) { // public abstract void setupAtBat(@Named("atBat") VectorAccessible atBat, @Named("output") VectorAccessible output); // public abstract boolean compareAtBat(@Named("index1") int index1, @Named("index2") int index2); final GeneratorMapping compareAtBat = GeneratorMapping.create("setupAtBat", "compareAtBat", null, null); final MappingSet index1 = new MappingSet("index1", "--na--", "atBat", "--na--", compareAtBat, compareAtBat); final MappingSet index2 = new MappingSet("index2", "--na--", "atBat", "--na--", compareAtBat, compareAtBat); cg.setMappingSet(index1); for (final LogicalExpression expr : keyExprs) { // first, we rewrite the evaluation stack for each side of the comparison. cg.setMappingSet(index1); final HoldingContainer first = cg.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE); cg.setMappingSet(index2); final HoldingContainer second = cg.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE); final LogicalExpression fh = FunctionGenerationHelper.getOrderingComparatorNullsHigh(first, second, context.getClassProducer()); final HoldingContainer out = cg.addExpr(fh, ClassGenerator.BlockCreateMode.MERGE); cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); } cg.getEvalBlock()._return(JExpr.TRUE); // public abstract void addAtBatRecord(@Named("atBatIndex") int index); // public abstract void outputAggregation(@Named("outIndex") int outputIndex); final GeneratorMapping evalInside = GeneratorMapping.create("setupAtBat", "addAtBatRecord", null, null); final GeneratorMapping evalOutside = GeneratorMapping.create("setupAtBat", "outputAggregation", "resetValues", "close"); final MappingSet eval = new MappingSet("atBatIndex", "outputIndex", "atBat", "output", evalInside, evalOutside, evalInside); cg.setMappingSet(eval); for (final LogicalExpression ex : valueExprs) { cg.addExpr(ex); } }
private void codeGenOnDeck(ClassGenerator<StreamingAggregator> cg, LogicalExpression[] keyExprs, LogicalExpression[] valueExprs) { // Methods associated with onDeck data. // public abstract void setupOnDeck(@Named("onDeck") VectorAccessible onDeck, @Named("atBat") VectorAccessible atBat, @Named("output") VectorAccessible output); // public abstract boolean compareOnDeckAndAtBat(@Named("onDeckIndex") int onDeckIndex, @Named("atBatIndex") int atBatIndex); final GeneratorMapping compareOnDeck = GeneratorMapping.create("setupOnDeck", "compareOnDeckAndAtBat", null, null); final MappingSet index1 = new MappingSet("onDeckIndex", "--na--", "onDeck", "--na--", compareOnDeck, compareOnDeck); final MappingSet index2 = new MappingSet("atBatIndex", "--na--", "atBat", "--na--", compareOnDeck, compareOnDeck); cg.setMappingSet(index1); for (final LogicalExpression expr : keyExprs) { // first, we rewrite the evaluation stack for each side of the comparison. cg.setMappingSet(index1); final HoldingContainer first = cg.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE); cg.setMappingSet(index2); final HoldingContainer second = cg.addExpr(expr, ClassGenerator.BlockCreateMode.MERGE); final LogicalExpression fh = FunctionGenerationHelper.getOrderingComparatorNullsHigh(first, second, context.getClassProducer()); final HoldingContainer out = cg.addExpr(fh, ClassGenerator.BlockCreateMode.MERGE); cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); } cg.getEvalBlock()._return(JExpr.TRUE); }
private void addOverrideBuilder(JDefinedClass thisJDefinedClass, JMethod parentBuilder, JVar parentParam) { if (thisJDefinedClass.getMethod(parentBuilder.name(), new JType[] {parentParam.type()}) == null) { JMethod builder = thisJDefinedClass.method(parentBuilder.mods().getValue(), thisJDefinedClass, parentBuilder.name()); builder.annotate(Override.class); JVar param = builder.param(parentParam.type(), parentParam.name()); JBlock body = builder.body(); body.invoke(JExpr._super(), parentBuilder).arg(param); body._return(JExpr._this()); } }
private void addSetter(JDefinedClass jclass, JType propertyType, JFieldVar field) { JMethod setter = jclass.method(JMod.PUBLIC, void.class, "setAdditionalProperty"); ruleFactory.getAnnotator().anySetter(setter); JVar nameParam = setter.param(String.class, "name"); JVar valueParam = setter.param(propertyType, "value"); JInvocation mapInvocation = setter.body().invoke(JExpr._this().ref(field), "put"); mapInvocation.arg(nameParam); mapInvocation.arg(valueParam); }
private JMethod addGetter(JDefinedClass jclass, JFieldVar field) { JMethod getter = jclass.method(JMod.PUBLIC, field.type(), "getAdditionalProperties"); ruleFactory.getAnnotator().anyGetter(getter); getter.body()._return(JExpr._this().ref(field)); return getter; }
private void addBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) { JMethod builder = jclass.method(JMod.PUBLIC, jclass, "withAdditionalProperty"); JVar nameParam = builder.param(String.class, "name"); JVar valueParam = builder.param(propertyType, "value"); JBlock body = builder.body(); JInvocation mapInvocation = body.invoke(JExpr._this().ref(field), "put"); mapInvocation.arg(nameParam); mapInvocation.arg(valueParam); body._return(JExpr._this()); }
private void addEquals(JDefinedClass jclass, JsonNode node) { Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node); JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); Class<?> equalsBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.EqualsBuilder.class : org.apache.commons.lang.builder.EqualsBuilder.class; JBlock body = equals.body(); body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE); body._if(otherObject._instanceof(jclass).eq(JExpr.FALSE))._then()._return(JExpr.FALSE); JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject)); JClass equalsBuilderClass = jclass.owner().ref(equalsBuilder); JInvocation equalsBuilderInvocation = JExpr._new(equalsBuilderClass); if (!jclass._extends().fullName().equals(Object.class.getName())) { equalsBuilderInvocation = equalsBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("equals").arg(otherObject)); } for (JFieldVar fieldVar : fields.values()) { if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } equalsBuilderInvocation = equalsBuilderInvocation.invoke("append") .arg(fieldVar) .arg(rhsVar.ref(fieldVar.name())); } JInvocation reflectionEquals = jclass.owner().ref(equalsBuilder).staticInvoke("reflectionEquals"); reflectionEquals.arg(JExpr._this()); reflectionEquals.arg(otherObject); body._return(equalsBuilderInvocation.invoke("isEquals")); equals.annotate(Override.class); }
/** * Calls the correct {@link JExpr} <code>lit</code> method. * * @param value * The literal value that must be output in an expresion. * @return The matching expression for the real type of value. */ public static JExpression literalExpr(Object value) { if (value == null) { return JExpr._null(); } else if (value instanceof String) { return JExpr.lit((String) value); } else if (value instanceof Integer) { return JExpr.lit((Integer) value); } throw new RuntimeException("Impossible to construct initial value for: " + value); }
/** * Generates a Holder class that will hold an {@link ArrayList} with all the * first level beans in the graph (contents of {@link #beans}) on it. */ private void generatePopulationCode() { try { // Generate the holder class JDefinedClass holderClass = cm._class(Config.CFG.getBasePackageName() + ".Holder"); JClass alObject = (JClass) cm._ref(ArrayList.class); alObject = alObject.narrow(Object.class); JFieldVar beansField = holderClass.field(JMod.PUBLIC, alObject, "beans", JExpr._new(alObject)); JMethod defConstructor = holderClass.constructor(JMod.PUBLIC); JBlock body = defConstructor.body(); // Init the beans and add them to the array for (MetaJavaBean mjb : beans) { mjb.generateStaticInitCode(); JVar beanDecl = generateBeanNonStaticInitCode(mjb, body, 0); body.add(beansField.invoke("add").arg(beanDecl)); } // Init the base beans but don't add them to the array for (MetaJavaBean bmjb : baseBeans) { bmjb.generateStaticInitCode(); } } catch (JClassAlreadyExistsException e) { throw new RuntimeException("Error generating the holder class.", e); } }
public static void generateCopies(ClassGenerator g, VectorAccessible batch, boolean hyper){ // we have parallel ids for each value vector so we don't actually have to deal with managing the ids at all. int fieldId = 0; JExpression inIndex = JExpr.direct("inIndex"); JExpression outIndex = JExpr.direct("outIndex"); for(VectorWrapper<?> vv : batch) { String copyMethod; if (!Types.isFixedWidthType(vv.getField().getType()) || Types.isRepeated(vv.getField().getType()) || Types.isComplex(vv.getField().getType())) { copyMethod = "copyFromSafe"; } else { copyMethod = "copyFrom"; } g.rotateBlock(); JVar inVV = g.declareVectorValueSetupAndMember("incoming", new TypedFieldId(vv.getField().getType(), vv.isHyper(), fieldId)); JVar outVV = g.declareVectorValueSetupAndMember("outgoing", new TypedFieldId(vv.getField().getType(), false, fieldId)); if(hyper){ g.getEvalBlock().add( outVV .invoke(copyMethod) .arg( inIndex.band(JExpr.lit((int) Character.MAX_VALUE))) .arg(outIndex) .arg( inVV.component(inIndex.shrz(JExpr.lit(16))) ) ); }else{ g.getEvalBlock().add(outVV.invoke(copyMethod).arg(inIndex).arg(outIndex).arg(inVV)); } g.rotateBlock(); fieldId++; } }
private List<Partitioner> createClassInstances(int actualPartitions) throws SchemaChangeException { // set up partitioning function final LogicalExpression expr = operator.getExpr(); final ErrorCollector collector = new ErrorCollectorImpl(); final ClassGenerator<Partitioner> cg ; cg = CodeGenerator.getRoot(Partitioner.TEMPLATE_DEFINITION, context.getFunctionRegistry()); ClassGenerator<Partitioner> cgInner = cg.getInnerGenerator("OutgoingRecordBatch"); final LogicalExpression materializedExpr = ExpressionTreeMaterializer.materialize(expr, incoming, collector, context.getFunctionRegistry()); if (collector.hasErrors()) { throw new SchemaChangeException(String.format( "Failure while trying to materialize incoming schema. Errors:\n %s.", collector.toErrorString())); } // generate code to copy from an incoming value vector to the destination partition's outgoing value vector JExpression bucket = JExpr.direct("bucket"); // generate evaluate expression to determine the hash ClassGenerator.HoldingContainer exprHolder = cg.addExpr(materializedExpr); cg.getEvalBlock().decl(JType.parse(cg.getModel(), "int"), "bucket", exprHolder.getValue().mod(JExpr.lit(outGoingBatchCount))); cg.getEvalBlock()._return(cg.getModel().ref(Math.class).staticInvoke("abs").arg(bucket)); CopyUtil.generateCopies(cgInner, incoming, incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.FOUR_BYTE); try { // compile and setup generated code List<Partitioner> subPartitioners = context.getImplementationClass(cg, actualPartitions); return subPartitioners; } catch (ClassTransformationException | IOException e) { throw new SchemaChangeException("Failure while attempting to load generated class", e); } }
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)); }
@Override void generateCode(ClassGenerator<WindowFramer> cg) { final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup"); final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping); cg.setMappingSet(mappingSet); final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId); final JExpression outIndex = cg.getMappingSet().getValueWriteIndex(); JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex).arg(JExpr.direct("partition." + getName())); cg.getEvalBlock().add(setMethod); }
private WindowFramer generateFramer(final List<LogicalExpression> keyExprs, final List<LogicalExpression> orderExprs, final List<WindowFunction> functions) throws IOException, ClassTransformationException { final ClassGenerator<WindowFramer> cg = CodeGenerator.getRoot(WindowFramer.TEMPLATE_DEFINITION, context.getFunctionRegistry()); { // generating framer.isSamePartition() final GeneratorMapping IS_SAME_PARTITION_READ = GeneratorMapping.create("isSamePartition", "isSamePartition", null, null); final MappingSet isaB1 = new MappingSet("b1Index", null, "b1", null, IS_SAME_PARTITION_READ, IS_SAME_PARTITION_READ); final MappingSet isaB2 = new MappingSet("b2Index", null, "b2", null, IS_SAME_PARTITION_READ, IS_SAME_PARTITION_READ); setupIsFunction(cg, keyExprs, isaB1, isaB2); } { // generating framer.isPeer() final GeneratorMapping IS_SAME_PEER_READ = GeneratorMapping.create("isPeer", "isPeer", null, null); final MappingSet isaP1 = new MappingSet("b1Index", null, "b1", null, IS_SAME_PEER_READ, IS_SAME_PEER_READ); final MappingSet isaP2 = new MappingSet("b2Index", null, "b2", null, IS_SAME_PEER_READ, IS_SAME_PEER_READ); setupIsFunction(cg, orderExprs, isaP1, isaP2); } for (final WindowFunction function : functions) { function.generateCode(cg); } cg.getBlock("resetValues")._return(JExpr.TRUE); return context.getImplementationClass(cg); }