Java Code Examples for com.sun.codemodel.JMethod#annotate()

The following examples show how to use com.sun.codemodel.JMethod#annotate() . 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: 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 2
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 3
Source File: ToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateObject$toString(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod object$toString = theClass.method(JMod.PUBLIC,
			codeModel.ref(String.class), "toString");
	object$toString.annotate(Override.class);
	{
		final JBlock body = object$toString.body();

		final JVar toStringStrategy =

		body.decl(JMod.FINAL, codeModel.ref(ToStringStrategy2.class),
				"strategy", createToStringStrategy(codeModel));

		final JVar buffer = body.decl(JMod.FINAL,
				codeModel.ref(StringBuilder.class), "buffer",
				JExpr._new(codeModel.ref(StringBuilder.class)));
		body.invoke("append").arg(JExpr._null()).arg(buffer)
				.arg(toStringStrategy);
		body._return(buffer.invoke("toString"));
	}
	return object$toString;
}
 
Example 4
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() 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");
    emField.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());

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

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
 
Example 5
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldGetterForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                        final JDefinedClass interfaceClass) {
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        final JMethod method = impl.method(JMod.PUBLIC, interfaceMethod.type(), interfaceMethod.name());
        method._throws(OrmException.class);
        method.annotate(Override.class);
        // TODO - add javadoc.
        // JDocComment jdoc = method.javadoc();
        // jdoc.add("");
        convertValueBody(interfaceClass, interfaceMethod, impl, method);
    } else {
        LOG.warn("Avoided duplicate getter method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example 6
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() 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, EntityManager.class, "em");
    emField.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(JpaUnitException.class));
    assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
 
Example 7
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithMultiplePersistenceUnitFields() 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, EntityManagerFactory.class, "emf1");
    emf1Field.annotate(PersistenceUnit.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2");
    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("Only single field is allowed"));
}
 
Example 8
Source File: EnumBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private void addToStringMethod() {
	JMethod toString = this.pojo.method(JMod.PUBLIC, String.class, "toString");
	toString.annotate(Override.class);

	JExpression toReturn = JExpr._this().ref(valueField);
	if (!valueField.type().fullName().equals(String.class.getName())) {
		toReturn = toReturn.invoke("toString");
	}
	toString.body()._return(toReturn);

}
 
Example 9
Source File: SpringShortcutMappingMethodAnnotationRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JAnnotationUse apply(ApiActionMetadata endpointMetadata, JMethod generatableType) {
	JAnnotationUse requestMappingAnnotation;
	switch (RequestMethod.valueOf(endpointMetadata.getActionType().name())) {
		case GET:
			requestMappingAnnotation = generatableType.annotate(GetMapping.class);
			break;
		case POST:
			requestMappingAnnotation = generatableType.annotate(PostMapping.class);
			break;
		case PUT:
			requestMappingAnnotation = generatableType.annotate(PutMapping.class);
			break;
		case PATCH:
			requestMappingAnnotation = generatableType.annotate(PatchMapping.class);
			break;
		case DELETE:
			requestMappingAnnotation = generatableType.annotate(DeleteMapping.class);
			break;
		default:
			requestMappingAnnotation = generatableType.annotate(RequestMapping.class);
			requestMappingAnnotation.param("method", RequestMethod.valueOf(endpointMetadata.getActionType().name()));
	}

	if (StringUtils.isNotBlank(endpointMetadata.getUrl())) {
		requestMappingAnnotation.param("value", endpointMetadata.getUrl());
	}
	return requestMappingAnnotation;
}
 
Example 10
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 11
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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 JpaUnitRunner runner = new JpaUnitRunner(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 12
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldSetterForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                        final JDefinedClass interfaceClass) {
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        final JMethod method = impl.method(JMod.PUBLIC, interfaceMethod.type(), interfaceMethod.name());
        method.param(interfaceMethod.params().get(0).type(), "arg");
        method._throws(OrmException.class);
        method.annotate(Override.class);
        if (interfaceMethod.params().get(0).type().fullName().startsWith("java.util.Set")) {
            method.body().invoke("setProperties")
                    .arg(JExpr.ref("valueConverterRegistry").invoke("convertTypes")
                            .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                    .arg(JExpr.ref("valueFactory").invoke("createIRI")
                            .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod))));
        } else {
            method.body().invoke("setProperty")
                    .arg(JExpr.ref("valueConverterRegistry").invoke("convertType")
                            .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                    .arg(JExpr.ref("valueFactory").invoke("createIRI")
                            .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod))));
        }
        // TODO - add javadoc.
        // JDocComment jdoc = method.javadoc();
        // jdoc.add("");
    } else {
        LOG.warn("Avoided duplicate setter method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example 13
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 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 14
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromAClassHierarchyHavingAMethodAnnotatedWithEmbeddedId() throws Exception {
    // GIVEN
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameB = "SubEntityClass";
    final String compositeIdPropertyName = "compositeKey";
    final String id1PropertyName = "key1";
    final String id2PropertyName = "key2";

    final JPackage jp = jCodeModel.rootPackage();

    final JDefinedClass jIdTypeClass = jp._class(JMod.PUBLIC, "IdType");
    jIdTypeClass.annotate(Embeddable.class);
    jIdTypeClass.field(JMod.PRIVATE, Integer.class, id1PropertyName);
    jIdTypeClass.field(JMod.PRIVATE, String.class, id2PropertyName);

    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.TABLE_PER_CLASS);
    final JMethod method = jBaseClass.method(JMod.PUBLIC, jIdTypeClass, "getCompositeKey");
    method.annotate(EmbeddedId.class);
    method.body()._return(JExpr._null());

    final JDefinedClass jSubclass = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclass.annotate(Entity.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> entityClass = loadClass(testFolder.getRoot(), jSubclass.name());

    // WHEN
    final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(2));
    assertThat(namesOfIdProperties,
            hasItems(compositeIdPropertyName + "." + id1PropertyName, compositeIdPropertyName + "." + id2PropertyName));
}
 
Example 15
Source File: ImplementationBuilder.java    From aem-component-generator with Apache License 2.0 5 votes vote down vote up
private void addExportedTypeMethod(JDefinedClass jc) {
    if (this.isAllowExporting) {
        JFieldVar jFieldVar = jc.field(PRIVATE, codeModel.ref(Resource.class), "resource");
        jFieldVar.annotate(codeModel.ref(SlingObject.class));
        JMethod method = jc.method(JMod.PUBLIC, codeModel.ref(String.class), "getExportedType");
        method.annotate(codeModel.ref(Override.class));
        method.body()._return(jFieldVar.invoke("getResourceType"));
    }
}
 
Example 16
Source File: PMMLPlugin.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static
public void createSingleton(JCodeModel codeModel, JDefinedClass beanClazz){
	JDefinedClass definedBeanClazz = codeModel.anonymousClass(beanClazz);

	JMethod hasExtensionsMethod = definedBeanClazz.method(JMod.PUBLIC, boolean.class, "hasExtensions");
	hasExtensionsMethod.annotate(Override.class);

	(hasExtensionsMethod.body())._return(JExpr.FALSE);

	JMethod getExtensionsMethod = definedBeanClazz.method(JMod.PUBLIC, List.class, "getExtensions");
	getExtensionsMethod.annotate(Override.class);

	(getExtensionsMethod.body())._throw(JExpr._new(codeModel.ref(UnsupportedOperationException.class)));

	JFieldVar instanceField = beanClazz.field(JMod.PUBLIC | JMod.FINAL | JMod.STATIC, beanClazz, "INSTANCE", JExpr._new(definedBeanClazz));
}
 
Example 17
Source File: HashCodePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected JMethod generateHashCode$hashCode(ClassOutline classOutline,
		final JDefinedClass theClass) {

	JCodeModel codeModel = theClass.owner();
	final JMethod hashCode$hashCode = theClass.method(JMod.PUBLIC,
			codeModel.INT, "hashCode");
	hashCode$hashCode.annotate(Override.class);
	{
		final JVar locator = hashCode$hashCode.param(ObjectLocator.class,
				"locator");
		final JVar hashCodeStrategy = hashCode$hashCode.param(
				HashCodeStrategy2.class, "strategy");
		final JBlock body = hashCode$hashCode.body();

		final JExpression currentHashCodeExpression;

		final Boolean superClassImplementsHashCode = StrategyClassUtils
				.superClassImplements(classOutline, ignoring,
						HashCode2.class);

		if (superClassImplementsHashCode == null) {
			currentHashCodeExpression = JExpr.lit(1);
		} else if (superClassImplementsHashCode.booleanValue()) {
			currentHashCodeExpression = JExpr._super().invoke("hashCode")
					.arg(locator).arg(hashCodeStrategy);
		} else {
			currentHashCodeExpression = JExpr._super().invoke("hashCode");
		}

		final JVar currentHashCode = body.decl(codeModel.INT,
				"currentHashCode", currentHashCodeExpression);

		final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
				classOutline.getDeclaredFields(), getIgnoring());

		if (declaredFields.length > 0) {

			for (final FieldOutline fieldOutline : declaredFields) {
				final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
						.createFieldAccessor(fieldOutline, JExpr._this());
				if (fieldAccessor.isConstant()) {
					continue;
				}
				final JBlock block = body.block();

				final JVar theValue = block.decl(
						fieldAccessor.getType(),
						"the"
								+ fieldOutline.getPropertyInfo().getName(
										true));

				final JExpression valueIsSet = (fieldAccessor.isAlwaysSet() || fieldAccessor
						.hasSetValue() == null) ? JExpr.TRUE
						: fieldAccessor.hasSetValue();

				fieldAccessor.toRawValue(block, theValue);

				block.assign(
						currentHashCode,
						hashCodeStrategy
								.invoke("hashCode")
								.arg(codeModel
										.ref(LocatorUtils.class)
										.staticInvoke("property")
										.arg(locator)
										.arg(fieldOutline.getPropertyInfo()
												.getName(false))
										.arg(theValue))
								.arg(currentHashCode).arg(theValue)
								.arg(valueIsSet));
			}
		}
		body._return(currentHashCode);
	}
	return hashCode$hashCode;
}
 
Example 18
Source File: SimpleHashCodePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
	protected void generate(ClassOutline classOutline, JDefinedClass theClass) {

		final JCodeModel codeModel = theClass.owner();
		final JMethod object$hashCode = theClass.method(JMod.PUBLIC,
				codeModel.INT, "hashCode");
		object$hashCode.annotate(Override.class);
		{
			final JBlock body = object$hashCode.body();

			final JExpression currentHashCodeExpression = JExpr.lit(1);

			final JVar currentHashCode = body.decl(codeModel.INT,
					"currentHashCode", currentHashCodeExpression);

			final Boolean superClassImplementsHashCode = StrategyClassUtils
					.superClassNotIgnored(classOutline, getIgnoring());

			if (superClassImplementsHashCode != null) {
				body.assign(
						currentHashCode,
						currentHashCode.mul(JExpr.lit(getMultiplier())).plus(
								JExpr._super().invoke("hashCode")));
			}

			final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
					classOutline.getDeclaredFields(), getIgnoring());

			if (declaredFields.length > 0) {

				for (final FieldOutline fieldOutline : declaredFields) {
					final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
							.createFieldAccessor(fieldOutline, JExpr._this());
					if (fieldAccessor.isConstant()) {
						continue;
					}
					final JBlock block = body.block();
					block.assign(currentHashCode,
							currentHashCode.mul(JExpr.lit(getMultiplier())));

					String propertyName = fieldOutline.getPropertyInfo()
							.getName(true);
					final JVar value = block.decl(fieldAccessor.getType(),
							"the" + propertyName);

					fieldAccessor.toRawValue(block, value);
					final JType exposedType = fieldAccessor.getType();

					final Collection<JType> possibleTypes = FieldUtils
							.getPossibleTypes(fieldOutline, Aspect.EXPOSED);
					final boolean isAlwaysSet = fieldAccessor.isAlwaysSet();
//					final JExpression hasSetValue = exposedType.isPrimitive() ? JExpr.TRUE
//							: value.ne(JExpr._null());
					
					final JExpression hasSetValue = (fieldAccessor.isAlwaysSet() || fieldAccessor
							.hasSetValue() == null) ? JExpr.TRUE
							: fieldAccessor.hasSetValue();					
					getCodeGenerator().generate(
							block,
							exposedType,
							possibleTypes,
							isAlwaysSet,
							new HashCodeArguments(codeModel, currentHashCode,
									getMultiplier(), value, hasSetValue));
				}
			}
			body._return(currentHashCode);
		}
	}
 
Example 19
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 3 votes vote down vote up
static
private void createGetMethod(JDefinedClass clazz, JClass valueClazz, JExpression valueExpression){
	JCodeModel codeModel = clazz.owner();

	JMethod method = clazz.method(JMod.PUBLIC, valueClazz, "get");
	method.annotate(Override.class);

	method.param(codeModel.INT, "index");

	JBlock body = method.body();

	body._return(JExpr._new(valueClazz).arg(valueExpression).arg(JExpr.invoke("newReport")));
}
 
Example 20
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 3 votes vote down vote up
static
private void createCopyMethod(JDefinedClass clazz){
	JCodeModel codeModel = clazz.owner();

	JClass reportClazz = codeModel.ref(Report.class);

	JMethod method = clazz.method(JMod.PUBLIC, clazz, "copy");
	method.annotate(Override.class);

	JBlock body = method.body();

	JVar reportVariable = body.decl(reportClazz, "report", JExpr.invoke("getReport"));

	body._return(JExpr._new(clazz).arg(JExpr._super().ref("value")).arg(reportVariable.invoke("copy")).arg(JExpr._null()));
}