/** * Creates the getter and setter methods on the supplied class for the supplied name. * * @param clazz to put getter and setter methods on * @param name of the property * @param syntaxType of the property * @param multivalue whether this property is a collection */ protected void createMutators( final JDefinedClass clazz, final String name, final Class<?> syntaxType, final boolean multivalue) { final String upperName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length()); if (multivalue) { final JClass detailClass = codeModel.ref(syntaxType); final JClass collectionClass = codeModel.ref(Collection.class); final JClass genericClass = collectionClass.narrow(detailClass); final JFieldVar field = clazz.field(JMod.PRIVATE, genericClass, name); final JMethod getterMethod = clazz.method(JMod.PUBLIC, genericClass, "get" + upperName); getterMethod.body()._return(field); final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName); setterMethod.param(genericClass, "c"); setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("c")); } else { final JFieldVar field = clazz.field(JMod.PRIVATE, syntaxType, name); final JMethod getterMethod = clazz.method(JMod.PUBLIC, syntaxType, "get" + upperName); getterMethod.body()._return(field); final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName); setterMethod.param(syntaxType, "s"); setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("s")); } }
private void addHashCode(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); if (fields.isEmpty()) { return; } 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().name().equals("Object")) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode")); } for (JFieldVar fieldVar : fields.values()) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar); } body._return(hashCodeBuilderInvocation.invoke("toHashCode")); hashCode.annotate(Override.class); }
@Override public void generate(JDefinedClass cls, GenerationContext context) { if (classSpec.getFields().isEmpty()) { return; // No equals needed. } // Import the objects class, for hash coding. JClass objects = context.getTypeManager().getClassDirect("java.util.Objects"); // Create the equals method. JMethod hashMethod = cls.method(JMod.PUBLIC, int.class, "hashCode"); hashMethod.annotate(Override.class); JBlock body = hashMethod.body(); // Check if the object is null. JVar hash = body.decl(JType.parse(context.getCodeModel(), "int"), "hash", JExpr.lit(3)); // Do check for each field. for (DataFieldSpecification fieldSpec : classSpec.getFields()) { List<String> parts = NameFormat.namesToList(fieldSpec.getFieldName()); String camelCaseFieldName = NameFormat.camelCase(parts, false); // Get the field value. JExpression thisField = JExpr.refthis(camelCaseFieldName); // Accumulate the hash code. JExpression fieldHashCode = objects.staticInvoke("hashCode").arg(thisField); body.assign(hash, JExpr.lit(79).mul(hash).plus(fieldHashCode)); } // Return the processed hash value. body._return(hash); }
private void addCreateFromParcel(JDefinedClass jclass, JDefinedClass creatorClass) { JMethod createFromParcel = creatorClass.method(JMod.PUBLIC, jclass, "createFromParcel"); JVar in = createFromParcel.param(Parcel.class, "in"); JVar instance = createFromParcel.body().decl(jclass, "instance", JExpr._new(jclass)); suppressWarnings(createFromParcel, "unchecked"); for (JFieldVar f : jclass.fields().values()) { if ((f.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } if (f.type().erasure().name().equals("List")) { createFromParcel .body() .invoke(in, "readList") .arg(instance.ref(f)) .arg(JExpr.direct(getGenericType(f.type()) + ".class.getClassLoader()")); } else { createFromParcel .body() .assign( instance.ref(f), JExpr.cast( f.type(), in.invoke("readValue") .arg(JExpr.direct(f.type().erasure().name() + ".class.getClassLoader()")))); } } createFromParcel.body()._return(instance); }
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); } } }
public void build() { declareMethod(); ExceptionWrapper mainTryBlock = new ExceptionWrapper(codeModel, method.body(), context); for (Integer arity : primitive.getArity()) { JInvocation invocation = invoke("doApply").arg(context).arg(environment); for (int i = 0; i < arity; ++i) { invocation.arg(args.component(lit(i))); } mainTryBlock .body() ._if(JExpr.direct("args.length").eq(JExpr.lit(arity))) ._then() ._return(invocation); } mainTryBlock.catchEvalExceptions(); mainTryBlock.catchRuntimeExceptions(); mainTryBlock.catchExceptions(); method .body() ._throw( JExpr._new(codeModel.ref(EvalException.class)) .arg(lit(primitive.getName() + ": max arity is " + primitive.getMaxArity()))); }
private void createConstructorAndBuilder() { List<ExecutableElement> constructors = new ArrayList<ExecutableElement>(); for (Element e : annotatedElement.getEnclosedElements()) { if (e.getKind() == CONSTRUCTOR) { constructors.add((ExecutableElement) e); } } for (ExecutableElement userConstructor : constructors) { JMethod copyConstructor = generatedClass.constructor(PUBLIC); JMethod staticHelper = generatedClass.method(PUBLIC | STATIC, generatedClass._extends(), "build"); codeModelHelper.generifyStaticHelper(this, staticHelper, getAnnotatedElement()); JBlock body = copyConstructor.body(); JInvocation superCall = body.invoke("super"); JInvocation newInvocation = JExpr._new(generatedClass); for (VariableElement param : userConstructor.getParameters()) { String paramName = param.getSimpleName().toString(); JClass paramType = codeModelHelper.typeMirrorToJClass(param.asType(), this); copyConstructor.param(paramType, paramName); staticHelper.param(paramType, paramName); superCall.arg(JExpr.ref(paramName)); newInvocation.arg(JExpr.ref(paramName)); } JVar newCall = staticHelper.body().decl(generatedClass, "instance", newInvocation); staticHelper.body().invoke(newCall, getOnFinishInflate()); staticHelper.body()._return(newCall); body.invoke(getInit()); } }
public void generateQuery(Feed feed) { try { JClass transformedType = getTransformedType(feed); if (transformedType == null) { return; } JDefinedClass cls = pkg._class(JMod.PUBLIC | JMod.FINAL, String.format("%sQuery", feed.getName())); cls._extends(parent.narrow(transformedType)); if (feed.getTitle() != null) { cls.javadoc().add(String.format("<p>%s</p>", feed.getTitle())); } addResourcePath(cls, feed); addResultTypeMethod(model, cls, transformedType); addConstructor(cls); JDefinedClass bldrCls = addBuilderCls(feed, cls); cls.method(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, bldrCls, "builder") .body() ._return(JExpr._new(bldrCls)); JMethod cpyMthd = cls.method(JMod.PROTECTED | JMod.FINAL, cls, "copy"); JVar cpyParam = cpyMthd.param(immutableMap.narrow(String.class, Object.class), "params"); cpyMthd.body()._return(JExpr._new(cls).arg(cpyParam)); } catch (Exception e) { throw new IllegalStateException(e); } }
private void getIndex(ClassGenerator<StreamingAggregator> g) { switch (incoming.getSchema().getSelectionVectorMode()) { case FOUR_BYTE: { JVar var = g.declareClassField("sv4_", g.getModel()._ref(SelectionVector4.class)); g.getBlock("setupInterior") .assign(var, JExpr.direct("incoming").invoke("getSelectionVector4")); g.getBlock("getVectorIndex")._return(var.invoke("get").arg(JExpr.direct("recordIndex"))); ; return; } case NONE: { g.getBlock("getVectorIndex")._return(JExpr.direct("recordIndex")); ; return; } case TWO_BYTE: { JVar var = g.declareClassField("sv2_", g.getModel()._ref(SelectionVector2.class)); g.getBlock("setupInterior") .assign(var, JExpr.direct("incoming").invoke("getSelectionVector2")); g.getBlock("getVectorIndex") ._return(var.invoke("getIndex").arg(JExpr.direct("recordIndex"))); ; return; } default: throw new IllegalStateException(); } }
/** * Sets up projection that will transfer all of the columns in batch, and also populate the * partition column based on which partition a record falls into in the partition table * * @param batch * @throws SchemaChangeException */ protected void setupNewSchema(VectorAccessible batch) throws SchemaChangeException { container.clear(); final ErrorCollector collector = new ErrorCollectorImpl(); final List<TransferPair> transfers = Lists.newArrayList(); final ClassGenerator<OrderedPartitionProjector> cg = CodeGenerator.getRoot( OrderedPartitionProjector.TEMPLATE_DEFINITION, context.getFunctionRegistry()); for (VectorWrapper<?> vw : batch) { TransferPair tp = vw.getValueVector().getTransferPair(); transfers.add(tp); container.add(tp.getTo()); } cg.setMappingSet(mainMapping); int count = 0; for (Ordering od : popConfig.getOrderings()) { final LogicalExpression expr = ExpressionTreeMaterializer.materialize( od.getExpr(), batch, collector, context.getFunctionRegistry()); if (collector.hasErrors()) throw new SchemaChangeException( "Failure while materializing expression. " + collector.toErrorString()); cg.setMappingSet(incomingMapping); ClassGenerator.HoldingContainer left = cg.addExpr(expr, false); cg.setMappingSet(partitionMapping); ClassGenerator.HoldingContainer right = cg.addExpr( new ValueVectorReadExpression(new TypedFieldId(expr.getMajorType(), count++)), false); cg.setMappingSet(mainMapping); LogicalExpression fh = FunctionGenerationHelper.getComparator(left, right, context.getFunctionRegistry()); ClassGenerator.HoldingContainer out = cg.addExpr(fh, false); JConditional jc = cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0))); if (od.getDirection() == Direction.ASCENDING) { jc._then()._return(out.getValue()); } else { jc._then()._return(out.getValue().minus()); } } cg.getEvalBlock()._return(JExpr.lit(0)); container.add(this.partitionKeyVector); container.buildSchema(batch.getSchema().getSelectionVectorMode()); try { this.projector = context.getImplementationClass(cg); projector.setup( context, batch, this, transfers, partitionVectors, partitions, popConfig.getRef()); } catch (ClassTransformationException | IOException e) { throw new SchemaChangeException("Failure while attempting to load generated class", e); } }
private static JInvocation generateInvocation(Method method) { JInvocation generatedInvocation = JExpr.invoke(JExpr.invoke("getWrapped"), method.getName()); for (Parameter parameter : method.getParameters()) { generatedInvocation.arg(JExpr.ref(parameter.getName())); } return generatedInvocation; }
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)); } }
protected HoldingContainer generateEvalBody( ClassGenerator<?> g, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) { // g.getBlock().directStatement(String.format("//---- start of eval portion of %s function. // ----//", functionName)); JBlock sub = new JBlock(true, true); JBlock topSub = sub; HoldingContainer out = null; MajorType returnValueType = returnValue.type; // add outside null handling if it is defined. if (nullHandling == NullHandling.NULL_IF_NULL) { JExpression e = null; for (HoldingContainer v : inputVariables) { if (v.isOptional()) { if (e == null) { e = v.getIsSet(); } else { e = e.mul(v.getIsSet()); } } } if (e != null) { // if at least one expression must be checked, set up the conditional. returnValueType = returnValue.type.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), returnValue.name, JExpr._new(g.getHolderType(returnValueType))); addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false); if (sub != topSub) sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode sub.assign(out.getHolder(), internalOutput); if (sub != topSub) sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode return out; }
/** * Creates the hashCode method on the supplied class. Leverages {@link * org.ldaptive.LdapUtils#computeHashCode(int, Object...)}. * * @param clazz to put hashCode method on */ private void createHashCode(final JDefinedClass clazz) { final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class); final JInvocation computeHashCode = ldapUtilsClass.staticInvoke("computeHashCode"); final JMethod hashCode = clazz.method(JMod.PUBLIC, int.class, "hashCode"); hashCode.annotate(java.lang.Override.class); // CheckStyle:MagicNumber OFF computeHashCode.arg(JExpr.lit(7919)); // CheckStyle:MagicNumber ON for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) { computeHashCode.arg(JExpr._this().ref(entry.getValue())); } hashCode.body()._return(computeHashCode); }
private void addActionInOnHandleIntent( EIntentServiceHolder holder, ExecutableElement executableElement, String methodName, JFieldVar actionKeyField) { // If action match, call the method JInvocation actionCondition = actionKeyField.invoke("equals").arg(holder.getOnHandleIntentIntentAction()); JBlock callActionBlock = holder.getOnHandleIntentBody()._if(actionCondition)._then(); JInvocation callActionInvocation = JExpr._super().invoke(methodName); // For each method params, we get back value from extras and put it // in super calls List<? extends VariableElement> methodParameters = executableElement.getParameters(); if (methodParameters.size() > 0) { // Extras JVar extras = callActionBlock.decl(classes().BUNDLE, "extras"); extras.init(holder.getOnHandleIntentIntent().invoke("getExtras")); JBlock extrasNotNullBlock = callActionBlock._if(extras.ne(_null()))._then(); // Extras params for (VariableElement param : methodParameters) { String paramName = param.getSimpleName().toString(); String extraParamName = paramName + "Extra"; JFieldVar paramVar = getStaticExtraField(holder, paramName); JClass extraParamClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder); BundleHelper bundleHelper = new BundleHelper(annotationHelper, param); JExpression getExtraExpression = JExpr.invoke(extras, bundleHelper.getMethodNameToRestore()).arg(paramVar); if (bundleHelper.restoreCallNeedCastStatement()) { getExtraExpression = JExpr.cast(extraParamClass, getExtraExpression); if (bundleHelper.restoreCallNeedsSuppressWarning()) { JMethod onHandleIntentMethod = holder.getOnHandleIntentMethod(); if (onHandleIntentMethod.annotations().size() == 0) { onHandleIntentMethod.annotate(SuppressWarnings.class).param("value", "unchecked"); } } } JVar extraField = extrasNotNullBlock.decl(extraParamClass, extraParamName, getExtraExpression); callActionInvocation.arg(extraField); } extrasNotNullBlock.add(callActionInvocation); } else { callActionBlock.add(callActionInvocation); } callActionBlock._return(); }
private MSorter createNewMSorter( FragmentContext context, List<Ordering> orderings, VectorAccessible batch, MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping) throws ClassTransformationException, IOException, SchemaChangeException { CodeGenerator<MSorter> cg = CodeGenerator.get( MSorter.TEMPLATE_DEFINITION, context.getFunctionRegistry(), context.getOptions()); ClassGenerator<MSorter> g = cg.getRoot(); g.setMappingSet(mainMapping); for (Ordering od : orderings) { // first, we rewrite the evaluation stack for each side of the comparison. ErrorCollector collector = new ErrorCollectorImpl(); final LogicalExpression expr = ExpressionTreeMaterializer.materialize( od.getExpr(), batch, collector, context.getFunctionRegistry()); if (collector.hasErrors()) { throw new SchemaChangeException( "Failure while materializing expression. " + collector.toErrorString()); } g.setMappingSet(leftMapping); HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE); g.setMappingSet(rightMapping); HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE); g.setMappingSet(mainMapping); // next we wrap the two comparison sides and add the expression block for the comparison. LogicalExpression fh = FunctionGenerationHelper.getOrderingComparator( od.nullsSortHigh(), left, right, context.getFunctionRegistry()); HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE); JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0))); if (od.getDirection() == Direction.ASCENDING) { jc._then()._return(out.getValue()); } else { jc._then()._return(out.getValue().minus()); } g.rotateBlock(); } g.rotateBlock(); g.getEvalBlock()._return(JExpr.lit(0)); return context.getImplementationClass(cg); }
private static void processAccessors( JFieldVar fieldVar, JDefinedClass packetClass, boolean fromClient) { String name = WordUtils.capitalize(fieldVar.name()); if (fromClient) { String methodName = "get" + name; JMethod getter = packetClass.method(JMod.PUBLIC, fieldVar.type(), methodName); getter.body()._return(fieldVar); } else { String methodName = "set" + name; JMethod setter = packetClass.method(JMod.PUBLIC, Void.TYPE, methodName); setter.param(fieldVar.type(), fieldVar.name()); setter.body().assign(JExpr._this().ref(fieldVar.name()), JExpr.ref(fieldVar.name())); } }
private void addConstructors(JDefinedClass jclass, List<String> properties) { // no properties to put in the constructor => default constructor is good enough. if (properties.isEmpty()) { return; } // add a no-args constructor for serialization purposes JMethod noargsConstructor = jclass.constructor(JMod.PUBLIC); noargsConstructor.javadoc().add("No args constructor for use in serialization"); // add the public constructor with property parameters JMethod fieldsConstructor = jclass.constructor(JMod.PUBLIC); JBlock constructorBody = fieldsConstructor.body(); Map<String, JFieldVar> fields = jclass.fields(); for (String property : properties) { JFieldVar field = fields.get(property); if (field == null) { throw new IllegalStateException( "Property " + property + " hasn't been added to JDefinedClass before calling addConstructors"); } fieldsConstructor.javadoc().addParam(property); JVar param = fieldsConstructor.param(field.type(), field.name()); constructorBody.assign(JExpr._this().ref(field), param); } }
private void addActionToIntentBuilder( EIntentServiceHolder holder, ExecutableElement executableElement, String methodName, JFieldVar actionKeyField) { JMethod method = holder.getIntentBuilderClass().method(PUBLIC, holder.getIntentBuilderClass(), methodName); JBlock body = method.body(); // setAction body.invoke("action").arg(actionKeyField); // For each method params, we get put value into extras List<? extends VariableElement> methodParameters = executableElement.getParameters(); if (methodParameters.size() > 0) { // Extras params for (VariableElement param : methodParameters) { String paramName = param.getSimpleName().toString(); JClass parameterClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder); JFieldVar paramVar = getStaticExtraField(holder, paramName); JVar methodParam = method.param(parameterClass, paramName); JMethod putExtraMethod = holder.getIntentBuilder().getPutExtraMethod(param.asType(), paramName, paramVar); body.invoke(putExtraMethod).arg(methodParam); } } body._return(JExpr._this()); }
@Override public Void visitEnumConstant(VariableElement c, JAnnotationArrayMember p) { JClass annotationClass = helper.typeMirrorToJClass(c.asType(), holder); JExpression expression = JExpr.direct(annotationClass.fullName() + "." + c.getSimpleName()); p.param(expression); return null; }
@Override public Void visitType(TypeMirror t, JAnnotationArrayMember p) { JClass annotationClass = helper.typeMirrorToJClass(t, holder); JExpression dotclass = JExpr.dotclass(annotationClass); p.param(dotclass); return null; }
private void addResultTypeMethod(JCodeModel model, JDefinedClass cls, JClass transformedType) { JClass classCls = model.ref(Class.class); JMethod method = cls.method(JMod.PROTECTED | JMod.FINAL, classCls.narrow(transformedType), "resultsType"); method.body()._return(JExpr.dotclass(transformedType)); method.annotate(Override.class); }
private void addResourcePath(JDefinedClass cls, Feed feed) { JFieldVar field = cls.field(privateStaticFinal, String.class, "RESOURCE_PATH"); field.init(JExpr.lit(feed.getHref())); JMethod method = cls.method(JMod.PROTECTED | JMod.FINAL, String.class, "resourcePath"); method.annotate(Override.class); method.body()._return(field); }
private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls) throws JClassAlreadyExistsException, ClassNotFoundException { JDefinedClass bldrCls = cls._class(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, "Builder"); JVar paramBuilder = bldrCls .field(JMod.PRIVATE | JMod.FINAL, immutableMapBldr, "params") .init(immutableMap.staticInvoke("builder")); for (Filter filter : feed.getFilters().getFilter()) { if (!Boolean.TRUE.equals(filter.isDeprecated())) { addWithersFor(filter, bldrCls, paramBuilder); } } if (feed.getMixins() != null && feed.getMixins().getMixin() != null) { JDefinedClass mixinEnum = getMixinEnum(feed); for (Mixin mixin : feed.getMixins().getMixin()) { String mixinName = mixin.getName().toUpperCase().replace(' ', '_'); JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName); mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+'))); } JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXIN"); field.init(JExpr.lit("mixin")); JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); JVar param = iterWither.param(iterable(mixinEnum), "mixins"); JBlock mthdBody = iterWither.body(); mthdBody.add( paramBuilder .invoke("put") .arg(field) .arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); param = varArgWither.varParam(mixinEnum, "mixins"); varArgWither .body() ._return(JExpr.invoke(iterWither).arg(immutableList.staticInvoke("copyOf").arg(param))); } JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build"); bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build"))); // TODO: add sorts return bldrCls; }
public JMethod createOnCreate() { JMethod onCreate = activity.method(JMod.PROTECTED, void.class, "onCreate"); onCreate.annotate(Override.class); JVar sis = onCreate.param(factory.ref(Const.BUNDLE), "savedInstanceState"); onCreate.body().invoke(JExpr._super(), "onCreate").arg(sis); return onCreate; }
/** * Creates the equals method on the supplied class. Leverages {@link * org.ldaptive.LdapUtils#areEqual(Object, Object)}. * * @param clazz to put equals method on */ private void createEquals(final JDefinedClass clazz) { final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class); final JInvocation areEqual = ldapUtilsClass.staticInvoke("areEqual"); final JMethod equals = clazz.method(JMod.PUBLIC, boolean.class, "equals"); equals.annotate(java.lang.Override.class); areEqual.arg(JExpr._this()); areEqual.arg(equals.param(Object.class, "o")); equals.body()._return(areEqual); }
private void addEquals(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); if (fields.isEmpty()) { return; } 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().name().equals("Object")) { equalsBuilderInvocation = equalsBuilderInvocation .invoke("appendSuper") .arg(JExpr._super().invoke("equals").arg(otherObject)); } for (JFieldVar fieldVar : fields.values()) { 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); }
private static void processToString(JDefinedClass packetClass, JCodeModel codeModel) { JClass string = codeModel.ref(String.class); JClass stringBuilder = codeModel.ref(StringBuilder.class); JClass arrays = codeModel.ref(Arrays.class); JMethod toStringMeth = packetClass.method(JMod.PUBLIC, String.class, "toString"); toStringMeth.annotate(Override.class); JBlock body = toStringMeth.body(); JVar stringBuilderVar = body.decl(stringBuilder, "sb"); stringBuilderVar = stringBuilderVar.init(JExpr._new(stringBuilder).arg(packetClass.name() + "[")); JInvocation appendChain = null; for (JFieldVar fieldVar : packetClass.fields().values()) { if (appendChain != null) { // a comma is needed appendChain = appendChain.invoke("append").arg("," + fieldVar.name() + "="); } else { appendChain = stringBuilderVar.invoke("append").arg(fieldVar.name() + "="); } // now add the field to the toString output JExpression expression = fieldVar.type().isArray() ? arrays.staticInvoke("toString").arg(JExpr._this().ref(fieldVar.name())) : fieldVar.type().isReference() ? JExpr._this().ref(fieldVar.name()).invoke("toString") : JExpr._this().ref(fieldVar.name()); appendChain = appendChain.invoke("append").arg(expression); } if (appendChain != null) { appendChain = appendChain.invoke("append").arg("]"); } else { appendChain = stringBuilderVar.invoke("append").arg("]"); } body.add(appendChain); body._return(stringBuilderVar.invoke("toString")); }
private void addWither( Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType) throws JClassAlreadyExistsException { JMethod method = createWitherMethod(filter, bldrCls); if (filter.getTitle() != null) { method.javadoc().add(String.format("<p>%s</p>", filter.getTitle())); } JVar param = addParam(filter, method, paramType); JBlock mthdBody = method.body(); boolean needsNullCheck = true; if (filter.getMinValue() != null) { mthdBody.add(precs.staticInvoke("checkNotNull").arg(param)); needsNullCheck = false; int min = filter.getMinValue().intValue(); mthdBody.add( precs .staticInvoke("checkArgument") .arg(JExpr.lit(min).lte(param)) .arg(JExpr.lit(param.name() + ": %s < " + min)) .arg(param)); } if (filter.getMaxValue() != null) { if (needsNullCheck) { mthdBody.add(precs.staticInvoke("checkNotNull").arg(param)); needsNullCheck = false; } int max = filter.getMaxValue().intValue(); mthdBody.add( precs .staticInvoke("checkArgument") .arg(JExpr.lit(max).gte(param)) .arg(JExpr.lit(param.name() + ": %s > " + max)) .arg(param)); } JInvocation putIntoMap = paramBuilder.invoke("put").arg(field); if (needsNullCheck) { putIntoMap.arg(precs.staticInvoke("checkNotNull").arg(param)); } else { putIntoMap.arg(param); } mthdBody.add(putIntoMap); mthdBody._return(JExpr._this()); }
private JInvocation buildScopeKey(InjectionNode injectionNode) { InjectionSignature signature = injectionNode.getTypeSignature(); JClass injectionNodeClassRef = generationUtil.ref(injectionNode.getASTType()); return codeModel .ref(ScopeKey.class) .staticInvoke(ScopeKey.GET_METHOD) .arg(injectionNodeClassRef.dotclass()) .arg(JExpr.lit(signature.buildScopeKeySignature())); }