private void source(JCodeModel codeModel, JDefinedClass clazz) throws SQLException, Exception { DatabaseMetaData dmd = conn.getMetaData(); ResultSet rs = dmd.getColumns(null, schema.toUpperCase(), table, null); String productName = dmd.getDatabaseProductName(); try { while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); int dataType = rs.getInt("DATA_TYPE"); int columnSize = rs.getInt("COLUMN_SIZE"); int digits = rs.getInt("DECIMAL_DIGITS"); String remarks = this.getColumnComment(table, columnName); String fieldName = toCamelCase(columnName); // privateなインスタンス変数 JFieldVar field = this.field(codeModel, clazz, fieldName, dataType, columnSize, digits); field.javadoc().add(remarks); getter(clazz, field, fieldName, remarks); setter(codeModel, clazz, field, fieldName, remarks); } } finally { rs.close(); } }
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 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); } } }
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); }
public void addCreator(JDefinedClass jclass) { JClass creatorType = jclass.owner().ref(Creator.class).narrow(jclass); JDefinedClass creatorClass = jclass.owner().anonymousClass(creatorType); addCreateFromParcel(jclass, creatorClass); addNewArray(jclass, creatorClass); JFieldVar creatorField = jclass.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, creatorType, "CREATOR"); creatorField.init(JExpr._new(creatorClass)); }
private void genListeners( Refs r, Map<Ref, JFieldVar> fieldVarMap, JFieldVar holdrListener, Collection<Ref> refs, JBlock body, Map<Listener.Type, ListenerType> listenerTypeMap) { if (holdrListener == null) return; for (Ref ref : refs) { if (ref instanceof View) { JFieldVar fieldVar = fieldVarMap.get(ref); View view = (View) ref; if (view.isNullable) { body = body._if(fieldVar.ne(_null()))._then(); } for (Listener listener : view.listeners) { ListenerType listenerType = listenerTypeMap.get(listener.type); JDefinedClass listenerClass = r.m.anonymousClass(listenerType.classType); JMethod method = listenerClass.method(PUBLIC, listenerType.methodReturn, listenerType.methodName); List<JVar> params = new ArrayList<JVar>(); for (Pair<JType, String> arg : listenerType.methodParams) { JVar param = method.param(arg.first, arg.second); params.add(arg.second.equals("view") ? fieldVar : param); } method.annotate(r.overrideAnnotation); JBlock innerBody = method.body(); JBlock innerIf = innerBody._if(holdrListener.ne(_null()))._then(); JInvocation invokeHoldrListener; if (listenerType.defaultReturn == null) { invokeHoldrListener = innerIf.invoke(holdrListener, listener.name); } else { invokeHoldrListener = holdrListener.invoke(listener.name); innerIf._return(invokeHoldrListener); innerBody._return(listenerType.defaultReturn); } for (JVar param : params) { invokeHoldrListener.arg(param); } body.invoke(fieldVar, listenerType.setter).arg(_new(listenerClass)); } } } }
private void addWithersFor(Filter filter, JDefinedClass bldrCls, JVar paramBuilder) throws ClassNotFoundException, JClassAlreadyExistsException { JDefinedClass cls = (JDefinedClass) bldrCls.parentContainer(); JFieldVar field = cls.field(privateStaticFinal, String.class, sanitize(filter.getName().toUpperCase())); field.init(JExpr.lit(filter.getName())); JClass paramType = mapType(filter); if (Boolean.TRUE.equals(filter.isMultipleValues())) { JMethod iterableWither = addIterableWither(filter, bldrCls, paramBuilder, field, paramType); addVarArgsWither(filter, iterableWither, bldrCls, paramType); } else { addWither(filter, bldrCls, paramBuilder, field, paramType); } }
public void addWriteToParcel(JDefinedClass jclass) { JMethod method = jclass.method(JMod.PUBLIC, void.class, "writeToParcel"); JVar dest = method.param(Parcel.class, "dest"); method.param(int.class, "flags"); for (JFieldVar f : jclass.fields().values()) { if ((f.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } if (f.type().erasure().name().equals("List")) { method.body().invoke(dest, "writeList").arg(f); } else { method.body().invoke(dest, "writeValue").arg(f); } } }
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 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 void generateSingularPropertyAccessor(final DefinedPropertyOutline fieldOutline) { final JFieldVar fieldVar = fieldOutline.getFieldVar(); if (fieldVar != null) { final JMethod modifier = this.modifierClass.method( JMod.PUBLIC, this.modifierClass.owner().VOID, ModifierGenerator.SETTER_PREFIX + fieldOutline.getBaseName()); final JVar parameter = modifier.param(JMod.FINAL, fieldVar.type(), fieldOutline.getFieldName()); if (this.implement) { modifier .body() .add( new NestedThisRef(this.classOutline.getImplClass()) .invoke(modifier.name()) .arg(parameter)); } } }
private void getter(JDefinedClass clazz, JFieldVar field, String fieldName, String remarks) { // getter JMethod getter = clazz.method(JMod.PUBLIC, field.type(), "get" + fieldName); /* Addign java doc for method */ JDocComment jDoc = addMethodDoc(getter, remarks + "取得"); JCommentPart rtn = jDoc.addReturn(); rtn.add(remarks); JBlock block = getter.body(); block._return(field); }
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 Map<Ref, JFieldVar> genFields(Refs r, JDefinedClass clazz, Collection<Ref> refs) { Map<Ref, JFieldVar> fieldVarMap = new LinkedHashMap<Ref, JFieldVar>(); for (Ref ref : refs) { String idPackage = (ref.isAndroidId ? "android" : r.packageName) + ".R"; JFieldVar var; if (ref instanceof View) { var = clazz.field(PUBLIC, r.ref(((View) ref).type), ref.fieldName); var.javadoc().append("View for {@link " + idPackage + ".id#" + ref.id + "}."); if (ref.isNullable) { var.annotate(r.nullableAnnotation); } } else if (ref instanceof Include) { var = clazz.field(PUBLIC, r.ref(getClassName(((Include) ref).layout)), ref.fieldName); var.javadoc() .append("Holdr for {@link " + idPackage + ".layout#" + ((Include) ref).layout + "}."); } else { throw new IllegalArgumentException("Unknown ref: " + ref); } fieldVarMap.put(ref, var); } return fieldVarMap; }
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 void setter( JCodeModel codeModel, JDefinedClass clazz, JFieldVar field, String fieldName, String remarks) { // setter JMethod setter = clazz.method(JMod.PUBLIC, codeModel.VOID, "set" + fieldName); JVar param = setter.param(field.type(), toFirstCharLower(fieldName)); // メソッド引数 /* Addign java doc for method */ addMethodDoc(setter, remarks + "設定", param); JBlock block2 = setter.body(); block2.assign(JExpr._this().ref(field), param); // ローカル変数からインスタンス変数へセット }
@Override public void propertyField( JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { field.annotate(JsonProperty.class).param("value", propertyName); if (field.type().erasure().equals(field.type().owner().ref(Set.class))) { field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class); } if (propertyNode.has("javaJsonView")) { field .annotate(JsonView.class) .param("value", field.type().owner().ref(propertyNode.get("javaJsonView").asText())); } if (propertyNode.has("description")) { field.annotate(JsonPropertyDescription.class).param("value", propertyNode.asText()); } }
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 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")); }
@Override public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) { field.annotate(JsonIgnore.class); }
private static void processField( FieldType field, JDefinedClass packetClass, JCodeModel codeModel, AtomicInteger numberOfUnknowns, boolean fromClient) throws JClassAlreadyExistsException { boolean isNested = (field.getType() == PacketSimpleTypes.OPTIONAL) || (field.getType() == PacketSimpleTypes.ARRAY_STATIC) || (field.getType() == PacketSimpleTypes.ARRAY_VAR_SMALL) || (field.getType() == PacketSimpleTypes.ARRAY_VAR_BIG); boolean isArray = (field.getType() == PacketSimpleTypes.BUFFER_STATIC) || (field.getType() == PacketSimpleTypes.BUFFER_VAR_SMALL) || (field.getType() == PacketSimpleTypes.BUFFER_VAR_BIG) || (isNested && (field.getType() != PacketSimpleTypes.OPTIONAL)); boolean isStaticLength = (isArray) && ((field.getType() == PacketSimpleTypes.ARRAY_STATIC) || (field.getType() == PacketSimpleTypes.BUFFER_STATIC)); // length is either not set for non arrays and static arrays, // its 1byte for small stuff and 2bytes for big stuff. int prefixLength = (!isArray || isStaticLength) ? -1 : (field.getType() == PacketSimpleTypes.ARRAY_VAR_SMALL) || (field.getType() == PacketSimpleTypes.BUFFER_VAR_SMALL) ? 1 : 2; String name = ""; if (field.getInfo() == null || field.getInfo().getName() == null) { // check if we got special fields... if (field.getType() == PacketSimpleTypes.AGENTID) { name = "AgentID"; } else if (field.getType() == PacketSimpleTypes.OPTIONAL) { name = "Optional"; } else { name = "Unknown"; } name += numberOfUnknowns.incrementAndGet(); } else { name = field.getInfo().getName(); } String fieldName = WordUtils.uncapitalize(name); String fieldDescription = (field.getInfo() == null || field.getInfo().getDescription() == null || field.getInfo().getDescription().isEmpty()) ? "" : "\n" + WordUtils.wrap(field.getInfo().getDescription(), /* maximumLength */ 50); JType fieldType; if (isNested) { JDefinedClass nestedClass = packetClass ._class(JMod.FINAL | JMod.STATIC | JMod.PUBLIC, "Nested" + name) ._implements(NestedMarker.class); AtomicInteger numberOfUnknownsNested = new AtomicInteger(); for (FieldType nested : field.getField()) { processField(nested, nestedClass, codeModel, numberOfUnknownsNested, fromClient); } // generate getters, setters for (JFieldVar fieldVar : nestedClass.fields().values()) { processAccessors(fieldVar, nestedClass, fromClient); } processToString(nestedClass, codeModel); // nested classes are either arrays or optional... // meaning we will later have to test if they are null before reading/writing fieldType = isArray ? nestedClass.array() : nestedClass; } else { Class<?> fieldClass = convertFieldTypeToClass(field); fieldType = codeModel._ref(fieldClass); } LOGGER.debug("|+-Processing field: {}, of type: {}", fieldName, fieldType); // add the field JFieldVar packetField = packetClass.field(JMod.PRIVATE, fieldType, fieldName); if (fieldDescription != null && !fieldDescription.trim().equals("")) { JDocComment jDocComment = packetField.javadoc(); jDocComment.add(fieldDescription); } // and dont forget array annotations if necessary if (isArray) { int size = (int) (field.getElements() == null ? -1 : field.getElements()); packetField .annotate(IsArray.class) .param("constant", isStaticLength) .param("size", size) .param("prefixLength", prefixLength); } // or any special annotations if (field.getType() == PacketSimpleTypes.LONG) { packetField.annotate(IsInt64.class); } if (field.getType() == PacketSimpleTypes.VARINT) { packetField.annotate(IsVarInt.class); } if (field.getType() == PacketSimpleTypes.ASCII) { packetField.annotate(IsASCII.class); } }