Java Code Examples for com.sun.codemodel.JFieldVar

The following examples show how to use com.sun.codemodel.JFieldVar. These examples are extracted from open source projects. 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
/**
 * add getter method for jFieldVar passed in.
 *
 * @param jc
 * @param jFieldVar
 */
private void addGetter(JDefinedClass jc, JFieldVar jFieldVar) {
    JMethod getMethod = jc.method(JMod.PUBLIC, jFieldVar.type(), getMethodFormattedString(jFieldVar.name()));
    getMethod.annotate(codeModel.ref(Override.class));

    if (this.isAllowExporting) {
        if (!this.fieldJsonExposeMap.get(jFieldVar.name())) {
            getMethod.annotate(codeModel.ref(JsonIgnore.class));
        }

        if (StringUtils.isNotBlank(this.fieldJsonPropertyMap.get(jFieldVar.name()))) {
            getMethod.annotate(codeModel.ref(JsonProperty.class))
                    .param("value", this.fieldJsonPropertyMap.get(jFieldVar.name()));
        }
    }


    if (jFieldVar.type().erasure().fullName().equals(List.class.getName())) {
        JExpression condition = new IsNullExpression(jFieldVar, false);
        JExpression ifTrue = codeModel.ref(Collections.class).staticInvoke("unmodifiableList").arg(jFieldVar);
        JExpression ifFalse = JExpr._null();
        getMethod.body()._return(new TernaryOperator(condition, ifTrue, ifFalse));
    } else {
        getMethod.body()._return(jFieldVar);
    }
}
 
Example 2
Source Project: activiti6-boot2   Source File: CxfWSDLImporter.java    License: 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 3
Source Project: immutable-xjc   Source File: PluginImpl.java    License: 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 4
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private JExpression defaultValue(JFieldVar field) {
    JType javaType = field.type();
    if (setDefaultValuesInConstructor) {
        Optional<JAnnotationUse> xmlElementAnnotation = getAnnotation(field.annotations(), javax.xml.bind.annotation.XmlElement.class.getCanonicalName());
        if (xmlElementAnnotation.isPresent()) {
            JAnnotationValue annotationValue = xmlElementAnnotation.get().getAnnotationMembers().get("defaultValue");
            if (annotationValue != null) {
                StringWriter sw = new StringWriter();
                JFormatter f = new JFormatter(sw);
                annotationValue.generate(f);
                return JExpr.lit(sw.toString().replaceAll("\"", ""));
            }
        }
    }
    if (javaType.isPrimitive()) {
        if (field.type().owner().BOOLEAN.equals(javaType)) {
            return JExpr.lit(false);
        } else if (javaType.owner().SHORT.equals(javaType)) {
            return JExpr.cast(javaType.owner().SHORT, JExpr.lit(0));
        } else {
            return JExpr.lit(0);
        }
    }
    return JExpr._null();
}
 
Example 5
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private ClassField[] getSuperclassFields(JDefinedClass clazz) {
    List<JDefinedClass> superclasses = getSuperClasses(clazz);

    // get all fields in class reverse order
    List<ClassField> superclassFields = new ArrayList<>();
    Collections.reverse(superclasses);
    for (JDefinedClass classOutline : superclasses) {
        Map<String, JFieldVar> fields = classOutline.fields();
        for (JFieldVar jFieldVar : fields.values()) {
            if (!(isStatic(jFieldVar) && isFinal(jFieldVar))) {
                superclassFields.add(new ClassField(classOutline, jFieldVar));
            }
        }
    }
    return superclassFields.toArray(new ClassField[0]);
}
 
Example 6
Source Project: raml-module-builder   Source File: ClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void addConstructorOkapi6Args(JFieldVar tokenVar, JFieldVar options, JFieldVar httpClient) {
  /* constructor, init the httpClient - allow to pass keep alive option */
  JMethod constructor = constructor();
  JVar okapiUrlVar = constructor.param(String.class, OKAPI_URL);
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar token = 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");

  /* populate constructor */
  JBlock conBody = constructor.body();
  conBody.assign(JExpr._this().ref(tenantId), tenantIdVar);
  conBody.assign(JExpr._this().ref(tokenVar), token);
  conBody.assign(JExpr._this().ref(okapiUrl), okapiUrlVar);
  conBody.assign(options, JExpr._new(jcodeModel.ref(HttpClientOptions.class)));
  conBody.invoke(options, "setLogActivity").arg(JExpr.TRUE);
  conBody.invoke(options, "setKeepAlive").arg(keepAlive);
  conBody.invoke(options, "setConnectTimeout").arg(connTimeout);
  conBody.invoke(options, "setIdleTimeout").arg(idleTimeout);

  JExpression vertx = jcodeModel
      .ref("org.folio.rest.tools.utils.VertxUtils")
      .staticInvoke("getVertxFromContextOrNew");
  conBody.assign(httpClient, vertx.invoke("createHttpClient").arg(options));
}
 
Example 7
Source Project: apicurio-studio   Source File: JaxRsEnumRule.java    License: 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 8
private void renderElementsClass(JDefinedClass classModel, List<FieldModel> fields) throws Exception {
	
	// define constants class
	JDefinedClass elementsClass = classModel._class(JMod.STATIC, Util.ELEMENTS_CLASS_NAME);
	
	// generate the javadoc on the top of the Elements class
	JDocComment javadoc = elementsClass.javadoc();
	javadoc.append(Util.ELEMENTS_CLASS_JAVADOC);
	
	// go through each field and create a corresponding constant
	for (FieldModel fieldModel : fields) {
		if (Util.isCommonElement(fieldModel.fieldName)) {
			continue;
		}
		JFieldVar elementFieldVar = elementsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.toConstantsVariable(fieldModel.fieldName));
		elementFieldVar.init(JExpr.lit(fieldModel.fieldName));
	}
}
 
Example 9
Source Project: springmvc-raml-plugin   Source File: PojoBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private JFieldVar parentContainsField(JClass pojo, String name) {
	if (pojo != null && !pojo.fullName().equals(Object.class.getName())) {
		JClass parent = pojo._extends();
		if (parent != null) {
			// Our parent has a parent, lets check if it has it
			JFieldVar parentField = parentContainsField(parent, name);
			if (parentField != null) {
				return parentField;
			} else {
				if (parent instanceof JDefinedClass) {
					return ((JDefinedClass) parent).fields().get(name);
				}
			}
		}
	}

	return null;
}
 
Example 10
Source Project: springmvc-raml-plugin   Source File: PojoBuilder.java    License: 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 11
Source Project: krasa-jaxb-tools   Source File: JaxbValidationsPlugins.java    License: Apache License 2.0 6 votes vote down vote up
private void processAttribute(CValuePropertyInfo property, ClassOutline clase, Outline model) {
		FieldOutline field = model.getField(property);
		String propertyName = property.getName(false);
		String className = clase.implClass.name();

		log("Attribute " + propertyName + " added to class " + className);
		XSComponent definition = property.getSchemaComponent();
		RestrictionSimpleTypeImpl particle = (RestrictionSimpleTypeImpl) definition;
		XSSimpleType type = particle.asSimpleType();
		JFieldVar var = clase.implClass.fields().get(propertyName);


//		if (particle.isRequired()) {
//			if (!hasAnnotation(var, NotNull.class)) {
//				if (notNullAnnotations) {
//					System.out.println("@NotNull: " + propertyName + " added to class " + className);
//					var.annotate(NotNull.class);
//				}
//			}
//		}

		validAnnotation(type, var, propertyName, className);
		processType(type, var, propertyName, className);
	}
 
Example 12
Source Project: springmvc-raml-plugin   Source File: PojoBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, JFieldVar> getNonTransientAndNonStaticFields() {
	Map<String, JFieldVar> nonStaticNonTransientFields = new LinkedHashMap<>();

	if (pojo instanceof JDefinedClass) {
		Map<String, JFieldVar> fields = ((JDefinedClass) pojo).fields();

		Iterator<Map.Entry<String, JFieldVar>> iterator = fields.entrySet().iterator();

		while (iterator.hasNext()) {
			Map.Entry<String, JFieldVar> pair = iterator.next();

			// If a field is not static or transient
			if ((pair.getValue().mods().getValue() & (JMod.STATIC | JMod.TRANSIENT)) == 0) {
				nonStaticNonTransientFields.put(pair.getKey(), pair.getValue());
			}
		}
	}

	return nonStaticNonTransientFields;
}
 
Example 13
private void fixDummyListField(DummyListField fieldOutline) {
	if (DummyListField_$get.get(fieldOutline) == null) {
		final JFieldVar field = AbstractListField_field.get(fieldOutline);
		final JType listT = AbstractListField_listT.get(fieldOutline);
		final JClass coreList = DummyListField_coreList
				.get(fieldOutline);
		final JMethod $get = fieldOutline.parent().implClass.method(
				JMod.PUBLIC, listT, "get" + 
				fieldOutline.getPropertyInfo().getName(true));
		JBlock block = $get.body();
		block._if(field.eq(JExpr._null()))._then()
				.assign(field, JExpr._new(coreList));
		block._return(JExpr._this().ref(field));
		DummyListField_$get.set(fieldOutline, $get);
	}
}
 
Example 14
@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 15
Source Project: springmvc-raml-plugin   Source File: RamlInterpreterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void interpretGetResponseBodyInheritanceModel() {
	assertThat(AbstractRuleTestBase.RAML, is(notNullValue()));
	RamlResource songs = AbstractRuleTestBase.RAML.getResource("/songs");
	RamlDataType songsGetType = songs.getAction(RamlActionType.GET).getResponses().get("200").getBody().get("application/json")
			.getType();
	assertThat(songsGetType, is(notNullValue()));
	ApiBodyMetadata songsGetRequest = RamlTypeHelper.mapTypeToPojo(jCodeModel, AbstractRuleTestBase.RAML, songsGetType.getType());
	assertThat(songsGetRequest, is(notNullValue()));

	assertThat(songsGetRequest.isArray(), is(false));

	JDefinedClass responsePOJO = getResponsePOJO("/songs", "Song");
	assertThat(responsePOJO.name(), is("Song"));
	JFieldVar jFieldVar = responsePOJO.fields().get("fee");
	assertThat(jFieldVar.type().name(), is("FeeCategory"));
	assertThat(jFieldVar.type().getClass().getName(), is(JDefinedClass.class.getName()));
	checkIntegration(jCodeModel);
}
 
Example 16
Source Project: springmvc-raml-plugin   Source File: RamlInterpreterTest.java    License: 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 17
@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler)
		throws SAXException {
	try {
		DummyListField_$get = new FieldAccessor<JMethod>(
				DummyListField.class, "$get", JMethod.class);

		IsSetField_core = new FieldAccessor<FieldOutline>(IsSetField.class,
				"core", FieldOutline.class);
		AbstractListField_field = new FieldAccessor<JFieldVar>(
				DummyListField.class.getSuperclass(), "field",
				JFieldVar.class);
		AbstractListField_listT = new FieldAccessor<JClass>(
				DummyListField.class.getSuperclass(), "listT", JClass.class);
		DummyListField_coreList = new FieldAccessor<JClass>(
				DummyListField.class, "coreList",
				JClass.class);
	} catch (Exception ex) {
		throw new SAXException("Could not create field accessors. "
				+ "This plugin can not be used in this environment.", ex);
	}

	for (ClassOutline classOutline : outline.getClasses()) {
		for (FieldOutline fieldOutline : classOutline.getDeclaredFields()) {
			fixFieldOutline(fieldOutline);
		}
	}
	return false;
}
 
Example 18
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 5 votes vote down vote up
private JExpression getInitJExpression(JFieldVar jFieldVar) {
    try {
        return (JExpression) FieldUtils.readField(jFieldVar, "init", true);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 19
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 20
Source Project: activiti6-boot2   Source File: WSDLImporter.java    License: Apache License 2.0 5 votes vote down vote up
protected void importStructure(Mapping mapping) {
  QName qname = mapping.getElement();
  JDefinedClass theClass = (JDefinedClass) mapping.getType().getTypeClass();
  SimpleStructureDefinition structure = (SimpleStructureDefinition) this.structures.get(this.namespace + qname.getLocalPart());

  Map<String, JFieldVar> fields = theClass.fields();
  int index = 0;
  for (Entry<String, JFieldVar> entry : fields.entrySet()) {
    Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().fullName());
    structure.setFieldName(index, entry.getKey(), fieldClass);
    index++;
  }
}
 
Example 21
Source Project: kafka-connect-transform-xml   Source File: ConnectPlugin.java    License: Apache License 2.0 5 votes vote down vote up
Map<String, Object> attributes(JFieldVar field, Class<?> annotationClass) {
  for (JAnnotationUse annotationUse : field.annotations()) {
    log.trace("isRequired() - name = '{}' getAnnotationClass = '{}'", field.name(), annotationUse.getAnnotationClass().fullName());
    if (annotationUse.getAnnotationClass().fullName().equals(annotationClass.getName())) {
      Map<String, Object> result = new LinkedHashMap<>();



      return result;
    }
  }
  return null;
}
 
Example 22
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 5 votes vote down vote up
private JVar addProperty(JDefinedClass clazz, JFieldVar field) {
    JType jType = getJavaType(field);
    int builderFieldVisibility = builderInheritance ? JMod.PROTECTED : JMod.PRIVATE;
    if (isCollection(field)) {
        return clazz.field(builderFieldVisibility, jType, field.name(),
                getNewCollectionExpression(field.type().owner(), jType));
    } else {
        return clazz.field(builderFieldVisibility, jType, field.name());
    }
}
 
Example 23
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 5 votes vote down vote up
private JMethod addPropertyContructor(JDefinedClass clazz, JFieldVar[] declaredFields, JFieldVar[] superclassFields, int constAccess) {
    JMethod ctor = clazz.getConstructor(getFieldTypes(declaredFields, superclassFields));
    if (ctor == null) {
        ctor = this.generatePropertyConstructor(clazz, declaredFields, superclassFields, constAccess);
    } else {
        this.log(Level.WARNING, "standardCtorExists");
    }
    return ctor;
}
 
Example 24
Source Project: jpa-unit   Source File: JpaUnitRuleTest.java    License: 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 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, 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());

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

        // THEN
        assertThat(e.getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
    }
}
 
Example 25
Source Project: jaxb2-rich-contract-plugin   Source File: ModifierGenerator.java    License: MIT License 5 votes vote down vote up
private void generateCollectionAccessor(final DefinedPropertyOutline fieldOutline) {
	final JFieldVar fieldVar = fieldOutline.getFieldVar();
	if(fieldVar != null) {
		final JMethod modifier = this.modifierClass.method(JMod.PUBLIC, fieldVar.type(), ModifierGenerator.GETTER_PREFIX + fieldOutline.getBaseName());
		if(this.implement) {
			final JFieldRef fieldRef = new NestedThisRef(this.classOutline.getImplClass()).ref(fieldVar);
			final JConditional ifNull = modifier.body()._if(fieldRef.eq(JExpr._null()));
			ifNull._then().assign(fieldRef, JExpr._new(this.classOutline.getImplClass().owner().ref(ArrayList.class).narrow(fieldOutline.getElementType())));
			modifier.body()._return(fieldRef);
		}
	}
}
 
Example 26
Source Project: jpa-unit   Source File: JpaUnitRuleTest.java    License: 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 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");
    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());

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

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
 
Example 27
Source Project: jpa-unit   Source File: JpaUnitRuleTest.java    License: 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 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 28
private boolean isIdrefField(FieldOutline fieldOutline) {
	JFieldVar field = ClassDiscoverer.field(fieldOutline);
	if(field == null) {
		return false;
	}
	for(JAnnotationUse use :  field.annotations()) {
		if(use.getAnnotationClass().fullName().equals("javax.xml.bind.annotation.XmlIDREF")) {
			return true;
		}
	}    	
	return false;
}
 
Example 29
Source Project: jpa-unit   Source File: JpaUnitRunnerTest.java    License: 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 Project: krasa-jaxb-tools   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isNumber(JFieldVar field) {
	for (String type : NUMBERS) {
		if (type.equalsIgnoreCase(field.type().name())) {
			return true;
		}
	}
	try {
		if (isNumber(Class.forName(field.type().fullName()))) return true;
	} catch (Exception e) {
		// whatever
	}
	return false;
}