Java Code Examples for com.sun.codemodel.JExpr#cast()

The following examples show how to use com.sun.codemodel.JExpr#cast() . 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: PluginImpl.java    From immutable-xjc with 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 2
Source File: SingleWrappingReferenceField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {

	final JType declaredType = getDeclaredType();

	final JClass elementClass = codeModel.ref(JAXBElement.class).narrow(
			declaredType.boxify().wildcard());

	// TODO remove if cast is not necessary
	final JExpression value = JExpr.cast(elementClass, source);

	if (xmlAdapterClass == null) {
		return XmlAdapterXjcUtils.unmarshallJAXBElement(codeModel, value);

	} else {
		return XmlAdapterXjcUtils.unmarshallJAXBElement(codeModel,
				xmlAdapterClass, value);
	}

}
 
Example 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: AbstractField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Case from {@link #exposedType} to {@link #implType} if necessary.
 */
protected final JExpression castToImplType( JExpression exp ) {
    if(implType==exposedType)
        return exp;
    else
        return JExpr.cast(implType,exp);
}
 
Example 5
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 6
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void processPrimitive(final Schema primitiveSchema, JExpression primitiveValueExpression, JBlock body) {
    String writeFunction;
    JClass primitiveClass = schemaAssistant.classFromSchema(primitiveSchema);
    JExpression castedValue = JExpr.cast(primitiveClass, primitiveValueExpression);

    switch (primitiveSchema.getType()) {
        case STRING:
            writeFunction = "writeString";
            if (SchemaAssistant.isStringable(primitiveSchema)) {
                castedValue = JExpr.cast(string, castedValue.invoke("toString"));
            }
            break;
        case BYTES:
            writeFunction = "writeBytes";
            break;
        case INT:
            writeFunction = "writeInt";
            break;
        case LONG:
            writeFunction = "writeLong";
            break;
        case FLOAT:
            writeFunction = "writeFloat";
            break;
        case DOUBLE:
            writeFunction = "writeDouble";
            break;
        case BOOLEAN:
            writeFunction = "writeBoolean";
            break;
        default:
            throw new FastSerializerGeneratorException(
                    "Unsupported primitive schema of type: " + primitiveSchema.getType());
    }

    body.invoke(JExpr.direct(ENCODER), writeFunction).arg(castedValue);
}
 
Example 7
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
private void processEnum(Schema enumSchema, JExpression enumValueExpression, JBlock body) {
    JClass enumClass = schemaAssistant.classFromSchema(enumSchema);
    JExpression enumValueCasted = JExpr.cast(enumClass, enumValueExpression);
    JExpression valueToWrite;
    if (useGenericTypes) {
        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 8
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processPrimitive(final Schema primitiveSchema, JExpression primitiveValueExpression, JBlock body, boolean cast) {
  String writeFunction;
  JClass primitiveClass = schemaAssistant.classFromSchema(primitiveSchema);
  JExpression writeFunctionArgument = cast
      ? JExpr.cast(primitiveClass, primitiveValueExpression)
      : primitiveValueExpression;
  switch (primitiveSchema.getType()) {
    case STRING:
      processString(primitiveSchema, primitiveValueExpression, body);
      return;
    case BYTES:
      writeFunction = "writeBytes";
      break;
    case INT:
      writeFunction = "writeInt";
      break;
    case LONG:
      writeFunction = "writeLong";
      break;
    case FLOAT:
      writeFunction = "writeFloat";
      break;
    case DOUBLE:
      writeFunction = "writeDouble";
      break;
    case BOOLEAN:
      writeFunction = "writeBoolean";
      break;
    default:
      throw new FastSerdeGeneratorException(
          "Unsupported primitive schema of type: " + primitiveSchema.getType());
  }

  body.invoke(JExpr.direct(ENCODER), writeFunction).arg(writeFunctionArgument);
}
 
Example 9
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 10
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {

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

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

      // Only when the input is a reader, use writer interface to copy value.
      // Otherwise, input is a holder and we use vv mutator to set value.
      if (inputContainer.isReader()) {
        JType writerImpl = generator.getModel()._ref(
                TypeHelper.getWriterImpl(getArrowMinorType(inputContainer.getCompleteType().toMinorType())));
        JType writerIFace = generator.getModel()._ref(
            TypeHelper.getWriterInterface(getArrowMinorType(inputContainer.getCompleteType().toMinorType())));

        JVar writer = generator.declareClassField("writer", writerIFace);
        generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv));
        generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));

        if (child.getCompleteType().isUnion() || child.getCompleteType().isComplex()) {
          final JClass complexCopierClass = generator.getModel()
              .ref(org.apache.arrow.vector.complex.impl.ComplexCopier.class);
          final JExpression castedWriter = JExpr.cast(generator.getModel().ref(FieldWriter.class), writer);
          generator.getEvalBlock()
              .add(complexCopierClass.staticInvoke("copy")
                  .arg(inputContainer.getHolder())
                  .arg(castedWriter));
        } else {
          String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
          generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
        }

        if (e.isSafe()) {
          HoldingContainer outputContainer = generator.declare(CompleteType.BIT);
          generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
          return outputContainer;
        }
      } else {

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

      }

      return null;
    }
 
Example 11
Source File: ElementField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {
	return super.unwrap(JExpr.cast(codeModel.ref(Element.class), source));
}
 
Example 12
Source File: SingleWrappingClassInfoField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {

	return JExpr.cast(_class, source);
}
 
Example 13
Source File: StringField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {
	return super.unwrap(JExpr.cast(codeModel.ref(String.class), source));
}
 
Example 14
Source File: SingleWrappingElementField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected JExpression unwrap(JExpression source) {
	final JType type = getTypeRef().getTarget().toType(outline.parent(),
			Aspect.EXPOSED);
	return JExpr.cast(type, super.unwrap(source));
}
 
Example 15
Source File: PluginContext.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
public JExpression castOnDemand(final JType fieldType, final JExpression expression) {
	return this.classes.containsKey(fieldType.fullName()) ? expression : JExpr.cast(fieldType, expression);
}
 
Example 16
Source File: BuilderGenerator.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
private void generateCollectionProperty(final JBlock initBody, final JVar productParam, final PropertyOutline propertyOutline, final JClass elementType) {
	final String fieldName = propertyOutline.getFieldName();
	final String propertyName = propertyOutline.getBaseName();
	final JClass iterableType = this.pluginContext.iterableClass.narrow(elementType.wildcard());
	final JMethod addIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName);
	final JVar addIterableParam = addIterableMethod.param(JMod.FINAL, iterableType, fieldName);
	generateAddMethodJavadoc(addIterableMethod, addIterableParam, propertyOutline.getSchemaAnnotationText().orElse(null));
	final JMethod withIterableMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withIterableParam = withIterableMethod.param(JMod.FINAL, iterableType, fieldName);
	generateWithMethodJavadoc(withIterableMethod, withIterableParam, propertyOutline.getSchemaAnnotationText().orElse(null));
	final JMethod addVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.ADD_METHOD_PREFIX + propertyName);
	final JVar addVarargsParam = addVarargsMethod.varParam(elementType, fieldName);
	generateAddMethodJavadoc(addVarargsMethod, addVarargsParam, propertyOutline.getSchemaAnnotationText().orElse(null));
	final JMethod withVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.type, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withVarargsParam = withVarargsMethod.varParam(elementType, fieldName);
	generateWithMethodJavadoc(withVarargsMethod, withVarargsParam, propertyOutline.getSchemaAnnotationText().orElse(null));
	final BuilderOutline childBuilderOutline = getBuilderDeclaration(elementType);
	final JMethod addMethod;
	if (childBuilderOutline != null && !childBuilderOutline.getClassOutline().getImplClass().isAbstract()) {
		final JClass builderWithMethodReturnType = childBuilderOutline.getBuilderClass().narrow(this.builderClass.type.wildcard());
		addMethod = this.builderClass.raw.method(JMod.PUBLIC, builderWithMethodReturnType, PluginContext.ADD_METHOD_PREFIX + propertyName);
		generateBuilderMethodJavadoc(addMethod, "add", propertyName, propertyOutline.getSchemaAnnotationText().orElse(null));
	} else {
		addMethod = null;
	}
	if (this.implement) {
		final JClass childBuilderType = childBuilderOutline == null ? this.pluginContext.buildableInterface : childBuilderOutline.getBuilderClass().narrow(this.builderClass.type);
		final JClass builderArrayListClass = this.pluginContext.arrayListClass.narrow(childBuilderType);
		final JClass builderListClass = this.pluginContext.listClass.narrow(childBuilderType);
		final JFieldVar builderField = this.builderClass.raw.field(JMod.PRIVATE, builderListClass, fieldName);
		addVarargsMethod.body().invoke(addIterableMethod).arg(this.pluginContext.asList(addVarargsParam));
		addVarargsMethod.body()._return(JExpr._this());
		withVarargsMethod.body().invoke(withIterableMethod).arg(this.pluginContext.asList(withVarargsParam));
		withVarargsMethod.body()._return(JExpr._this());
		final JConditional addIterableIfParamNull = addIterableMethod.body()._if(addIterableParam.ne(JExpr._null()));
		final JConditional addIterableIfNull = addIterableIfParamNull._then()._if(JExpr._this().ref(builderField).eq(JExpr._null()));
		addIterableIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass));
		final JForEach jForEach = addIterableIfParamNull._then().forEach(elementType, BuilderGenerator.ITEM_VAR_NAME, addIterableParam);
		final JExpression builderCreationExpression = childBuilderOutline == null
				? JExpr._new(this.pluginContext.buildableClass).arg(jForEach.var())
				: JExpr._new(childBuilderType).arg(JExpr._this()).arg(jForEach.var()).arg(this.settings.isCopyAlways() ? JExpr.TRUE : JExpr.FALSE);
		jForEach.body().add(JExpr._this().ref(builderField).invoke("add").arg(builderCreationExpression));
		addIterableMethod.body()._return(JExpr._this());
		final JConditional withIterableIfNull = withIterableMethod.body()._if(JExpr._this().ref(builderField).ne(JExpr._null()));
		withIterableIfNull._then().add(JExpr._this().ref(builderField).invoke("clear"));
		withIterableMethod.body()._return(JExpr.invoke(addIterableMethod).arg(withIterableParam));
		final JConditional ifNull = initBody._if(JExpr._this().ref(builderField).ne(JExpr._null()));
		final JVar collectionVar = ifNull._then().decl(JMod.FINAL, this.pluginContext.listClass.narrow(elementType), fieldName, JExpr._new(this.pluginContext.arrayListClass.narrow(elementType)).arg(JExpr._this().ref(builderField).invoke("size")));
		final JForEach initForEach = ifNull._then().forEach(childBuilderType, BuilderGenerator.ITEM_VAR_NAME, JExpr._this().ref(builderField));
		final JInvocation buildMethodInvocation = initForEach.var().invoke(this.settings.getBuildMethodName());
		final JExpression buildExpression = childBuilderOutline == null ? JExpr.cast(elementType, buildMethodInvocation) : buildMethodInvocation;
		initForEach.body().add(collectionVar.invoke("add").arg(buildExpression));
		ifNull._then().assign(productParam.ref(fieldName), collectionVar);
		if (addMethod != null) {
			final JConditional addIfNull = addMethod.body()._if(JExpr._this().ref(builderField).eq(JExpr._null()));
			addIfNull._then().assign(JExpr._this().ref(builderField), JExpr._new(builderArrayListClass));
			final JVar childBuilderVar = addMethod.body().decl(JMod.FINAL, childBuilderType, fieldName + this.settings.getBuilderFieldSuffix(), JExpr._new(childBuilderType).arg(JExpr._this()).arg(JExpr._null()).arg(JExpr.FALSE));
			addMethod.body().add(JExpr._this().ref(builderField).invoke("add").arg(childBuilderVar));
			addMethod.body()._return(childBuilderVar);
		}
		this.pluginContext.generateImmutableFieldInit(initBody, productParam, propertyOutline);
	}
}
 
Example 17
Source File: DrillComplexWriterFuncHolder.java    From Bats with Apache License 2.0 2 votes vote down vote up
@Override
  protected HoldingContainer generateEvalBody(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, String body,
                                              JVar[] workspaceJVars, FieldReference fieldReference) {

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

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;

    JVar complexWriter = classGenerator.declareClassField("complexWriter", classGenerator.getModel()._ref(ComplexWriter.class));


    JInvocation container = classGenerator.getMappingSet().getOutgoing().invoke("getOutgoingContainer");

    //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));

    JClass projBatchClass = classGenerator.getModel().ref(ProjectRecordBatch.class);
    JExpression projBatch = JExpr.cast(projBatchClass, classGenerator.getMappingSet().getOutgoing());

    classGenerator.getSetupBlock().add(projBatch.invoke("addComplexWriter").arg(complexWriter));


    classGenerator.getEvalBlock().add(complexWriter.invoke("setPosition").arg(classGenerator.getMappingSet().getValueWriteIndex()));

    sub.decl(classGenerator.getModel()._ref(ComplexWriter.class), getReturnValue().getName(), complexWriter);

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

    addProtectedBlock(classGenerator, sub, body, inputVariables, workspaceJVars, false);


//    JConditional jc = classGenerator.getEvalBlock()._if(complexWriter.invoke("ok").not());

//    jc._then().add(complexWriter.invoke("reset"));
    //jc._then().directStatement("System.out.println(\"debug : write ok fail!, inIndex = \" + inIndex);");
//    jc._then()._return(JExpr.FALSE);

    //jc._else().directStatement("System.out.println(\"debug : write successful, inIndex = \" + inIndex);");

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

    return null;
  }