com.sun.codemodel.JMethod Java Examples

The following examples show how to use com.sun.codemodel.JMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnotateOutline.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processAttributeWildcard(ClassOutline classOutline) {
	logger.debug("The class ["
			+ OutlineUtils.getClassName(classOutline)
			+ "] declares an attribute wildcard which will be made transient.");
	String FIELD_NAME = "otherAttributes";
	String METHOD_SEED = classOutline.parent().getModel()
			.getNameConverter().toClassName(FIELD_NAME);

	final JMethod getOtherAttributesMethod = classOutline.ref.getMethod(
			"get" + METHOD_SEED, new JType[0]);

	if (getOtherAttributesMethod == null) {
		logger.error("Could not find the attribute wildcard method in the class ["
				+ OutlineUtils.getClassName(classOutline) + "].");
	} else {
		getOtherAttributesMethod.annotate(Transient.class);
	}
}
 
Example #2
Source File: CodeModelUtils.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static JMethod getMethod(JDefinedClass theClass, String name,
		JType[] arguments) {
	final JMethod method = theClass.getMethod(name, arguments);
	if (method != null) {
		return method;
	} else {
		final JClass draftSuperClass = theClass._extends();
		if (draftSuperClass == null
				|| !(draftSuperClass instanceof JDefinedClass)) {
			return null;
		} else {
			final JDefinedClass superClass = (JDefinedClass) draftSuperClass;
			return getMethod(superClass, name, arguments);
		}
	}
}
 
Example #3
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holder, ClassGenerator<?> generator) throws RuntimeException {
  inc();
  if (allowNewMethods && shouldNestMethod()) {
    exprCount.push(0);
    HoldingContainer out = generator.declare(holder.getCompleteType(), false);
    JMethod setupMethod = generator.nestSetupMethod();
    JMethod method = generator.innerMethod(holder.getCompleteType());
    HoldingContainer returnContainer = super.visitFunctionHolderExpression(holder, generator);
    method.body()._return(returnContainer.getHolder());
    generator.unNestEvalBlock();
    generator.unNestSetupBlock();
    JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
    generator.getEvalBlock().assign(out.getHolder(), methodCall);
    generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));

    exprCount.pop();
    return out;
  }
  return super.visitFunctionHolderExpression(holder, generator);
}
 
Example #4
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean variablesOverlap(JMethod method, JMethod interfaceMethod) {
    boolean overlap = true;
    for (JVar implParam : method.params()) {
        boolean found = false;
        for (JVar newParam : interfaceMethod.params()) {
            if (newParam.type().fullName().equalsIgnoreCase(implParam.type().fullName())) {
                found = true;
                break;
            }
        }
        if (!found) {
            overlap = false;
            break;
        }
    }
    return overlap;
}
 
Example #5
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
static
private JInvocation createSuperInvocation(JDefinedClass clazz, JMethod method){
	JInvocation invocation;

	if(method.type() != null){
		invocation = JExpr._super().invoke(method.name());
	} else

	{
		invocation = JExpr.invoke("super");
	}

	List<JVar> parameters = method.params();
	for(JVar parameter : parameters){
		invocation.arg(parameter);
	}

	return invocation;
}
 
Example #6
Source File: MergeablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateMergeFrom$mergeFrom0(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	JCodeModel codeModel = theClass.owner();
	final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC,
			codeModel.VOID, "mergeFrom");
	mergeFrom$mergeFrom.annotate(Override.class);
	{
		final JVar left = mergeFrom$mergeFrom.param(Object.class, "left");
		final JVar right = mergeFrom$mergeFrom.param(Object.class, "right");
		final JBlock body = mergeFrom$mergeFrom.body();

		final JVar mergeStrategy = body.decl(JMod.FINAL,
				codeModel.ref(MergeStrategy2.class), "strategy",
				createMergeStrategy(codeModel));

		body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null())
				.arg(left).arg(right).arg(mergeStrategy);
	}
	return mergeFrom$mergeFrom;
}
 
Example #7
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) {
    // remove the old getter
    ownerClass.methods().remove(getter);
    // and create a new one
    JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name());
    JBlock block = newGetter.body();

    JVar ret = block.decl(getJavaType(field), "ret");
    JCodeModel codeModel = field.type().owner();
    JVar param = generateMethodParameter(getter, field);
    JConditional conditional = block._if(param.eq(JExpr._null()));
    conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param));
    conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param));
    block._return(ret);

    getter.javadoc().append("Returns unmodifiable collection.");
}
 
Example #8
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
JMethod generateBuildMethod(final JMethod initMethod) {
	final JMethod buildMethod = this.builderClass.raw.method(JMod.PUBLIC, this.definedClass, this.settings.getBuildMethodName());
	if (!(this.builderClass.type._extends() == null || this.builderClass.type._extends().name().equals("java.lang.Object"))) {
		buildMethod.annotate(Override.class);
	}
	if (this.implement) {
		final JExpression buildExpression = JExpr._this().invoke(initMethod).arg(JExpr._new(this.definedClass));
		if (this.settings.isCopyAlways()) {
			buildMethod.body()._return(buildExpression);
		} else if (this.definedClass.isAbstract()) {
			buildMethod.body()._return(JExpr.cast(this.definedClass, this.storedValueField));
		} else {
			final JConditional jConditional = buildMethod.body()._if(this.storedValueField.eq(JExpr._null()));
			jConditional._then()._return(buildExpression);
			jConditional._else()._return(JExpr.cast(this.definedClass, this.storedValueField));
		}
	}
	return buildMethod;
}
 
Example #9
Source File: ConnectPlugin.java    From kafka-connect-transform-xml with Apache License 2.0 6 votes vote down vote up
void processToStruct(JFieldVar schemaField, JCodeModel codeModel, ClassOutline classOutline) {
  final Map<String, JFieldVar> fields = classOutline.implClass.fields();
  final JClass structClass = codeModel.ref(Struct.class);
  final JMethod method = classOutline.implClass.method(JMod.PUBLIC, structClass, "toStruct");
  final JBlock methodBody = method.body();
  final JVar structVar = methodBody.decl(structClass, "struct", JExpr._new(structClass).arg(schemaField));

  for (final Map.Entry<String, JFieldVar> field : fields.entrySet()) {
    log.trace("processSchema() - processing name = '{}' type = '{}'", field.getKey(), field.getValue().type().name());
    if (schemaField.name().equals(field.getKey())) {
      log.trace("processSchema() - skipping '{}' cause we added it.", field.getKey());
      continue;
    }

    methodBody.invoke(structVar, "put")
        .arg(field.getKey())
        .arg(JExpr.ref(JExpr._this(), field.getKey()));
  }

  methodBody._return(structVar);
}
 
Example #10
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private JMethod generateLazyProxyInitGetter(final ClassOutline classOutline, final FieldOutline fieldOutline) {
	final JCodeModel m = classOutline.parent().getCodeModel();
	final JDefinedClass definedClass = classOutline.implClass;
	final String fieldName = fieldOutline.getPropertyInfo().getName(false);
	final String getterName = "get" + fieldOutline.getPropertyInfo().getName(true);
	final JFieldVar collectionField = definedClass.fields().get(fieldName);
	final JClass elementType = ((JClass) collectionField.type()).getTypeParameters().get(0);
	final JClass proxyFieldType = m.ref(BoundList.class).narrow(elementType);
	final JFieldRef collectionFieldRef = JExpr._this().ref(collectionField);
	final JFieldRef proxyField = JExpr._this().ref(collectionField.name() + BoundPropertiesPlugin.PROXY_SUFFIX);
	final JMethod oldGetter = definedClass.getMethod(getterName, new JType[0]);
	definedClass.methods().remove(oldGetter);
	final JMethod newGetter = definedClass.method(JMod.PUBLIC, proxyFieldType, getterName);
	newGetter.body()._if(collectionFieldRef.eq(JExpr._null()))._then().assign(collectionFieldRef, JExpr._new(m.ref(ArrayList.class).narrow(elementType)));
	final JBlock ifProxyNull = newGetter.body()._if(proxyField.eq(JExpr._null()))._then();
	ifProxyNull.assign(proxyField, JExpr._new(m.ref(BoundListProxy.class).narrow(elementType)).arg(collectionFieldRef));
	newGetter.body()._return(proxyField);
	return newGetter;
}
 
Example #11
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private JMethod generateGetterMethod(JFieldVar field, String fieldName, JExpression defaultValue) {

		String javaName = NamingHelper.convertToClassName(fieldName);

		// Add get method
		JMethod getter = this.pojo.method(JMod.PUBLIC, field.type(), "get" + javaName);
		if (defaultValue != null) {
			JBlock body = getter.body();
			body._if(field.eq(JExpr._null()))._then()._return(defaultValue);
		}
		getter.body()._return(field);
		getter.javadoc().add("Returns the " + fieldName + ".");
		getter.javadoc().addReturn().add(field.name());

		return getter;
	}
 
Example #12
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private JMethod createMethod(final Schema schema, boolean read) {
  if (!Schema.Type.RECORD.equals(schema.getType())) {
    throw new FastDeserializerGeneratorException("Methods are defined only for records, not for " + schema.getType());
  }
  if (methodAlreadyDefined(schema, read)) {
    throw new FastDeserializerGeneratorException("Method already exists for: " + schema.getFullName());
  }

  JClass schemaClass = schemaAssistant.classFromSchema(schema);
  JMethod method = generatedClass.method(JMod.PUBLIC, read ? schemaClass : codeModel.VOID,
      getUniqueName("deserialize" + schema.getName()));

  method._throws(IOException.class);
  method.param(Object.class, VAR_NAME_FOR_REUSE);
  method.param(Decoder.class, DECODER);

  (read ? deserializeMethodMap : skipMethodMap).put(schema.getFullName(), method);

  return method;
}
 
Example #13
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitConvertExpression(ConvertExpression e, ClassGenerator<?> generator) throws RuntimeException {
  inc();
  if (shouldNestMethod()) {
    exprCount.push(0);
    HoldingContainer out = generator.declare(e.getCompleteType(), false);
    JMethod setupMethod = generator.nestSetupMethod();
    JMethod method = generator.innerMethod(e.getCompleteType());
    HoldingContainer returnContainer = super.visitConvertExpression(e, generator);
    method.body()._return(returnContainer.getHolder());
    generator.unNestEvalBlock();
    generator.unNestSetupBlock();
    JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
    generator.getEvalBlock().assign(out.getHolder(), methodCall);
    generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));

    exprCount.pop();
    return out;
  }
  return super.visitConvertExpression(e, generator);
}
 
Example #14
Source File: GroupInterfaceGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private FieldOutline generateProperty(final DefinedInterfaceOutline groupInterface, final FieldOutline implementedField) {
	if (implementedField != null) {
		final JMethod implementedGetter = PluginContext.findGetter(implementedField);
		if (implementedGetter != null) {
			if(this.overrideCollectionClass != null && implementedField.getPropertyInfo().isCollection()) {
				groupInterface.getImplClass().method(JMod.NONE, this.overrideCollectionClass.narrow(((JClass)implementedGetter.type()).getTypeParameters().get(0)), implementedGetter.name());
			} else {
				groupInterface.getImplClass().method(JMod.NONE, implementedGetter.type(), implementedGetter.name());
			}
			if (!this.immutable) {
				final JMethod implementedSetter = PluginContext.findSetter(implementedField);
				if (implementedSetter != null) {
					final JMethod newSetter = groupInterface.getImplClass().method(JMod.NONE, implementedSetter.type(),
							implementedSetter.name());
					newSetter.param(implementedSetter.listParamTypes()[0], implementedSetter.listParams()[0].name());
					if (this.throwsPropertyVetoException) {
						newSetter._throws(PropertyVetoException.class);
					}
				}
			}
			groupInterface.addField(implementedField);
		}
	}
	return implementedField;
}
 
Example #15
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private void addConstructor7Args() {
  /* constructor, init the httpClient - allow to pass keep alive option */
  JMethod constructor = constructor();
  JVar host = constructor.param(String.class, "host");
  JVar port = constructor.param(int.class, "port");
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar tokenVar = constructor.param(String.class, TOKEN);
  JVar keepAlive = constructor.param(boolean.class, KEEP_ALIVE);
  JVar connTimeout = constructor.param(int.class, "connTO");
  JVar idleTimeout = constructor.param(int.class, "idleTO");

  JBlock conBody = constructor.body();
  conBody.invoke("this").arg(okapiUrl(host, port)).arg(tenantIdVar).arg(tokenVar).arg(keepAlive)
    .arg(connTimeout).arg(idleTimeout);
  deprecate(constructor);
}
 
Example #16
Source File: EqualsPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateObject$equals(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod objectEquals = theClass.method(JMod.PUBLIC,
			codeModel.BOOLEAN, "equals");
	objectEquals.annotate(Override.class);
	{
		final JVar object = objectEquals.param(Object.class, "object");
		final JBlock body = objectEquals.body();
		final JVar equalsStrategy = body.decl(JMod.FINAL,
				codeModel.ref(EqualsStrategy2.class), "strategy",
				createEqualsStrategy(codeModel));
		body._return(JExpr.invoke("equals").arg(JExpr._null())
				.arg(JExpr._null()).arg(object).arg(equalsStrategy));
	}
	return objectEquals;
}
 
Example #17
Source File: GenericJavaClassRule.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * @throws IllegalStateException
 *             if a packageRule or classRule is missing or if the
 *             ApiControllerMetadata requires a missing methodSignatureRule.
 */
@Override
public JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel codeModel) {

	if (packageRule == null || classRule == null) {
		throw new IllegalStateException("A packageRule and classRule are mandatory.");
	}
	if (!metadata.getApiCalls().isEmpty() && methodSignatureRule == null) {
		throw new IllegalStateException("Since there are API Calls in the metadata at least a methodSignatureRule is mandatory");
	}

	JPackage jPackage = packageRule.apply(metadata, codeModel);
	JDefinedClass jClass = classRule.apply(metadata, jPackage);
	implementsExtendsRule.ifPresent(rule -> rule.apply(metadata, jClass));
	classCommentRule.ifPresent(rule -> rule.apply(metadata, jClass));
	classAnnotationRules.forEach(rule -> rule.apply(metadata, jClass));
	fieldDeclerationRules.forEach(rule -> rule.apply(metadata, jClass));
	metadata.getApiCalls().forEach(apiMappingMetadata -> {
		JMethod jMethod = methodSignatureRule.apply(apiMappingMetadata, jClass);
		methodCommentRule.ifPresent(rule -> rule.apply(apiMappingMetadata, jMethod));
		methodAnnotationRules.forEach(rule -> rule.apply(apiMappingMetadata, jMethod));
		methodBodyRule.ifPresent(rule -> rule.apply(apiMappingMetadata, CodeModelHelper.ext(jMethod, jClass.owner())));
	});
	return jClass;
}
 
Example #18
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private void generateBuilderMethodJavadoc(
		final JMethod method,
		final String methodPrefix,
		final String propertyName,
           final String schemaAnnotation) {
	final String endMethodClassName = method.type().erasure().fullName();
	JavadocUtils.appendJavadocCommentParagraphs(
				method.javadoc(),
				settings.isGeneratingJavadocFromAnnotations() ? schemaAnnotation : null,
				MessageFormat.format(
						this.resources.getString("comment." + methodPrefix + "BuilderMethod"),
						propertyName,
						endMethodClassName))
			.addReturn()
			.append(JavadocUtils.hardWrapTextForJavadoc(MessageFormat.format(
					this.resources.getString("comment." + methodPrefix + "BuilderMethod.return"),
					propertyName,
					endMethodClassName)));
}
 
Example #19
Source File: SpringRulesTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applySpringMethodParamsRule_shouldCreate_validMethodParams() throws JClassAlreadyExistsException {

	SpringMethodParamsRule rule = new SpringMethodParamsRule();
	JDefinedClass jClass = jCodeModel.rootPackage()._class("TestController");
	JMethod jMethod = jClass.method(JMod.PUBLIC, ResponseEntity.class, "getBaseById");
	jMethod = rule.apply(getEndpointMetadata(2), ext(jMethod, jCodeModel));

	assertThat(jMethod.params(), hasSize(1));
	String serializeModel = serializeModel();
	assertThat(serializeModel, containsString("import org.springframework.web.bind.annotation.PathVariable;"));
	assertThat(serializeModel, containsString("public ResponseEntity getBaseById("));
	assertThat(serializeModel, containsString("@PathVariable"));
	assertThat(serializeModel, containsString("String id) {"));
}
 
Example #20
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean alreadyHasMethod(final JDefinedClass impl, final JDefinedClass interfaceClass,
                                 final JMethod interfaceMethod) {
    boolean alreadyHas = false;
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        for (JMethod method : impl.methods()) {
            if (interfaceMethod.name().equals(method.name()) && variablesOverlap(method, interfaceMethod)) {
                alreadyHas = true;
                break;
            }
        }
    } else {
        alreadyHas = true;
    }
    return alreadyHas;
}
 
Example #21
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private void addConstructor4Args() {
  JMethod constructor = constructor();
  JVar hostVar = constructor.param(String.class, "host");
  JVar portVar = constructor.param(int.class, "port");
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar tokenVar = constructor.param(String.class, TOKEN);
  JBlock conBody = constructor.body();
  conBody.invoke("this").arg(hostVar).arg(portVar).arg(tenantIdVar).arg(tokenVar).arg(JExpr.TRUE)
    .arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
  deprecate(constructor);
}
 
Example #22
Source File: ToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void processClassOutline(ClassOutline classOutline) {
	final JDefinedClass theClass = classOutline.implClass;
	ClassUtils._implements(theClass, theClass.owner().ref(ToString2.class));

	@SuppressWarnings("unused")
	final JMethod object$toString = generateObject$toString(classOutline,
			theClass);
	@SuppressWarnings("unused")
	final JMethod toString$append = generateToString$append(classOutline,
			theClass);
	@SuppressWarnings("unused")
	final JMethod toString$appendFields = generateToString$appendFields(
			classOutline, theClass);
}
 
Example #23
Source File: SelectorGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
MetaInfoOutline(final SelectorGenerator selectorGenerator, final ClassOutline classOutline, final JDefinedClass selectorClass, final JTypeVar rootTypeParam, final JTypeVar parentTypeParam, final JMethod buildChildrenMethod, final JVar productMapVar) {
	this.selectorGenerator = selectorGenerator;
	this.classOutline = classOutline;
	this.selectorClass = selectorClass;
	this.rootTypeParam = rootTypeParam;
	this.parentTypeParam = parentTypeParam;
	this.buildChildrenMethod = buildChildrenMethod;
	this.buildChildrenMethod.body().add(productMapVar.invoke("putAll").arg(JExpr._super().invoke(buildChildrenMethod)));
	this.productMapVar = productMapVar;
}
 
Example #24
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() 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, EntityManagerFactory.class, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.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 #25
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitWithoutUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emField.annotate(PersistenceUnit.class);
    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 RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(JpaUnitException.class));
    assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
 
Example #26
Source File: AbstractWrapCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod createGetter() {
	final MethodWriter writer = outline.createMethodWriter();
	final JMethod getter = writer.declareMethod(propertyListType,
			getGetterName());
	final JBlock body = getter.body();
	fix(body);
	body._return(propertyField);
	return getter;
}
 
Example #27
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private JMethod addStandardConstructor(final JDefinedClass clazz, JFieldVar[] declaredFields, JFieldVar[] superclassFields) {
    JMethod ctor = clazz.getConstructor(NO_ARGS);
    if (ctor == null) {
        ctor = this.generateStandardConstructor(clazz, declaredFields, superclassFields);
    } else {
        this.log(Level.WARNING, "standardCtorExists");
    }
    return ctor;
}
 
Example #28
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emf1Field.annotate(PersistenceContext.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emf2Field.annotate(PersistenceUnit.class);
    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 RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
}
 
Example #29
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithMultiplePersistenceContextFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1");
    em1Field.annotate(PersistenceContext.class);
    final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2");
    em2Field.annotate(PersistenceContext.class);
    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 RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
 
Example #30
Source File: PMMLPlugin.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
private void moveAfter(JDefinedClass beanClazz, JMethod method, JMethod referenceMethod){
	List<JMethod> methods = (List<JMethod>)beanClazz.methods();

	int index = methods.indexOf(referenceMethod);
	if(index < 0){
		throw new RuntimeException();
	}

	methods.remove(method);
	methods.add(index + 1, method);
}