@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minItems") || node.has("maxItems"))) { JAnnotationUse annotation = field.annotate(Size.class); if (node.has("minItems")) { annotation.param("min", node.get("minItems").asInt()); } if (node.has("maxItems")) { annotation.param("max", node.get("maxItems").asInt()); } } return field; }
@Override public void dateField(JFieldVar field, JsonNode node) { String pattern = null; if (node.has("customDatePattern")) { pattern = node.get("customDatePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) { pattern = getGenerationConfig().getCustomDatePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_DATE_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern); } }
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); }
/** * Applies this schema rule to take the required code generation steps. * <p> * Default values are implemented by assigning an expression to the given * field (so when instances of the generated POJO are created, its fields * will then contain their default values). * <p> * Collections (Lists and Sets) are initialized to an empty collection, even * when no default value is present in the schema (node is null). * * @param nodeName * the name of the property which has (or may have) a default * @param node * the default node (may be null if no default node was present * for this property) * @param field * the Java field that has added to a generated type to represent * this property * @return field, which will have an init expression is appropriate */ @Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { boolean defaultPresent = node != null && isNotEmpty(node.asText()); String fieldType = field.type().fullName(); if (defaultPresent && !field.type().isPrimitive() && node.isNull()) { field.init(JExpr._null()); } else if (fieldType.startsWith(List.class.getName())) { field.init(getDefaultList(field.type(), node)); } else if (fieldType.startsWith(Set.class.getName())) { field.init(getDefaultSet(field.type(), node)); } else if (fieldType.startsWith(String.class.getName()) && node != null ) { field.init(getDefaultValue(field.type(), node)); } else if (defaultPresent) { field.init(getDefaultValue(field.type(), node)); } return field; }
/** * Applies this schema rule to take the not required code generation steps. * <p> * The not required rule adds a Nullable annotation if JSR-305 annotations are desired. * * @param nodeName * the name of the schema node for which this "required" rule has * been added * @param node * the "not required" node, having a value <code>false</code> or * <code>no value</code> * @param generatableType * the class or method which may be marked as "not required" * @return the JavaDoc comment attached to the generatableType, which * <em>may</em> have an added not to mark this construct as * not required. */ @Override public JDocCommentable apply(String nodeName, JsonNode node, JDocCommentable generatableType, Schema schema) { // Since NotRequiredRule is executed for all fields that do not have "required" present, // we need to recognize whether the field is part of the RequiredArrayRule. JsonNode requiredArray = schema.getContent().get("required"); if (requiredArray != null) { for (Iterator<JsonNode> iterator = requiredArray.elements(); iterator.hasNext(); ) { String requiredArrayItem = iterator.next().asText(); if (nodeName.equals(requiredArrayItem)) { return generatableType; } } } if (ruleFactory.getGenerationConfig().isIncludeJsr305Annotations() && generatableType instanceof JFieldVar) { generatableType.javadoc().append(NOT_REQUIRED_COMMENT_TEXT); ((JFieldVar) generatableType).annotate(Nullable.class); } return generatableType; }
/** * Applies this schema rule to take the required code generation steps. * <p> * The required rule simply adds a note to the JavaDoc comment to mark a * property as required. * * @param nodeName * the name of the schema node for which this "required" rule has * been added * @param node * the "required" node, having a value <code>true</code> or * <code>false</code> * @param generatableType * the class or method which may be marked as "required" * @return the JavaDoc comment attached to the generatableType, which * <em>may</em> have an added not to mark this construct as * required. */ @Override public JDocCommentable apply(String nodeName, JsonNode node, JDocCommentable generatableType, Schema schema) { if (node.asBoolean()) { generatableType.javadoc().append("\n(Required)"); if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && generatableType instanceof JFieldVar) { ((JFieldVar) generatableType).annotate(NotNull.class); } if (ruleFactory.getGenerationConfig().isIncludeJsr305Annotations() && generatableType instanceof JFieldVar) { ((JFieldVar) generatableType).annotate(Nonnull.class); } } else { if (ruleFactory.getGenerationConfig().isIncludeJsr305Annotations() && generatableType instanceof JFieldVar) { ((JFieldVar) generatableType).annotate(Nullable.class); } } return generatableType; }
@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minLength") || node.has("maxLength"))) { JAnnotationUse annotation = field.annotate(Size.class); if (node.has("minLength")) { annotation.param("min", node.get("minLength").asInt()); } if (node.has("maxLength")) { annotation.param("max", node.get("maxLength").asInt()); } } return field; }
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 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.get("description").asText()); } }
@Override public void timeField(JFieldVar field, JsonNode node) { String pattern = null; if (node.has("customTimePattern")) { pattern = node.get("customTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomTimePattern())) { pattern = getGenerationConfig().getCustomTimePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_TIME_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern); } }
@Override public void dateTimeField(JFieldVar field, JsonNode node) { String timezone = node.has("customTimezone") ? node.get("customTimezone").asText() : "UTC"; String pattern = null; if (node.has("customDateTimePattern")) { pattern = node.get("customDateTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDateTimePattern())) { pattern = getGenerationConfig().getCustomDateTimePattern(); } else if (getGenerationConfig().isFormatDateTimes()) { pattern = FormatRule.ISO_8601_DATETIME_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern).param("timezone", timezone); } }
public JFieldVar create( final JDefinedClass instance, final Iterable<Annotation> annotation, final Type type, final String name, final Object value, final boolean isImutable, final boolean isNullable, final boolean isPrimitivesEnabled, final boolean isArrayNullable, final boolean isCollectionNullable) throws CreationException { final String fieldName = createFieldName(name); final JType clazz = _class(type, isPrimitivesEnabled); final JFieldVar field = isInstanceOfMap(clazz) // ? mapMember(instance, clazz, fieldName, type.generics()) : isInstanceOfList(clazz) // ? listMember(instance, clazz, fieldName, type.generics(), isNullable, isCollectionNullable) : objectMember(instance, clazz, fieldName, value, isImutable, isArrayNullable); annotate(field, annotation); return field; }
private JFieldVar listMember( final JDefinedClass instance, final JType clazz, final String name, final String[] generics, final boolean isNullable, final boolean isCollectionNullable) { final JFieldVar field = instance.field(JMod.FINAL | JMod.PRIVATE, clazz, name); if (isNullable && isCollectionNullable) { return field; } final JType type = withoutGenerics(clazz.fullName()).startsWith(JAVA_UTIL_LIST) ? _type(JAVA_UTIL_ARRAYLIST, generics) : clazz; field.init(JExpr._new(type)); return field; }
public Map<Member, JFieldVar> fields(final JDefinedClass instance, final Bean configuration) throws CreationException { final Map<Member, JFieldVar> result = new LinkedHashMap<>(); for (final Member member : configuration.members()) { if (!member.setter().isEnabled()) { continue; } final JFieldVar field = this.memberFactory.create( instance, member.annotations(), member.type(), member.name(), member.value(), false, member.isNullable(), configuration.isPrimitivesEnabled(), configuration.isArrayNullable(), configuration.isCollectionNullable()); result.put(member, field); } return result; }
public Map<Member, JFieldVar> fields(final JDefinedClass instance, final Bean configuration) throws CreationException { final Map<Member, JFieldVar> result = new LinkedHashMap<>(); for (final Member member : configuration.members()) { final JFieldVar field = this.memberFactory.create( instance, member.annotations(), member.type(), member.name(), member.value(), member.isImutable(), member.isNullable(), configuration.isPrimitivesEnabled(), configuration.isArrayNullable(), configuration.isCollectionNullable()); result.put(member, field); } return result; }
public JVar create( final JDefinedClass instance, final boolean returnInstance, final JFieldVar field, final String name, final boolean isImutable, final boolean isNullable, final boolean isArrayNullable, final boolean isCollectionNullable, final List<Annotation> annotations) throws CreationException { final JMethod method = instance.method(JMod.PUBLIC, returnInstance ? instance : _void(), name); annotate(method, annotations); final JVar variable = addParameter( method, returnInstance ? JExpr._this() : null, field, isImutable, isNullable, isArrayNullable, isCollectionNullable); if (returnInstance) { method.body()._return(JExpr._this()); } return variable; }
private JVar addParameter( final JMethod method, final JExpression returnValue, final JFieldVar field, final boolean isImutable, final boolean isNullable, final boolean isArrayNullable, final boolean isCollectionNullable) { if (isImutable) { return SourceFactoryUtilities.addParameter(method, field); } if (isInstanceOfMap(field.type())) { return mapSetter(method, returnValue, field, isNullable); } if (isInstanceOfList(field.type())) { return listSetter(method, returnValue, field, isNullable, isCollectionNullable); } return objectSetter(method, returnValue, field, isNullable, isArrayNullable); }
private JVar listSetter( final JMethod method, final JExpression returnValue, final JFieldVar field, final boolean isNullable, final boolean isCollectionNullable) { if (isNullable) { if (!isCollectionNullable) { return addListParameter(method, field, true, createAddIfNullClearListAndReturnClosure(method, returnValue)); } return addListParameter(method, field, true, createAddIfNullReturnClosure(method, returnValue)); } return addListParameter( method, field, true, createEnsureArgumentNotNullClosure(this.ensurePredicateFactory, method)); }
private JVar objectSetter( final JMethod method, final JExpression returnValue, final JFieldVar field, final boolean isNullable, final boolean isArrayNullable) { if (isNullable) { if (!isArrayNullable && field.type().isArray()) { return addObjectParameter( method, field, createAddIfNullSetEmptyArrayAndReturnClosure(this.codeModel, method, returnValue)); } return addObjectParameter(method, field); } return addObjectParameter(method, field, createEnsureArgumentNotNullClosure(this.ensurePredicateFactory, method)); }
public void createEquals(final JDefinedClass bean, final Iterable<JFieldVar> fields) { final JMethod method = bean.method(JMod.PUBLIC, this.codeModel.BOOLEAN, "equals"); method.annotate(java.lang.Override.class); final JVar object = method.param(_type(java.lang.Object.class.getName()), "object"); final JBlock block = method.body(); block._if(JExpr._this().eq(object))._then()._return(JExpr.TRUE); block._if(object._instanceof(bean).not())._then()._return(JExpr.FALSE); JExpression result = JExpr.TRUE; final JExpression other = block.decl(bean, "other", JExpr.cast(bean, object)); final JClass objectUtilities = _classByNames(net.anwiba.commons.lang.object.ObjectUtilities.class.getName()); for (final JFieldVar field : fields) { result = result.cand(objectUtilities.staticInvoke("equals").arg(JExpr.refthis(field.name())).arg(other.ref(field))); } block._return(result); }
@SafeVarargs public static JVar addMapParameter( final JMethod method, final JFieldVar field, final JType nameType, final String nameVariableName, final JType valueType, final String valueVariableName, final boolean isInjection, final IProcedure<JVar, RuntimeException>... procedure) { if (method == null || field == null) { return null; } final JVar nameParam = method.param(JMod.FINAL, nameType, nameVariableName); final JVar valueParam = method.param(JMod.FINAL, valueType, valueVariableName); for (final IProcedure<JVar, RuntimeException> closure : procedure) { closure.execute(nameParam); closure.execute(valueParam); } if (isInjection) { method.body().invoke("_inject").arg(nameParam).arg(valueParam); //$NON-NLS-1$ } method.body().add(JExpr.refthis(field.name()).invoke("put").arg(nameParam).arg(valueParam)); //$NON-NLS-1$ return valueParam; }
@SafeVarargs public static JVar setMapParameters( final JMethod method, final JFieldVar field, final boolean isClearEnabled, final IProcedure<JVar, RuntimeException>... procedure) { if (method == null || field == null) { return null; } final JVar param = method.param(JMod.FINAL, field.type(), field.name()); for (final IProcedure<JVar, RuntimeException> closure : procedure) { closure.execute(param); } if (isClearEnabled) { method.body().add(JExpr.refthis(field.name()).invoke("clear")); //$NON-NLS-1$ } method.body().add(JExpr.refthis(field.name()).invoke("putAll").arg(param)); //$NON-NLS-1$ return param; }
@SafeVarargs public static JVar addListParameter( final JMethod method, final JFieldVar field, final boolean isClearEnabled, final IProcedure<JVar, RuntimeException>... procedure) { if (method == null || field == null) { return null; } final JVar param = method.param(JMod.FINAL, field.type(), field.name()); for (final IProcedure<JVar, RuntimeException> closure : procedure) { closure.execute(param); } if (isClearEnabled) { method.body().add(JExpr.refthis(field.name()).invoke("clear")); //$NON-NLS-1$ } method.body().add(JExpr.refthis(field.name()).invoke("addAll").arg(param)); //$NON-NLS-1$ return param; }
private void addDiscriminator(JDefinedClass klass, ObjectTypeDeclaration type) { if (type.discriminator() == null) { return; } String discriminatorValue = type.discriminatorValue(); if (discriminatorValue == null) { discriminatorValue = type.name(); } JFieldVar field = klass.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, codeModel._ref(String.class), DISCRIMINATOR); field.init(JExpr.lit(discriminatorValue)); if (context.getConfig().isDiscriminatorMutable()) { klass.constructor(JMod.PUBLIC).body().invoke(getSetterName(type.discriminator())) .arg(field); } else { generateDiscriminatorGetter(type, klass, type.discriminator()); } }
/** * @param klass * @param property */ private void generateAdditionalPropertiesFieldAndAccessors(JDefinedClass klass, TypeDeclaration property) { String fieldName = Names.buildVariableName(property); JClass mapType = codeModel.ref(Map.class).narrow(String.class, Object.class); JFieldVar field = klass.field(JMod.PRIVATE, mapType, fieldName); annotateFieldWithPropertyName(field, property); JMethod getter = klass.method(JMod.PUBLIC, mapType, getGetterName(fieldName)); getter.body()._return(field); if (property.description() != null) { getter.javadoc().add(property.description().value()); } generateSetter(klass, mapType, fieldName); }
private void generateListFieldAndAccessors(JDefinedClass klass, ArrayTypeDeclaration property) { String fieldName = Names.buildVariableName(property); String itemTypeName = context.getApiModel().getItemType(property); JType elementType = findTypeVar(klass, property).orElse(context.getJavaType(itemTypeName)); JClass listType = codeModel.ref(List.class).narrow(elementType); JFieldVar field = klass.field(JMod.PRIVATE, listType, fieldName); annotateFieldWithPropertyName(field, property); JMethod getter = klass.method(JMod.PUBLIC, listType, getGetterName(fieldName)); getter.body()._return(field); if (property.description() != null) { getter.javadoc().add(property.description().value()); } generateSetter(klass, listType, fieldName); }
private void generateObjectFieldAndAccessors(JDefinedClass klass, TypeDeclaration property) { String fieldName = Names.buildVariableName(property); JType jtype = findTypeVar(klass, property).orElse(context.getJavaType(property)); List<String> args = Annotations.getStringAnnotations(property, TYPE_ARGS); if (!args.isEmpty()) { JClass jclass = (JClass) jtype; for (String arg : args) { JType typeArg = findTypeParam(klass, arg).get(); jclass = jclass.narrow(typeArg); } jtype = jclass; } JFieldVar field = klass.field(JMod.PRIVATE, jtype, fieldName); annotateFieldWithPropertyName(field, property); generateGetter(property, klass, field, this::getGetterName); generateSetter(klass, jtype, fieldName); }
protected void assertProperty(JDefinedClass klass, String memberName, String typeName, String getterName, String setterName) { JFieldVar field = klass.fields().get(memberName); assertThat(field).isNotNull(); assertThat(field.type().name()).isEqualTo(typeName); List<JMethod> getters = klass.methods().stream().filter(m -> m.name().equals(getterName)).collect(toList()); assertThat(getters).hasSize(1); JMethod getter = getters.get(0); assertThat(getter.type().name()).isEqualTo(typeName); assertThat(getter.hasSignature(new JType[0])).isEqualTo(true); List<JMethod> setters = klass.methods().stream().filter(m -> m.name().equals(setterName)).collect(toList()); assertThat(setters).hasSize(1); JMethod setter = setters.get(0); assertThat(setter.type()).isEqualTo(codeModel.VOID); assertThat(setter.hasSignature(new JType[]{field.type()})).isEqualTo(true); fieldNames.remove(memberName); methodNames.remove(getterName); methodNames.remove(setterName); }
@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")); }
@BeforeClass public static void generateModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); JAnnotationUse jAnnotationUse = jClass.annotate(InitialDataSets.class); jAnnotationUse.param("value", "Script.file"); jClass.annotate(Cleanup.class); final JFieldVar jField = jClass.field(JMod.PRIVATE, String.class, "testField"); jField.annotate(PersistenceContext.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jAnnotationUse = jMethod.annotate(InitialDataSets.class); jAnnotationUse.param("value", "InitialDataSets.file"); jAnnotationUse = jMethod.annotate(ApplyScriptsAfter.class); jAnnotationUse.param("value", "ApplyScriptsAfter.file"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); cut = loadClass(testFolder.getRoot(), jClass.name()); }
protected static void _importFields(final JDefinedClass theClass, final AtomicInteger index, final SimpleStructureDefinition structure) { final JClass parentClass = theClass._extends(); if (parentClass instanceof JDefinedClass) { _importFields((JDefinedClass) parentClass, index, structure); } for (Entry<String, JFieldVar> entry : theClass.fields().entrySet()) { Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().erasure().fullName()); String fieldName = entry.getKey(); if (fieldName.startsWith("_")) { if (!JJavaName.isJavaIdentifier(fieldName.substring(1))) { fieldName = fieldName.substring(1); // it was prefixed with '_' so we should use the original name. } } structure.setFieldName(index.getAndIncrement(), fieldName, fieldClass); } }
private void renderConstantsClass(JDefinedClass classModel) throws Exception { // define constants class JDefinedClass constantsClass = classModel._class(JMod.STATIC, Util.CONSTANTS_CLASS_NAME); // generate the javadoc on the top of the Constants class JDocComment javadoc = constantsClass.javadoc(); javadoc.append(Util.CONSTANTS_CLASS_JAVADOC); // render root element name JFieldVar rootElementField = constantsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.ROOT_ELEMENT_NAME_FIELD); rootElementField.init(JExpr.lit(Util.toLowerCaseFirstLetter(classModel.name()))); // render type name JFieldVar typeNameField = constantsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.TYPE_NAME_FIELD); typeNameField.init(JExpr.lit(classModel.name() + Util.TYPE_NAME_SUFFIX)); }
private void renderElementsClass(JDefinedClass classModel, List<FieldModel> fields) throws Exception { // define constants class JDefinedClass elementsClass = classModel._class(JMod.STATIC, Util.ELEMENTS_CLASS_NAME); // generate the javadoc on the top of the Elements class JDocComment javadoc = elementsClass.javadoc(); javadoc.append(Util.ELEMENTS_CLASS_JAVADOC); // go through each field and create a corresponding constant for (FieldModel fieldModel : fields) { if (Util.isCommonElement(fieldModel.fieldName)) { continue; } JFieldVar elementFieldVar = elementsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.toConstantsVariable(fieldModel.fieldName)); elementFieldVar.init(JExpr.lit(fieldModel.fieldName)); } }
@Override public void process(Element element, EComponentHolder holder) throws Exception { if (skipGeneratedClass(element)) // I can't prevent copying @Module to generated class, so just don't process it return; holder.getGeneratedClass()._implements(ModuleObjectsShare.IModule.class); final JFieldVar instances = holder.getGeneratedClass().field(JMod.PRIVATE, ModuleObjectsShare.InstancesHolder.class, "instances_"); String moduleName = element.getAnnotation(EModule.class).moduleName(); if (Utility.isEmpty(moduleName)) moduleName = element.asType().toString(); holder.getInitBody().assign(instances, ModuleCodeGenerator.createModule(moduleName, holder)); holder.getInitBody().add(ModuleCodeGenerator.moduleSetInstance(holder, refClass(ModuleObjectsShare.IModule.class), _this())); holder.getInitBody().directStatement("// submodules communicate via {@link " + refClass(Bus.class).fullName() + "}, so we only need to store them"); final JArray submodules = ModuleCodeGenerator.generateSubmodulesArray(element, holder, annotationHelper, getTarget()); if (submodules != null) { final JFieldVar submodulesField = holder.getGeneratedClass().field(JMod.PRIVATE, Object[].class, "submodules_"); holder.getInitBody().assign(submodulesField, submodules); } }
private Map<String, JFieldVar> getNonTransientAndNonStaticFields() { Map<String, JFieldVar> nonStaticNonTransientFields = new LinkedHashMap<>(); if (pojo instanceof JDefinedClass) { Map<String, JFieldVar> fields = ((JDefinedClass) pojo).fields(); Iterator<Map.Entry<String, JFieldVar>> iterator = fields.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, JFieldVar> pair = iterator.next(); // If a field is not static or transient if ((pair.getValue().mods().getValue() & (JMod.STATIC | JMod.TRANSIENT)) == 0) { nonStaticNonTransientFields.put(pair.getKey(), pair.getValue()); } } } return nonStaticNonTransientFields; }
@Override public JFieldVar apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) { JFieldVar field = generatableType.field(JMod.PRIVATE, this.fieldClazz, this.fieldName); //add @Autowired field annoation if (autowire) { field.annotate(Autowired.class); } //add @Qualifier("qualifierBeanName") if (qualifierAnnotation && !StringUtils.isEmpty(qualifier)){ field.annotate(Qualifier.class).param("value", qualifier); } //add @Value(value="") annotation to the field if (valueAnnotation){ field.annotate(Value.class).param("value", valueAnnotationValue); } return field; }
@Test public void interpretGetResponseBodyInheritanceModel() { assertThat(ramlRoot, is(notNullValue())); RamlResource songs = ramlRoot.getResource("/songs"); RamlDataType songsGetType = songs.getAction(RamlActionType.GET).getResponses().get("200").getBody().get("application/json").getType(); assertThat(songsGetType, is(notNullValue())); ApiBodyMetadata songsGetRequest = RamlTypeHelper.mapTypeToPojo( config, jCodeModel, ramlRoot, songsGetType.getType()); assertThat(songsGetRequest, is(notNullValue())); assertThat(songsGetRequest.isArray(), is(false)); JDefinedClass responsePOJO = getResponsePOJO("/songs", "Song"); assertThat(responsePOJO.name(), is("Song")); JFieldVar jFieldVar = responsePOJO.fields().get("fee"); assertThat(jFieldVar.type().name(), is("FeeCategory")); assertThat(jFieldVar.type().getClass().getName(), is(JDefinedClass.class.getName())); checkIntegration(jCodeModel); }
@Test public void checkTypeOfDates() throws Exception { JDefinedClass pojo = getResponsePOJO("/validations", "Validation"); JFieldVar field = getField(pojo, "dateO"); assertThat(field.type().fullName(), is("java.util.Date")); assertAnnotations(field, "yyyy-MM-dd"); field = getField(pojo, "timeO"); assertThat(field.type().fullName(), is("java.util.Date")); assertAnnotations(field, "HH:mm:ss"); field = getField(pojo, "dateTO"); assertThat(field.type().fullName(), is("java.util.Date")); assertAnnotations(field, "yyyy-MM-dd'T'HH:mm:ss"); field = getField(pojo, "dateT"); assertThat(field.type().fullName(), is("java.util.Date")); assertAnnotations(field, "yyyy-MM-dd'T'HH:mm:ssXXX"); field = getField(pojo, "datetimeRFC2616"); assertThat(field.type().fullName(), is("java.util.Date")); assertAnnotations(field, "EEE, dd MMM yyyy HH:mm:ss z"); }
private void fixDummyListField(DummyListField fieldOutline) { if (DummyListField_$get.get(fieldOutline) == null) { final JFieldVar field = AbstractListField_field.get(fieldOutline); final JType listT = AbstractListField_listT.get(fieldOutline); final JClass coreList = DummyListField_coreList .get(fieldOutline); final JMethod $get = fieldOutline.parent().implClass.method( JMod.PUBLIC, listT, "get" + fieldOutline.getPropertyInfo().getName(true)); JBlock block = $get.body(); block._if(field.eq(JExpr._null()))._then() .assign(field, JExpr._new(coreList)); block._return(JExpr._this().ref(field)); DummyListField_$get.set(fieldOutline, $get); } }