com.sun.codemodel.JFieldVar Java Examples

The following examples show how to use com.sun.codemodel.JFieldVar. 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: 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 #2
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 #3
Source File: PluginImpl.java    From immutable-xjc with 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 #4
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 #5
Source File: ClientGenerator.java    From raml-module-builder with 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 #6
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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 #7
Source File: RamlInterpreterTest.java    From springmvc-raml-plugin with 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 #8
Source File: PojoBuilder.java    From springmvc-raml-plugin with 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 #9
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 #10
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 #11
Source File: JaxbValidationsPlugins.java    From krasa-jaxb-tools with 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 File: PluginImpl.java    From immutable-xjc with 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 #13
Source File: FixJAXB1058Plugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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
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 #15
Source File: PojoBuilder.java    From springmvc-raml-plugin with 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 #16
Source File: ImplementationBuilder.java    From aem-component-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #17
Source File: RamlInterpreterTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private JFieldVar getField(JDefinedClass classToCheck, String fieldToFind) {
	for (JFieldVar field : classToCheck.fields().values()) {
		if (fieldToFind.equals(field.name())) {
			return field;
		}
	}
	return null;
}
 
Example #18
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
private void addToString(JDefinedClass _enum, JFieldVar valueField) {
    JMethod toString = _enum.method(JMod.PUBLIC, String.class, "toString");
    JBlock body = toString.body();

    JExpression toReturn = JExpr._this().ref(valueField);
    if(!isString(valueField.type())){
        toReturn = toReturn.plus(JExpr.lit(""));
    }
    
    body._return(toReturn);

    toString.annotate(Override.class);
}
 
Example #19
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 #20
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private void createSupportProperty(final Outline outline,
									final ClassOutline classOutline,
									final Class<?> supportClass,
									final Class<?> listenerClass,
									final String aspectName) {
	final JCodeModel m = outline.getCodeModel();
	final JDefinedClass definedClass = classOutline.implClass;

	final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1);

	if (classOutline.getSuperClass() == null) { // only generate fields in topmost classes
		final JFieldVar supportField = definedClass.field(JMod.PROTECTED | JMod.FINAL | JMod.TRANSIENT, supportClass, aspectName + BoundPropertiesPlugin.SUPPORT_FIELD_SUFFIX, JExpr._new(m.ref(supportClass)).arg(JExpr._this()));
		final JMethod addMethod = definedClass.method(JMod.PUBLIC, m.VOID, "add" + aspectNameCap + "Listener");
		final JVar addParam = addMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener");
		addMethod.body().invoke(JExpr._this().ref(supportField), "add" + aspectNameCap + "Listener").arg(addParam);

		final JMethod removeMethod = definedClass.method(JMod.PUBLIC, m.VOID, "remove" + aspectNameCap + "Listener");
		final JVar removeParam = removeMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener");
		removeMethod.body().invoke(JExpr._this().ref(supportField), "remove" + aspectNameCap + "Listener").arg(removeParam);
	}
	final JMethod withMethod = definedClass.method(JMod.PUBLIC, definedClass, "with" + aspectNameCap + "Listener");
	final JVar withParam = withMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener");
	withMethod.body().invoke("add" + aspectNameCap + "Listener").arg(withParam);
	withMethod.body()._return(JExpr._this());

	if (classOutline.getSuperClass() != null) {
		withMethod.annotate(Override.class);
	}
}
 
Example #21
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private JMethod getGetterProperty(final JFieldVar field, final JDefinedClass clazz) {
    JMethod getter = clazz.getMethod("get" + StringUtils.capitalize(field.name()), NO_ARGS);
    if (getter == null) {
        getter = clazz.getMethod("is" + StringUtils.capitalize(field.name()), NO_ARGS);
    }

    if (getter == null) {
        List<JDefinedClass> superClasses = getSuperClasses(clazz);
        for (JDefinedClass definedClass : superClasses) {
            getter = getGetterProperty(field, definedClass);

            if (getter != null) {
                break;
            }
        }
    }
    if (getter == null) {
        //XJC does not work conform Introspector.decapitalize when multiple upper-case letter are in field name
        Optional<JAnnotationUse> xmlElementAnnotation = getAnnotation(field.annotations(), javax.xml.bind.annotation.XmlElement.class.getCanonicalName());
        if (xmlElementAnnotation.isPresent()) {
            JAnnotationValue annotationValue = xmlElementAnnotation.get().getAnnotationMembers().get("name");
            if (annotationValue != null) {
                StringWriter sw = new StringWriter();
                JFormatter f = new JFormatter(sw);
                annotationValue.generate(f);
                getter = clazz.getMethod("get" + sw.toString().replaceAll("\"", ""), NO_ARGS);
            }
        }
    }
    return getter;
}
 
Example #22
Source File: WrappedCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JFieldRef createField() {

		final JFieldVar field = outline.implClass.field(JMod.PROTECTED
				+ JMod.TRANSIENT,

		propertyListType, property.getName(false));
		// field.annotate(XmlTransient.class);
		annotate(field);
		return JExpr._this().ref(field);
	}
 
Example #23
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JFieldVar generateProxyField(final ClassOutline classOutline, final FieldOutline fieldOutline) {
	final JCodeModel m = classOutline.parent().getCodeModel();
	final JDefinedClass definedClass = classOutline.implClass;
	final JFieldVar collectionField = definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false));
	final JClass elementType = ((JClass) collectionField.type()).getTypeParameters().get(0);
	return definedClass.field(JMod.PRIVATE | JMod.TRANSIENT, m.ref(BoundList.class).narrow(elementType), collectionField.name() + BoundPropertiesPlugin.PROXY_SUFFIX, JExpr._null());
}
 
Example #24
Source File: SelectorGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
public void generateMetaFields() {
	if(this.classOutline.getSuperClass() != null) {
		this.selectorClass._extends(this.selectorGenerator.getInfoClass(this.classOutline.getSuperClass().implClass).selectorClass.narrow(this.rootTypeParam).narrow(this.parentTypeParam));
	}
	for (final FieldOutline fieldOutline : this.classOutline.getDeclaredFields()) {
		final JFieldVar definedField = PluginUtil.getDeclaredField(fieldOutline);
		if (definedField != null) {
			final JType elementType = PluginUtil.getElementType(fieldOutline);
			if (elementType.isReference()) {
				final ClassOutline modelClass = this.selectorGenerator.getPluginContext().getClassOutline(elementType);
				final JClass returnType;
				if (modelClass != null) {
					returnType = this.selectorGenerator.getInfoClass(modelClass.implClass).selectorClass.narrow(this.rootTypeParam).narrow(this.selectorClass.narrow(this.rootTypeParam).narrow(this.parentTypeParam));
				} else {
					returnType = this.selectorGenerator.getPluginContext().codeModel.ref(this.selectorGenerator.selectorBaseClass).narrow(this.rootTypeParam).narrow(this.selectorClass.narrow(this.rootTypeParam).narrow(this.parentTypeParam));
				}
				final JFieldVar includeField = this.selectorClass.field(JMod.PRIVATE, returnType, definedField.name(), JExpr._null());
				final JFieldRef fieldRef = JExpr._this().ref(includeField);
				final JMethod includeMethod = this.selectorClass.method(JMod.PUBLIC, returnType, definedField.name());
				if(this.selectorGenerator.selectorParamName != null) {
					final JVar includeParam = includeMethod.param(JMod.FINAL, this.selectorGenerator.getSelectorParamType(this.classOutline.implClass, elementType), this.selectorGenerator.selectorParamName);
					includeMethod.body()._return(JOp.cond(fieldRef.eq(JExpr._null()), fieldRef.assign(JExpr._new(returnType).arg(JExpr._this().ref("_root")).arg(JExpr._this()).arg(JExpr.lit(definedField.name())).arg(includeParam)), fieldRef));
				} else {
					includeMethod.body()._return(JOp.cond(fieldRef.eq(JExpr._null()), fieldRef.assign(JExpr._new(returnType).arg(JExpr._this().ref("_root")).arg(JExpr._this()).arg(JExpr.lit(definedField.name()))), fieldRef));
				}

				this.buildChildrenMethod.body()._if(fieldRef.ne(JExpr._null()))._then().add(this.productMapVar.invoke("put").arg(JExpr.lit(definedField.name())).arg(fieldRef.invoke("init")));
			}
		}
	}
	this.buildChildrenMethod.body()._return(this.productMapVar);
}
 
Example #25
Source File: ClassDiscoverer.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the annotations on the field to see if there is an XmlElements
 * annotation on it. If so, we'll check this annotation to see if it
 * refers to any classes that are external from our code schema compile.
 * If we find any, then we'll add them to our visitor.
 * @param outline root of the generated code
 * @param field parses the xml annotations looking for an external class
 * @param directClasses set of direct classes to append to
 * @throws IllegalAccessException throw if there's an error introspecting the annotations
 */
private static void parseXmlAnnotations(Outline outline, FieldOutline field, Set<String> directClasses) throws IllegalAccessException {
    if (field instanceof UntypedListField) {
        JFieldVar jfv = (JFieldVar) FieldHack.listField.get(field);
        for(JAnnotationUse jau : jfv.annotations()) {
            JClass jc = jau.getAnnotationClass();
            if (jc.fullName().equals(XmlElements.class.getName())) {
                JAnnotationArrayMember value = (JAnnotationArrayMember) jau.getAnnotationMembers().get("value");
                for(JAnnotationUse anno : value.annotations()) {
                    handleXmlElement(outline, directClasses, anno.getAnnotationMembers().get("type"));
                }
            }
        }
    }
}
 
Example #26
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 #27
Source File: AdaptingWrappingCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JFieldRef createField() {

		final JFieldVar field = outline.implClass.field(JMod.PROTECTED
				+ JMod.TRANSIENT,

		propertyListType, property.getName(false));
		// field.annotate(XmlTransient.class);
		return JExpr._this().ref(field);
	}
 
Example #28
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() 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 JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.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 JpaUnitRunner(cut);
        fail("InitializationError expected");
    } catch (final InitializationError e) {
        // expected
        assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other"));
    }

}
 
Example #29
Source File: FixJAXB1058Plugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@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 #30
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private void generatePropertyAssignment(final JMethod method, JFieldVar field, boolean wrapUnmodifiable) {
    JBlock block = method.body();
    JCodeModel codeModel = field.type().owner();
    String fieldName = field.name();
    JVar param = generateMethodParameter(method, field);
    if (isCollection(field) && !leaveCollectionsMutable && wrapUnmodifiable) {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then().assign(JExpr.refthis(fieldName), JExpr._null());
        conditional._else().assign(JExpr.refthis(fieldName),
                getDefensiveCopyExpression(codeModel, getJavaType(field), param));
    } else {
        block.assign(JExpr.refthis(fieldName), JExpr.ref(fieldName));
    }
}