com.sun.codemodel.JClass Java Examples

The following examples show how to use com.sun.codemodel.JClass. 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: XJCCMInfoFactory.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected NClass getClazz(final Class<?> _clas) {
	return new NClass() {

		@Override
		public boolean isBoxedType() {
			return false;
		}

		@Override
		public String fullName() {
			return _clas.getName();
		}

		@Override
		public JClass toType(Outline o, Aspect aspect) {
			return o.getCodeModel().ref(_clas);
		}

		@Override
		public boolean isAbstract() {
			return false;
		}
	};
}
 
Example #2
Source File: RuleHelper.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private static JClass getReturnEntity(ApiActionMetadata endpointMetadata, JCodeModel owner, JClass callable,
		boolean useResponseEntity) {

	ApiBodyMetadata apiBodyMetadata = endpointMetadata.getResponseBody().values().iterator().next();
	JClass type = findFirstClassBySimpleName(apiBodyMetadata.getCodeModel(), apiBodyMetadata.getName());
	if (apiBodyMetadata.isArray()) {
		type = updateType(owner, callable, type, useResponseEntity, true);
	} else if (BigDecimal.class.getSimpleName().equals(apiBodyMetadata.getName())) {
		type = updateType(owner, callable, owner.ref(BigDecimal.class), useResponseEntity, false);
	} else if (BigInteger.class.getSimpleName().equals(apiBodyMetadata.getName())) {
		type = updateType(owner, callable, owner.ref(BigInteger.class), useResponseEntity, false);
	} else {
		type = updateType(owner, callable, type, useResponseEntity, false);
	}
	return type;
}
 
Example #3
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
JMethod generateNewCopyBuilderMethod(final boolean partial) {
	final JDefinedClass typeDefinition = this.typeOutline.isInterface() && ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() != null ? ((DefinedInterfaceOutline)this.typeOutline).getSupportInterface() : this.definedClass;
	final int mods = this.implement ? this.definedClass.isAbstract() ? JMod.PUBLIC | JMod.ABSTRACT : JMod.PUBLIC : JMod.NONE;
	final JMethod copyBuilderMethod = typeDefinition.method(mods, this.builderClass.raw, this.settings.getNewCopyBuilderMethodName());
	final JTypeVar copyBuilderMethodTypeParam = copyBuilderMethod.generify(BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
	final JVar parentBuilderParam = copyBuilderMethod.param(JMod.FINAL, copyBuilderMethodTypeParam, BuilderGenerator.PARENT_BUILDER_PARAM_NAME);
	final CopyGenerator copyGenerator = this.pluginContext.createCopyGenerator(copyBuilderMethod, partial);
	copyBuilderMethod.type(this.builderClass.raw.narrow(copyBuilderMethodTypeParam));
	final JMethod copyBuilderConvenienceMethod = typeDefinition.method(mods, this.builderClass.raw.narrow(this.pluginContext.voidClass), this.settings.getNewCopyBuilderMethodName());
	final CopyGenerator copyConvenienceGenerator = this.pluginContext.createCopyGenerator(copyBuilderConvenienceMethod, partial);
	if (this.implement && !this.definedClass.isAbstract()) {
		copyBuilderMethod.body()._return(copyGenerator.generatePartialArgs(this.pluginContext._new((JClass)copyBuilderMethod.type()).arg(parentBuilderParam).arg(JExpr._this()).arg(JExpr.TRUE)));
		copyBuilderConvenienceMethod.body()._return(copyConvenienceGenerator.generatePartialArgs(this.pluginContext.invoke(this.settings.getNewCopyBuilderMethodName()).arg(JExpr._null())));
	}
	if (this.typeOutline.getSuperClass() != null) {
		copyBuilderMethod.annotate(Override.class);
		copyBuilderConvenienceMethod.annotate(Override.class);
	}
	return copyBuilderMethod;
}
 
Example #4
Source File: ImplementationBuilder.java    From aem-component-generator with Apache License 2.0 6 votes vote down vote up
/**
 * method that add the fieldname as private to jc.
 *
 * @param property
 * @param propertyType
 */
private void addPropertyAsPrivateField(JDefinedClass jc, Property property, final String propertyType) {
    String fieldType = JavaCodeModel.getFieldType(property);

    JClass fieldClass = property.getType().equalsIgnoreCase("multifield")
            ? codeModel.ref(fieldType).narrow(codeModel.ref(JavaCodeModel.getFieldType(property.getItems().get(0))))
            : codeModel.ref(fieldType);
    JFieldVar jFieldVar = jc.field(PRIVATE, fieldClass, property.getField());

    if (StringUtils.equalsIgnoreCase(property.getType(), "image")) {
        jFieldVar.annotate(codeModel.ref(ChildResourceFromRequest.class))
                .param(INJECTION_STRATEGY,
                        codeModel.ref(InjectionStrategy.class).staticRef(OPTIONAL_INJECTION_STRATEGY));

    } else if (StringUtils.equalsIgnoreCase(propertyType, Constants.PROPERTY_TYPE_PRIVATE)) {
        jFieldVar.annotate(codeModel.ref(ValueMapValue.class))
                .param(INJECTION_STRATEGY,
                        codeModel.ref(InjectionStrategy.class).staticRef(OPTIONAL_INJECTION_STRATEGY));
    } else {
        jFieldVar.annotate(codeModel.ref(SharedValueMapValue.class))
                .param(INJECTION_STRATEGY,
                        codeModel.ref(InjectionStrategy.class).staticRef(OPTIONAL_INJECTION_STRATEGY));
    }

    setupFieldGetterAnnotations(jFieldVar, property);
}
 
Example #5
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private void withEquals() {
	JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals");
	JVar otherObject = equals.param(Object.class, "other");

	Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class;
	if (!Config.getPojoConfig().isUseCommonsLang3()) {
		equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class;
	}

	JBlock body = equals.body();

	body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE);
	body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
	body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE);

	JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject));

	JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass);

	JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef);

	body._return(equalsBuilderInvocation.invoke("isEquals"));
}
 
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: TypeToJTypeConvertingVisitor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public JType visit(ClassOrInterfaceType type, JCodeModel codeModel) {
	final String name = getName(type);
	final JClass knownClass = this.knownClasses.get(name);
	final JClass jclass = knownClass != null ? knownClass : codeModel
			.ref(name);
	final List<Type> typeArgs = type.getTypeArgs();
	if (typeArgs == null || typeArgs.isEmpty()) {
		return jclass;
	} else {
		final List<JClass> jtypeArgs = new ArrayList<JClass>(
				typeArgs.size());
		for (Type typeArg : typeArgs) {
			final JType jtype = typeArg.accept(this, codeModel);
			if (!(jtype instanceof JClass)) {
				throw new IllegalArgumentException("Type argument ["
						+ typeArg.toString() + "] is not a class.");
			} else {
				jtypeArgs.add((JClass) jtype);
			}
		}
		return jclass.narrow(jtypeArgs);
	}
}
 
Example #8
Source File: CodeModelUtils.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static JMethod getMethod(JDefinedClass theClass, String name,
		JType[] arguments) {
	final JMethod method = theClass.getMethod(name, arguments);
	if (method != null) {
		return method;
	} else {
		final JClass draftSuperClass = theClass._extends();
		if (draftSuperClass == null
				|| !(draftSuperClass instanceof JDefinedClass)) {
			return null;
		} else {
			final JDefinedClass superClass = (JDefinedClass) draftSuperClass;
			return getMethod(superClass, name, arguments);
		}
	}
}
 
Example #9
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JMethod addAddMethod(JDefinedClass builderClass, JFieldVar field, boolean inherit) {
    List<JClass> typeParams = ((JClass) getJavaType(field)).getTypeParameters();
    if (!typeParams.iterator().hasNext()) {
        return null;
    }
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "add" + StringUtils.capitalize(field.name()));
    JBlock block = method.body();
    String fieldName = field.name();
    JVar param = method.param(JMod.FINAL, typeParams.iterator().next(), fieldName);
    if (inherit) {
        generateSuperCall(method);
    } else {
        JInvocation invocation = JExpr.refthis(fieldName).invoke("add").arg(param);
        block.add(invocation);
    }
    block._return(JExpr._this());
    return method;
}
 
Example #10
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 #11
Source File: SingleWrappingReferenceField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected JExpression wrap(JExpression target) {

	final JClass declaredType = (JClass) getDeclaredType();

	final JClass scope = getScope();

	final QName name = getName();

	JExpression value = target;

	if (xmlAdapterClass == null) {
		return XmlAdapterXjcUtils.marshallJAXBElement(codeModel,
				declaredType, name, scope, value);

	} else {
		return XmlAdapterXjcUtils.marshallJAXBElement(codeModel,
				xmlAdapterClass, declaredType, name, scope, value);
	}
}
 
Example #12
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private JInvocation appendFieldsToString(Map<String, JFieldVar> nonTransientAndNonStaticFields, JClass toStringBuilderRef) {
	JInvocation invocation = JExpr._new(toStringBuilderRef).arg(JExpr._this());
	Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();

	if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) { // If
																				// this
																				// POJO
																				// has
																				// a
																				// superclass,
																				// append
																				// the
																				// superclass
																				// toString()
																				// method.
		invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("toString"));
	}

	while (iterator.hasNext()) {
		Map.Entry<String, JFieldVar> pair = iterator.next();
		invocation = invocation.invoke("append").arg(JExpr.lit(pair.getKey())).arg(pair.getValue());
	}

	return invocation;
}
 
Example #13
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 #14
Source File: EnumBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
public EnumBuilder withValueField(Class<?> type) {
	pojoCreationCheck();
	if (!this.pojo.fields().containsKey("value")) {
		// Create Field
		valueField = this.pojo.field(JMod.PRIVATE | JMod.FINAL, type, "value");

		// Create private Constructor
		JMethod constructor = this.pojo.constructor(JMod.PRIVATE);
		JVar valueParam = constructor.param(type, "value");
		constructor.body().assign(JExpr._this().ref(valueField), valueParam);

		// add values to map
		JClass lookupType = this.pojo.owner().ref(Map.class).narrow(valueField.type().boxify(), this.pojo);
		lookupMap = this.pojo.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "VALUE_CACHE");

		JClass lookupImplType = this.pojo.owner().ref(HashMap.class).narrow(valueField.type().boxify(), this.pojo);
		lookupMap.init(JExpr._new(lookupImplType));

		JForEach forEach = this.pojo.init().forEach(this.pojo, "c", JExpr.invoke("values"));
		JInvocation put = forEach.body().invoke(lookupMap, "put");
		put.arg(forEach.var().ref("value"));
		put.arg(forEach.var());

		// Add method to retrieve value
		JMethod fromValue = this.pojo.method(JMod.PUBLIC, valueField.type(), "value");
		fromValue.body()._return(JExpr._this().ref(valueField));

		addFromValueMethod();
		addToStringMethod();
	}
	return this;
}
 
Example #15
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createReportingConstructor(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(initialOperation != null){
		throw new RuntimeException();
	}

	body.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, constructor.params(), type)));
}
 
Example #16
Source File: RuleHelper.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private static JClass getResponseEntityNarrow(JCodeModel owner, JClass genericType, JClass callable) {

		JClass responseEntity = owner.ref(ResponseEntity.class);
		JClass returnNarrow = responseEntity.narrow(genericType);

		if (callable != null) {
			returnNarrow = callable.narrow(returnNarrow);
		}
		return returnNarrow;
	}
 
Example #17
Source File: InheritancePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private JClass generateExtends(EnumOutline enumOutline,
		Map<String, JClass> knownClasses) {
	final JDefinedClass theClass = enumOutline.clazz;
	final CPluginCustomization extendsClassCustomization = CustomizationUtils
			.findCustomization(enumOutline,
					Customizations.EXTENDS_ELEMENT_NAME);
	return generateExtends(theClass, extendsClassCustomization,
			knownClasses);
}
 
Example #18
Source File: RamlTypeHelper.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Maps a RAML Data Type to a JCodeModel using JSONSchema2Pojo and
 * encapsulates it along with some metadata into an {@link ApiBodyMetadata}
 * object.
 * 
 * @param pojoCodeModel
 *            The code model containing the classes generated during
 *            generation
 * @param document
 *            The Raml document being parsed
 * @param type
 *            The RAML type declaration
 * @return Object representing this Body
 */
public static ApiBodyMetadata mapTypeToPojo(JCodeModel pojoCodeModel, RamlRoot document, TypeDeclaration type) {
	RamlInterpretationResult interpret = RamlInterpreterFactory.getInterpreterForType(type).interpret(document, type, pojoCodeModel,
			false);

	// here we expect that a new object is created i guess... we'd need to
	// see how primitive arrays fit in
	JClass pojo = null;
	if (interpret.getBuilder() != null) {
		pojo = interpret.getBuilder().getPojo();
	} else if (interpret.getResolvedClass() != null) {
		pojo = interpret.getResolvedClass();
	}

	if (pojo == null) {
		throw new IllegalStateException("No Pojo created or resolved for type " + type.getClass().getSimpleName() + ":" + type.name());
	}

	if (pojo.name().equals("Void")) {
		return null;
	}

	boolean array = false;
	String pojoName = pojo.name();
	if (pojo.name().contains("List<") || pojo.name().contains("Set<")) {
		array = true;
		pojoName = pojo.getTypeParameters().get(0).name();
	}

	return new ApiBodyMetadata(pojoName, type, array, pojoCodeModel);
}
 
Example #19
Source File: EqualsCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onFloat(EqualsArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	final JClass Float$class = getCodeModel().ref(Float.class);
	final JExpression leftValueLongBits = Float$class.staticInvoke(
			"floatToIntBits").arg(arguments.leftValue());
	final JExpression rightValueLongBits = Float$class.staticInvoke(
			"floatToIntBits").arg(arguments.rightValue());
	returnFalseIfNotEqualsCondition(arguments, block, isAlwaysSet,
			JOp.ne(leftValueLongBits, rightValueLongBits));
}
 
Example #20
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createConstructor(JDefinedClass clazz, ExecutableElement executableElement, boolean hasExpression){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(hasExpression){
		JVar expressionParameter = constructor.param(String.class, "expression");

		body._if(expressionParameter.ne(JExpr._null()))._then().add(JExpr.invoke("report").arg(expressionParameter));
	}
}
 
Example #21
Source File: AdaptingWrappingCollectionField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void fix(JBlock body) {

	body._if(wrappingPropertyField.eq(JExpr._null()))
			._then()
			.assign(wrappingPropertyField,
					JExpr._new(codeModel.ref(ArrayList.class).narrow(
							wrappingPropertyExposedType.boxify())));

	final JClass utilsClass = codeModel.ref(TransformUtils.class);
	//
	// (wrappedProperty instanceof CReferencePropertyInfo &&
	// ((CReferencePropertyInfo) wrappedProperty)
	// .isMixed()) ? codeModel.ref(MixedItemUtils.class) : codeModel
	// .ref(ItemUtils.class);
	body._if(
			utilsClass.staticInvoke("shouldBeWrapped").arg(
					wrappedPropertyField))
			._then()
			.assign(wrappedPropertyField,

					utilsClass
							.staticInvoke("wrap")
							.arg(wrappedPropertyField)
							.arg(wrappingPropertyField)
							.arg(wrappingProperty.getAdapter()
									.getAdapterClass(outline.parent())
									.dotclass()));
}
 
Example #22
Source File: PluginImpl.java    From xero-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Update getters to use Java List. For example:
 * ArrayOfInvoices getInvoices() -> List<Invoice> getInvoices()
 */
private void updateArrayOfGetters(ClassOutline co, JCodeModel model) {
  JDefinedClass implClass = co.implClass;

  List<JMethod> removedMethods = new ArrayList<>();
  Iterator<JMethod> iter = implClass.methods().iterator();
  while (iter.hasNext()) {
    JMethod method = iter.next();
    if (method.type().name().startsWith("ArrayOf")) {
      removedMethods.add(method);
      iter.remove();
    }
  }

  for (JMethod removed : removedMethods) {
    // Parse the old code to get the variable name
    StringWriter oldWriter = new StringWriter();
    removed.body().state(new JFormatter(oldWriter));
    String oldBody = oldWriter.toString();
    String varName = oldBody.substring(oldBody.indexOf("return ") + "return ".length(), oldBody.indexOf(";"));

    // Build the new method
    JClass newReturnType = (JClass) ((JDefinedClass) removed.type()).fields().values().iterator().next().type();
    JMethod newMethod = implClass.method(removed.mods().getValue(), newReturnType, removed.name());
    JFieldVar field = implClass.fields().get(varName);          
    JClass typeParameter = newReturnType.getTypeParameters().get(0);
    String fieldName = model._getClass(field.type().fullName()).fields().keySet().iterator().next();

    newMethod.body()._return(
        JOp.cond(field.eq(JExpr._null()),
            JExpr._new(model.ref("java.util.ArrayList").narrow(typeParameter)),
            field.invoke("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1))));
  }    
}
 
Example #23
Source File: XmlAdapterXjcUtils.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static JExpression isJAXBElement(JCodeModel codeModel,
		JClass declaredType, QName name, JClass scope, JExpression value) {

	return codeModel.ref(XmlAdapterUtils.class).staticInvoke(
			"isJAXBElement").arg(declaredType.dotclass()).

	arg(JExprUtils.newQName(codeModel, name)).arg(scope.dotclass()).arg(
			value);
}
 
Example #24
Source File: EnumValuePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void processEnumOutline(EnumOutline enumOutline) {
	CEnumLeafInfo enumLeafInfo = enumOutline.target;
	JClass enumType = enumLeafInfo.base.toType(enumOutline.parent(),
			Aspect.EXPOSED).boxify();

	final JDefinedClass theClass = enumOutline.clazz;

	ClassUtils._implements(theClass, theClass.owner().ref(EnumValue.class)
			.narrow(enumType));

	final JMethod enumValue$enumValue = theClass.method(JMod.PUBLIC,
			enumType, "enumValue");
	enumValue$enumValue.annotate(Override.class);
	enumValue$enumValue.body()._return(JExpr._this().invoke("value"));
}
 
Example #25
Source File: XmlAdapterXjcUtils.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static JExpression unmarshallJAXBElement(JCodeModel codeModel,
		JClass xmlAdapterClass, JExpression value) {

	return codeModel.ref(XmlAdapterUtils.class).staticInvoke(
			"unmarshallJAXBElement").arg(xmlAdapterClass.dotclass()).arg(
			value);
}
 
Example #26
Source File: SpringDelegateFieldDeclerationRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JFieldVar apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) {
	if (!generatableType._implements().hasNext()) {
		throw new RuleCanNotProcessModelException(
				"The class " + generatableType.fullName() + " does not implement a super class that can be delegated to.");
	}
	JClass controllerInterface = generatableType._implements().next();
	JFieldVar field = generatableType.field(JMod.PRIVATE, controllerInterface, delegateFieldName);
	field.annotate(Autowired.class);
	return field;
}
 
Example #27
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 #28
Source File: PluginContext.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
boolean mustCatch(final JClass fieldType) {
	final Class<? extends Cloneable> elementRuntimeClass;
	try {
		elementRuntimeClass = (Class<? extends Cloneable>) Class.forName(fieldType.binaryName());
	} catch (final ClassNotFoundException e) {
		return false;
	}
	return cloneThrows(elementRuntimeClass);
}
 
Example #29
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void processPrimitive(final Schema primitiveSchema, JExpression primitiveValueExpression, JBlock body) {
    String writeFunction;
    JClass primitiveClass = schemaAssistant.classFromSchema(primitiveSchema);
    JExpression castedValue = JExpr.cast(primitiveClass, primitiveValueExpression);

    switch (primitiveSchema.getType()) {
        case STRING:
            writeFunction = "writeString";
            if (SchemaAssistant.isStringable(primitiveSchema)) {
                castedValue = JExpr.cast(string, castedValue.invoke("toString"));
            }
            break;
        case BYTES:
            writeFunction = "writeBytes";
            break;
        case INT:
            writeFunction = "writeInt";
            break;
        case LONG:
            writeFunction = "writeLong";
            break;
        case FLOAT:
            writeFunction = "writeFloat";
            break;
        case DOUBLE:
            writeFunction = "writeDouble";
            break;
        case BOOLEAN:
            writeFunction = "writeBoolean";
            break;
        default:
            throw new FastSerializerGeneratorException(
                    "Unsupported primitive schema of type: " + primitiveSchema.getType());
    }

    body.invoke(JExpr.direct(ENCODER), writeFunction).arg(castedValue);
}
 
Example #30
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void processEnum(Schema enumSchema, JExpression enumValueExpression, JBlock body) {
    JClass enumClass = schemaAssistant.classFromSchema(enumSchema);
    JExpression enumValueCasted = JExpr.cast(enumClass, enumValueExpression);
    JExpression valueToWrite;
    if (useGenericTypes) {
        valueToWrite = JExpr.invoke(enumValueCasted.invoke("getSchema"), "getEnumOrdinal")
                .arg(enumValueCasted.invoke("toString"));
    } else {
        valueToWrite = enumValueCasted.invoke("ordinal");
    }

    body.invoke(JExpr.direct(ENCODER), "writeEnum").arg(valueToWrite);
}