Java Code Examples for com.sun.codemodel.JInvocation#arg()

The following examples show how to use com.sun.codemodel.JInvocation#arg() . 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: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * The code generator creates a method called __DRILL_INIT__ which takes the
 * place of the constructor when the code goes though the byte code merge.
 * For Plain-old Java, we call the method from a constructor created for
 * that purpose. (Generated code, fortunately, never includes a constructor,
 * so we can create one.) Since the init block throws an exception (which
 * should never occur), the generated constructor converts the checked
 * exception into an unchecked one so as to not require changes to the
 * various places that create instances of the generated classes.
 *
 * Example:<code><pre>
 * public StreamingAggregatorGen1() {
 *       try {
 *         __DRILL_INIT__();
 *     } catch (SchemaChangeException e) {
 *         throw new UnsupportedOperationException(e);
 *     }
 * }</pre></code>
 *
 * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's
 * introspection package. But, Drill prefers Java 7 which only provides
 * parameter types.
 */

private void addCtor(Class<?>[] parameters) {
  JMethod ctor = clazz.constructor(JMod.PUBLIC);
  JBlock body = ctor.body();

  // If there are parameters, need to pass them to the super class.
  if (parameters.length > 0) {
    JInvocation superCall = JExpr.invoke("super");

    // This case only occurs for nested classes, and all nested classes
    // in Drill are inner classes. Don't pass along the (hidden)
    // this$0 field.

    for (int i = 1; i < parameters.length; i++) {
      Class<?> p = parameters[i];
      superCall.arg(ctor.param(model._ref(p), "arg" + i));
    }
    body.add(superCall);
  }
  JTryBlock tryBlock = body._try();
  tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD);
  JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class));
  catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e")));
}
 
Example 2
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private void processFixed(final Schema schema, JBlock body, FieldAction action,
        BiConsumer<JBlock, JExpression> putFixedIntoParent) {
    if (action.getShouldRead()) {
        JVar fixedBuffer = body.decl(codeModel.ref(byte[].class), getVariableName(schema.getName()))
                .init(JExpr.direct(" new byte[" + schema.getFixedSize() + "]"));

        body.directStatement(DECODER + ".readFixed(" + fixedBuffer.name() + ");");

        JInvocation createFixed = JExpr._new(schemaAssistant.classFromSchema(schema));
        if (useGenericTypes)
            createFixed = createFixed.arg(getSchemaExpr(schema));

        putFixedIntoParent.accept(body, createFixed.arg(fixedBuffer));
    } else {
        body.directStatement(DECODER + ".skipFixed(" + schema.getFixedSize() + ");");
    }
}
 
Example 3
Source File: ClassGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
  final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);

  final Class<?> valueVectorClass = fieldId.getIntermediateClass();
  final JClass vvClass = model.ref(valueVectorClass);
  final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;

  final JVar vv = declareClassField("vv", retClass);
  final JBlock b = getSetupBlock();
  int[] fieldIndices = fieldId.getFieldIds();
  JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
      .arg(batchName)
      .arg(vvClass.dotclass());

  for(int i = 0; i < fieldIndices.length; i++){
    invoke.arg(JExpr.lit(fieldIndices[i]));
  }

  // we have to cast here since Janino doesn't handle generic inference well.
  JExpression casted = JExpr.cast(retClass, invoke);
  b.assign(vv, casted);
  vvDeclaration.put(setup, vv);

  return vv;
}
 
Example 4
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(backingType, "value");

    JBlock body = fromValue.body();
    JVar constant = body.decl(_enum, "constant");
    constant.init(quickLookupMap.invoke("get").arg(valueParam));

    JConditional _if = body._if(constant.eq(JExpr._null()));

    JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
    JExpression expr = valueParam;

    // if string no need to add ""
    if(!isString(backingType)){
        expr = expr.plus(JExpr.lit(""));
    }
    
    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
 
Example 5
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 6
Source File: ClassGenerator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException {
  this.codeGenerator = codeGenerator;
  this.clazz = clazz;
  this.mappings = mappingSet;
  this.sig = signature;
  this.evaluationVisitor = eval;
  this.model = Preconditions.checkNotNull(model, "Code model object cannot be null.");
  blocks = new LinkedList[sig.size()];

  for (int i =0; i < sig.size(); i++) {
    blocks[i] = Lists.newLinkedList();
  }
  rotateBlock();

  for (SignatureHolder child : signature.getChildHolders()) {
    final String innerClassName = child.getSignatureClass().getSimpleName();
    final JDefinedClass innerClazz;
    // we need to extend the template class and avoid using static inner classes.
    innerClazz = clazz._class(JMod.FINAL, innerClassName)._extends(child.getSignatureClass());

    // we also need to delegate any inner class constructors.
    for(Constructor<?> c : child.getSignatureClass().getDeclaredConstructors()){
      final Class<?>[] params = c.getParameterTypes();
      JMethod constructor = innerClazz.constructor(JMod.PUBLIC);
      JBlock block = constructor.body();
      JInvocation invoke = block.invoke("super");
      block.invoke(SignatureHolder.INIT_METHOD);

      // start at 1 since first parameter is the parent class
      for (int i = 1; i < params.length; i++) {
        constructor.param(params[i], "arg" + i);
        invoke.arg(JExpr.direct("arg" + i));
      }
    }

    innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model));
  }
}
 
Example 7
Source File: ClassGenerator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public JInvocation invokeInnerMethod(JMethod method, BlockType blockType) {
  JInvocation invocation = JExpr.invoke(method);
  String methodName = getCurrentMapping().getMethodName(blockType);
  CodeGeneratorMethod cgm = sig.get(sig.get(methodName));
  for (CodeGeneratorArgument arg : cgm) {
    invocation.arg(JExpr.ref(arg.getName()));
  }
  return invocation;
}
 
Example 8
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
private JFieldVar addQuickLookupMap(JDefinedClass _enum, JType backingType) {

        JClass lookupType = _enum.owner().ref(Map.class).narrow(backingType.boxify(), _enum);
        JFieldVar lookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "CONSTANTS");

        JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(backingType.boxify(), _enum);
        lookupMap.init(JExpr._new(lookupImplType));

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

        return lookupMap;
    }
 
Example 9
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private void addSuperConstructorInvocation(JMethod constructor, Map<String, JVar> superParametersToAdd) {
	JBlock constructorBody = constructor.body();
	JInvocation invocation = constructorBody.invoke("super");
	for (JVar arg : superParametersToAdd.values()) {
		JVar param = constructor.param(arg.type(), arg.name());
		invocation.arg(param);
	}

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

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

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

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

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

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

		addFromValueMethod();
		addToStringMethod();
	}
	return this;
}
 
Example 11
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 12
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private void generateSuperCall(JMethod method) {
    method.annotate(Override.class);
    JBlock block = method.body();
    JInvocation superInvocation = block.invoke(JExpr._super(), method);
    for (JVar param : method.params()) {
        superInvocation.arg(param);
    }
}
 
Example 13
Source File: GetSetVectorHelper.java    From Bats with Apache License 2.0 4 votes vote down vote up
public static JInvocation write(MajorType type, JVar vector, HoldingContainer in, JExpression indexVariable, String setMethodName) {

    JInvocation setMethod = vector.invoke("getMutator").invoke(setMethodName).arg(indexVariable);

    if (type.getMinorType() == MinorType.UNION) {
      return setMethod.arg(in.getHolder());
    }
    switch(type.getMode()){
    case OPTIONAL:
      setMethod = setMethod.arg(in.f("isSet"));
    case REQUIRED:
      switch (type.getMinorType()) {
      case BIGINT:
      case FLOAT4:
      case FLOAT8:
      case INT:
      case MONEY:
      case SMALLINT:
      case TINYINT:
      case UINT1:
      case UINT2:
      case UINT4:
      case UINT8:
      case INTERVALYEAR:
      case DATE:
      case TIME:
      case TIMESTAMP:
      case BIT:
      case DECIMAL9:
      case DECIMAL18:
        return setMethod
            .arg(in.getValue());
      case DECIMAL28DENSE:
      case DECIMAL28SPARSE:
      case DECIMAL38DENSE:
      case DECIMAL38SPARSE:
        return setMethod
            .arg(in.f("start"))
            .arg(in.f("buffer"));
      case INTERVAL:{
        return setMethod
            .arg(in.f("months"))
            .arg(in.f("days"))
            .arg(in.f("milliseconds"));
      }
      case INTERVALDAY: {
        return setMethod
            .arg(in.f("days"))
            .arg(in.f("milliseconds"));
      }
      case VAR16CHAR:
      case VARBINARY:
      case VARCHAR:
      case VARDECIMAL:
        return setMethod
            .arg(in.f("start"))
            .arg(in.f("end"))
            .arg(in.f("buffer"));
      }
    }

    return setMethod.arg(in.getHolder());

  }
 
Example 14
Source File: ClassGenerator.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Prepare the generated class for use as a plain-old Java class
 * (to be compiled by a compiler and directly loaded without a
 * byte-code merge. Three additions are necessary:
 * <ul>
 * <li>The class must extend its template as we won't merge byte
 * codes.</li>
 * <li>A constructor is required to call the <tt>__DRILL_INIT__</tt>
 * method. If this is a nested class, then the constructor must
 * include parameters defined by the base class.</li>
 * <li>For each nested class, create a method that creates an
 * instance of that nested class using a well-defined name. This
 * method overrides the base class method defined for this purpose.</li>
 */

public void preparePlainJava() {

  // If this generated class uses the "straight Java" technique
  // (no byte code manipulation), then the class must extend the
  // template so it plays by normal Java rules for finding the
  // template methods via inheritance rather than via code injection.

  Class<?> baseClass = sig.getSignatureClass();
  clazz._extends(baseClass);

  // Create a constuctor for the class: either a default one,
  // or (for nested classes) one that passes along arguments to
  // the super class constructor.

  Constructor<?>[] ctors = baseClass.getConstructors();
  for (Constructor<?> ctor : ctors) {
    addCtor(ctor.getParameterTypes());
  }

  // Some classes have no declared constructor, but we need to generate one
  // anyway.

  if ( ctors.length == 0 ) {
    addCtor( new Class<?>[] {} );
  }

  // Repeat for inner classes.

  for(ClassGenerator<T> child : innerClasses.values()) {
    child.preparePlainJava();

    // If there are inner classes, then we need to generate a "shim" method
    // to instantiate that class.
    //
    // protected TemplateClass.TemplateInnerClass newTemplateInnerClass( args... ) {
    //    return new GeneratedClass.GeneratedInnerClass( args... );
    // }
    //
    // The name is special, it is "new" + inner class name. The template must
    // provide a method of this name that creates the inner class instance.

    String innerClassName = child.clazz.name();
    JMethod shim = clazz.method(JMod.PROTECTED, child.sig.getSignatureClass(), "new" + innerClassName);
    JInvocation childNew = JExpr._new(child.clazz);
    Constructor<?>[] childCtors = child.sig.getSignatureClass().getConstructors();
    Class<?>[] params;
    if (childCtors.length==0) {
      params = new Class<?>[0];
    } else {
      params = childCtors[0].getParameterTypes();
    }
    for (int i = 1; i < params.length; i++) {
      Class<?> p = params[i];
      childNew.arg(shim.param(model._ref(p), "arg" + i));
    }
    shim.body()._return(JExpr._this().invoke("injectMembers").arg(childNew));
  }
}
 
Example 15
Source File: GetSetVectorHelper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static JInvocation write(MinorType type, JVar vector, HoldingContainer in, JExpression indexVariable, String setMethodName) {

    JInvocation setMethod = vector.invoke(setMethodName).arg(indexVariable);

    if (type == MinorType.UNION) {
      return setMethod.arg(in.getHolder());
    } else {
      setMethod = setMethod.arg(in.f("isSet"));
    }

    switch (type) {
    case BIGINT:
    case FLOAT4:
    case FLOAT8:
    case INT:
    case MONEY:
    case SMALLINT:
    case TINYINT:
    case UINT1:
    case UINT2:
    case UINT4:
    case UINT8:
    case INTERVALYEAR:
    case DATE:
    case TIME:
    case TIMESTAMP:
    case BIT:
    case DECIMAL9:
    case DECIMAL18:
      return setMethod //
          .arg(in.getValue());
    case DECIMAL28DENSE:
    case DECIMAL28SPARSE:
    case DECIMAL38DENSE:
    case DECIMAL38SPARSE:
    case DECIMAL:
      return setMethod //
          .arg(in.f("start")) //
          .arg(in.f("buffer"));
    case INTERVAL:{
      return setMethod //
          .arg(in.f("months")) //
          .arg(in.f("days")) //
          .arg(in.f("milliseconds"));
    }
    case INTERVALDAY: {
      return setMethod //
          .arg(in.f("days")) //
          .arg(in.f("milliseconds"));
    }
    case VAR16CHAR:
    case VARBINARY:
    case VARCHAR:
      return setMethod //
          .arg(in.f("start")) //
          .arg(in.f("end")) //
          .arg(in.f("buffer"));
    }


    return setMethod.arg(in.getHolder());

  }