com.sun.codemodel.JDefinedClass Java Examples

The following examples show how to use com.sun.codemodel.JDefinedClass. 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: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    final String idPropertyName = "key";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

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

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

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(1));
    assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
 
Example #2
Source File: ImplementationBuilder.java    From aem-component-generator with Apache License 2.0 6 votes vote down vote up
private void addSlingAnnotations(JDefinedClass jDefinedClass, JClass adapterClass, String resourceType) {
    JAnnotationUse jAUse = jDefinedClass.annotate(codeModel.ref(Model.class));
    JAnnotationArrayMember adaptablesArray = jAUse.paramArray("adaptables");
    for (String adaptable : adaptables) {
        if ("resource".equalsIgnoreCase(adaptable)) {
            adaptablesArray.param(codeModel.ref(Resource.class));
        }
        if ("request".equalsIgnoreCase(adaptable)) {
            adaptablesArray.param(codeModel.ref(SlingHttpServletRequest.class));
        }
    }
    if (this.isAllowExporting) {
        jAUse.paramArray("adapters").param(adapterClass).param(codeModel.ref(ComponentExporter.class));
    } else {
        jAUse.param("adapters", adapterClass);
    }
    if (StringUtils.isNotBlank(resourceType)) {
        jAUse.param("resourceType", resourceType);
    }
    if (this.isAllowExporting) {
        jAUse = jDefinedClass.annotate(codeModel.ref(Exporter.class));
        jAUse.param("name", codeModel.ref(ExporterConstants.class).staticRef(SLING_MODEL_EXPORTER_NAME));
        jAUse.param("extensions", codeModel.ref(ExporterConstants.class).staticRef(SLING_MODEL_EXTENSION));
    }
}
 
Example #3
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 6 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(_enum, fromValue);
}
 
Example #4
Source File: SpringControllerStubRule.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public final JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel generatableType) {

	GenericJavaClassRule generator = new GenericJavaClassRule().setPackageRule(new PackageRule())
			.setClassCommentRule(new ClassCommentRule()).addClassAnnotationRule(getControllerAnnotationRule())
			.addClassAnnotationRule(new SpringRequestMappingClassAnnotationRule())
			.addClassAnnotationRule(new SpringValidatedClassAnnotationRule()).addClassAnnotationRule(new GeneratedClassAnnotationRule())
			.setClassRule(new ControllerClassDeclarationRule()).setMethodCommentRule(new MethodCommentRule())
			.addMethodAnnotationRule(new SpringRequestMappingMethodAnnotationRule())
			.addMethodAnnotationRule(getResponseBodyAnnotationRule())
			.setMethodSignatureRule(new ControllerMethodSignatureRule(getReturnTypeRule(false), new SpringMethodParamsRule(
					isAddParameterJavadoc(), isAllowArrayParameters(), !Config.isInjectHttpHeadersParameter())))
			.setMethodBodyRule(new ImplementMeMethodBodyRule());

	return generator.apply(metadata, generatableType);
}
 
Example #5
Source File: MetaPlugin.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private void generateMetaClass(final PluginContext pluginContext, final ClassOutline classOutline, final ErrorHandler errorHandler) throws SAXException {
	try {
		final JDefinedClass metaClass = classOutline.implClass._class(JMod.PUBLIC | JMod.STATIC, this.metaClassName);
		final JMethod visitMethod = generateVisitMethod(classOutline);
		for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) {
			if (this.extended) {
				generateExtendedMetaField(pluginContext, metaClass, visitMethod, fieldOutline);
			} else {
				generateNameOnlyMetaField(pluginContext, metaClass, fieldOutline);
			}
		}
		visitMethod.body()._return(JExpr._this());
	} catch (final JClassAlreadyExistsException e) {
		errorHandler.error(new SAXParseException(getMessage("error.metaClassExists", classOutline.implClass.name(), this.metaClassName), classOutline.target.getLocator()));
	}
}
 
Example #6
Source File: CxfWSDLImporter.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected static void _importFields(final JDefinedClass theClass, final AtomicInteger index, final SimpleStructureDefinition structure) {
    
  final JClass parentClass = theClass._extends();
  if (parentClass != null && parentClass instanceof JDefinedClass) {
    _importFields((JDefinedClass)parentClass, index, structure);
  }
  for (Entry<String, JFieldVar> entry : theClass.fields().entrySet()) {
    Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().erasure().fullName());

    String fieldName = entry.getKey();
    if (fieldName.startsWith("_")) {
      if (!JJavaName.isJavaIdentifier(fieldName.substring(1))) {
        fieldName = fieldName.substring(1); //it was prefixed with '_' so we should use the original name.
      }
    }

    structure.setFieldName(index.getAndIncrement(), fieldName, fieldClass);
  }
}
 
Example #7
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
private void generateForDirectClass(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    String visitMethodName = visitMethodNamer.apply(implClass.name());
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodName);
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");

    travVizBloc.assign(retVal, JExpr.invoke(JExpr.invoke("getVisitor"), visitMethodName).arg(beanVar));

    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    addTraverseBlock(travViz, beanVar, false);

    travVizBloc._return(retVal);
}
 
Example #8
Source File: RamlInterpreterTest.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void checkTypeOfDates() throws Exception {

	JDefinedClass pojo = getResponsePOJO("/validations", "Validation");

	JFieldVar field = getField(pojo, "dateO");
	assertThat(field.type().fullName(), is("java.util.Date"));
	assertDateFormatAnnotation(field, "yyyy-MM-dd");

	field = getField(pojo, "timeO");
	assertThat(field.type().fullName(), is("java.util.Date"));
	assertDateFormatAnnotation(field, "HH:mm:ss");

	field = getField(pojo, "dateTO");
	assertThat(field.type().fullName(), is("java.util.Date"));
	assertDateFormatAnnotation(field, "yyyy-MM-dd'T'HH:mm:ss");

	field = getField(pojo, "dateT");
	assertThat(field.type().fullName(), is("java.util.Date"));
	assertDateFormatAnnotation(field, "yyyy-MM-dd'T'HH:mm:ssXXX");

	field = getField(pojo, "datetimeRFC2616");
	assertThat(field.type().fullName(), is("java.util.Date"));
	assertDateFormatAnnotation(field, "EEE, dd MMM yyyy HH:mm:ss z");
}
 
Example #9
Source File: ClassFieldDeclarationRule.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public JFieldVar apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) {
	JFieldVar field = generatableType.field(JMod.PRIVATE, this.fieldClazz, this.fieldName);

	// add @Autowired field annoation
	if (autowire) {
		field.annotate(Autowired.class);
	}

	// add @Qualifier("qualifierBeanName")
	if (qualifierAnnotation && !StringUtils.isEmpty(qualifier)) {
		field.annotate(Qualifier.class).param("value", qualifier);
	}

	// add @Value(value="") annotation to the field
	if (valueAnnotation) {
		field.annotate(Value.class).param("value", valueAnnotationValue);
	}
	return field;
}
 
Example #10
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, JFieldVar field, JMethod unconditionalWithMethod, boolean inherit) {
    if (field.type().isPrimitive())
        return null;
    String fieldName = StringUtils.capitalize(field.name());
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull");
    JVar param = generateMethodParameter(method, field);
    JBlock block = method.body();
    if (inherit) {
        generateSuperCall(method);
        method.body()._return(JExpr._this());
    } else {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then()._return(JExpr._this());
        conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param));
    }
    return method;
}
 
Example #11
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JClass getBuilderClass(JClass clazz) {
    //Current limitation: this only works for classes from this model / outline, i.e. that are part of this generator run
    if (!createBuilder || clazz.isAbstract()) {
        return null;
    }
    String builderClassName = getBuilderClassName(clazz);
    if (clazz instanceof JDefinedClass) {
        JDefinedClass definedClass = (JDefinedClass) clazz;
        for (Iterator<JDefinedClass> i = definedClass.classes(); i.hasNext(); ) {
            JDefinedClass innerClass = i.next();
            if (builderClassName.equals(innerClass.name())) {
                return innerClass;
            }
        }
    }
    return null;
}
 
Example #12
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceUnitFieldOfWrongType() 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, "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(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(),
            containsString("annotated with @PersistenceUnit is not of type EntityManagerFactory"));
}
 
Example #13
Source File: JpaUnitRunnerTest.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 JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    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 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 #14
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 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 #15
Source File: ResourceClassDeclarationRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JDefinedClass apply(ApiResourceMetadata controllerMetadata, JPackage generatableType) {
	String resourceClassName = controllerMetadata.getName() + classNameSuffix;
	JDefinedClass definedClass;
	try {
		definedClass = generatableType._class(resourceClassName);
	} catch (JClassAlreadyExistsException e1) {
		definedClass = generatableType._getClass(resourceClassName);
	}
	return definedClass;
}
 
Example #16
Source File: InheritancePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JClass generateImplements(final JDefinedClass theClass,
		final ImplementsInterface implementsInterface,
		Map<String, JClass> knownClasses) {

	String _interface = implementsInterface.getInterfaceName();
	if (_interface != null) {
		final JClass targetClass = parseClass(_interface, theClass.owner(),
				knownClasses);
		theClass._implements(targetClass);
		return targetClass;
	} else {
		return null;
	}
}
 
Example #17
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void recurseImplementations(final JDefinedClass impl, final JClass interfaceClass) {
    // implement the supplied interface class.
    impl._implements(interfaceClass);
    if (interfaceClass instanceof JDefinedClass) {
        // If the interface is a JDefinedClass (will be), then we'll recurse
        // up the lineage.
        generateFieldAccessorsForEachInterfaceMethod(impl, (JDefinedClass) interfaceClass);
        interfaceClass._implements().forEachRemaining(parentInterface -> {
            recurseImplementations(impl, parentInterface);
        });
    }
}
 
Example #18
Source File: Issue284RulesTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void check_feign_path_and_param_names() throws Exception {
	loadRaml("issue-284.raml");
	Rule<JCodeModel, JDefinedClass, ApiResourceMetadata> rule = new SpringFeignClientInterfaceDecoratorRule();
	rule.apply(getControllerMetadata(), jCodeModel);
	verifyGeneratedCode("Issue284FeignClientInterface");
}
 
Example #19
Source File: RamlInterpreterTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private void checkIfFieldContainsAnnotation(boolean expected, JDefinedClass classToCheck, Class<?> annotationClass, String... fields) {
	for (JFieldVar field : classToCheck.fields().values()) {
		if ((fields == null || fields.length == 0 || ArrayUtils.contains(fields, field.name()))
				&& !field.name().equals("serialVersionUID")) {
			boolean found = false;
			for (JAnnotationUse annotation : field.annotations()) {
				if (annotation.getAnnotationClass().name().equals(annotationClass.getSimpleName())) {
					found = true;
				}
			}
			assertThat(found, is(expected));
		}
	}
}
 
Example #20
Source File: DummyXjcPlugin.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean run(Outline arg0, Options arg1, ErrorHandler arg2) {

    for (ClassOutline classOutline : arg0.getClasses()) {
        JDefinedClass implClass = classOutline.implClass;
        JCodeModel codeModel = implClass.owner();
        JMethod dummyMethod =
            implClass.method(JMod.PUBLIC, codeModel.ref(String.class), "dummy");
        dummyMethod.body()._return(JExpr.lit("dummy"));
    }
    return true;
}
 
Example #21
Source File: SettersPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void generateSetters(ClassOutline classOutline,
		JDefinedClass theClass) {

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

	for (final FieldOutline fieldOutline : declaredFields) {

		final String publicName = fieldOutline.getPropertyInfo().getName(
				true);

		final String getterName = "get" + publicName;

		final JMethod getter = theClass.getMethod(getterName, ABSENT);

		if (getter != null) {
			final JType type = getter.type();
			final JType rawType = fieldOutline.getRawType();
			final String setterName = "set" + publicName;
			final JMethod boxifiedSetter = theClass.getMethod(setterName,
					new JType[] { rawType.boxify() });
			final JMethod unboxifiedSetter = theClass.getMethod(setterName,
					new JType[] { rawType.unboxify() });
			final JMethod setter = boxifiedSetter != null ? boxifiedSetter
					: unboxifiedSetter;

			if (setter == null) {
				final JMethod generatedSetter = theClass.method(
						JMod.PUBLIC, theClass.owner().VOID, setterName);
				final JVar value = generatedSetter.param(type, "value");

				mode.generateSetter(fieldOutline, theClass,
						generatedSetter, value);
			}
		}
	}
}
 
Example #22
Source File: InheritancePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JClass generateExtends(final JDefinedClass theClass,
		final CPluginCustomization extendsClassCustomization,
		Map<String, JClass> knownClasses) throws AssertionError {
	if (extendsClassCustomization != null) {

		final ExtendsClass extendsClass = (ExtendsClass) CustomizationUtils
				.unmarshall(Customizations.getContext(),
						extendsClassCustomization);

		return generateExtends(theClass, extendsClass, knownClasses);
	} else {
		return null;
	}
}
 
Example #23
Source File: JpaUnitRuleTest.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 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 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());

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

        // THEN
        assertThat(e.getMessage(), containsString("Only single field is allowed"));
    }
}
 
Example #24
Source File: ModifierGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private ModifierGenerator(final PluginContext pluginContext, final DefinedTypeOutline classOutline, final String modifierClassName, final String modifierInterfaceName, final Collection<TypeOutline> interfaces, final String modifierMethodName, final boolean implement) throws JClassAlreadyExistsException {
	this.classOutline = classOutline;
	final JDefinedClass definedClass = classOutline.getImplClass();
	this.implement = implement;
	this.modifierClass = definedClass._class(JMod.PUBLIC, modifierClassName, classOutline.getImplClass().getClassType());
	if(interfaces != null) {
		for (final TypeOutline interfaceOutline : interfaces) {
			this.modifierClass._implements( pluginContext.ref(interfaceOutline.getImplClass(), modifierInterfaceName, true));
		}
	}
	final JFieldRef cachedModifierField;
	if(!"java.lang.Object".equals(definedClass._extends().fullName())) {
		this.modifierClass._extends(pluginContext.ref(definedClass._extends(), modifierClassName, false));
		cachedModifierField = JExpr.refthis(ModifierGenerator.MODIFIER_CACHE_FIELD_NAME);
	} else {
		if(implement) {
			cachedModifierField = JExpr._this().ref(definedClass.field(JMod.PROTECTED | JMod.TRANSIENT, this.modifierClass, ModifierGenerator.MODIFIER_CACHE_FIELD_NAME));
		} else {
			cachedModifierField = null;
		}
	}

	final JDefinedClass typeDefinition = classOutline.isInterface() && ((DefinedInterfaceOutline)classOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)classOutline).getSupportInterface() : definedClass;
	final JMethod modifierMethod = typeDefinition.method(JMod.PUBLIC, this.modifierClass, modifierMethodName);
	if(this.implement) {
		final JConditional ifCacheNull = modifierMethod.body()._if(JExpr._null().eq(cachedModifierField));
		ifCacheNull._then().assign(cachedModifierField, JExpr._new(this.modifierClass));
		modifierMethod.body()._return(JExpr.cast(this.modifierClass, cachedModifierField));
	}

}
 
Example #25
Source File: InheritancePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private List<JClass> generateImplements(ClassOutline classOutline,
		Map<String, JClass> knownClasses) {
	final JDefinedClass theClass = classOutline.implClass;
	final List<CPluginCustomization> implementsInterfaceCustomizations = CustomizationUtils
			.findCustomizations(classOutline,
					Customizations.IMPLEMENTS_ELEMENT_NAME);
	return generateImplements(theClass, implementsInterfaceCustomizations,
			knownClasses);
}
 
Example #26
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);
}
 
Example #27
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithEmbeddedId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    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 jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    final JMethod method = jClass.method(JMod.PUBLIC, jIdTypeClass, "getCompositeKey");
    method.annotate(EmbeddedId.class);
    method.body()._return(JExpr._null());

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

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

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

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(2));
    assertThat(namesOfIdProperties,
            hasItems(compositeIdPropertyName + "." + id1PropertyName, compositeIdPropertyName + "." + id2PropertyName));
}
 
Example #28
Source File: ImplementsControllerInferfaceRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyRule_shouldCreate_classImplementsInterfaceExpression() throws JClassAlreadyExistsException {

	JPackage jPackage = jCodeModel.rootPackage();
	JDefinedClass jInterface = jPackage._interface("MyInterface");
	JDefinedClass jClass = jPackage._class("MyClass");

	rule = new ImplementsControllerInterfaceRule(jInterface);
	rule.apply(getControllerMetadata(), jClass);

	assertThat(jClass, is(notNullValue()));
	assertThat(jClass.name(), equalTo("MyClass"));
	assertThat(serializeModel(), containsString("public class MyClass"));
	assertThat(serializeModel(), containsString("implements MyInterface"));
}
 
Example #29
Source File: SourceGenerator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldAdderRemoverForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                              final JDefinedClass interfaceClass, final boolean add) {
    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);
        method.body()._return(JExpr.ref("this").invoke(add ? "addProperty" : "removeProperty").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)))));
    } else {
        LOG.warn("Avoided duplicate adder method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example #30
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithEmbeddedId() throws Exception {
    // GIVEN
    final String simpleClassName = "EntityClass";
    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 jClass = jp._class(JMod.PUBLIC, simpleClassName);
    jClass.annotate(Entity.class);
    jClass.field(JMod.PRIVATE, jIdTypeClass, compositeIdPropertyName).annotate(EmbeddedId.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

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

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

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(2));
    assertThat(namesOfIdProperties,
            hasItems(compositeIdPropertyName + "." + id1PropertyName, compositeIdPropertyName + "." + id2PropertyName));
}