com.sun.codemodel.JVar Java Examples

The following examples show how to use com.sun.codemodel.JVar. 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 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 #2
Source File: CodeGenMemberInjector.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Generated code for a class may have several class members, they
 * are initialized by invoking this method when the instance created.
 *
 * @param cg       the class generator
 * @param instance the class instance created by the compiler
 * @param context  the fragment context
 */
public static void injectMembers(ClassGenerator<?> cg, Object instance, FragmentContext context) {
  Map<Integer, Object> cachedInstances = new HashMap<>();
  for (Map.Entry<Pair<Integer, JVar>, Function<DrillBuf, ? extends ValueHolder>> setter : cg.getConstantVars().entrySet()) {
    try {
      JVar var = setter.getKey().getValue();
      Integer depth = setter.getKey().getKey();
      Object varInstance = getFieldInstance(instance, depth, cachedInstances);
      Field field = varInstance.getClass().getDeclaredField(var.name());
      field.setAccessible(true);
      field.set(varInstance, setter.getValue().apply(context.getManagedBuffer()));
    } catch (ReflectiveOperationException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example #3
Source File: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * declare a constant field for the class.
 * argument {@code function} holds the constant value which
 * returns a value holder must be set to the class field when the class instance created.
 * the class field innerClassField will be created if innerClassGenerator exists.
 *
 * @param prefix the prefix name of class field
 * @param t the type of class field
 * @param init init expression
 * @param function the function holds the constant value
 * @return the depth of nested class, class field
 */
public Pair<Integer, JVar> declareClassConstField(String prefix, JType t, JExpression init,
                                                  Function<DrillBuf, ? extends ValueHolder> function) {
  JVar var;
  int depth = 1;
  if (innerClassGenerator != null) {
    Pair<Integer, JVar> nested = innerClassGenerator.declareClassConstField(prefix, t, init, function);
    depth = nested.getKey() + 1;
    var = nested.getValue();
  } else {
    var = clazz.field(JMod.NONE, t, prefix + index++, init);
  }
  Pair<Integer, JVar> depthVar = Pair.of(depth, var);
  constantVars.put(depthVar, function);
  return depthVar;
}
 
Example #4
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 #5
Source File: EvaluationVisitor.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holderExpr,
    ClassGenerator<?> generator) throws RuntimeException {

  AbstractFuncHolder holder = (AbstractFuncHolder) holderExpr.getHolder();

  JVar[] workspaceVars = holder.renderStart(generator, null, holderExpr.getFieldReference());

  if (holder.isNested()) {
    generator.getMappingSet().enterChild();
  }

  HoldingContainer[] args = new HoldingContainer[holderExpr.args.size()];
  for (int i = 0; i < holderExpr.args.size(); i++) {
    args[i] = holderExpr.args.get(i).accept(this, generator);
  }

  holder.renderMiddle(generator, args, workspaceVars);

  if (holder.isNested()) {
    generator.getMappingSet().exitChild();
  }

  return holder.renderEnd(generator, args, workspaceVars, holderExpr.getFieldReference());
}
 
Example #6
Source File: ClassGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Adds local variable declaration based on given name and type.
 *
 * @param t major type
 * @param name variable name
 * @param includeNewInstance whether to create new instance
 * @return holder instance
 */
public HoldingContainer declare(MajorType t, String name, boolean includeNewInstance) {
  JType holderType = getHolderType(t);
  JVar var;
  if (includeNewInstance) {
    var = getEvalBlock().decl(holderType, name + index, JExpr._new(holderType));
  } else {
    var = getEvalBlock().decl(holderType, name + index);
  }
  JFieldRef outputSet = null;
  if (t.getMode() == DataMode.OPTIONAL) {
    outputSet = var.ref("isSet");
  }
  index++;
  return new HoldingContainer(t, var, var.ref("value"), outputSet);
}
 
Example #7
Source File: DrillComplexWriterAggFuncHolder.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public JVar[] renderStart(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, FieldReference fieldReference) {
  if (!classGenerator.getMappingSet().isHashAggMapping()) {  //Declare workspace vars for non-hash-aggregation.
    JInvocation container = classGenerator.getMappingSet().getOutgoing().invoke("getOutgoingContainer");

    complexWriter = classGenerator.declareClassField("complexWriter", classGenerator.getModel()._ref(ComplexWriter.class));
    writerIdx = classGenerator.declareClassField("writerIdx", classGenerator.getModel()._ref(int.class));
    lastWriterIdx = classGenerator.declareClassField("lastWriterIdx", classGenerator.getModel()._ref(int.class));
    //Default name is "col", if not passed in a reference name for the output vector.
    String refName = fieldReference == null ? "col" : fieldReference.getRootSegment().getPath();
    JClass cwClass = classGenerator.getModel().ref(VectorAccessibleComplexWriter.class);
    classGenerator.getSetupBlock().assign(complexWriter, cwClass.staticInvoke("getWriter").arg(refName).arg(container));
    classGenerator.getSetupBlock().assign(writerIdx, JExpr.lit(0));
    classGenerator.getSetupBlock().assign(lastWriterIdx, JExpr.lit(-1));

    JVar[] workspaceJVars = declareWorkspaceVariables(classGenerator);
    generateBody(classGenerator, ClassGenerator.BlockType.SETUP, setup(), null, workspaceJVars, true);
    return workspaceJVars;
  } else {
    return super.renderStart(classGenerator, inputVariables, fieldReference);
  }
}
 
Example #8
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 #9
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 #10
Source File: DrillSimpleFuncHolder.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) {
  //If the function's annotation specifies a parameter has to be constant expression, but the HoldingContainer
  //for the argument is not, then raise exception.
  for (int i = 0; i < inputVariables.length; i++) {
    if (getParameters()[i].isConstant() && !inputVariables[i].isConstant()) {
      throw new DrillRuntimeException(String.format("The argument '%s' of Function '%s' has to be constant!", getParameters()[i].getName(), this.getRegisteredNames()[0]));
    }
  }
  generateBody(classGenerator, BlockType.SETUP, setupBody(), inputVariables, workspaceJVars, true);
  HoldingContainer c = generateEvalBody(classGenerator, inputVariables, evalBody(), workspaceJVars, fieldReference);
  generateBody(classGenerator, BlockType.RESET, resetBody(), null, workspaceJVars, false);
  generateBody(classGenerator, BlockType.CLEANUP, cleanupBody(), null, workspaceJVars, false);
  return c;
}
 
Example #11
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public EqualsArguments cast(String suffix, JBlock block,
		JType jaxbElementType, boolean suppressWarnings) {
	final JVar castedLeftValue = block.decl(JMod.FINAL, jaxbElementType,
			leftValue().name() + suffix,
			JExpr.cast(jaxbElementType, leftValue()));
	if (suppressWarnings) {
		castedLeftValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	final JVar castedRightValue = block.decl(JMod.FINAL, jaxbElementType,
			rightValue().name() + suffix,
			JExpr.cast(jaxbElementType, rightValue()));
	if (suppressWarnings) {
		castedRightValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	return new EqualsArguments(getCodeModel(), castedLeftValue, JExpr.TRUE,
			castedRightValue, JExpr.TRUE);
}
 
Example #12
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 #13
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JExpression getUnmodifiableWrappedExpression(JCodeModel codeModel, JVar param) {
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableCollection").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableList").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableMap").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSet").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedMap").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedSet").arg(param);
    }
    return param;
}
 
Example #14
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private JVar declareSchemaVar(Schema valueSchema, String variableName, JInvocation getValueType) {
    if (!useGenericTypes) {
        return null;
    }
    if (SchemaAssistant.isComplexType(valueSchema) || Schema.Type.ENUM.equals(valueSchema.getType())) {
        int schemaId = getSchemaId(valueSchema);
        if (schemaVarMap.get(schemaId) != null) {
            return schemaVarMap.get(schemaId);
        } else {
            JVar schemaVar = schemaMapMethod.body().decl(codeModel.ref(Schema.class),
                    getVariableName(StringUtils.uncapitalize(variableName)), getValueType);
            registerSchema(valueSchema, schemaId, schemaVar);
            schemaVarMap.put(schemaId, schemaVar);
            return schemaVar;
        }
    } else {
        return null;
    }
}
 
Example #15
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 #16
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 6 votes vote down vote up
private void processRecord(final Schema recordSchema, JExpression recordExpr, final JBlock containerBody) {
    if (methodAlreadyDefined(recordSchema)) {
        containerBody.invoke(getMethod(recordSchema)).arg(recordExpr).arg(JExpr.direct(ENCODER));
        return;
    }
    JMethod method = createMethod(recordSchema);
    containerBody.invoke(getMethod(recordSchema)).arg(recordExpr).arg(JExpr.direct(ENCODER));

    JBlock body = method.body();
    recordExpr = method.listParams()[0];

    for (Schema.Field field : recordSchema.getFields()) {
        Schema fieldSchema = field.schema();
        if (SchemaAssistant.isComplexType(fieldSchema)) {
            JClass fieldClass = schemaAssistant.classFromSchema(fieldSchema);
            JVar containerVar = declareValueVar(field.name(), fieldSchema, body);
            JExpression valueExpression = JExpr.invoke(recordExpr, "get").arg(JExpr.lit(field.pos()));
            containerVar.init(JExpr.cast(fieldClass, valueExpression));

            processComplexType(fieldSchema, containerVar, body);
        } else {
            processSimpleType(fieldSchema, recordExpr.invoke("get").arg(JExpr.lit(field.pos())), body);
        }

    }
}
 
Example #17
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processComplexType(JVar fieldSchemaVar, String name, Schema schema, Schema readerFieldSchema,
    JBlock methodBody, FieldAction action, BiConsumer<JBlock, JExpression> putExpressionIntoParent,
    Supplier<JExpression> reuseSupplier) {
  switch (schema.getType()) {
    case RECORD:
      processRecord(fieldSchemaVar, schema.getName(), schema, readerFieldSchema, methodBody, action,
          putExpressionIntoParent, reuseSupplier);
      break;
    case ARRAY:
      processArray(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case MAP:
      processMap(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case UNION:
      processUnion(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    default:
      throw new FastDeserializerGeneratorException("Incorrect complex type: " + action.getType());
  }
}
 
Example #18
Source File: PluginContext.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
JBlock catchCloneNotSupported(final JBlock body, final JClass elementType) {
	final Class<? extends Cloneable> elementRuntimeClass;
	try {
		elementRuntimeClass = (Class<? extends Cloneable>) Class.forName(elementType.binaryName());
	} catch (final ClassNotFoundException e) {
		return body;
	}
	if (!cloneThrows(elementRuntimeClass)) {
		return body;
	} else {
		final JTryBlock tryBlock = body._try();
		final JCatchBlock catchBlock = tryBlock._catch(this.codeModel.ref(CloneNotSupportedException.class));
		final JVar exceptionVar = catchBlock.param("e");
		catchBlock.body()._throw(JExpr._new(this.codeModel.ref(RuntimeException.class)).arg(exceptionVar));
		return tryBlock.body();
	}
}
 
Example #19
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
private void generateForDirectClass(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    String visitMethodName = visitMethodNamer.apply(implClass.name());
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodName);
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");

    travVizBloc.assign(retVal, JExpr.invoke(JExpr.invoke("getVisitor"), visitMethodName).arg(beanVar));

    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    addTraverseBlock(travViz, beanVar, false);

    travVizBloc._return(retVal);
}
 
Example #20
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private void withEquals() {
	JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals");
	JVar otherObject = equals.param(Object.class, "other");

	Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class;
	if (!Config.getPojoConfig().isUseCommonsLang3()) {
		equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class;
	}

	JBlock body = equals.body();

	body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE);
	body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
	body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE);

	JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject));

	JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass);

	JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef);

	body._return(equalsBuilderInvocation.invoke("isEquals"));
}
 
Example #21
Source File: PojoBuilder.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private Map<String, JVar> getSuperParametersToAdd(JClass pojo) {
	Map<String, JVar> tFields = new LinkedHashMap<>();
	JClass parent = pojo._extends();
	if (!parent.name().equals(Object.class.getSimpleName())) {
		parent = CodeModelHelper.findFirstClassBySimpleName(this.pojoModel, parent.name());
		if (parent instanceof JDefinedClass) {
			JDefinedClass jParent = (JDefinedClass) parent;
			JMethod constructor = null;
			Iterator<JMethod> constructors = jParent.constructors();
			while (constructors.hasNext()) {
				JMethod targetConstructor = constructors.next();
				if (constructor == null || constructor.params().size() < targetConstructor.params().size()) {
					constructor = targetConstructor;
				}
			}
			for (JVar var : constructor.params()) {
				tFields.put(var.name(), var);
			}
		}
	}
	return tFields;
}
 
Example #22
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, JFieldVar field, JMethod unconditionalWithMethod, boolean inherit) {
    if (field.type().isPrimitive())
        return null;
    String fieldName = StringUtils.capitalize(field.name());
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull");
    JVar param = generateMethodParameter(method, field);
    JBlock block = method.body();
    if (inherit) {
        generateSuperCall(method);
        method.body()._return(JExpr._this());
    } else {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then()._return(JExpr._this());
        conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param));
    }
    return method;
}
 
Example #23
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 #24
Source File: WindowFunction.java    From dremio-oss with 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 #25
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void registerSchema(final Schema writerSchema, int schemaId, JVar schemaVar) {
    if ((Schema.Type.RECORD.equals(writerSchema.getType()) || Schema.Type.ENUM.equals(writerSchema.getType())
            || Schema.Type.ARRAY.equals(writerSchema.getType())) && schemaNotRegistered(writerSchema)) {
        schemaMap.put(schemaId, writerSchema);
        schemaMapMethod.body().invoke(schemaMapField, "put").arg(JExpr.lit(schemaId)).arg(schemaVar);
    }
}
 
Example #26
Source File: CopyUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static void generateCopies(ClassGenerator<?> g, VectorAccessible batch, boolean hyper){
  // we have parallel ids for each value vector so we don't actually have to deal with managing the ids at all.
  int fieldId = 0;

  JExpression inIndex = JExpr.direct("inIndex");
  JExpression outIndex = JExpr.direct("outIndex");
  for(VectorWrapper<?> vv : batch) {
    String copyMethod;
    if (!Types.isFixedWidthType(vv.getField().getType()) || Types.isRepeated(vv.getField().getType()) || Types.isComplex(vv.getField().getType())) {
      copyMethod = "copyFromSafe";
    } else {
      copyMethod = "copyFrom";
    }
    g.rotateBlock();
    JVar inVV = g.declareVectorValueSetupAndMember("incoming", new TypedFieldId(vv.getField().getType(), vv.isHyper(), fieldId));
    JVar outVV = g.declareVectorValueSetupAndMember("outgoing", new TypedFieldId(vv.getField().getType(), false, fieldId));

    if(hyper){

      g.getEvalBlock().add(
              outVV
                      .invoke(copyMethod)
                      .arg(
                              inIndex.band(JExpr.lit((int) Character.MAX_VALUE)))
                      .arg(outIndex)
                      .arg(
                              inVV.component(inIndex.shrz(JExpr.lit(16)))
                      )
      );
    }else{
      g.getEvalBlock().add(outVV.invoke(copyMethod).arg(inIndex).arg(outIndex).arg(inVV));
    }

    g.rotateBlock();
    fieldId++;
  }
}
 
Example #27
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void processArray(final Schema arraySchema, JExpression arrayExpr, JBlock body) {
    final JClass arrayClass = schemaAssistant.classFromSchema(arraySchema);
    body.invoke(JExpr.direct(ENCODER), "writeArrayStart");

    final JExpression emptyArrayCondition = arrayExpr.eq(JExpr._null())
            .cor(JExpr.invoke(arrayExpr, "isEmpty"));

    final JConditional emptyArrayIf = body._if(emptyArrayCondition);
    final JBlock emptyArrayBlock = emptyArrayIf._then();
    emptyArrayBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));

    final JBlock nonEmptyArrayBlock = emptyArrayIf._else();
    nonEmptyArrayBlock.invoke(JExpr.direct(ENCODER), "setItemCount")
            .arg(JExpr.invoke(arrayExpr, "size"));
    final JForLoop forLoop = nonEmptyArrayBlock._for();
    final JVar counter = forLoop.init(codeModel.INT, getVariableName("counter"), JExpr.lit(0));
    forLoop.test(counter.lt(JExpr.invoke(JExpr.cast(arrayClass, 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), "get").arg(counter));
        processComplexType(elementSchema, containerVar, forBody);
    } else {
        processSimpleType(elementSchema, arrayExpr.invoke("get").arg(counter), forBody);
    }

    body.invoke(JExpr.direct(ENCODER), "writeArrayEnd");
}
 
Example #28
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private JVar addProperty(JDefinedClass clazz, JFieldVar field) {
    JType jType = getJavaType(field);
    int builderFieldVisibility = builderInheritance ? JMod.PROTECTED : JMod.PRIVATE;
    if (isCollection(field)) {
        return clazz.field(builderFieldVisibility, jType, field.name(),
                getNewCollectionExpression(field.type().owner(), jType));
    } else {
        return clazz.field(builderFieldVisibility, jType, field.name());
    }
}
 
Example #29
Source File: ModifierGenerator.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private void generateSingularPropertyAccessor(final DefinedPropertyOutline fieldOutline) {
	final JFieldVar fieldVar = fieldOutline.getFieldVar();
	if(fieldVar != null) {
		final JMethod modifier = this.modifierClass.method(JMod.PUBLIC, this.modifierClass.owner().VOID, ModifierGenerator.SETTER_PREFIX + fieldOutline.getBaseName());
		final JVar parameter = modifier.param(JMod.FINAL, fieldVar.type(), fieldOutline.getFieldName());
		if(this.implement) {
			modifier.body().add(new NestedThisRef(this.classOutline.getImplClass()).invoke(modifier.name()).arg(parameter));
		}
	}
}
 
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());
    }
}