com.sun.codemodel.JOp Java Examples

The following examples show how to use com.sun.codemodel.JOp. 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: SingleWrappingElementField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public JExpression unwrapCondifiton(JExpression source) {
	
	final JType type = getTypeRef().getTarget().toType(outline.parent(),
			Aspect.EXPOSED);
	return JOp._instanceof(source, type);
}
 
Example #2
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 #3
Source File: MetaPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private void generateAccessors(final FieldOutline fieldOutline, final String propertyName, final JType returnType, final JDefinedClass declaringClass, final F1<JExpression, JVar> getMaker, final F3<JExpression, JBlock, JVar, JVar> setMaker) {
	final String constantName = getConstantName(fieldOutline);
	final JMethod getMethod = declaringClass.method(JMod.PUBLIC, returnType, "get");
	getMethod.annotate(Override.class);
	final JVar instanceParam = getMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
	getMethod.body()._return(JOp.cond(instanceParam.eq(JExpr._null()), JExpr._null(), getMaker.f(instanceParam)));
	final JMethod setMethod = declaringClass.method(JMod.PUBLIC, void.class, "set");
	setMethod.annotate(Override.class);
	final JVar setInstanceParam = setMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
	final JVar valueParam = setMethod.param(JMod.FINAL, returnType, "_value_");
	if (constantName == null) {
		final JConditional ifNotNull = setMethod.body()._if(setInstanceParam.ne(JExpr._null()));
		setMaker.f(ifNotNull._then(), setInstanceParam, valueParam);
	}
}
 
Example #4
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 #5
Source File: PartialCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JExpression getIncludeCondition(final JVar fieldPathVar) {
	return JOp.cond(
			PartialCopyGenerator.this.propertyTreeUseParam.eq(PartialCopyGenerator.this.pluginContext.includeConst),
			fieldPathVar.ne(JExpr._null()),
			fieldPathVar.eq(JExpr._null()).cor(fieldPathVar.invoke("isLeaf").not())
	);
}
 
Example #6
Source File: PartialCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
public TreeVarGenerator(final JBlock body, final String fieldName) {
	this.fieldPathVar = body.decl(JMod.FINAL,
			PartialCopyGenerator.this.pluginContext.codeModel._ref(PropertyTree.class),
			fieldName + "PropertyTree",
			JOp.cond(PartialCopyGenerator.this.propertyTreeParam.eq(JExpr._null()), JExpr._null(),PartialCopyGenerator.this.propertyTreeParam.invoke("get").arg(JExpr.lit(fieldName)))
	);
}
 
Example #7
Source File: SingleWrappingReferenceObjectField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public JExpression unwrapCondifiton(JExpression source) {

	final CReferencePropertyInfo core = (CReferencePropertyInfo) this.core;

	JExpression predicate = null;
	if (core.getElements().isEmpty()) {
		predicate = null;
	} else {
		for (CElement element : core.getElements()) {
			if (element instanceof CElementInfo) {
				CElementInfo elementinfo = (CElementInfo) element;

				final SingleWrappingReferenceElementInfoField field = new SingleWrappingReferenceElementInfoField(
						outline, prop, core, elementinfo);
				final JExpression condition = field
						.unwrapCondifiton(source);
				predicate = (predicate == null) ? condition : JOp.cor(
						predicate, condition);
			} else {
				// TODO Other cases currently not supported.
			}
		}
	}

	final JExpression isElement = codeModel.ref(JAXBContextUtils.class)
			.staticInvoke("isElement").arg(contextPath).arg(source);
	return predicate == null ? isElement : JOp.cand(JOp.not(predicate),
			isElement);
}
 
Example #8
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 #9
Source File: EqualsCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onDouble(EqualsArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	final JClass Double$class = getCodeModel().ref(Double.class);
	final JExpression leftValueLongBits = Double$class.staticInvoke(
			"doubleToLongBits").arg(arguments.leftValue());
	final JExpression rightValueLongBits = Double$class.staticInvoke(
			"doubleToLongBits").arg(arguments.rightValue());
	returnFalseIfNotEqualsCondition(arguments, block, isAlwaysSet,
			JOp.ne(leftValueLongBits, rightValueLongBits));
}
 
Example #10
Source File: HashCodeCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onDouble(HashCodeArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	// long bits = doubleToLongBits(value);
	final JVar bits = block.decl(JMod.FINAL, getCodeModel().LONG, arguments
			.value().name() + "Bits", getCodeModel().ref(Double.class)
			.staticInvoke("doubleToLongBits").arg(arguments.value()));
	// return (int)(bits ^ (bits >>> 32));
	final JExpression valueHashCode = JExpr.cast(getCodeModel().INT,
			JOp.xor(bits, JOp.shrz(bits, JExpr.lit(32))));
	ifHasSetValueAssignPlusValueHashCode(arguments, block, valueHashCode,
			isAlwaysSet, true);
}
 
Example #11
Source File: HashCodeCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onBoolean(HashCodeArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	ifHasSetValueAssignPlusValueHashCode(arguments, block,
			JOp.cond(arguments.value(), JExpr.lit(1231), JExpr.lit(1237)),
			isAlwaysSet, true);
}
 
Example #12
Source File: SingleWrappingClassInfoField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public JExpression unwrapCondifiton(JExpression source) {
	return JOp._instanceof(source, _class);
}
 
Example #13
Source File: SingleWrappingClassInfoField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public JExpression wrapCondifiton(JExpression source) {
	return JOp.ne(source, JExpr._null());
}
 
Example #14
Source File: AbstractListField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public JExpression count() {
    return JOp.cond( field.eq(JExpr._null()), JExpr.lit(0), field.invoke("size") );
}
 
Example #15
Source File: DrillSimpleFuncHolder.java    From Bats with Apache License 2.0 4 votes vote down vote up
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, HoldingContainer[] inputVariables, String body,
                                            JVar[] workspaceJVars, FieldReference ref) {

  g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", getRegisteredNames()[0]));

  JBlock sub = new JBlock(true, true);
  JBlock topSub = sub;
  HoldingContainer out = null;
  MajorType returnValueType = getReturnType();

  // add outside null handling if it is defined.
  if (getNullHandling() == NullHandling.NULL_IF_NULL) {
    JExpression e = null;
    for (HoldingContainer v : inputVariables) {
      if (v.isOptional()) {
        JExpression isNullExpr;
        if (v.isReader()) {
         isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }
    }

    if (e != null) {
      // if at least one expression must be checked, set up the conditional.
      returnValueType = getReturnType().toBuilder().setMode(DataMode.OPTIONAL).build();
      out = g.declare(returnValueType);
      e = e.eq(JExpr.lit(0));
      JConditional jc = sub._if(e);
      jc._then().assign(out.getIsSet(), JExpr.lit(0));
      sub = jc._else();
    }
  }

  if (out == null) {
    out = g.declare(returnValueType);
  }

  // add the subblock after the out declaration.
  g.getEvalBlock().add(topSub);


  JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValueType), getReturnValue().getName(), JExpr._new(g.getHolderType(returnValueType)));
  addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);

  List<String> holderFields = ValueHolderHelper.getHolderParams(returnValueType);
  for (String holderField : holderFields) {
    sub.assign(out.f(holderField), internalOutput.ref(holderField));
  }

  if (sub != topSub) {
    sub.assign(out.f("isSet"),JExpr.lit(1));  // Assign null if NULL_IF_NULL mode
  }

  g.getEvalBlock().directStatement(String.format("//---- end of eval portion of %s function. ----//", getRegisteredNames()[0]));

  return out;
}
 
Example #16
Source File: SingleElementField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public JExpression hasSetValue() {
	return JOp.ne(field, JExpr._null());
}
 
Example #17
Source File: SingleEnumValueWrappingField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {
	return JOp.cond(source.eq(JExpr._null()), JExpr._null(), source
			.invoke("value"));
}
 
Example #18
Source File: SingleEnumValueWrappingField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected JExpression wrap(JExpression target) {
	return JOp.cond(target.eq(JExpr._null()), JExpr._null(), this.enumClass
			.staticInvoke("fromValue").arg(target));
}
 
Example #19
Source File: PluginUtil.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
public static JExpression nullSafe(final JExpression test, final JExpression source) {
	return JOp.cond(test.eq(JExpr._null()), JExpr._null(), source);
}
 
Example #20
Source File: EqualsCodeGenerationImplementor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void returnFalseIfNe(EqualsArguments arguments, JBlock block,
		boolean isAlwaysSet) {
	returnFalseIfNotEqualsCondition(arguments, block, isAlwaysSet,
			JOp.ne(arguments.leftValue(), arguments.rightValue()));
}
 
Example #21
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public JExpression _instanceof(JType type) {
	return JOp.cand(leftValue()._instanceof(type), rightValue()
			._instanceof(type));
}
 
Example #22
Source File: SimpleFunctionHolder.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) {

    g.getEvalBlock().directStatement(String.format("//---- start of eval portion of %s function. ----//", registeredNames[0]));

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;
    HoldingContainer out = null;


    // add outside null handling if it is defined.
    if (nullHandling == NullHandling.NULL_IF_NULL) {
      JExpression e = null;
      for (HoldingContainer v : inputVariables) {
        final JExpression isNullExpr;
        if (v.isReader()) {
          isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }

      if (e != null) {
        // if at least one expression must be checked, set up the conditional.
        out = g.declare(resolvedOutput);
        e = e.eq(JExpr.lit(0));
        JConditional jc = sub._if(e);
        jc._then().assign(out.getIsSet(), JExpr.lit(0));
        sub = jc._else();
      }
    }

    if (out == null) {
      out = g.declare(resolvedOutput);
    }

    // add the subblock after the out declaration.
    g.getEvalBlock().add(topSub);


    JVar internalOutput = sub.decl(JMod.FINAL, CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel()), getReturnName(), JExpr._new(CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel())));
    addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);

    if (sub != topSub || inputVariables.length == 0) {
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1));// Assign null if NULL_IF_NULL mode
    }
    sub.assign(out.getHolder(), internalOutput);

    g.getEvalBlock().directStatement(String.format("//---- end of eval portion of %s function. ----//", registeredNames[0]));

    return out;
  }