/** * Creates a default value for a set property by: * <ol> * <li>Creating a new {@link LinkedHashSet} with the correct generic type * <li>Using {@link Arrays#asList(Object...)} to initialize the set with the * correct default values * </ol> * * @param fieldType * the java type that applies for this field ({@link Set} with * some generic type argument) * @param node * the node containing default values for this set * @return an expression that creates a default value that can be assigned * to this field */ private JExpression getDefaultSet(JType fieldType, JsonNode node) { JClass setGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass setImplClass = fieldType.owner().ref(LinkedHashSet.class); setImplClass = setImplClass.narrow(setGenericType); JInvocation newSetImpl = JExpr._new(setImplClass); if (node instanceof ArrayNode && node.size() > 0) { JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList"); for (JsonNode defaultValue : node) { invokeAsList.arg(getDefaultValue(setGenericType, defaultValue)); } newSetImpl.arg(invokeAsList); } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) { return JExpr._null(); } return newSetImpl; }
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); }
/** * 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; }
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); }
private void addHashCode(JDefinedClass jclass, JsonNode node) { Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node); JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode"); Class<?> hashCodeBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.HashCodeBuilder.class : org.apache.commons.lang.builder.HashCodeBuilder.class; JBlock body = hashCode.body(); JClass hashCodeBuilderClass = jclass.owner().ref(hashCodeBuilder); JInvocation hashCodeBuilderInvocation = JExpr._new(hashCodeBuilderClass); if (!jclass._extends().fullName().equals(Object.class.getName())) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode")); } for (JFieldVar fieldVar : fields.values()) { if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar); } body._return(hashCodeBuilderInvocation.invoke("toHashCode")); hashCode.annotate(Override.class); }
@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); }
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) { final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId); final Class<?> valueVectorClass = fieldId.getIntermediateClass(); final JClass vvClass = model.ref(valueVectorClass); final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass; final JVar vv = declareClassField("vv", retClass); final JBlock b = getSetupBlock(); int[] fieldIndices = fieldId.getFieldIds(); JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple") .arg(batchName) .arg(vvClass.dotclass()); for(int i = 0; i < fieldIndices.length; i++){ invoke.arg(JExpr.lit(fieldIndices[i])); } // we have to cast here since Janino doesn't handle generic inference well. JExpression casted = JExpr.cast(retClass, invoke); b.assign(vv, casted); vvDeclaration.put(setup, vv); return vv; }
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())); } }
public static IProcedure<JVar, RuntimeException> createAddIfNullSetEmptyArrayAndReturnClosure( final JCodeModel codeModel, final JMethod method, final JExpression returnValue) { ensureThatArgument(method, notNull()); return new IProcedure<JVar, RuntimeException>() { @Override public void execute(final JVar param) throws RuntimeException { ensureThatArgument(param, notNull()); final ValueConverter valueConverter = new ValueConverter(codeModel); final JInvocation invocation = JExpr._new(param.type()); method .body() ._if(param.eq(JExpr._null())) ._then() .block() .assign(JExpr.refthis(param.name()), valueConverter.convert(invocation)) ._return(returnValue); } }; }
protected void addCode(JMethod method, AbstractType tp, String kind, Action action) { ArrayList<Link> arrayList = links.get(tp); if (arrayList == null) { arrayList = new ArrayList<>(); links.put(tp, arrayList); } String role = kind; if (kind.equals("get")) { role = "self"; } arrayList.add(new Link(role, action.resource().getUri(), action.method())); JType type = context.getType(tp); if (type == null) { return; } JInvocation iv = JExpr.invoke(JExpr.ref("manager"), kind).arg(JExpr.dotclass((JClass) type)) .arg(JExpr.ref(method.name() + "_meta")); method.body().decl((JClass) type, "result", iv); method.params().forEach(x -> iv.arg(x)); }
@Test public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
/** * The code generator creates a method called __DRILL_INIT__ which takes the * place of the constructor when the code goes though the byte code merge. * For Plain-old Java, we call the method from a constructor created for * that purpose. (Generated code, fortunately, never includes a constructor, * so we can create one.) Since the init block throws an exception (which * should never occur), the generated constructor converts the checked * exception into an unchecked one so as to not require changes to the * various places that create instances of the generated classes. * * Example:<code><pre> * public StreamingAggregatorGen1() { * try { * __DRILL_INIT__(); * } catch (SchemaChangeException e) { * throw new UnsupportedOperationException(e); * } * }</pre></code> * * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's * introspection package. But, Drill prefers Java 7 which only provides * parameter types. */ private void addCtor(Class<?>[] parameters) { JMethod ctor = clazz.constructor(JMod.PUBLIC); JBlock body = ctor.body(); // If there are parameters, need to pass them to the super class. if (parameters.length > 0) { JInvocation superCall = JExpr.invoke("super"); // This case only occurs for nested classes, and all nested classes // in Drill are inner classes. Don't pass along the (hidden) // this$0 field. for (int i = 1; i < parameters.length; i++) { Class<?> p = parameters[i]; superCall.arg(ctor.param(model._ref(p), "arg" + i)); } body.add(superCall); } JTryBlock tryBlock = body._try(); tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD); JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class)); catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e"))); }
private void withEquals() { JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class; if (!config.isUseCommonsLang3()) { equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class; } JBlock body = equals.body(); body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE); body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE); body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE); JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject)); JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass); JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef); body._return(equalsBuilderInvocation.invoke("isEquals")); }
@Override public void caseAPrimaryMethodInvocation(APrimaryMethodInvocation node) { ExpressionAdapter ea = new ExpressionAdapter(new JExprParent(), context); node.getExpressionNoName().apply(ea); JExpression lhs = ea.expr; JInvocation inv = parent.invoke(lhs, node.getIdentifier().getText()); if (!node.getNonWildTypeArguments().isEmpty()) { Logger.error(context.getFile(), node.getIdentifier(), "CodeModel does not support type arguments for methods, yet. Ignoring..."); } Argumentable ia = new InvocationArgumentable(inv); for (PArgument arg : node.getArgument()) { ArgumentAdapter aa = new ArgumentAdapter(ia, context); arg.apply(aa); } expr = inv; }
@Override public void caseAClassMethodInvocation(AClassMethodInvocation node) { AClassName acname = (AClassName) node.getClassName(); String name = nameToString(acname.getName()); JClass jc = context.resolveType(acname.getName()); JExpression jcs = JExpr.dotsuper(jc); JInvocation inv = jcs.invoke(node.getIdentifier().getText()); Argumentable ia = new InvocationArgumentable(inv); for (PArgument arg : node.getArgument()) { ArgumentAdapter aa = new ArgumentAdapter(ia, context); arg.apply(aa); } expr = inv; parent.addInvocation(inv); }
@Override public void caseAClassInitializerArrayCreationExpression(AClassInitializerArrayCreationExpression node) { TypeAdapter ta = new TypeAdapter(context); node.getClassOrInterfaceType().apply(ta); int dim = node.getDim().size(); JType type = ta.type; for (int i = 0; i < dim; i++) { type = type.array(); } JInvocation inv = JExpr._new(type); AArrayInitializer inits = (AArrayInitializer) node.getArrayInitializer(); for (PVariableInitializer init : inits.getVariableInitializer()) { VarInitAdapter via = new VarInitAdapter(context); init.apply(via); inv.arg(via.expr); } expr = inv; }
@Override public void caseAPrimitiveInitializerArrayCreationExpression(APrimitiveInitializerArrayCreationExpression node) { TypeAdapter ta = new TypeAdapter(context); node.getPrimitiveType().apply(ta); int dim = node.getDim().size(); JType type = ta.type; for (int i = 0; i < dim; i++) { type = type.array(); } JInvocation inv = JExpr._new(type); AArrayInitializer inits = (AArrayInitializer) node.getArrayInitializer(); for (PVariableInitializer init : inits.getVariableInitializer()) { VarInitAdapter via = new VarInitAdapter(context); init.apply(via); inv.arg(via.expr); } expr = inv; }
private void createMethodFieldIsSet(JDefinedClass _class, Map<String, JType> fields) { JMethod method = _class.method(JMod.PUBLIC, codeModel.BOOLEAN, "isSet"); JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD); JVar param = method.param(refEnumFields, "field"); method.body()._if(param.eq(JExpr._null()))._then()._throw(JExpr._new(codeModel.ref(IllegalStateException.class))); JSwitch _switch = method.body()._switch(param); for (Map.Entry<String, JType> entry : fields.entrySet()) { JBlock bodyCase = _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body(); String capitalizeName = JavaGeneratorUtil.getCapitalizeString(entry.getKey()); bodyCase._return(JExpr.invoke("isSet" + capitalizeName)); } JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class)); method.body()._throw(_newException); }
private void createMethodFielGetFieldValue(JDefinedClass _class, Map<String, JType> fields) { JMethod method = _class.method(JMod.PUBLIC, codeModel.ref(Object.class), "getFieldValue"); JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD); JVar param = method.param(refEnumFields, "field"); JBlock body = method.body(); JSwitch _switch = body._switch(param); for (Map.Entry<String, JType> entry : fields.entrySet()) { _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body()._return(JExpr.invoke("get" + JavaGeneratorUtil.getCapitalizeString(entry.getKey()))); } JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class)); // _switch._default().body()._throw(_newException); body._throw(_newException); }
private void defineReduceAction(Action a, JBlock body) { Rule r = a.production(); JDefinedClass nodeClass = nodes.getConcreteNode(r); String[] rhs = r.rightHandSide(); JVar[] fields = new JVar[rhs.length]; for( int i = fields.length - 1 ; i >= 0 ; --i ){ JDefinedClass type = nodes.getAbstractNode(rhs[i]); if(type == null){ throw new NullPointerException("Node for: "+rhs[i]+" is null."); } fields[i] = body.decl(type, "field"+i, JExpr.cast(type, JExpr.invoke(stack, "pop"))); } JInvocation newNodeClass = JExpr._new(nodeClass); for(JVar field : fields){ newNodeClass = newNodeClass.arg(field); } JVar node = body.decl(nodes.getNodeInterface(), "reduced", JExpr.invoke(newNodeClass, "replace")); body.invoke(JExpr._this(), advance) .arg(stack).arg(node); body._return(JExpr.invoke(JExpr._this(), advance) .arg(stack).arg(lookahead)); }
public JMethod define(JDefinedClass clazz){ JCodeModel model= clazz.owner(); JMethod hashCode= clazz.method(JMod.PUBLIC, int.class, "hashCode"); hashCode.annotate(Override.class); JBlock jBlock = hashCode.body(); //define variable for hash value to return JVar hash= jBlock.decl(model.INT, "hash", JExpr.lit(initPrime)); for(JVar f:fields){ jBlock.assign(hash, hash.mul(JExpr.lit(incPrime)).plus(JExpr.invoke(f, "hashCode"))); } for(JInvocation m:methods){ jBlock.assign(hash, hash.mul(JExpr.lit(incPrime)).plus(JExpr.invoke(m, "hashCode"))); } //add the class of the object to the hash code jBlock.assign(hash, hash.mul(JExpr.lit(incPrime)).plus(JExpr.invoke(JExpr.invoke("getClass"), "hashCode"))); hashCode.body()._return(hash); return hashCode; }
static private JInvocation createSuperInvocation(JDefinedClass clazz, JMethod method){ JInvocation invocation; if(method.type() != null){ invocation = JExpr._super().invoke(method.name()); } else { invocation = JExpr.invoke("super"); } List<JVar> parameters = method.params(); for(JVar parameter : parameters){ invocation.arg(parameter); } return invocation; }
@Override public void build() { declareMethod(); ExceptionWrapper mainTryBlock = new ExceptionWrapper(codeModel, method.body(), context); JInvocation invocation = codeModel.ref(primitive.getPassThrough().getDeclaringClass()) .staticInvoke(primitive.getPassThrough().getName()) .arg(context) .arg(environment) .arg(call); mainTryBlock.body()._return(invocation); mainTryBlock.catchEvalExceptions(); mainTryBlock.catchRuntimeExceptions(); mainTryBlock.catchExceptions(); }
private void addFactoryMethod(JsonNode node, JDefinedClass _enum) { JFieldVar quickLookupMap = addQuickLookupMap(_enum); JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue"); JVar valueParam = fromValue.param(String.class, "value"); JBlock body = fromValue.body(); JVar constant = body.decl(_enum, "constant"); constant.init(quickLookupMap.invoke("get").arg(valueParam)); JConditional _if = body._if(constant.eq(JExpr._null())); JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class)); illegalArgumentException.arg(valueParam); _if._then()._throw(illegalArgumentException); _if._else()._return(constant); ruleFactory.getAnnotator().enumCreatorMethod(fromValue); }
/** * 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); } return newListImpl; }
/** * Creates a default value for a set property by: * <ol> * <li>Creating a new {@link HashSet} with the correct generic type * <li>Using {@link Arrays#asList(Object...)} to initialize the set with the * correct default values * </ol> * * @param fieldType * the java type that applies for this field ({@link Set} with * some generic type argument) * @param node * the node containing default values for this set * @return an expression that creates a default value that can be assigned * to this field */ private JExpression getDefaultSet(JType fieldType, JsonNode node) { JClass setGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass setImplClass = fieldType.owner().ref(HashSet.class); setImplClass = setImplClass.narrow(setGenericType); JInvocation newSetImpl = JExpr._new(setImplClass); if (node instanceof ArrayNode) { JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList"); for (JsonNode defaultValue : node) { invokeAsList.arg(getDefaultValue(setGenericType, defaultValue)); } newSetImpl.arg(invokeAsList); } return newSetImpl; }
private JFieldVar addQuickLookupMap(JDefinedClass _enum, JType backingType) { JClass lookupType = _enum.owner().ref(Map.class).narrow(backingType.boxify(), _enum); JFieldVar lookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "CONSTANTS"); JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(backingType.boxify(), _enum); lookupMap.init(JExpr._new(lookupImplType)); JForEach forEach = _enum.init().forEach(_enum, "c", JExpr.invoke("values")); JInvocation put = forEach.body().invoke(lookupMap, "put"); put.arg(forEach.var().ref("value")); put.arg(forEach.var()); return lookupMap; }
/** * @see EnumRule */ private static JExpression getDefaultEnum(JType fieldType, JsonNode node) { JDefinedClass enumClass = (JDefinedClass) fieldType; JType backingType = enumClass.fields().get("value").type(); JInvocation invokeFromValue = enumClass.staticInvoke("fromValue"); invokeFromValue.arg(getDefaultValue(backingType, node)); return invokeFromValue; }
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 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); }
@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 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; }
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) { final LogicalExpression child = e.getChild(); final HoldingContainer inputContainer = child.accept(this, generator); JBlock block = generator.getEvalBlock(); JExpression outIndex = generator.getMappingSet().getValueWriteIndex(); JVar vv = generator.declareVectorValueSetupAndMember(generator.getMappingSet().getOutgoing(), e.getFieldId()); // Only when the input is a reader, use writer interface to copy value. // Otherwise, input is a holder and we use vv mutator to set value. if (inputContainer.isReader()) { JType writerImpl = generator.getModel()._ref( TypeHelper.getWriterImpl(getArrowMinorType(inputContainer.getCompleteType().toMinorType()))); JType writerIFace = generator.getModel()._ref( TypeHelper.getWriterInterface(getArrowMinorType(inputContainer.getCompleteType().toMinorType()))); JVar writer = generator.declareClassField("writer", writerIFace); generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv)); generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex)); String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue"; generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer)); if (e.isSafe()) { HoldingContainer outputContainer = generator.declare(CompleteType.BIT); generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1)); return outputContainer; } } else { final JInvocation setMeth = GetSetVectorHelper.write(e.getChild().getCompleteType().toMinorType(), vv, inputContainer, outIndex, e.isSafe() ? "setSafe" : "set"); JConditional jc = block._if(inputContainer.getIsSet().eq(JExpr.lit(0)).not()); block = jc._then(); block.add(setMeth); } return null; }
@SuppressWarnings("unchecked") ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException { this.codeGenerator = codeGenerator; this.clazz = clazz; this.mappings = mappingSet; this.sig = signature; this.evaluationVisitor = eval; this.model = Preconditions.checkNotNull(model, "Code model object cannot be null."); blocks = new LinkedList[sig.size()]; for (int i =0; i < sig.size(); i++) { blocks[i] = Lists.newLinkedList(); } rotateBlock(); for (SignatureHolder child : signature.getChildHolders()) { final String innerClassName = child.getSignatureClass().getSimpleName(); final JDefinedClass innerClazz; // we need to extend the template class and avoid using static inner classes. innerClazz = clazz._class(JMod.FINAL, innerClassName)._extends(child.getSignatureClass()); // we also need to delegate any inner class constructors. for(Constructor<?> c : child.getSignatureClass().getDeclaredConstructors()){ final Class<?>[] params = c.getParameterTypes(); JMethod constructor = innerClazz.constructor(JMod.PUBLIC); JBlock block = constructor.body(); JInvocation invoke = block.invoke("super"); block.invoke(SignatureHolder.INIT_METHOD); // start at 1 since first parameter is the parent class for (int i = 1; i < params.length; i++) { constructor.param(params[i], "arg" + i); invoke.arg(JExpr.direct("arg" + i)); } } innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model)); } }
public void create(final JDefinedClass beanBuilder, final String name, final Iterable<JFieldVar> fields) { final JClass bean = _classByNames(name); final JMethod method = beanBuilder.method(JMod.PUBLIC, bean, "build"); //$NON-NLS-1$ JInvocation instance = JExpr._new(bean); for (final JFieldVar field : fields) { instance = instance.arg(field); } method.body()._return(instance); }
public JExpression format(final String string, final JExpression... params) { final JClass formater = _classByNames(java.text.MessageFormat.class.getName()); JInvocation expression = formater.staticInvoke("format").arg(string); //$NON-NLS-1$ for (final JExpression var : params) { expression = expression.arg(var); } return expression; }