/** * 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")); } }
@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 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); }
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 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); }
/** * 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 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())); }
@Test public void testLoadedInterfaces() throws Exception { String[] namesToLoad = new String[] { "InterfaceA.json", "InterfaceB.json", "ABImpl.json", }; List<ObjectSchema> schemaList = new ArrayList<ObjectSchema>(); for (String name : namesToLoad) { String fileString = FileUtils.loadFileAsStringFromClasspath( PojoGeneratorDriverTest.class.getClassLoader(), name); ObjectSchema schema = new ObjectSchema(new JSONObjectAdapterImpl(fileString)); // schema.setName(name); schema.setId(schema.getName()); schemaList.add(schema); } JCodeModel codeModel = new JCodeModel(); driver.createAllClasses(codeModel, schemaList); // Get the class JPackage _package = codeModel._package(""); JDefinedClass impl = null; try { impl = _package._class("ABImpl"); } catch (JClassAlreadyExistsException e) { impl = e.getExistingClass(); } String classString = declareToString(impl); // System.out.println(classString); Iterator<JClass> it = impl._implements(); assertNotNull(it); String intA = "InterfaceA"; String intB = "InterfaceB"; String jsonEntity = "JSONEntity"; Map<String, JClass> map = new HashMap<String, JClass>(); while (it.hasNext()) { JClass impClass = it.next(); if (intA.equals(impClass.name())) { map.put(intA, impClass); } else if (intB.equals(impClass.name())) { map.put(intB, impClass); } else if (jsonEntity.equals(impClass.name())) { map.put(jsonEntity, impClass); } } assertEquals("Should have implemented two interfaces", 3, map.size()); // Now get the fields from the object an confirm they are all there Map<String, JFieldVar> fields = impl.fields(); assertNotNull(fields); assertEquals(6, fields.size()); assertNotNull(fields.get("fromInterfaceA")); assertNotNull(fields.get("alsoFromInterfaceB")); assertNotNull(fields.get("fromMe")); }
/** * 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); }
public static void addEventHandlerRegistrationMethods(Option option, JDefinedClass jClass) { List<JClass> list = EventRegistry.INSTANCE.getRegistry().get(option.getFullname()); if (list != null) { for (JClass handlerClass : list) { String handlerClassName = handlerClass.name(); String paramName = handlerClassName.substring(0, 1).toLowerCase() + handlerClassName.substring(1); jClass .method(JMod.NONE, void.class, EventHelper.ADD_HANDLER_METHOD_PREFIX + handlerClassName) .param(handlerClass, paramName); } } }
/** * Add the pre-check to see if we are already in the UI thread. * * @param delegatingMethod * @param holder * @throws JClassAlreadyExistsException */ private void addUIThreadCheck( JMethod delegatingMethod, JBlock previousBody, EComponentHolder holder) throws JClassAlreadyExistsException { // Get the Thread and Looper class. JClass tClass = holder.classes().THREAD; JClass lClass = holder.classes().LOOPER; // invoke the methods. JExpression lhs = tClass.staticInvoke(METHOD_CUR_THREAD); JExpression rhs = lClass.staticInvoke(METHOD_MAIN_LOOPER).invoke(METHOD_GET_THREAD); // create the conditional and the block. JConditional con = delegatingMethod.body()._if(JOp.eq(lhs, rhs)); JBlock thenBlock = con._then().add(previousBody); thenBlock._return(); }
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; }
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()); }
/** * Creates the toString method on the supplied class. Creates a string that contains every * property on the generated bean. * * @param clazz to put toString method on */ private void createToString(final JDefinedClass clazz) { final JClass stringClass = codeModel.ref(java.lang.String.class); final JInvocation format = stringClass.staticInvoke("format"); final JMethod toString = clazz.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(java.lang.Override.class); final StringBuilder sb = new StringBuilder("[%s@%d::"); for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) { sb.append(entry.getKey()).append("=%s, "); } sb.setLength(sb.length() - 2); sb.append("]"); format.arg(sb.toString()); format.arg(JExpr._this().invoke("getClass").invoke("getName")); format.arg(JExpr._this().invoke("hashCode")); for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) { format.arg(JExpr._this().ref(entry.getValue())); } toString.body()._return(format); }
private void addVarArgsWither( Filter filter, JMethod wither, JDefinedClass bldrCls, JClass paramType) throws JClassAlreadyExistsException { JMethod method = bldrCls.method(wither.mods().getValue(), wither.type(), wither.name()); if (filter.getTitle() != null) { method.javadoc().add(String.format("<p>%s</p>", filter.getTitle())); } JVar param = method.varParam(paramType, wither.listParams()[0].name()); method .body() ._return(JExpr.invoke(wither).arg(immutableList.staticInvoke("copyOf").arg(param))); }
private Refs(JCodeModel m, String packageName, String layoutName, String superclass) { this.m = m; this.packageName = packageName; this.layoutName = layoutName; viewHolder = m.ref(superclass); viewClass = m.ref("android.view.View"); androidRClass = m.ref("android.R"); rClass = m.ref(packageName + ".R"); nullableAnnotation = m.ref("android.support.annotation.Nullable"); overrideAnnotation = m.ref("java.lang.Override"); layoutRef = rClass.staticRef("layout").ref(layoutName); }
@Override public JType visit(ClassOrInterfaceType type, JCodeModel codeModel) { final String name = getName(type); final JClass knownClass = this.knownClasses.get(name); final JClass jclass = knownClass != null ? knownClass : codeModel.ref(name); final List<Type> typeArgs = type.getTypeArgs(); if (typeArgs == null || typeArgs.isEmpty()) { return jclass; } else { final List<JClass> jtypeArgs = new ArrayList<JClass>(typeArgs.size()); for (Type typeArg : typeArgs) { final JType jtype = typeArg.accept(this, codeModel); if (!(jtype instanceof JClass)) { throw new IllegalArgumentException( "Type argument [" + typeArg.toString() + "] is not a class."); } else { jtypeArgs.add((JClass) jtype); } } return jclass.narrow(jtypeArgs); } }
@Override public JType visit(WildcardType type, JCodeModel codeModel) { if (type.getExtends() != null) { final ReferenceType _extends = type.getExtends(); final JType boundType = _extends.accept(this, codeModel); if (!(boundType instanceof JClass)) { throw new IllegalArgumentException( "Bound type [" + _extends + "]in the wildcard type must be class."); } final JClass boundClass = (JClass) boundType; return boundClass.wildcard(); } else if (type.getSuper() != null) { // TODO throw new IllegalArgumentException( "Wildcard types with super clause are not supported at the moment."); } else { throw new IllegalArgumentException("Wildcard type must have either extends or super clause."); } }
private JMethod addIterableWither( 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, iterable(paramType)); JBlock mthdBody = method.body(); mthdBody.add( paramBuilder.invoke("put").arg(field).arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); return method; }
public boolean isAbstract() { return clazz.isAbstract(); }
public boolean isBoxedType() { return clazz.getPrimitiveType() != null; }
public String fullName() { return clazz.fullName(); }