Java Code Examples for com.sun.codemodel.JExpr

The following examples show how to use com.sun.codemodel.JExpr. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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 2
Source Project: dremio-oss   Source File: AggrFunctionHolder.java    License: 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 3
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: 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
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 5
Source Project: jaxb2-basics   Source File: EqualsPlugin.java    License: 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 Project: Bats   Source File: DrillAggFuncHolder.java    License: 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 7
Source Project: springmvc-raml-plugin   Source File: PojoBuilder.java    License: 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 8
Source Project: immutable-xjc   Source File: PluginImpl.java    License: 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 9
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 10
Source Project: immutable-xjc   Source File: PluginImpl.java    License: 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 11
Source Project: avro-util   Source File: SchemaAssistant.java    License: 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 12
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 13
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 14
@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 15
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 16
public boolean isAlwaysSet() {
	if (constantField != null) {
		return true;
	} else {
		return JExpr.TRUE == fieldAccessor.hasSetValue();
	}
}
 
Example 17
Source Project: jpa-unit   Source File: JpaUnitRuleTest.java    License: 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 18
protected JFieldVar generateField() {
	final JFieldVar field = referenceClass.field(
			JMod.PROTECTED,
			type,
			propertyInfo.getPrivateName(),

			JExpr._new(codeModel.ref(HashMap.class).narrow(QName.class)
					.narrow(Object.class)));
	return field;
}
 
Example 19
Source Project: dremio-oss   Source File: WindowFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
  final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
  final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);

  cg.setMappingSet(mappingSet);
  final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
  final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
  JInvocation setMethod = vv.invoke("setSafe").arg(outIndex).arg(JExpr.direct("partition." + getName()));

  cg.getEvalBlock().add(setMethod);
}
 
Example 20
Source Project: Bats   Source File: WindowFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
  final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
  final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);

  cg.setMappingSet(mappingSet);
  final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
  final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
  JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex).arg(JExpr.direct("partition." + getName()));

  cg.getEvalBlock().add(setMethod);
}
 
Example 21
Source Project: mobi   Source File: SourceGenerator.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void generateFieldSetterForImpl(final JDefinedClass impl, final JMethod interfaceMethod,
                                        final JDefinedClass interfaceClass) {
    if (impl.getMethod(interfaceMethod.name(), interfaceMethod.listParamTypes()) == null) {
        final JMethod method = impl.method(JMod.PUBLIC, interfaceMethod.type(), interfaceMethod.name());
        method.param(interfaceMethod.params().get(0).type(), "arg");
        method._throws(OrmException.class);
        method.annotate(Override.class);
        if (interfaceMethod.params().get(0).type().fullName().startsWith("java.util.Set")) {
            method.body().invoke("setProperties")
                    .arg(JExpr.ref("valueConverterRegistry").invoke("convertTypes")
                            .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                    .arg(JExpr.ref("valueFactory").invoke("createIRI")
                            .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod))));
        } else {
            method.body().invoke("setProperty")
                    .arg(JExpr.ref("valueConverterRegistry").invoke("convertType")
                            .arg(interfaceMethod.params().get(0)).arg(JExpr._this()))
                    .arg(JExpr.ref("valueFactory").invoke("createIRI")
                            .arg(interfaceClass.staticRef(classMethodIriMap.get(interfaceClass).get(interfaceMethod))));
        }
        // TODO - add javadoc.
        // JDocComment jdoc = method.javadoc();
        // jdoc.add("");
    } else {
        LOG.warn("Avoided duplicate setter method: " + interfaceMethod.name() + " on class: " + impl.name());
    }
}
 
Example 22
Source Project: dremio-oss   Source File: EvaluationVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HoldingContainer visitIntConstant(IntExpression e, ClassGenerator<?> generator) throws RuntimeException {
  HoldingContainer out = generator.declare(e.getCompleteType());
  generator.getEvalBlock().assign(out.getValue(), JExpr.lit(e.getInt()));
  setIsSet(out, generator);
  return out;
}
 
Example 23
Source Project: Bats   Source File: ChainedHashTable.java    License: Apache License 2.0 5 votes vote down vote up
private void setupGetHash(ClassGenerator<HashTable> cg, MappingSet incomingMapping, VectorAccessible batch, LogicalExpression[] keyExprs)
  throws SchemaChangeException {

  cg.setMappingSet(incomingMapping);

  if (keyExprs == null || keyExprs.length == 0) {
    cg.getEvalBlock()._return(JExpr.lit(0));
    return;
  }

  /*
   * We use the same logic to generate run time code for the hash function both for hash join and hash
   * aggregate. For join we need to hash everything as double (both for distribution and for comparison) but
   * for aggregation we can avoid the penalty of casting to double
   */


  /*
    Generate logical expression for each key so expression can be split into blocks if number of expressions in method exceeds upper limit.
    `seedValue` is used as holder to pass generated seed value for the new methods.
  */
  String seedValue = "seedValue";
  LogicalExpression seed = ValueExpressions.getParameterExpression(seedValue, Types.required(TypeProtos.MinorType.INT));

  for (LogicalExpression expr : keyExprs) {
    LogicalExpression hashExpression = HashPrelUtil.getHashExpression(expr, seed, incomingProbe != null);
    LogicalExpression materializedExpr = ExpressionTreeMaterializer.materializeAndCheckErrors(hashExpression, batch, context.getFunctionRegistry());
    HoldingContainer hash = cg.addExpr(materializedExpr, ClassGenerator.BlkCreateMode.TRUE_IF_BOUND);
    cg.getEvalBlock().assign(JExpr.ref(seedValue), hash.getValue());
  }

  cg.getEvalBlock()._return(JExpr.ref(seedValue));
}
 
Example 24
Source Project: xero-java-client   Source File: PluginImpl.java    License: 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 25
protected JMethod generateSetter() {
	final JMethod setter = referenceClass.method(JMod.PUBLIC,
			codeModel.VOID, getSetterMethodName());
	final JVar value = setter.param(type, "value");
	setter.body().assign(JExpr._this().ref(field), value);
	return setter;
}
 
Example 26
Source Project: Bats   Source File: EvaluationVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {

      final LogicalExpression child = e.getChild();
      final HoldingContainer inputContainer = child.accept(this, generator);

      JBlock block = generator.getEvalBlock();
      JExpression outIndex = generator.getMappingSet().getValueWriteIndex();
      JVar vv = generator.declareVectorValueSetupAndMember(generator.getMappingSet().getOutgoing(), e.getFieldId());

      // Only when the input is a reader, use writer interface to copy value.
      // Otherwise, input is a holder and we use vv mutator to set value.
      if (inputContainer.isReader()) {
        JType writerImpl = generator.getModel()._ref(
            TypeHelper.getWriterImpl(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JType writerIFace = generator.getModel()._ref(
            TypeHelper.getWriterInterface(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JVar writer = generator.declareClassField("writer", writerIFace);
        generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv).arg(JExpr._null()));
        generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));
        String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
        generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
        if (e.isSafe()) {
          HoldingContainer outputContainer = generator.declare(Types.REQUIRED_BIT);
          generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
          return outputContainer;
        }
      } else {

        final JInvocation setMeth = GetSetVectorHelper.write(e.getChild().getMajorType(), vv, inputContainer, outIndex, e.isSafe() ? "setSafe" : "set");
          if (inputContainer.isOptional()) {
            JConditional jc = block._if(inputContainer.getIsSet().eq(JExpr.lit(0)).not());
            block = jc._then();
          }
          block.add(setMeth);

      }

      return null;
    }
 
Example 27
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 Project: Bats   Source File: EvaluationVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private HoldingContainer renderConstantExpression(ClassGenerator<?> generator, HoldingContainer input) {
  JVar fieldValue = generator.declareClassField("constant", generator.getHolderType(input.getMajorType()));
  // Creates a new vector for class field and assigns to its fields values from output field
  // to allow scalar replacement for source objects
  generator.getEvalBlock().assign(fieldValue, JExpr._new(generator.getHolderType(input.getMajorType())));
  List<String> holderFields = ValueHolderHelper.getHolderParams(input.getMajorType());
  for (String holderField : holderFields) {
    generator.getEvalBlock().assign(fieldValue.ref(holderField), input.getHolder().ref(holderField));
  }
  generator.getMappingSet().exitConstant();
  return new HoldingContainer(input.getMajorType(), fieldValue, fieldValue.ref("value"), fieldValue.ref("isSet"))
      .setConstant(true);
}
 
Example 29
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: MIT License 5 votes vote down vote up
void generateArrayProperty(final JBlock initBody, final JVar productParam, final PropertyOutline fieldOutline, final JType elementType, final JType builderType) {
	final String fieldName = fieldOutline.getFieldName();
	final String propertyName = fieldOutline.getBaseName();
	final JType fieldType = fieldOutline.getRawType();
	final JMethod withVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, builderType, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withVarargsParam = withVarargsMethod.varParam(elementType, fieldName);
	if (this.implement) {
		final JFieldVar builderField = this.builderClass.raw.field(JMod.PRIVATE, fieldType, fieldName, JExpr._null());
		withVarargsMethod.body().assign(JExpr._this().ref(builderField), withVarargsParam);
		withVarargsMethod.body()._return(JExpr._this());
		initBody.assign(productParam.ref(fieldName), JExpr._this().ref(builderField));
	}
}
 
Example 30
Source Project: jaxb2-rich-contract-plugin   Source File: BuilderGenerator.java    License: MIT License 5 votes vote down vote up
JMethod generateCopyOfMethod(final TypeOutline paramType, final boolean partial) {
	if (paramType.getSuperClass() != null) {
		generateCopyOfMethod(paramType.getSuperClass(), partial);
	}
	final JMethod copyOfMethod = this.definedClass.method(JMod.PUBLIC | JMod.STATIC, this.builderClass.raw.narrow(Void.class), this.pluginContext.buildCopyMethodName);
	final JTypeVar copyOfMethodTypeParam = copyOfMethod.generify(BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
	copyOfMethod.type(this.builderClass.raw.narrow(copyOfMethodTypeParam));
	final JVar otherParam = copyOfMethod.param(JMod.FINAL, paramType.getImplClass(), BuilderGenerator.OTHER_PARAM_NAME);
	final CopyGenerator copyGenerator = this.pluginContext.createCopyGenerator(copyOfMethod, partial);
	final JVar newBuilderVar = copyOfMethod.body().decl(JMod.FINAL, copyOfMethod.type(), BuilderGenerator.NEW_BUILDER_VAR_NAME, JExpr._new(copyOfMethod.type()).arg(JExpr._null()).arg(JExpr._null()).arg(JExpr.FALSE));
	copyOfMethod.body().add(copyGenerator.generatePartialArgs(this.pluginContext.invoke(otherParam, this.settings.getCopyToMethodName()).arg(newBuilderVar)));
	copyOfMethod.body()._return(newBuilderVar);
	return copyOfMethod;
}