com.sun.codemodel.JExpr Java Examples

The following examples show how to use com.sun.codemodel.JExpr. 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: DrillAggFuncHolder.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables,
                                  JVar[] workspaceJVars, FieldReference fieldReference) {
  HoldingContainer out = null;
  JVar internalOutput = null;
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    out = classGenerator.declare(getReturnType(), false);
  }
  JBlock sub = new JBlock();
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    internalOutput = sub.decl(JMod.FINAL, classGenerator.getHolderType(getReturnType()), getReturnValue().getName(), JExpr._new(classGenerator.getHolderType(getReturnType())));
  }
  classGenerator.getEvalBlock().add(sub);
  addProtectedBlock(classGenerator, sub, output(), null, workspaceJVars, false);
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    sub.assign(out.getHolder(), internalOutput);
  }
  //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
  if (!classGenerator.getMappingSet().isHashAggMapping()) {
    generateBody(classGenerator, BlockType.RESET, reset(), null, workspaceJVars, false);
  }
  generateBody(classGenerator, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
 
Example #2
Source File: SingleWrappingReferenceField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {

	final JType declaredType = getDeclaredType();

	final JClass elementClass = codeModel.ref(JAXBElement.class).narrow(
			declaredType.boxify().wildcard());

	// TODO remove if cast is not necessary
	final JExpression value = JExpr.cast(elementClass, source);

	if (xmlAdapterClass == null) {
		return XmlAdapterXjcUtils.unmarshallJAXBElement(codeModel, value);

	} else {
		return XmlAdapterXjcUtils.unmarshallJAXBElement(codeModel,
				xmlAdapterClass, value);
	}

}
 
Example #3
Source File: PropertyFieldAccessorFactory.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void fromRawValue(JBlock block, String uniqueName,
		JExpression $var) {
	if (constantField != null) {

	} else if (setter != null) {
		block.invoke(targetObject, setter).arg($var);
	} else {
		unsetValues(block);
		if (fieldOutline.getPropertyInfo().isCollection()) {
			fieldAccessor.fromRawValue(block
					._if($var.ne(JExpr._null()))._then(), uniqueName,
					$var);
		} else {
			fieldAccessor.fromRawValue(block, uniqueName, $var);
		}
	}
}
 
Example #4
Source File: MergeablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateMergeFrom$createNewInstance(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	final JMethod existingMethod = theClass.getMethod("createNewInstance",
			new JType[0]);
	if (existingMethod == null) {

		final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass
				.owner().ref(Object.class), "createNewInstance");
		newMethod.annotate(Override.class);
		{
			final JBlock body = newMethod.body();
			body._return(JExpr._new(theClass));
		}
		return newMethod;
	} else {
		return existingMethod;
	}
}
 
Example #5
Source File: CopyablePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected JMethod generateCopyTo$createNewInstance(
		final ClassOutline classOutline, final JDefinedClass theClass) {

	final JMethod existingMethod = theClass.getMethod("createNewInstance",
			new JType[0]);
	if (existingMethod == null) {

		final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass
				.owner().ref(Object.class), "createNewInstance");
		newMethod.annotate(Override.class);
		{
			final JBlock body = newMethod.body();
			body._return(JExpr._new(theClass));
		}
		return newMethod;
	} else {
		return existingMethod;
	}
}
 
Example #6
Source File: AggrFunctionHolder.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[]  workspaceJVars) {
  HoldingContainer out = g.declare(resolvedOutput, false);
  JBlock sub = new JBlock();
  g.getEvalBlock().add(sub);
  JVar internalOutput = sub.decl(JMod.FINAL, CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel()), getReturnName(), JExpr._new(CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel())));
  addProtectedBlock(g, sub, output(), null, workspaceJVars, false);
  sub.assign(out.getHolder(), internalOutput);
      //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
      if (!g.getMappingSet().isHashAggMapping()) {
        generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false);
      }
     generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
 
Example #7
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
static
private JInvocation createSuperInvocation(JDefinedClass clazz, JMethod method){
	JInvocation invocation;

	if(method.type() != null){
		invocation = JExpr._super().invoke(method.name());
	} else

	{
		invocation = JExpr.invoke("super");
	}

	List<JVar> parameters = method.params();
	for(JVar parameter : parameters){
		invocation.arg(parameter);
	}

	return invocation;
}
 
Example #8
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 #9
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private void renderConstantsClass(JDefinedClass classModel) throws Exception {
	
	// define constants class
	JDefinedClass constantsClass = classModel._class(JMod.STATIC, Util.CONSTANTS_CLASS_NAME);
	
	// generate the javadoc on the top of the Constants class
	JDocComment javadoc = constantsClass.javadoc();
	javadoc.append(Util.CONSTANTS_CLASS_JAVADOC);
	
	// render root element name
	JFieldVar rootElementField = constantsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.ROOT_ELEMENT_NAME_FIELD);
	rootElementField.init(JExpr.lit(Util.toLowerCaseFirstLetter(classModel.name())));
	
	// render type name
	JFieldVar typeNameField = constantsClass.field(JMod.FINAL | JMod.STATIC, String.class, Util.TYPE_NAME_FIELD);
	typeNameField.init(JExpr.lit(classModel.name() + Util.TYPE_NAME_SUFFIX));
          
}
 
Example #10
Source File: SchemaAssistant.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public JExpression getEnumValueByIndex(Schema enumSchema, JExpression indexExpr, JExpression getSchemaExpr) {
  if (useGenericTypes) {
    /**
     * TODO: Consider ways to avoid instantiating a new {@link org.apache.avro.generic.GenericData.EnumSymbol}
     *       instance, e.g. can we pre-allocate one "canonical" enum instance for each ordinal and keep handing
     *       out the same one repeatedly, given that they are not mutable? */
    if (Utils.isAvro14()) {
      return JExpr._new(codeModel.ref(GenericData.EnumSymbol.class))
          .arg(getSchemaExpr.invoke("getEnumSymbols").invoke("get").arg(indexExpr));
    } else {
      return JExpr._new(codeModel.ref(GenericData.EnumSymbol.class))
          .arg(getSchemaExpr)
          .arg(getSchemaExpr.invoke("getEnumSymbols").invoke("get").arg(indexExpr));
    }
  } else {
    return codeModel.ref(enumSchema.getFullName()).staticInvoke("values").component(indexExpr);
  }
}
 
Example #11
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) {
    // remove the old getter
    ownerClass.methods().remove(getter);
    // and create a new one
    JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name());
    JBlock block = newGetter.body();

    JVar ret = block.decl(getJavaType(field), "ret");
    JCodeModel codeModel = field.type().owner();
    JVar param = generateMethodParameter(getter, field);
    JConditional conditional = block._if(param.eq(JExpr._null()));
    conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param));
    conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param));
    block._return(ret);

    getter.javadoc().append("Returns unmodifiable collection.");
}
 
Example #12
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processArrayElementLoop(final Schema arraySchema, final JClass arrayClass, JExpression arrayExpr, JBlock body, String getMethodName) {
  final JForLoop forLoop = body._for();
  final JVar counter = forLoop.init(codeModel.INT, getUniqueName("counter"), JExpr.lit(0));
  forLoop.test(counter.lt(JExpr.invoke(arrayExpr, "size")));
  forLoop.update(counter.incr());
  final JBlock forBody = forLoop.body();
  forBody.invoke(JExpr.direct(ENCODER), "startItem");

  final Schema elementSchema = arraySchema.getElementType();
  if (SchemaAssistant.isComplexType(elementSchema)) {
    JVar containerVar = declareValueVar(elementSchema.getName(), elementSchema, forBody);
    forBody.assign(containerVar, JExpr.invoke(JExpr.cast(arrayClass, arrayExpr), getMethodName).arg(counter));
    processComplexType(elementSchema, containerVar, forBody);
  } else {
    processSimpleType(elementSchema, arrayExpr.invoke(getMethodName).arg(counter), forBody, false);
  }
}
 
Example #13
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JExpression getEmptyCollectionExpression(JCodeModel codeModel, JVar param) {
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyList");
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyList");
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyMap");
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptySet");
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        return JExpr._new(codeModel.ref(TreeMap.class));
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        return JExpr._new(codeModel.ref(TreeSet.class));
    }
    return param;
}
 
Example #14
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private JInvocation appendFieldsToHashCode(Map<String, JFieldVar> nonTransientAndNonStaticFields, JClass hashCodeBuilderRef) {
	JInvocation invocation = JExpr._new(hashCodeBuilderRef);
	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
																				// hashCode()
																				// method.
		invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode"));
	}

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

	return invocation;
}
 
Example #15
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 #16
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 #17
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private void formatDateParameter(JBlock b, ParameterDetails details) {
  JExpression expr = jcodeModel.ref(java.time.format.DateTimeFormatter.class)
    .staticRef("ISO_LOCAL_DATE_TIME")
    .invoke("format")
      .arg(jcodeModel.ref(java.time.ZonedDateTime.class)
        .staticInvoke("ofInstant")
          .arg(JExpr.ref(details.valueName).invoke("toInstant"))
          .arg(jcodeModel.ref(java.time.ZoneId.class)
            .staticInvoke("systemDefault")));
  b.invoke(details.queryParams, APPEND).arg(expr);
}
 
Example #18
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JInvocation invokeListener(final JBlock block, final JFieldVar field, final JVar oldValueVar, final JVar setterArg, final String aspectName) {
	final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1);
	final JInvocation fvcInvoke = block.invoke(JExpr._this().ref(aspectName + BoundPropertiesPlugin.SUPPORT_FIELD_SUFFIX), "fire" + aspectNameCap);
	fvcInvoke.arg(JExpr.lit(field.name()));
	fvcInvoke.arg(oldValueVar);
	fvcInvoke.arg(setterArg);
	return fvcInvoke;
}
 
Example #19
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private HoldingContainer visitReturnValueExpression(ReturnValueExpression e, ClassGenerator<?> generator) {
  LogicalExpression child = e.getChild();
  // Preconditions.checkArgument(child.getMajorType().equals(Types.REQUIRED_BOOLEAN));
  HoldingContainer hc = child.accept(this, generator);
  if (e.isReturnTrueOnOne()) {
    generator.getEvalBlock()._return(hc.getValue().eq(JExpr.lit(1)));
  } else {
    generator.getEvalBlock()._return(hc.getValue());
  }

  return null;
}
 
Example #20
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public EqualsArguments iterator(JBlock block, JType elementType) {
	final JVar leftListIterator = block.decl(JMod.FINAL, getCodeModel()
			.ref(ListIterator.class).narrow(elementType), leftValue()
			.name() + "ListIterator", leftValue().invoke("listIterator"));
	final JVar rightListIterator = block.decl(JMod.FINAL, getCodeModel()
			.ref(ListIterator.class).narrow(elementType), rightValue()
			.name() + "ListIterator", rightValue().invoke("listIterator"));

	return spawn(rightListIterator, JExpr.TRUE, leftListIterator,
			JExpr.TRUE);
}
 
Example #21
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 #22
Source File: JpaUnitRuleTest.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 JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emField.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

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

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

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
 
Example #23
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 #24
Source File: SchemaAssistant.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
public JExpression getEnumValueByIndex(Schema enumSchema, JExpression indexExpr, JInvocation getSchemaExpr) {
    if (useGenericTypes) {
        return JExpr._new(codeModel.ref(GenericData.EnumSymbol.class)).arg(getSchemaExpr)
                .arg(getSchemaExpr.invoke("getEnumSymbols").invoke("get").arg(indexExpr));
    } else {
        return codeModel.ref(enumSchema.getFullName()).staticInvoke("values").component(indexExpr);
    }
}
 
Example #25
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
private JFieldVar addValueField(JDefinedClass _enum, JType type) {
    JFieldVar valueField = _enum.field(JMod.PRIVATE | JMod.FINAL, type, VALUE_FIELD_NAME);

    JMethod constructor = _enum.constructor(JMod.PRIVATE);
    JVar valueParam = constructor.param(type, VALUE_FIELD_NAME);
    JBlock body = constructor.body();
    body.assign(JExpr._this().ref(valueField), valueParam);

    return valueField;
}
 
Example #26
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextFieldOfWrongType() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "em");
    emField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

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

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

        // THEN
        assertThat(e.getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager"));
    }
}
 
Example #27
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private void addConstructorOkapi3Args() {
  JMethod constructor = constructor();
  JVar okapiUrlVar = constructor.param(String.class, OKAPI_URL);
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar tokenVar = constructor.param(String.class, TOKEN);
  JBlock conBody = constructor.body();
  conBody.invoke("this").arg(okapiUrlVar).arg(tenantIdVar).arg(tokenVar).arg(JExpr.TRUE)
    .arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
}
 
Example #28
Source File: HashCodeArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public HashCodeArguments property(JBlock block, String propertyName,
		String propertyMethod, JType declarablePropertyType,
		JType propertyType, Collection<JType> possiblePropertyTypes) {
	block.assign(currentHashCode(),
			currentHashCode().mul(JExpr.lit(multiplier())));		
	final JVar propertyValue = block.decl(JMod.FINAL,
			declarablePropertyType, value().name() + propertyName, value()
					.invoke(propertyMethod));
	// We assume that primitive properties are always set
	boolean isAlwaysSet = propertyType.isPrimitive();
	final JExpression propertyHasSetValue = isAlwaysSet ? JExpr.TRUE
			: propertyValue.ne(JExpr._null());
	return spawn(propertyValue, propertyHasSetValue);
}
 
Example #29
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createAggregationMethod(JDefinedClass clazz, JClass valueClazz, String name, JExpression valueExpression, String operation, JPrimitiveType type){
	JMethod method = clazz.method(JMod.PUBLIC, valueClazz, name);
	method.annotate(Override.class);

	JBlock body = method.body();

	body._return(JExpr._new(valueClazz).arg(valueExpression).arg(JExpr.invoke("newReport")).arg(createReportInvocation(clazz, operation, Collections.emptyList(), type)));
}
 
Example #30
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private JVar declareValueVar(final String name, final Schema schema, JBlock block) {
    if (SchemaAssistant.isComplexType(schema)) {
        return block.decl(schemaAssistant.classFromSchema(schema, true),
                getVariableName(StringUtils.uncapitalize(name)), JExpr._null());
    } else {
        throw new FastDeserializerGeneratorException("Incorrect container variable: " + schema.getType().getName());
    }
}