Java Code Examples for com.sun.codemodel.JMethod

The following are top voted examples for showing how to use com.sun.codemodel.JMethod. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: EnumRule.java   Source Code and License 7 votes vote down vote up
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);
}
 
Example 2
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 3
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 4
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 5
Project: GitHub   File: ObjectRule.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 6
Project: GitHub   File: ObjectRule.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 7
Project: beanvalidation-benchmark   File: Jsr303Annotator.java   Source Code and License 6 votes vote down vote up
/**
 * @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;
}
 
Example 8
Project: jpa-unit   File: AnnotationInspectorTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 9
Project: libraries   File: SetterFactory.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 10
Project: libraries   File: SetterFactory.java   Source Code and License 6 votes vote down vote up
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));
}
 
Example 11
Project: libraries   File: CreatorFactory.java   Source Code and License 6 votes vote down vote up
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;
  }
 
Example 12
Project: libraries   File: SourceFactoryUtilities.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 13
Project: libraries   File: SourceFactoryUtilities.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 14
Project: libraries   File: SourceFactoryUtilities.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 15
Project: libraries   File: SourceFactoryUtilities.java   Source Code and License 6 votes vote down vote up
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);
    }
  };
}
 
Example 16
Project: libraries   File: SourceFactoryUtilities.java   Source Code and License 6 votes vote down vote up
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);
    }
  };
}
 
Example 17
Project: org.ops4j.ramler   File: AbstractGeneratorTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 18
Project: libraries   File: SourceFactoryUtilities.java   Source Code and License 6 votes vote down vote up
@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));
    }
  };
}
 
Example 19
Project: aml   File: Context.java   Source Code and License 6 votes vote down vote up
/**
 * <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);
}
 
Example 20
Project: aml   File: Generator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 21
Project: aml   File: AbstractGenerator.java   Source Code and License 6 votes vote down vote up
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());
		}
	}
}
 
Example 22
Project: aml   File: AbstractGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * <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);
		}
	}
}
 
Example 23
Project: jpa-unit   File: JpaUnitRuleTest.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 24
Project: aml   File: Context.java   Source Code and License 6 votes vote down vote up
/**
 * <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);
}
 
Example 25
Project: aml   File: Generator.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 26
Project: aml   File: AbstractGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * <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);
		}
	}
}
 
Example 27
Project: aml   File: AbstractGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * <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);
	}
}
 
Example 28
Project: org.ops4j.ramler   File: ResourceGeneratingApiVisitor.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 29
Project: org.ops4j.ramler   File: PojoGeneratingApiVisitor.java   Source Code and License 6 votes vote down vote up
/**
 * @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);
}
 
Example 30
Project: org.ops4j.ramler   File: PojoGeneratingApiVisitor.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 31
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 33
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 34
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 35
Project: GitHub   File: DynamicPropertiesRule.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 36
Project: GitHub   File: EnumRule.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 37
Project: GitHub   File: EnumRule.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 38
Project: GitHub   File: EnumRule.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 39
Project: GitHub   File: RequiredArrayRule.java   Source Code and License 5 votes vote down vote up
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);
        }
    }
}
 
Example 40
Project: GitHub   File: PropertyRule.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 41
Project: GitHub   File: PropertyRule.java   Source Code and License 5 votes vote down vote up
private JMethod addSetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) {
    JMethod setter = c.method(JMod.PUBLIC, void.class, getSetterName(jsonPropertyName, node));

    JVar param = setter.param(field.type(), field.name());
    JBlock body = setter.body();
    body.assign(JExpr._this().ref(field), param);

    return setter;
}
 
Example 42
Project: GitHub   File: PropertyRule.java   Source Code and License 5 votes vote down vote up
private JMethod addBuilder(JDefinedClass c, JFieldVar field) {
    JMethod builder = c.method(JMod.PUBLIC, c, getBuilderName(field.name()));

    JVar param = builder.param(field.type(), field.name());
    JBlock body = builder.body();
    body.assign(JExpr._this().ref(field), param);
    body._return(JExpr._this());

    return builder;
}
 
Example 43
Project: GitHub   File: PropertiesRule.java   Source Code and License 5 votes vote down vote up
private void addOverrideBuilders(JDefinedClass jclass, JDefinedClass parentJclass) {
    if (parentJclass == null) {
        return;
    }

    for (JMethod parentJMethod : parentJclass.methods()) {
        if (parentJMethod.name().startsWith("with") && parentJMethod.params().size() == 1) {
            addOverrideBuilder(jclass, parentJMethod, parentJMethod.params().get(0));
        }
    }
}
 
Example 44
Project: GitHub   File: PropertiesRule.java   Source Code and License 5 votes vote down vote up
private void addOverrideBuilder(JDefinedClass thisJDefinedClass, JMethod parentBuilder, JVar parentParam) {

        if (thisJDefinedClass.getMethod(parentBuilder.name(), new JType[] {parentParam.type()}) == null) {

            JMethod builder = thisJDefinedClass.method(parentBuilder.mods().getValue(), thisJDefinedClass, parentBuilder.name());
            builder.annotate(Override.class);

            JVar param = builder.param(parentParam.type(), parentParam.name());
            JBlock body = builder.body();
            body.invoke(JExpr._super(), parentBuilder).arg(param);
            body._return(JExpr._this());

        }
    }
 
Example 45
Project: GitHub   File: AdditionalPropertiesRule.java   Source Code and License 5 votes vote down vote up
private void addSetter(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    JMethod setter = jclass.method(JMod.PUBLIC, void.class, "setAdditionalProperty");

    ruleFactory.getAnnotator().anySetter(setter);

    JVar nameParam = setter.param(String.class, "name");
    JVar valueParam = setter.param(propertyType, "value");

    JInvocation mapInvocation = setter.body().invoke(JExpr._this().ref(field), "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
}
 
Example 46
Project: GitHub   File: AdditionalPropertiesRule.java   Source Code and License 5 votes vote down vote up
private JMethod addGetter(JDefinedClass jclass, JFieldVar field) {
    JMethod getter = jclass.method(JMod.PUBLIC, field.type(), "getAdditionalProperties");

    ruleFactory.getAnnotator().anyGetter(getter);

    getter.body()._return(JExpr._this().ref(field));
    return getter;
}
 
Example 47
Project: GitHub   File: AdditionalPropertiesRule.java   Source Code and License 5 votes vote down vote up
private void addBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    JMethod builder = jclass.method(JMod.PUBLIC, jclass, "withAdditionalProperty");

    JVar nameParam = builder.param(String.class, "name");
    JVar valueParam = builder.param(propertyType, "value");

    JBlock body = builder.body();
    JInvocation mapInvocation = body.invoke(JExpr._this().ref(field), "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
    body._return(JExpr._this());
}
 
Example 48
Project: GitHub   File: ObjectRule.java   Source Code and License 5 votes vote down vote up
private void addEquals(JDefinedClass jclass, JsonNode node) {
    Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);

    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().fullName().equals(Object.class.getName())) {
        equalsBuilderInvocation = equalsBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("equals").arg(otherObject));
    }

    for (JFieldVar fieldVar : fields.values()) {
        if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        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);
}
 
Example 49
Project: GitHub   File: Models.java   Source Code and License 5 votes vote down vote up
public static void suppressWarnings(JMethod method, String... values) {
    JAnnotationUse annotation = method.annotate(SuppressWarnings.class);
    JAnnotationArrayMember member = annotation.paramArray("value");
    for( String value : values ) {
        member.param(value);
    }
}
 
Example 50
Project: beanvalidation-benchmark   File: Jsr303Annotator.java   Source Code and License 5 votes vote down vote up
private JMethod getIsValidMethod(JDefinedClass alwaysValidValidator) {
    for ( JMethod method : alwaysValidValidator.methods() ) {
        if ( method.name().equals("isValid") ) {
            return method;
        }
    }
    return null;
}
 
Example 51
Project: beanvalidation-benchmark   File: Jsr303Annotator.java   Source Code and License 5 votes vote down vote up
private JDefinedClass buildTemplateConstraintValidator(String name, JDefinedClass constraint, Class<?> param) {
    try {
        JClass cv = (JClass) codeModel._ref(ConstraintValidator.class);
        cv = cv.narrow(constraint, (JClass) codeModel._ref(param));
        JDefinedClass validator = constraint._class(JMod.STATIC | JMod.PUBLIC, name);
        validator._implements(cv);
        validator.method(JMod.PUBLIC, void.class, "initialize").param(constraint, "parameters");
        JMethod isValid = validator.method(JMod.PUBLIC, boolean.class, "isValid");
        isValid.param(Object.class, "value");
        isValid.param(ConstraintValidatorContext.class, "context");
        return validator;
    } catch (JClassAlreadyExistsException e) {
        throw new RuntimeException("Tried to create an already existing class: " + name, e);
    }
}
 
Example 52
Project: beanvalidation-benchmark   File: Generator.java   Source Code and License 5 votes vote down vote up
/**
 * Generates a Holder class that will hold an {@link ArrayList} with all the
 * first level beans in the graph (contents of {@link #beans}) on it.
 */
private void generatePopulationCode() {
    try {
        // Generate the holder class
        JDefinedClass holderClass = cm._class(Config.CFG.getBasePackageName() + ".Holder");
        JClass alObject = (JClass) cm._ref(ArrayList.class);
        alObject = alObject.narrow(Object.class);
        JFieldVar beansField = holderClass.field(JMod.PUBLIC, alObject, "beans", JExpr._new(alObject));
        JMethod defConstructor = holderClass.constructor(JMod.PUBLIC);
        JBlock body = defConstructor.body();

        // Init the beans and add them to the array
        for (MetaJavaBean mjb : beans) {
            mjb.generateStaticInitCode();
            JVar beanDecl = generateBeanNonStaticInitCode(mjb, body, 0);
            body.add(beansField.invoke("add").arg(beanDecl));
        }

        // Init the base beans but don't add them to the array
        for (MetaJavaBean bmjb : baseBeans) {
            bmjb.generateStaticInitCode();
        }

    } catch (JClassAlreadyExistsException e) {
        throw new RuntimeException("Error generating the holder class.", e);
    }
}
 
Example 53
Project: dremio-oss   File: ClassGenerator.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException {
  this.codeGenerator = codeGenerator;
  this.clazz = clazz;
  this.mappings = mappingSet;
  this.sig = signature;
  this.evaluationVisitor = eval;
  this.model = Preconditions.checkNotNull(model, "Code model object cannot be null.");
  blocks = new LinkedList[sig.size()];

  for (int i =0; i < sig.size(); i++) {
    blocks[i] = Lists.newLinkedList();
  }
  rotateBlock();

  for (SignatureHolder child : signature.getChildHolders()) {
    final String innerClassName = child.getSignatureClass().getSimpleName();
    final JDefinedClass innerClazz;
    // we need to extend the template class and avoid using static inner classes.
    innerClazz = clazz._class(JMod.FINAL, innerClassName)._extends(child.getSignatureClass());

    // we also need to delegate any inner class constructors.
    for(Constructor<?> c : child.getSignatureClass().getDeclaredConstructors()){
      final Class<?>[] params = c.getParameterTypes();
      JMethod constructor = innerClazz.constructor(JMod.PUBLIC);
      JBlock block = constructor.body();
      JInvocation invoke = block.invoke("super");
      block.invoke(SignatureHolder.INIT_METHOD);

      // start at 1 since first parameter is the parent class
      for (int i = 1; i < params.length; i++) {
        constructor.param(params[i], "arg" + i);
        invoke.arg(JExpr.direct("arg" + i));
      }
    }

    innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model));
  }
}
 
Example 54
Project: libraries   File: GetterFactory.java   Source Code and License 5 votes vote down vote up
public void create(
    final JDefinedClass instance,
    final boolean isNullable,
    final boolean isCollectionNullable,
    final List<Annotation> annotationConfigurations,
    final JFieldVar field,
    final String name) throws CreationException {
  final JMethod method = instance.method(JMod.PUBLIC, field.type(), name);
  annotate(method, annotationConfigurations);
  final JBlock body = method.body();
  if (isCollectionNullable && isNullable && isInstanceOfMap(field.type())) {
    body._if(JExpr.refthis(field.name()).invoke("isEmpty"))._then()._return(JExpr._null()); //$NON-NLS-1$
  }
  body._return(JExpr.refthis(field.name()));
}
 
Example 55
Project: jpa-unit   File: JpaUnitRuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testClassWithoutPersistenceContextField() 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 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());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("EntityManagerFactory or EntityManager field annotated"));
    }
}
 
Example 56
Project: libraries   File: SetterFactory.java   Source Code and License 5 votes vote down vote up
private JVar mapSetter(
    final JMethod method,
    final JExpression returnValue,
    final JFieldVar field,
    final boolean isNullable) {
  if (isNullable) {
    return setMapParameters(method, field, true, createAddIfNullClearMapAndReturnClosure(method, returnValue));
  }
  return setMapParameters(
      method,
      field,
      true,
      createEnsureArgumentNotNullClosure(this.ensurePredicateFactory, method));
}
 
Example 57
Project: libraries   File: NamedValueProviderFactory.java   Source Code and License 5 votes vote down vote up
private void valueGetter(
    final JDefinedClass instance,
    final String methodName,
    final Iterable<Annotation> annotations,
    final Type type,
    final JFieldVar field) throws CreationException {
  final JMethod method = instance.method(JMod.PUBLIC, _class(type, true), methodName);
  final JVar param = method.param(JMod.FINAL, _type(JAVA_LANG_STRING), "name"); //$NON-NLS-1$
  annotate(method, annotations);
  createAddIfNullReturnNullClosure(method).execute(param);
  method.body()._return(JExpr.refthis(field.name()).invoke("get").arg(param)); //$NON-NLS-1$
}
 
Example 58
Project: org.ops4j.ramler   File: EnumGenerator.java   Source Code and License 5 votes vote down vote up
private void generateEnumFromStringMethod(JDefinedClass klass, JFieldVar valueField) {
    JMethod converter = klass.method(JMod.PUBLIC | JMod.STATIC, klass, "fromString");
    JVar param = converter.param(String.class, VALUE);

    JBlock body = converter.body();
    JForEach forEach = body.forEach(klass, "v", klass.staticInvoke("values"));
    JBlock loopBlock = forEach.body();
    loopBlock._if(forEach.var().ref(valueField).invoke("equals").arg(param))._then()
        ._return(forEach.var());
    body._throw(JExpr._new(codeModel._ref(IllegalArgumentException.class)).arg(param));
}
 
Example 59
Project: libraries   File: CreatorFactory.java   Source Code and License 5 votes vote down vote up
private void createTypeCreateMethod(final Bean configuration, final Creator creator, final JDefinedClass bean)
    throws CreationException {
  final JMethod method = bean.method(JMod.PUBLIC | JMod.STATIC, bean, creator.name());
  annotate(method, creator.annotations());
  final Iterable<Argument> arguments = creator.arguments();
  final Argument argument = arguments.iterator().next();
  final JVar type = method.param(_class(argument.type(), true), argument.name());
  annotate(type, argument.annotations());

  method.body()._if(isNullOrTrimmedEmpty(type))._then()._return(JExpr._new(bean));

  final JVar clazz = method.body().decl(
      _classByNames(java.lang.Class.class.getName(), MessageFormat.format("? extends {0}", bean.name())), //$NON-NLS-1$
      "clazz",
      _createClass(type));
  JBlock block = method.body()._if(clazz.ne(JExpr._null()))._then();
  block._return(_createBean(clazz));
  method.body().assign(clazz, _createClass(lowerCase(type)));
  block = method.body()._if(clazz.ne(JExpr._null()))._then();
  block._return(_createBean(clazz));
  final JVar className = method.body().decl(
      _String(),
      "className", //$NON-NLS-1$
      format("{0}{1}", type, JExpr.lit(bean.name())));
  method.body().assign(clazz, _createClass(className));
  block = method.body()._if(clazz.ne(JExpr._null()))._then();
  block._return(_createBean(clazz));
  method.body().assign(className, format("{0}{1}", lowerCase(type), JExpr.lit(bean.name()))); //$NON-NLS-1$
  method.body().assign(clazz, _createClass(className));
  block = method.body()._if(clazz.ne(JExpr._null()))._then();
  block._return(_createBean(clazz));
  method.body()._return(JExpr._new(bean));
}
 
Example 60
Project: libraries   File: CreatorFactory.java   Source Code and License 5 votes vote down vote up
private JMethod createSetFirstCharacterToUpperCase(final JDefinedClass bean) {
  final JMethod method = bean.method(JMod.PRIVATE | JMod.STATIC, _String(), "_setFirstCharacterToUpperCase");
  final JVar value = method.param(java.lang.String.class, "value");
  final JBlock body = method.body();
  body._if(value.eq(JExpr._null()).cor(value.invoke("trim").invoke("isEmpty")))._then()._return(JExpr._null());
  final JInvocation firstCharacter = value
      .invoke("substring")
      .arg(JExpr.lit(0))
      .arg(JExpr.lit(1))
      .invoke("toUpperCase");
  final JInvocation restCharacters = value.invoke("substring").arg(JExpr.lit(1)).arg(value.invoke("length"));
  body._return(firstCharacter.plus(restCharacters));
  return method;
}