private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) { JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME); JTypeVar returnType = method.generify("T"); method.type(returnType); Models.suppressWarnings(method, "unchecked"); JVar nameParam = method.param(String.class, "name"); JBlock body = method.body(); JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value", invoke(internalGetMethod).arg(nameParam).arg(notFoundValue)); JConditional found = method.body()._if(notFoundValue.ne(valueVar)); found._then()._return(cast(returnType, valueVar)); JBlock notFound = found._else(); JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {}); if (getAdditionalProperties != null) { notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam))); } else { notFound._throw(illegalArgumentInvocation(jclass, nameParam)); } return method; }
private JMethod addPublicSetMethod(JDefinedClass jclass, JMethod internalSetMethod) { JMethod method = jclass.method(PUBLIC, jclass.owner().VOID, SETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar valueParam = method.param(Object.class, "value"); JBlock body = method.body(); JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then(); // if we have additional properties, then put value. JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {}); if (getAdditionalProperties != null) { JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1); notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam) .arg(cast(additionalPropertiesType, valueParam))); } // else throw exception. else { notFound._throw(illegalArgumentInvocation(jclass, nameParam)); } return method; }
private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) { JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME); JVar nameParam = method.param(String.class, "name"); JVar valueParam = method.param(Object.class, "value"); JBlock body = method.body(); JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then(); // if we have additional properties, then put value. JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {}); if (getAdditionalProperties != null) { JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1); notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam) .arg(cast(additionalPropertiesType, valueParam))); } // else throw exception. else { notFound._throw(illegalArgumentInvocation(jclass, nameParam)); } body._return(_this()); return method; }
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); }
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); }
/** * @return A list of the class level annotations that the annotator will * use. */ private List<MetaAnnotation> buildClassAnnotations() { List<MetaAnnotation> anns = Lists.newArrayList(); HashMap<String, Object> annotParams; // AlwaysValid JDefinedClass alwaysValid = buildTemplateConstraint("AlwaysValid"); JDefinedClass alwaysValidValidator = buildTemplateConstraintValidator("AlwaysValidValidator", alwaysValid, Object.class); JMethod isValid = getIsValidMethod(alwaysValidValidator); isValid.body()._return(JExpr.TRUE); alwaysValid.annotate(Constraint.class).param("validatedBy", alwaysValidValidator); annotParams = Maps.newHashMap(); anns.add(new MetaAnnotation(alwaysValid, AnnotationType.JSR_303, annotParams)); return anns; }
@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()); }
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)); }
public JMethod createCreateBeanMethod(final JDefinedClass bean) { final JMethod method = bean.method(JMod.PRIVATE | JMod.STATIC, bean, "_createBean"); final JVar param = method.param( _classByNames(java.lang.Class.class.getName(), MessageFormat.format("? extends {0}", bean.name())), "clazz"); final JClass invokerClass = _classByNames( "net.anwiba.commons.reflection.ReflectionConstructorInvoker", bean.name()); final JTryBlock _try = method.body()._try(); final JVar invoker = _try.body().decl(invokerClass, "invoker", JExpr._new(invokerClass).arg(param)); //$NON-NLS-1$ _try.body()._return(invoker.invoke("invoke")); final JCatchBlock _catch = _try._catch(_classByNames(java.lang.reflect.InvocationTargetException.class.getName())); final JVar exception = _catch.param("exception"); //$NON-NLS-1$ _catch.body()._throw(JExpr._new(_classByNames(java.lang.RuntimeException.class.getName())).arg(exception)); return method; }
@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; }
public static IProcedure<JVar, RuntimeException> createAddIfNullSetEmptyArrayAndReturnClosure( final JCodeModel codeModel, final JMethod method, final JExpression returnValue) { ensureThatArgument(method, notNull()); return new IProcedure<JVar, RuntimeException>() { @Override public void execute(final JVar param) throws RuntimeException { ensureThatArgument(param, notNull()); final ValueConverter valueConverter = new ValueConverter(codeModel); final JInvocation invocation = JExpr._new(param.type()); method .body() ._if(param.eq(JExpr._null())) ._then() .block() .assign(JExpr.refthis(param.name()), valueConverter.convert(invocation)) ._return(returnValue); } }; }
public static IProcedure<JVar, RuntimeException> createAddIfNullClearMapAndReturnClosure( final JMethod method, final JExpression returnValue) { ensureThatArgument(method, notNull()); return new IProcedure<JVar, RuntimeException>() { @Override public void execute(final JVar param) throws RuntimeException { ensureThatArgument(param, notNull()); method .body() ._if(param.eq(JExpr._null())) ._then() .block() .add(JExpr.refthis(param.name()).invoke("clear")) ._return(returnValue); } }; }
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); }
@SafeVarargs public static IProcedure<JVar, RuntimeException> createEnsureArgumentNotNullClosure( final EnsurePredicateFactory ensurePredicateFactory, final JMethod method, final IAcceptor<JVar>... acceptors) { ensureThatArgument(ensurePredicateFactory, notNull()); ensureThatArgument(method, notNull()); return new IProcedure<JVar, RuntimeException>() { @Override public void execute(final JVar param) throws RuntimeException { ensureThatArgument(param, notNull()); for (final IAcceptor<JVar> acceptor : acceptors) { if (!acceptor.accept(param)) { return; } } method.body().add(ensurePredicateFactory.ensureArgumentNotNull(param)); } }; }
/** * <p>createResourceMethod.</p> * * @param resourceInterface a {@link com.sun.codemodel.JDefinedClass} object. * @param methodName a {@link java.lang.String} object. * @param returnType a {@link com.sun.codemodel.JType} object. * @return a {@link com.sun.codemodel.JMethod} object. */ public JMethod createResourceMethod(final JDefinedClass resourceInterface, final String methodName, final JType returnType) { final Set<String> existingMethodNames = resourcesMethods.get(resourceInterface.name()); String actualMethodName; int i = -1; while (true) { actualMethodName = methodName + (++i == 0 ? "" : Integer.toString(i)); if (!existingMethodNames.contains(actualMethodName)) { existingMethodNames.add(actualMethodName); break; } } return resourceInterface.method(JMod.NONE, returnType, actualMethodName); }
protected JClass createResourceMethodReturnType(final String methodName, final Action action, final JDefinedClass resourceInterface) throws Exception { final JDefinedClass responseClass = resourceInterface._class(capitalize(methodName) + "Response") ._extends(context.getResponseWrapperType()); final JMethod responseClassConstructor = responseClass.constructor(JMod.PRIVATE); responseClassConstructor.param(javax.ws.rs.core.Response.class, "delegate"); responseClassConstructor.body().invoke("super").arg(JExpr.ref("delegate")); for (final Response statusCodeAndResponse : action.responses()) { createResponseBuilderInResourceMethodReturnType(action, responseClass, statusCodeAndResponse); } return responseClass; }
private void addCatchAllFormParametersArgument(final MimeType bodyMimeType, final JMethod method, final JDocComment javadoc, final JType argumentType) { method.param(argumentType, GENERIC_PAYLOAD_ARGUMENT_NAME); // build a javadoc text out of all the params List<INamedParam> formParameters = bodyMimeType.getFormParameters(); if(formParameters!=null){ for (INamedParam formParameter : formParameters) { final StringBuilder sb = new StringBuilder(); sb.append(formParameter.getKey()).append(": "); appendParameterJavadocDescription(formParameter, sb); javadoc.addParam(GENERIC_PAYLOAD_ARGUMENT_NAME).add(sb.toString()); } } }
/** * <p>addFormParameters.</p> * * @param bodyMimeType a {@link org.aml.apimodel.MimeType} object. * @param method a {@link com.sun.codemodel.JMethod} object. * @param javadoc a {@link com.sun.codemodel.JDocComment} object. * @throws java.lang.Exception if any. */ protected void addFormParameters(final MimeType bodyMimeType, final JMethod method, final JDocComment javadoc) throws Exception { if (hasAMultiTypeFormParameter(bodyMimeType)) { // use a "catch all" MultivaluedMap<String, String> parameter final JClass type = types.getGeneratorClass(MultivaluedMap.class) .narrow(String.class, String.class); addCatchAllFormParametersArgument(bodyMimeType, method, javadoc, type); } else { for (final INamedParam namedFormParameters : bodyMimeType.getFormParameters()) { addParameter(namedFormParameters.getKey(), namedFormParameters, FormParam.class, method, javadoc); } } }
@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")); }
private JDefinedClass createResourceMethodReturnType(final String methodName, final Action action, final JDefinedClass resourceInterface) throws Exception { final JDefinedClass responseClass = resourceInterface._class(capitalize(methodName) + "Response") ._extends(context.getResponseWrapperType()); final JMethod responseClassConstructor = responseClass.constructor(JMod.PRIVATE); responseClassConstructor.param(javax.ws.rs.core.Response.class, "delegate"); responseClassConstructor.body().invoke("super").arg(JExpr.ref("delegate")); for (final Response statusCodeAndResponse : action.responses()) { createResponseBuilderInResourceMethodReturnType(action, responseClass, statusCodeAndResponse); } return responseClass; }
/** * <p>addBodyParameters.</p> * * @param bodyMimeType a {@link org.aml.apimodel.MimeType} object. * @param method a {@link com.sun.codemodel.JMethod} object. * @param javadoc a {@link com.sun.codemodel.JDocComment} object. * @throws java.lang.Exception if any. */ protected void addBodyParameters(final MimeType bodyMimeType, final JMethod method, final JDocComment javadoc) throws Exception { if (bodyMimeType == null) { return; } else if (MediaType.APPLICATION_FORM_URLENCODED.equals(bodyMimeType .getType())) { addFormParameters(bodyMimeType, method, javadoc); } else if (MediaType.MULTIPART_FORM_DATA.equals(bodyMimeType.getType())) { // use a "catch all" javax.mail.internet.MimeMultipart parameter addCatchAllFormParametersArgument(bodyMimeType, method, javadoc, types.getGeneratorType(MimeMultipart.class)); } else { addPlainBodyArgument(bodyMimeType, method, javadoc); } }
private void buildNonVoidMethods(Method method, int numResponseTypes) { for (int bodyIndex = 0; bodyIndex < numResponseTypes; bodyIndex++) { TypeDeclaration body = method.responses().get(0).body().get(bodyIndex); String methodName = buildMethodName(method, bodyIndex); JMethod codeMethod = klass.method(JMod.NONE, klass, methodName); addJavadoc(method, codeMethod); addSubresourcePath(codeMethod); addHttpMethodAnnotation(method.method(), codeMethod); addBodyParameters(method, codeMethod); addPathParameters(method, codeMethod); addQueryParameters(method, codeMethod); addReturnType(method, codeMethod, body); addProduces(codeMethod, body); } }
/** * @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 JMethod addInternalGetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) { JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue"); JBlock body = method.body(); JSwitch propertySwitch = body._switch(nameParam); if (propertiesNode != null) { for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) { Map.Entry<String, JsonNode> property = properties.next(); String propertyName = property.getKey(); JsonNode node = property.getValue(); String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node); JType propertyType = jclass.fields().get(fieldName).type(); addGetPropertyCase(jclass, propertySwitch, propertyName, propertyType, node); } } JClass extendsType = jclass._extends(); if (extendsType != null && extendsType instanceof JDefinedClass) { JDefinedClass parentClass = (JDefinedClass) extendsType; JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME, new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) }); propertySwitch._default().body() ._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam)); } else { propertySwitch._default().body() ._return(notFoundParam); } return method; }
private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) { JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue"); JBlock body = method.body(); JConditional propertyConditional = null; if (propertiesNode != null) { for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) { Map.Entry<String, JsonNode> property = properties.next(); String propertyName = property.getKey(); JsonNode node = property.getValue(); String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node); JType propertyType = jclass.fields().get(fieldName).type(); JExpression condition = lit(propertyName).invoke("equals").arg(nameParam); if (propertyConditional == null) { propertyConditional = body._if(condition); } else { propertyConditional = propertyConditional._elseif(condition); } JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {}); propertyConditional._then()._return(invoke(propertyGetter)); } } JClass extendsType = jclass._extends(); JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else(); if (extendsType != null && extendsType instanceof JDefinedClass) { JDefinedClass parentClass = (JDefinedClass) extendsType; JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME, new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) }); lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam)); } else { lastBlock._return(notFoundParam); } return method; }
private JMethod addInternalSetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) { JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar valueParam = method.param(Object.class, "value"); JBlock body = method.body(); JSwitch propertySwitch = body._switch(nameParam); if (propertiesNode != null) { for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) { Map.Entry<String, JsonNode> property = properties.next(); String propertyName = property.getKey(); JsonNode node = property.getValue(); String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node); JType propertyType = jclass.fields().get(fieldName).type(); addSetPropertyCase(jclass, propertySwitch, propertyName, propertyType, valueParam, node); } } JBlock defaultBlock = propertySwitch._default().body(); JClass extendsType = jclass._extends(); if (extendsType != null && extendsType instanceof JDefinedClass) { JDefinedClass parentClass = (JDefinedClass) extendsType; JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME, new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) }); defaultBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam)); } else { defaultBlock._return(FALSE); } return method; }
private JMethod addInternalSetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) { JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar valueParam = method.param(Object.class, "value"); JBlock body = method.body(); JConditional propertyConditional = null; if (propertiesNode != null) { for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) { Map.Entry<String, JsonNode> property = properties.next(); String propertyName = property.getKey(); JsonNode node = property.getValue(); String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node); JType propertyType = jclass.fields().get(fieldName).type(); JExpression condition = lit(propertyName).invoke("equals").arg(nameParam); propertyConditional = propertyConditional == null ? propertyConditional = body._if(condition) : propertyConditional._elseif(condition); JBlock callSite = propertyConditional._then(); addSetProperty(jclass, callSite, propertyName, propertyType, valueParam, node); callSite._return(TRUE); } } JClass extendsType = jclass._extends(); JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else(); if (extendsType != null && extendsType instanceof JDefinedClass) { JDefinedClass parentClass = (JDefinedClass) extendsType; JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME, new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) }); lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam)); } else { lastBlock._return(FALSE); } return method; }
private void addSetProperty(JDefinedClass jclass, JBlock callSite, String propertyName, JType propertyType, JVar valueVar, JsonNode node) { JMethod propertySetter = jclass.getMethod(getSetterName(propertyName, node), new JType[] { propertyType }); JConditional isInstance = callSite._if(valueVar._instanceof(propertyType.boxify().erasure())); isInstance._then() .invoke(propertySetter).arg(cast(propertyType.boxify(), valueVar)); isInstance._else() ._throw(illegalArgumentInvocation(jclass, propertyName, propertyType, valueVar)); }
private JFieldVar addValueField(JDefinedClass _enum, JType type) { JFieldVar valueField = _enum.field(JMod.PRIVATE | JMod.FINAL, type, VALUE_FIELD_NAME); JMethod constructor = _enum.constructor(JMod.PRIVATE); JVar valueParam = constructor.param(type, VALUE_FIELD_NAME); JBlock body = constructor.body(); body.assign(JExpr._this().ref(valueField), valueParam); return valueField; }
private void addToString(JDefinedClass _enum, JFieldVar valueField) { JMethod toString = _enum.method(JMod.PUBLIC, String.class, "toString"); JBlock body = toString.body(); JExpression toReturn = JExpr._this().ref(valueField); if(!isString(valueField.type())){ toReturn = toReturn.plus(JExpr.lit("")); } body._return(toReturn); toString.annotate(Override.class); }
private void addValueMethod(JDefinedClass _enum, JFieldVar valueField) { JMethod fromValue = _enum.method(JMod.PUBLIC, valueField.type(), "value"); JBlock body = fromValue.body(); body._return(JExpr._this().ref(valueField)); ruleFactory.getAnnotator().enumValueMethod(fromValue); }
private void updateGetterSetterJavaDoc(JDefinedClass jclass, List<String> requiredFieldMethods) { for (Iterator<JMethod> methods = jclass.methods().iterator(); methods.hasNext();) { JMethod method = methods.next(); if (requiredFieldMethods.contains(method.name())) { addJavaDoc(method); } } }
private JMethod addGetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) { JMethod getter = c.method(JMod.PUBLIC, field.type(), getGetterName(jsonPropertyName, field.type(), node)); JBlock body = getter.body(); body._return(field); return getter; }