Java Code Examples for com.sun.codemodel.JExpression

The following examples show how to use com.sun.codemodel.JExpression. 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
Source Project: dremio-oss   Source File: PartitionSenderOperator.java    License: Apache License 2.0 6 votes vote down vote up
private List<Partitioner> createClassInstances(int actualPartitions) throws SchemaChangeException {
  // set up partitioning function
  final LogicalExpression expr = config.getExpr();
  final ClassGenerator<Partitioner> cg = context.getClassProducer().createGenerator(Partitioner.TEMPLATE_DEFINITION).getRoot();
  ClassGenerator<Partitioner> cgInner = cg.getInnerGenerator("OutgoingRecordBatch");

  final LogicalExpression materializedExpr = context.getClassProducer().materialize(expr, incoming);

  // generate code to copy from an incoming value vector to the destination partition's outgoing value vector
  JExpression bucket = JExpr.direct("bucket");

  // generate evaluate expression to determine the hash
  ClassGenerator.HoldingContainer exprHolder = cg.addExpr(materializedExpr);
  cg.getEvalBlock().decl(JType.parse(cg.getModel(), "int"), "bucket", exprHolder.getValue().mod(JExpr.lit(outGoingBatchCount)));
  cg.getEvalBlock()._return(cg.getModel().ref(Math.class).staticInvoke("abs").arg(bucket));

  CopyUtil.generateCopies(cgInner, incoming, incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.FOUR_BYTE);

  // compile and setup generated code
  List<Partitioner> subPartitioners = cg.getCodeGenerator().getImplementationClass(actualPartitions);
  return subPartitioners;
}
 
Example 2
/**
 * add getter method for jFieldVar passed in.
 *
 * @param jc
 * @param jFieldVar
 */
private void addGetter(JDefinedClass jc, JFieldVar jFieldVar) {
    JMethod getMethod = jc.method(JMod.PUBLIC, jFieldVar.type(), getMethodFormattedString(jFieldVar.name()));
    getMethod.annotate(codeModel.ref(Override.class));

    if (this.isAllowExporting) {
        if (!this.fieldJsonExposeMap.get(jFieldVar.name())) {
            getMethod.annotate(codeModel.ref(JsonIgnore.class));
        }

        if (StringUtils.isNotBlank(this.fieldJsonPropertyMap.get(jFieldVar.name()))) {
            getMethod.annotate(codeModel.ref(JsonProperty.class))
                    .param("value", this.fieldJsonPropertyMap.get(jFieldVar.name()));
        }
    }


    if (jFieldVar.type().erasure().fullName().equals(List.class.getName())) {
        JExpression condition = new IsNullExpression(jFieldVar, false);
        JExpression ifTrue = codeModel.ref(Collections.class).staticInvoke("unmodifiableList").arg(jFieldVar);
        JExpression ifFalse = JExpr._null();
        getMethod.body()._return(new TernaryOperator(condition, ifTrue, ifFalse));
    } else {
        getMethod.body()._return(jFieldVar);
    }
}
 
Example 3
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 4
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private JExpression getDefensiveCopyExpression(JCodeModel codeModel, JType jType, JVar param) {
    List<JClass> typeParams = ((JClass) jType).getTypeParameters();
    JClass typeParameter = null;
    if (typeParams.iterator().hasNext()) {
        typeParameter = typeParams.iterator().next();
    }

    JClass newClass = null;
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        newClass = codeModel.ref(ArrayList.class);
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        newClass = codeModel.ref(ArrayList.class);
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        newClass = codeModel.ref(HashMap.class);
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        newClass = codeModel.ref(HashSet.class);
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        newClass = codeModel.ref(TreeMap.class);
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        newClass = codeModel.ref(TreeSet.class);
    }
    if (newClass != null && typeParameter != null) {
        newClass = newClass.narrow(typeParameter);
    }
    return newClass == null ? JExpr._null() : JExpr._new(newClass).arg(param);
}
 
Example 5
private void processBytes(JBlock body, FieldAction action, BiConsumer<JBlock, JExpression> putValueIntoParent,
    Supplier<JExpression> reuseSupplier) {
  if (action.getShouldRead()) {
    if (reuseSupplier.get().equals(JExpr._null())) {
      putValueIntoParent.accept(body, JExpr.invoke(JExpr.direct(DECODER), "readBytes").arg(JExpr.direct("null")));
    } else {
      ifCodeGen(body,
          reuseSupplier.get()._instanceof(codeModel.ref("java.nio.ByteBuffer")),
          thenBlock -> putValueIntoParent.accept(thenBlock, JExpr.invoke(JExpr.direct(DECODER), "readBytes")
              .arg(JExpr.cast(codeModel.ref(ByteBuffer.class), reuseSupplier.get()))),
          elseBlock -> putValueIntoParent.accept(elseBlock,
              JExpr.invoke(JExpr.direct(DECODER), "readBytes").arg(JExpr.direct("null")))
      );
    }
  } else {
    body.directStatement(DECODER + ".skipBytes()");
  }
}
 
Example 6
private void processString(Schema schema, JBlock body, FieldAction action,
    BiConsumer<JBlock, JExpression> putValueIntoParent, Supplier<JExpression> reuseSupplier) {
  if (action.getShouldRead()) {
    JClass stringClass = schemaAssistant.findStringClass(schema);
    if (stringClass.equals(codeModel.ref(Utf8.class))) {
      if (reuseSupplier.equals(EMPTY_SUPPLIER)) {
        putValueIntoParent.accept(body, JExpr.invoke(JExpr.direct(DECODER), "readString").arg(JExpr._null()));
      } else {
        ifCodeGen(body, reuseSupplier.get()._instanceof(codeModel.ref(Utf8.class)),
            thenBlock -> putValueIntoParent.accept(thenBlock, JExpr.invoke(JExpr.direct(DECODER), "readString").arg(JExpr.cast(codeModel.ref(Utf8.class), reuseSupplier.get()))),
            elseBlock -> putValueIntoParent.accept(elseBlock,
                JExpr.invoke(JExpr.direct(DECODER), "readString").arg(JExpr._null())));
      }
    } else if (stringClass.equals(codeModel.ref(String.class))) {
      putValueIntoParent.accept(body, JExpr.invoke(JExpr.direct(DECODER), "readString"));
    } else {
      putValueIntoParent.accept(body, readStringableExpression(stringClass));
    }
  } else {
    body.directStatement(DECODER + ".skipString();");
  }
}
 
Example 7
private void processComplexType(Schema schema, JExpression valueExpr, JBlock body) {
  switch (schema.getType()) {
    case RECORD:
      processRecord(schema, valueExpr, body);
      break;
    case ARRAY:
      processArray(schema, valueExpr, body);
      break;
    case UNION:
      processUnion(schema, valueExpr, body);
      break;
    case MAP:
      processMap(schema, valueExpr, body);
      break;
    default:
      throw new FastSerdeGeneratorException("Not a complex schema type: " + schema.getType());
  }
}
 
Example 8
Source Project: immutable-xjc   Source File: PluginImpl.java    License: MIT License 6 votes vote down vote up
private JExpression defaultValue(JFieldVar field) {
    JType javaType = field.type();
    if (setDefaultValuesInConstructor) {
        Optional<JAnnotationUse> xmlElementAnnotation = getAnnotation(field.annotations(), javax.xml.bind.annotation.XmlElement.class.getCanonicalName());
        if (xmlElementAnnotation.isPresent()) {
            JAnnotationValue annotationValue = xmlElementAnnotation.get().getAnnotationMembers().get("defaultValue");
            if (annotationValue != null) {
                StringWriter sw = new StringWriter();
                JFormatter f = new JFormatter(sw);
                annotationValue.generate(f);
                return JExpr.lit(sw.toString().replaceAll("\"", ""));
            }
        }
    }
    if (javaType.isPrimitive()) {
        if (field.type().owner().BOOLEAN.equals(javaType)) {
            return JExpr.lit(false);
        } else if (javaType.owner().SHORT.equals(javaType)) {
            return JExpr.cast(javaType.owner().SHORT, JExpr.lit(0));
        } else {
            return JExpr.lit(0);
        }
    }
    return JExpr._null();
}
 
Example 9
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 10
Source Project: avro-fastserde   Source File: FastDeserializerGenerator.java    License: Apache License 2.0 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) {
    switch (schema.getType()) {
    case RECORD:
        processRecord(fieldSchemaVar, schema.getName(), schema, readerFieldSchema, methodBody, action,
                putExpressionIntoParent);
        break;
    case ARRAY:
        processArray(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent);
        break;
    case MAP:
        processMap(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent);
        break;
    case UNION:
        processUnion(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent);
        break;
    default:
        throw new FastDeserializerGeneratorException("Incorrect complex type: " + action.getType());
    }
}
 
Example 11
Source Project: raml-module-builder   Source File: ClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void addConstructorOkapi6Args(JFieldVar tokenVar, JFieldVar options, JFieldVar httpClient) {
  /* constructor, init the httpClient - allow to pass keep alive option */
  JMethod constructor = constructor();
  JVar okapiUrlVar = constructor.param(String.class, OKAPI_URL);
  JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
  JVar token = constructor.param(String.class, TOKEN);
  JVar keepAlive = constructor.param(boolean.class, KEEP_ALIVE);
  JVar connTimeout = constructor.param(int.class, "connTO");
  JVar idleTimeout = constructor.param(int.class, "idleTO");

  /* populate constructor */
  JBlock conBody = constructor.body();
  conBody.assign(JExpr._this().ref(tenantId), tenantIdVar);
  conBody.assign(JExpr._this().ref(tokenVar), token);
  conBody.assign(JExpr._this().ref(okapiUrl), okapiUrlVar);
  conBody.assign(options, JExpr._new(jcodeModel.ref(HttpClientOptions.class)));
  conBody.invoke(options, "setLogActivity").arg(JExpr.TRUE);
  conBody.invoke(options, "setKeepAlive").arg(keepAlive);
  conBody.invoke(options, "setConnectTimeout").arg(connTimeout);
  conBody.invoke(options, "setIdleTimeout").arg(idleTimeout);

  JExpression vertx = jcodeModel
      .ref("org.folio.rest.tools.utils.VertxUtils")
      .staticInvoke("getVertxFromContextOrNew");
  conBody.assign(httpClient, vertx.invoke("createHttpClient").arg(options));
}
 
Example 12
public EqualsArguments property(JBlock block, String propertyName,
		String propertyMethod, JType declarablePropertyType,
		JType propertyType, Collection<JType> possiblePropertyTypes) {
	final JVar leftPropertyValue = block.decl(JMod.FINAL,
			declarablePropertyType, leftValue().name() + propertyName,
			leftValue().invoke(propertyMethod));
	final JVar rightPropertyValue = block.decl(JMod.FINAL,
			declarablePropertyType, rightValue().name() + propertyName,
			rightValue().invoke(propertyMethod));
	// We assume that primitive properties are always set
	boolean isAlwaysSet = propertyType.isPrimitive();
	final JExpression leftPropertyHasSetValue = isAlwaysSet ? JExpr.TRUE
			: leftPropertyValue.ne(JExpr._null());
	final JExpression rightPropertyHasSetValue = isAlwaysSet ? JExpr.TRUE
			: rightPropertyValue.ne(JExpr._null());
	return spawn(leftPropertyValue, leftPropertyHasSetValue,
			rightPropertyValue, rightPropertyHasSetValue);
}
 
Example 13
Source Project: jaxb2-rich-contract-plugin   Source File: DeepCopyGenerator.java    License: MIT License 5 votes vote down vote up
private void generateFieldCopyExpressions(final CopyGenerator cloneGenerator, final JBlock body, final JExpression targetObject, final JExpression sourceObject) {
	for (final FieldOutline fieldOutline : this.classOutline.getDeclaredFields()) {
		final JFieldVar field = PluginUtil.getDeclaredField(fieldOutline);
		if (field != null) {
			if ((field.mods().getValue() & (JMod.FINAL | JMod.STATIC)) == 0) {
				generateFieldCopyExpression(cloneGenerator, body, targetObject, field, targetObject.ref(field.name()), sourceObject.ref(field.name()));
			}
		}
	}
}
 
Example 14
public static JExpression unmarshallJAXBElement(JCodeModel codeModel,
		JClass xmlAdapterClass, JExpression value) {

	return codeModel.ref(XmlAdapterUtils.class).staticInvoke(
			"unmarshallJAXBElement").arg(xmlAdapterClass.dotclass()).arg(
			value);
}
 
Example 15
Source Project: jaxb2-rich-contract-plugin   Source File: MetaPlugin.java    License: 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 16
@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 17
protected JFieldVar generateField() {
	// generate the constant
	JExpression value = createValue();

	JFieldVar field = referenceClass.field(JMod.PUBLIC | JMod.STATIC
			| JMod.FINAL, type, propertyInfo.getPublicName(), value);

	annotate(field);

	return field;
}
 
Example 18
Source Project: parceler   Source File: WriteReferenceVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JExpression visit(FieldReference fieldReference, WriteContext input) {

    return invocationBuilder.buildFieldGet(
            input.getContainer(),
            fieldReference.getField(),
            input.getExpression().getType(),
            new TypedExpression(fieldReference.getOwner(), input.getExpression().getExpression()));
}
 
Example 19
public static JExpression isJAXBElement(JCodeModel codeModel,
		JClass declaredType, QName name, JClass scope, JExpression value) {

	return codeModel.ref(XmlAdapterUtils.class).staticInvoke(
			"isJAXBElement").arg(declaredType.dotclass()).

	arg(JExprUtils.newQName(codeModel, name)).arg(scope.dotclass()).arg(
			value);
}
 
Example 20
private void processSimpleType(Schema schema, JExpression valueExpression, JBlock body, boolean cast) {
  switch (schema.getType()) {
    case ENUM:
      processEnum(schema, valueExpression, body);
      break;
    case FIXED:
      processFixed(schema, valueExpression, body);
      break;
    default:
      processPrimitive(schema, valueExpression, body, cast);
      break;
  }
}
 
Example 21
@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 22
private void processEnum(Schema enumSchema, JExpression enumValueExpression, JBlock body) {
  JClass enumClass = schemaAssistant.classFromSchema(enumSchema);
  JExpression enumValueCasted = JExpr.cast(enumClass, enumValueExpression);
  JExpression valueToWrite;
  if (useGenericTypes) {
    if (Utils.isAvro14()) {
      /**
       * In Avro-1.4, there is no way to infer/extract enum schema from {@link org.apache.avro.generic.GenericData.EnumSymbol},
       * so the serializer needs to record the schema id and the corresponding {@link org.apache.avro.Schema.EnumSchema},
       * and maintain a mapping between the schema id and EnumSchema JVar for future use.
       */
      JVar enumSchemaVar = enumSchemaVarMap.computeIfAbsent(Utils.getSchemaFingerprint(enumSchema), s->
          generatedClass.field(
              JMod.PRIVATE | JMod.FINAL,
              Schema.class,
              getUniqueName(enumSchema.getName() + "EnumSchema"),
              codeModel.ref(Schema.class).staticInvoke("parse").arg(enumSchema.toString()))
      );
      valueToWrite = JExpr.invoke(enumSchemaVar, "getEnumOrdinal").arg(enumValueCasted.invoke("toString"));
    } else {
      valueToWrite = JExpr.invoke(
          enumValueCasted.invoke("getSchema"),
          "getEnumOrdinal"
      ).arg(enumValueCasted.invoke("toString"));
    }
  } else {
    valueToWrite = enumValueCasted.invoke("ordinal");
  }

  body.invoke(JExpr.direct(ENCODER), "writeEnum").arg(valueToWrite);
}
 
Example 23
public static JExpression marshallJAXBElement(JCodeModel codeModel,
		JClass declaredType, QName name, JClass scope, JExpression value) {

	return codeModel.ref(XmlAdapterUtils.class).staticInvoke(
			"marshallJAXBElement").arg(declaredType.dotclass()).

	arg(JExprUtils.newQName(codeModel, name)).arg(scope.dotclass()).arg(
			value);
}
 
Example 24
Source Project: avro-util   Source File: SchemaAssistant.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public JExpression getFixedValue(Schema schema, JExpression fixedBytesExpr, JInvocation getSchemaExpr) {
  if (!useGenericTypes) {
    return JExpr._new(codeModel.ref(schema.getFullName())).arg(fixedBytesExpr);
  } else {
    return JExpr._new(codeModel.ref(GenericData.Fixed.class)).arg(getSchemaExpr).arg(fixedBytesExpr);
  }
}
 
Example 25
Source Project: avro-util   Source File: SchemaAssistant.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public JExpression getStringableValue(Schema schema, JExpression stringExpr) {
  if (isStringable(schema)) {
    return JExpr._new(classFromSchema(schema)).arg(stringExpr);
  } else {
    return JExpr._new(defaultStringType()).arg(stringExpr);
  }
}
 
Example 26
Source Project: groovy-cps   Source File: Translator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Replaces non-serializable types with CPS-specific variants.
 *
 * @param original a {@link JType} to inspect
 * @return The {@link JType#dotclass()} for either the original {@link JType} or for the CPS equivalent.
 */
private JExpression cpsTypeTranslation(JType original) {
    if (original.fullName().equals("org.codehaus.groovy.runtime.callsite.BooleanClosureWrapper")) {
        return codeModel.ref("com.cloudbees.groovy.cps.impl.CpsBooleanClosureWrapper").dotclass();
    } else {
        return original.dotclass();
    }
}
 
Example 27
Source Project: avro-fastserde   Source File: SchemaAssistant.java    License: Apache License 2.0 5 votes vote down vote up
public JExpression getFixedValue(Schema schema, JExpression fixedBytesExpr, JInvocation getSchemaExpr) {
    if (!useGenericTypes) {
        return JExpr._new(codeModel.ref(schema.getFullName())).arg(fixedBytesExpr);
    } else {
        return JExpr._new(codeModel.ref(GenericData.Fixed.class)).arg(getSchemaExpr).arg(fixedBytesExpr);
    }
}
 
Example 28
Source Project: avro-fastserde   Source File: SchemaAssistant.java    License: Apache License 2.0 5 votes vote down vote up
public JExpression getStringableValue(Schema schema, JExpression stringExpr) {
    if (isStringable(schema)) {
        return JExpr._new(classFromSchema(schema)).arg(stringExpr);
    } else {
        return stringExpr;
    }
}
 
Example 29
Source Project: dremio-oss   Source File: CopyUtil.java    License: 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(getMajorTypeForField(vv.getField())) || Types.isRepeated(getMajorTypeForField(vv.getField())) || Types.isComplex(getMajorTypeForField(vv.getField()))) {
      copyMethod = "copyFromSafe";
    } else {
      copyMethod = "copyFrom";
    }
    g.rotateBlock();
    JVar inVV = g.declareVectorValueSetupAndMember("incoming", new TypedFieldId(CompleteType.fromField(vv.getField()), vv.isHyper(), fieldId));
    JVar outVV = g.declareVectorValueSetupAndMember("outgoing", new TypedFieldId(CompleteType.fromField(vv.getField()), 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 30
public static JExpression unmarshallJAXBElement(JCodeModel codeModel,
		JExpression value) {

	final JExpression argument = value;
	return codeModel.ref(XmlAdapterUtils.class).staticInvoke(
			"unmarshallJAXBElement").arg(argument);
}