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

The following examples show how to use com.sun.codemodel.JMethod#param() . 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: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private JMethod createMethod(final Schema schema, boolean read) {
    if (!Schema.Type.RECORD.equals(schema.getType())) {
        throw new FastDeserializerGeneratorException(
                "Methods are defined only for records, not for " + schema.getType());
    }
    if (methodAlreadyDefined(schema, read)) {
        throw new FastDeserializerGeneratorException("Method already exists for: " + schema.getFullName());
    }

    JMethod method = deserializerClass.method(JMod.PUBLIC,
            read ? schemaAssistant.classFromSchema(schema) : codeModel.VOID,
            getVariableName("deserialize" + schema.getName()));

    method._throws(IOException.class);
    method.param(Decoder.class, DECODER);

    (read ? deserializeMethodMap : skipMethodMap).put(schema.getFullName(), method);

    return method;
}
 
Example 2
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 3
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 4
Source File: CreateVisitableInterface.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
@Override
  protected void run(Set<ClassOutline> classes, Set<JClass> directClasses) {
      final JDefinedClass _interface = outline.getClassFactory().createInterface(jpackage, "Visitable", null);
setOutput( _interface );
final JMethod _method = getOutput().method(JMod.NONE, void.class, "accept");
final JTypeVar returnType = _method.generify("R");
final JTypeVar exceptionType = _method.generify("E", Throwable.class);
_method.type(returnType);
_method._throws(exceptionType);
final JClass narrowedVisitor = visitor.narrow(returnType, exceptionType);
_method.param(narrowedVisitor, "aVisitor");
      
      for(ClassOutline classOutline : classes) {
          classOutline.implClass._implements(getOutput());
      }
  }
 
Example 5
Source File: EqualsPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateObject$equals(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod objectEquals = theClass.method(JMod.PUBLIC,
			codeModel.BOOLEAN, "equals");
	objectEquals.annotate(Override.class);
	{
		final JVar object = objectEquals.param(Object.class, "object");
		final JBlock body = objectEquals.body();
		final JVar equalsStrategy = body.decl(JMod.FINAL,
				codeModel.ref(EqualsStrategy2.class), "strategy",
				createEqualsStrategy(codeModel));
		body._return(JExpr.invoke("equals").arg(JExpr._null())
				.arg(JExpr._null()).arg(object).arg(equalsStrategy));
	}
	return objectEquals;
}
 
Example 6
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 7
Source File: CreateBaseVisitorClass.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
private void implementVisitMethod(JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    JMethod _method;
    String methodName = visitMethodNamer.apply(implClass.name());
    _method = getOutput().method(JMod.PUBLIC, returnType, methodName);
    _method._throws(exceptionType);
    _method.param(implClass, "aBean");
    _method.body()._return(JExpr._null());
    _method.annotate(Override.class);
}
 
Example 8
Source File: MetaPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JMethod generateVisitMethod(final ClassOutline classOutline) {
	final JDefinedClass definedClass = classOutline.implClass;
	final JMethod visitMethod = definedClass.method(JMod.PUBLIC, definedClass, this.visitMethodName);
	final JCodeModel codeModel = definedClass.owner();
	final JClass visitorType = codeModel.ref(PropertyVisitor.class);
	final JVar visitorParam = visitMethod.param(JMod.FINAL, visitorType, "_visitor_");
	if (classOutline.getSuperClass() != null) {
		visitMethod.body().add(JExpr._super().invoke(this.visitMethodName).arg(visitorParam));
	} else {
		visitMethod.body().add(visitorParam.invoke("visit").arg(JExpr._this()));
	}
	return visitMethod;
}
 
Example 9
Source File: ToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod generateToString$append(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod toString$append = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "append");
	toString$append.annotate(Override.class);
	{

		final JVar locator = toString$append.param(ObjectLocator.class,
				"locator");
		final JVar buffer = toString$append.param(StringBuilder.class,
				"buffer");
		final JVar toStringStrategy = toString$append.param(
				ToStringStrategy2.class, "strategy");

		final JBlock body = toString$append.body();

		body.invoke(toStringStrategy, "appendStart").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body.invoke("appendFields").arg(locator).arg(buffer)
				.arg(toStringStrategy);
		body.invoke(toStringStrategy, "appendEnd").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body._return(buffer);
	}
	return toString$append;
}
 
Example 10
Source File: CreateTraverserInterface.java    From jaxb-visitor with Apache License 2.0 5 votes vote down vote up
private void implTraverse(JTypeVar exceptionType, JClass narrowedVisitor, JClass implClass) {
    JMethod traverseMethod;
    String methodName = traverseMethodNamer.apply(implClass.name());
    traverseMethod = getOutput().method(JMod.NONE, void.class, methodName);
    traverseMethod._throws(exceptionType);
    traverseMethod.param(implClass, "aBean");
    traverseMethod.param(narrowedVisitor, "aVisitor");
}
 
Example 11
Source File: DeepCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
JMethod generateConveniencePartialCopyMethod(final JMethod cloneMethod, final String methodName, final JExpression secondParam) {
	final JDefinedClass definedClass = this.classOutline.implClass;
	final JMethod cloneExceptMethod = definedClass.method(JMod.PUBLIC, definedClass, methodName);
	final JVar propertyTreeParam = cloneExceptMethod.param(JMod.FINAL, PropertyTree.class, PartialCopyGenerator.PROPERTY_TREE_PARAM_NAME);
	cloneExceptMethod.body()._return(JExpr.invoke(cloneMethod).arg(propertyTreeParam).arg(secondParam));
	cloneExceptMethod.annotate(Override.class);
	return cloneExceptMethod;
}
 
Example 12
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a constructor with all the fields in the POJO. If no fields are
 * present it will not create an empty constructor because default
 * constructor (without fields) is already present.
 * 
 * @return This builder instance
 */
public PojoBuilder withCompleteConstructor() {
	pojoCreationCheck();

	// first we need to check if there are any fields to add to constructor
	// because default constructor (without fields) is already present
	Map<String, JFieldVar> nonTransientAndNonStaticFields = getNonTransientAndNonStaticFields();

	// if nonTransientAndNonStaticFields is not empty
	if (!Optional.ofNullable(nonTransientAndNonStaticFields).map(Map::isEmpty).orElse(true)) {
		// Create complete constructor
		JMethod constructor = this.pojo.constructor(JMod.PUBLIC);
		Map<String, JVar> superParametersToAdd = getSuperParametersToAdd(this.pojo);
		addSuperConstructorInvocation(constructor, superParametersToAdd);
		constructor.javadoc().add("Creates a new " + this.pojo.name() + ".");

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

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

			constructor.param(pair.getValue().type(), pair.getKey());
			constructor.body().assign(JExpr._this().ref(pair.getKey()), JExpr.ref(pair.getKey()));
		}
	}

	return this;
}
 
Example 13
Source File: SimpleToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod generateToString$append(final ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();
	final JMethod toString$append = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "append");
	toString$append.annotate(Override.class);
	{

		final JVar locator = toString$append.param(ObjectLocator.class,
				"locator");
		final JVar buffer = toString$append.param(StringBuilder.class,
				"buffer");
		final JVar toStringStrategy = toString$append.param(
				ToStringStrategy2.class, "strategy");

		final JBlock body = toString$append.body();

		body.invoke(toStringStrategy, "appendStart").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body.invoke("appendFields").arg(locator).arg(buffer)
				.arg(toStringStrategy);
		body.invoke(toStringStrategy, "appendEnd").arg(locator)
				.arg(JExpr._this()).arg(buffer);
		body._return(buffer);
	}
	return toString$append;
}
 
Example 14
Source File: AnyAttributePropertyOutline.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected JMethod generateSetter() {
	JMethod setter = referenceClass.method(JMod.PUBLIC, codeModel.VOID,
			"set" + propertyInfo.getPublicName());

	JVar value = setter.param(type, "value");

	setter.body().invoke(JExpr._this().ref(this.field), "clear");
	setter.body().invoke(JExpr._this().ref(this.field), "putAll")
			.arg(value);
	return setter;
}
 
Example 15
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 16
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private void renderBuilderCreateContract(JDefinedClass builderClass, JClass literalBuilderClass, List<FieldModel> fields, Class<?> contractInterface) {
	JMethod createContractMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JVar contractParam = createContractMethod.param(contractInterface, "contract");
	JBlock body = createContractMethod.body();
	JConditional nullContractCheck = body._if(contractParam.eq(JExpr._null()));
	nullContractCheck._then().directStatement("throw new IllegalArgumentException(\"contract was null\");");
	body.directStatement("// TODO if create() is modified to accept required parameters, this will need to be modified");
	body.directStatement("Builder builder = create();");
	for (FieldModel fieldModel : fields) {
		String fieldName = fieldModel.fieldName;
		body.directStatement("builder." + Util.generateSetter(fieldName, "contract." + Util.generateGetter(fieldName, isBoolean(fieldModel.fieldType))) + ";");
	}
	body.directStatement("return builder;");
}
 
Example 17
Source File: SimpleToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected JMethod generateToString$appendFields(ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();

	final JMethod toString$appendFields = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "appendFields");
	toString$appendFields.annotate(Override.class);
	{
		final JVar locator = toString$appendFields.param(
				ObjectLocator.class, "locator");
		final JVar buffer = toString$appendFields.param(
				StringBuilder.class, "buffer");
		final JVar toStringStrategy = toString$appendFields.param(
				ToStringStrategy2.class, "strategy");
		final JBlock body = toString$appendFields.body();

		final Boolean superClassImplementsToString = StrategyClassUtils
				.superClassImplements(classOutline, ignoring,
						ToString2.class);

		if (superClassImplementsToString == null) {
			// No superclass
		} else if (superClassImplementsToString.booleanValue()) {
			body.invoke(JExpr._super(), "appendFields").arg(locator)
					.arg(buffer).arg(toStringStrategy);
		} else {
			// Superclass does not implement ToString
		}

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

		if (declaredFields.length > 0) {

			for (final FieldOutline fieldOutline : declaredFields) {
				final JBlock block = body.block();
				final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
						.createFieldAccessor(fieldOutline, JExpr._this());
				final JVar theValue = block.decl(
						fieldAccessor.getType(),
						"the"
								+ fieldOutline.getPropertyInfo().getName(
										true));
				final JExpression valueIsSet = (fieldAccessor.isAlwaysSet() || fieldAccessor
						.hasSetValue() == null) ? JExpr.TRUE
						: fieldAccessor.hasSetValue();

				fieldAccessor.toRawValue(block, theValue);

				block.invoke(toStringStrategy, "appendField")
						.arg(locator)
						.arg(JExpr._this())
						.arg(JExpr.lit(fieldOutline.getPropertyInfo()
								.getName(false))).arg(buffer).arg(theValue)
						.arg(valueIsSet);
			}
		}
		body._return(buffer);
	}
	return toString$appendFields;
}
 
Example 18
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
@Override
public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException {

	if (!this.constrained && !this.bound) {
		return true;
	}

	final PluginContext pluginContext = PluginContext.get(outline, opt, errorHandler);

	final JCodeModel m = outline.getCodeModel();

	if (this.generateTools) {
		// generate bound collection helper classes
		pluginContext.writeSourceFile(BoundList.class);
		pluginContext.writeSourceFile(BoundListProxy.class);
		pluginContext.writeSourceFile(CollectionChangeEventType.class);
		pluginContext.writeSourceFile(CollectionChangeEvent.class);
		pluginContext.writeSourceFile(CollectionChangeListener.class);
		pluginContext.writeSourceFile(VetoableCollectionChangeListener.class);
	}

	if(pluginContext.hasPlugin(ImmutablePlugin.class)) {
		errorHandler.error(new SAXParseException(getMessage("error.immutableAndConstrainedProperties"), outline.getModel().getLocator()));
	}

	final int setterAccess = JMod.PUBLIC;

	for (final ClassOutline classOutline : outline.getClasses()) {
		final JDefinedClass definedClass = classOutline.implClass;

		// Create bound collection proxies
		for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) {
			if (fieldOutline.getPropertyInfo().isCollection() && !definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false)).type().isArray()) {
				generateProxyField(classOutline, fieldOutline);
				generateLazyProxyInitGetter(classOutline, fieldOutline);
			}
		}


		if (this.constrained && this.setterThrows) {
			for (final JMethod method : definedClass.methods()) {
				if (method.name().startsWith("with")
						&& !"withVetoableChangeListener".equals(method.name())
						&& !"withPropertyChangeListener".equals(method.name())
						) {
					method._throws(PropertyVetoException.class);
				}
			}
		}

		if (this.constrained)
			createSupportProperty(outline, classOutline, VetoableChangeSupport.class, VetoableChangeListener.class, "vetoableChange");
		if (this.bound)
			createSupportProperty(outline, classOutline, PropertyChangeSupport.class, PropertyChangeListener.class, "propertyChange");


		for (final JFieldVar field : definedClass.fields().values()) {
			//final JFieldVar field = definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false));
			final JMethod oldSetter = definedClass.getMethod("set" + outline.getModel().getNameConverter().toPropertyName(field.name()), new JType[]{field.type()});
			if (oldSetter != null && !field.type().isArray()) {
				definedClass.methods().remove(oldSetter);
				final JMethod setter = definedClass.method(setterAccess, m.VOID, "set" + outline.getModel().getNameConverter().toPropertyName(field.name()));
				final JVar setterArg = setter.param(JMod.FINAL, field.type(), "value");
				final JBlock body = setter.body();
				final JVar oldValueVar = body.decl(JMod.FINAL, field.type(), BoundPropertiesPlugin.OLD_VALUE_VAR_NAME, JExpr._this().ref(field));

				if (this.constrained) {
					final JTryBlock tryBlock;
					final JBlock block;
					if (this.setterThrows) {
						block = body;
						setter._throws(PropertyVetoException.class);
					} else {
						tryBlock = body._try();
						block = tryBlock.body();
						final JCatchBlock catchBlock = tryBlock._catch(m.ref(PropertyVetoException.class));
						final JVar exceptionVar = catchBlock.param("x");
						catchBlock.body()._throw(JExpr._new(m.ref(RuntimeException.class)).arg(exceptionVar));
					}
					invokeListener(block, field, oldValueVar, setterArg, "vetoableChange");
				}

				body.assign(JExpr._this().ref(field), setterArg);

				if (this.bound) {
					invokeListener(body, field, oldValueVar, setterArg, "propertyChange");
				}
			}
		}
	}
	return true;
}
 
Example 19
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
private void generateSingularChoiceProperty(final JBlock initBody, final JVar productParam, final PropertyOutline propertyOutline) {
	// First create the builder field, init and withXXX methods for the supertype of the choices
    JFieldVar superTypeBuilderField = generateSingularChoiceSuperTypeProperty(initBody, productParam, propertyOutline)
			.orElseThrow(() -> new RuntimeException(String.format(
			        "Expecting to have a builderField for property %s", propertyOutline.getFieldName())));

	// Now create the withXXX methods for each choice type
	for (final PropertyOutline.TagRef typeInfo : propertyOutline.getChoiceProperties()) {
		final QName elementName = typeInfo.getTagName();
		final JType elementType = getTagRefType(typeInfo, this.pluginContext.outline, Aspect.EXPOSED);
		final String fieldName = this.pluginContext.toVariableName(elementName.getLocalPart());
		final String propertyName = this.pluginContext.toPropertyName(elementName.getLocalPart());
		final BuilderOutline childBuilderOutline = getBuilderDeclaration(elementType);
		if (childBuilderOutline == null) {
		    // TODO not sure when we will come in here so throw ex to highlight in testing
			throw new RuntimeException(String.format(
					"Don't think we should ever come in here, fieldName: %s", propertyOutline.getFieldName()));
		} else {
			final JClass builderFieldElementType = childBuilderOutline.getBuilderClass().narrow(this.builderClass.type);
			final JClass builderWithMethodReturnType = childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard());
			final JMethod withValueMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName);
			final JVar param = withValueMethod.param(JMod.FINAL, elementType, fieldName);
			generateWithMethodJavadoc(
					withValueMethod, param, propertyOutline.getSchemaAnnotationText(typeInfo).orElse(null));
			final JMethod withBuilderMethod = this.builderClass.raw.method(JMod.PUBLIC, builderWithMethodReturnType, PluginContext.WITH_METHOD_PREFIX + propertyName);
			generateBuilderMethodJavadoc(
			        withBuilderMethod,
					"with",
					fieldName,
					propertyOutline.getSchemaAnnotationText(typeInfo).orElse(null));
			if (this.implement) {
				// Generate the withXXX method that takes a value and returns the parent builder
				withValueMethod.body().assign(
						JExpr._this().ref(superTypeBuilderField),
						nullSafe(param, JExpr._new(builderFieldElementType).arg(JExpr._this()).arg(param).arg(JExpr.FALSE)));
				withValueMethod.body()._return(JExpr._this());

				// Generate the withXXX method that takes no args and returns a new child builder for that type
				JVar childBuilder = withBuilderMethod.body().decl(
				        JMod.FINAL,
						builderFieldElementType,
						fieldName + this.settings.getBuilderFieldSuffix(),
						JExpr._new(builderFieldElementType)
								.arg(JExpr._this())
								.arg(JExpr._null())
								.arg(JExpr.FALSE));

				withBuilderMethod.body().assign(
						JExpr._this().ref(superTypeBuilderField),
						childBuilder);
				withBuilderMethod.body()._return(childBuilder);
			}
		}
	}
}
 
Example 20
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
public void generateMethodMeta(String methodName, JsonObject params, String url,
    String httpVerb, JsonArray contentType, JsonArray accepts){

  /* Adding method to the Class which is public and returns void */

  JMethod jmCreate = method(JMod.PUBLIC, void.class, methodName);
  JBlock body = jmCreate.body();

  /* create the query parameter string builder */
  JVar queryParams = body.decl(jcodeModel._ref(StringBuilder.class), "queryParams",
          JExpr._new(jcodeModel.ref(StringBuilder.class)).arg("?"));


  ////////////////////////---- Handle place holders in the url  ----//////////////////
  /* create request */
  /* Handle place holders in the URL
    * replace {varName} with "+varName+" so that it will be replaced
    * in the url at runtime with the correct values */
  Matcher m = Pattern.compile("\\{.*?\\}").matcher(url);
  while(m.find()){
    String varName = m.group().replace("{","").replace("}", "");
    url = url.replace("{"+varName+"}", "\"+"+varName+"+\"");
  }

  url = "\""+url.substring(1)+"\"+queryParams.toString()";

  /* Adding java doc for method */
  jmCreate.javadoc().add("Service endpoint " + url);


  /* iterate on function params and add the relevant ones
   * --> functionSpecificQueryParamsPrimitives is populated by query parameters that are primitives
   * --> functionSpecificHeaderParams (used later on) is populated by header params
   * --> functionSpecificQueryParamsEnums is populated by query parameters that are enums */
  Iterator<Entry<String, Object>> paramList = params.iterator();

  boolean [] bodyContentExists = new boolean[]{false};
  paramList.forEachRemaining(entry -> {
    String valueName = ((JsonObject) entry.getValue()).getString("value");
    String valueType = ((JsonObject) entry.getValue()).getString("type");
    String paramType = ((JsonObject) entry.getValue()).getString("param_type");
    if(handleParams(jmCreate, queryParams, paramType, valueType, valueName)){
      bodyContentExists[0] = true;
    }
  });

  //////////////////////////////////////////////////////////////////////////////////////

  /* create the http client request object */
  body.directStatement("io.vertx.core.http.HttpClientRequest request = httpClient."+
      httpVerb.substring(httpVerb.lastIndexOf('.')+1).toLowerCase()+"Abs(okapiUrl+"+url+");");
  body.directStatement("request.handler(responseHandler);");

  /* add headers to request */
  functionSpecificHeaderParams.forEach(body::directStatement);
  //reset for next method usage
  functionSpecificHeaderParams = new ArrayList<>();

  /* add content and accept headers if relevant */
  if(contentType != null){
    String cType = contentType.toString().replace("\"", "").replace("[", "").replace("]", "");
    if(contentType.contains("multipart/form-data")){
      body.directStatement("request.putHeader(\"Content-type\", \""+cType+"; boundary=--BOUNDARY\");");
    }
    else{
      body.directStatement("request.putHeader(\"Content-type\", \""+cType+"\");");
    }
  }
  if(accepts != null){
    String aType = accepts.toString().replace("\"", "").replace("[", "").replace("]", "");
    //replace any/any with */* to allow declaring accpet */* which causes compilation issues
    //when declared in raml. so declare any/any in raml instead and replaced here
    aType = aType.replaceAll("any/any", "");
    body.directStatement("request.putHeader(\"Accept\", \""+aType+"\");");
  }

  /* push tenant id into x-okapi-tenant and authorization headers for now */
  JConditional ifClause = body._if(tenantId.ne(JExpr._null()));
  ifClause._then().directStatement("request.putHeader(\"X-Okapi-Token\", token);");
  ifClause._then().directStatement("request.putHeader(\""+OKAPI_HEADER_TENANT+"\", tenantId);");

  JConditional ifClause2 = body._if(this.okapiUrl.ne(JExpr._null()));
  ifClause2._then().directStatement("request.putHeader(\"X-Okapi-Url\", okapiUrl);");

  /* add response handler to each function */
  JClass handler = jcodeModel.ref(Handler.class).narrow(HttpClientResponse.class);
  jmCreate.param(handler, "responseHandler");

  /* if we need to pass data in the body */
  if(bodyContentExists[0]){
    body.directStatement("request.putHeader(\"Content-Length\", buffer.length()+\"\");");
    body.directStatement("request.setChunked(true);");
    body.directStatement("request.write(buffer);");
  }

  body.directStatement("request.end();");
}