Java Code Examples for com.sun.codemodel.JConditional#_then

The following examples show how to use com.sun.codemodel.JConditional#_then . 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: ClientGenerator.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private void addParameter(ParameterDetails details) {
  JBlock b = details.methodBody;
  if (Boolean.TRUE.equals(details.nullCheck)) {
    JConditional ifClause = details.methodBody._if(JExpr.ref(details.valueName).ne(JExpr._null()));
    b = ifClause._then();
  }
  b.invoke(details.queryParams, APPEND).arg(JExpr.lit(details.valueName + "="));
  switch (details.op) {
    case ENCODE:
      encodeParameter(b, details);
      break;
    case FORMAT_DATE:
      formatDateParameter(b, details);
      break;
    case PROCESS_LIST:
      processListParameter(b, details);
      break;
    case NONE:
      b.invoke(details.queryParams, APPEND).arg(JExpr.ref(details.valueName));
      break;
  }
  b.invoke(details.queryParams, APPEND).arg(JExpr.lit("&"));
}
 
Example 2
Source File: EqualsArguments.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public JBlock ifHasSetValue(JBlock block, boolean isAlwaysSet,
		boolean checkForNullRequired) {
	if (isAlwaysSet || !checkForNullRequired) {
		return block;
	} else {
		final JConditional ifLeftHasSetValue = block._if(leftHasSetValue());
		final JConditional ifLeftHasSetValueAndRightHasSetValue = ifLeftHasSetValue
				._then()._if(rightHasSetValue());
		final JBlock subBlock = ifLeftHasSetValueAndRightHasSetValue
				._then();
		ifLeftHasSetValueAndRightHasSetValue._else()._return(JExpr.FALSE);
		ifLeftHasSetValue._elseif(rightHasSetValue())._then()
				._return(JExpr.FALSE);
		return subBlock;
	}
}
 
Example 3
Source File: EvaluationVisitor.java    From Bats with Apache License 2.0 5 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(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JType writerIFace = generator.getModel()._ref(
            TypeHelper.getWriterInterface(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JVar writer = generator.declareClassField("writer", writerIFace);
        generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv).arg(JExpr._null()));
        generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));
        String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
        generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
        if (e.isSafe()) {
          HoldingContainer outputContainer = generator.declare(Types.REQUIRED_BIT);
          generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
          return outputContainer;
        }
      } else {

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

      }

      return null;
    }
 
Example 4
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 5
Source File: FastDeserializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void processUnion(JVar unionSchemaVar, final String name, final Schema unionSchema,
    final Schema readerUnionSchema, JBlock body, FieldAction action,
    BiConsumer<JBlock, JExpression> putValueIntoParent, Supplier<JExpression> reuseSupplier) {
  JVar unionIndex = body.decl(codeModel.INT, getUniqueName("unionIndex"), JExpr.direct(DECODER + ".readIndex()"));
  JConditional ifBlock = null;
  for (int i = 0; i < unionSchema.getTypes().size(); i++) {
    Schema optionSchema = unionSchema.getTypes().get(i);
    Schema readerOptionSchema = null;
    FieldAction unionAction;

    if (Schema.Type.NULL.equals(optionSchema.getType())) {
      body._if(unionIndex.eq(JExpr.lit(i)))._then().directStatement(DECODER + ".readNull();");
      continue;
    }

    if (action.getShouldRead()) {
      readerOptionSchema = readerUnionSchema.getTypes().get(i);
      Symbol.Alternative alternative = null;
      if (action.getSymbol() instanceof Symbol.Alternative) {
        alternative = (Symbol.Alternative) action.getSymbol();
      } else if (action.getSymbol().production != null) {
        for (Symbol symbol : action.getSymbol().production) {
          if (symbol instanceof Symbol.Alternative) {
            alternative = (Symbol.Alternative) symbol;
            break;
          }
        }
      }

      if (alternative == null) {
        throw new FastDeserializerGeneratorException("Unable to determine action for field: " + name);
      }

      Symbol.UnionAdjustAction unionAdjustAction = (Symbol.UnionAdjustAction) alternative.symbols[i].production[0];
      unionAction =
          FieldAction.fromValues(optionSchema.getType(), action.getShouldRead(), unionAdjustAction.symToParse);
    } else {
      unionAction = FieldAction.fromValues(optionSchema.getType(), false, EMPTY_SYMBOL);
    }

    JExpression condition = unionIndex.eq(JExpr.lit(i));
    ifBlock = ifBlock != null ? ifBlock._elseif(condition) : body._if(condition);
    final JBlock thenBlock = ifBlock._then();

    JVar optionSchemaVar = null;
    if (useGenericTypes && unionAction.getShouldRead()) {
      JInvocation optionSchemaExpression = unionSchemaVar.invoke("getTypes").invoke("get").arg(JExpr.lit(i));
      optionSchemaVar = declareSchemaVar(optionSchema, name + "OptionSchema", optionSchemaExpression);
    }

    if (SchemaAssistant.isComplexType(optionSchema)) {
      String optionName = name + "Option";
      if (Schema.Type.UNION.equals(optionSchema.getType())) {
        throw new FastDeserializerGeneratorException("Union cannot be sub-type of union!");
      }
      processComplexType(optionSchemaVar, optionName, optionSchema, readerOptionSchema, thenBlock, unionAction,
          putValueIntoParent, reuseSupplier);
    } else {
      processSimpleType(optionSchema, thenBlock, unionAction, putValueIntoParent, reuseSupplier);
    }
  }
}
 
Example 6
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void processMap(final Schema mapSchema, JExpression mapExpr, JBlock body) {
  final JClass mapClass = schemaAssistant.classFromSchema(mapSchema);
  JClass keyClass = schemaAssistant.findStringClass(mapSchema);

  body.invoke(JExpr.direct(ENCODER), "writeMapStart");

  final JExpression emptyMapCondition = mapExpr.eq(JExpr._null()).cor(JExpr.invoke(mapExpr, "isEmpty"));
  final JConditional emptyMapIf = body._if(emptyMapCondition);
  final JBlock emptyMapBlock = emptyMapIf._then();
  emptyMapBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));

  final JBlock nonEmptyMapBlock = emptyMapIf._else();
  nonEmptyMapBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.invoke(mapExpr, "size"));

  final JForEach mapKeysLoop = nonEmptyMapBlock.forEach(keyClass, getUniqueName("key"),
      JExpr.invoke(JExpr.cast(mapClass, mapExpr), "keySet"));

  final JBlock forBody = mapKeysLoop.body();
  forBody.invoke(JExpr.direct(ENCODER), "startItem");

  JVar keyStringVar;
  if (SchemaAssistant.hasStringableKey(mapSchema)) {
    keyStringVar =
        forBody.decl(codeModel.ref(String.class), getUniqueName("keyString"), mapKeysLoop.var().invoke("toString"));
  } else {
    keyStringVar = mapKeysLoop.var();
  }

  final Schema valueSchema = mapSchema.getValueType();

  forBody.invoke(JExpr.direct(ENCODER), "writeString").arg(keyStringVar);

  JVar containerVar;
  if (SchemaAssistant.isComplexType(valueSchema)) {
    containerVar = declareValueVar(valueSchema.getName(), valueSchema, forBody);
    forBody.assign(containerVar, JExpr.invoke(JExpr.cast(mapClass, mapExpr), "get").arg(mapKeysLoop.var()));

    processComplexType(valueSchema, containerVar, forBody);
  } else {
    processSimpleType(valueSchema, mapExpr.invoke("get").arg(mapKeysLoop.var()), forBody);
  }
  body.invoke(JExpr.direct(ENCODER), "writeMapEnd");
}
 
Example 7
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processUnion(JVar unionSchemaVar, final String name, final Schema unionSchema,
        final Schema readerUnionSchema, JBlock body, FieldAction action,
        BiConsumer<JBlock, JExpression> putValueIntoParent) {
    JVar unionIndex = body.decl(codeModel.INT, getVariableName("unionIndex"),
            JExpr.direct(DECODER + ".readIndex()"));
    JConditional ifBlock = null;
    for (int i = 0; i < unionSchema.getTypes().size(); i++) {
        Schema optionSchema = unionSchema.getTypes().get(i);
        Schema readerOptionSchema = null;
        FieldAction unionAction;

        if (Schema.Type.NULL.equals(optionSchema.getType())) {
            JBlock nullReadBlock = body._if(unionIndex.eq(JExpr.lit(i)))._then().block();
            nullReadBlock.directStatement(DECODER + ".readNull();");
            if (action.getShouldRead()) {
                putValueIntoParent.accept(nullReadBlock, JExpr._null());
            }
            continue;
        }

        if (action.getShouldRead()) {
            readerOptionSchema = readerUnionSchema.getTypes().get(i);
            Symbol.Alternative alternative = null;
            if (action.getSymbol() instanceof Symbol.Alternative) {
                alternative = (Symbol.Alternative) action.getSymbol();
            } else if (action.getSymbol().production != null) {
                for (Symbol symbol : action.getSymbol().production) {
                    if (symbol instanceof Symbol.Alternative) {
                        alternative = (Symbol.Alternative) symbol;
                        break;
                    }
                }
            }

            if (alternative == null) {
                throw new FastDeserializerGeneratorException("Unable to determine action for field: " + name);
            }

            Symbol.UnionAdjustAction unionAdjustAction = (Symbol.UnionAdjustAction) alternative.symbols[i].production[0];
            unionAction = FieldAction.fromValues(optionSchema.getType(), action.getShouldRead(),
                    unionAdjustAction.symToParse);
        } else {
            unionAction = FieldAction.fromValues(optionSchema.getType(), false, EMPTY_SYMBOL);
        }

        JExpression condition = unionIndex.eq(JExpr.lit(i));
        ifBlock = ifBlock != null ? ifBlock._elseif(condition) : body._if(condition);
        final JBlock thenBlock = ifBlock._then();

        JVar optionSchemaVar = null;
        if (useGenericTypes && unionAction.getShouldRead()) {
            JInvocation optionSchemaExpression = unionSchemaVar.invoke("getTypes").invoke("get").arg(JExpr.lit(i));
            optionSchemaVar = declareSchemaVar(optionSchema, name + "OptionSchema", optionSchemaExpression);
        }

        if (SchemaAssistant.isComplexType(optionSchema)) {
            String optionName = name + "Option";
            if (Schema.Type.UNION.equals(optionSchema.getType())) {
                throw new FastDeserializerGeneratorException("Union cannot be sub-type of union!");
            }
            processComplexType(optionSchemaVar, optionName, optionSchema, readerOptionSchema, thenBlock,
                    unionAction, putValueIntoParent);
        } else {
            // to preserve reader string specific options use reader option schema
            if (action.getShouldRead() && Schema.Type.STRING.equals(optionSchema.getType())) {
                processSimpleType(readerOptionSchema, thenBlock, unionAction, putValueIntoParent);

            } else {
                processSimpleType(optionSchema, thenBlock, unionAction, putValueIntoParent);
            }
        }
    }
}
 
Example 8
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processArray(JVar arraySchemaVar, final String name, final Schema arraySchema,
        final Schema readerArraySchema, JBlock parentBody, FieldAction action,
        BiConsumer<JBlock, JExpression> putArrayIntoParent) {

    if (action.getShouldRead()) {
        Symbol valuesActionSymbol = null;
        for (Symbol symbol : action.getSymbol().production) {
            if (Symbol.Kind.REPEATER.equals(symbol.kind)
                    && "array-end".equals(getSymbolPrintName(((Symbol.Repeater) symbol).end))) {
                valuesActionSymbol = symbol;
                break;
            }
        }

        if (valuesActionSymbol == null) {
            throw new FastDeserializerGeneratorException("Unable to determine action for array: " + name);
        }

        action = FieldAction.fromValues(arraySchema.getElementType().getType(), action.getShouldRead(),
                valuesActionSymbol);
    } else {
        action = FieldAction.fromValues(arraySchema.getElementType().getType(), false, EMPTY_SYMBOL);
    }

    final JVar arrayVar = action.getShouldRead() ? declareValueVar(name, readerArraySchema, parentBody) : null;
    JVar chunkLen = parentBody.decl(codeModel.LONG, getVariableName("chunkLen"),
            JExpr.direct(DECODER + ".readArrayStart()"));

    JConditional conditional = parentBody._if(chunkLen.gt(JExpr.lit(0)));
    JBlock ifBlock = conditional._then();

    JClass arrayClass = schemaAssistant.classFromSchema(action.getShouldRead() ? readerArraySchema : arraySchema, false);

    if (action.getShouldRead()) {
        JInvocation newArrayExp = JExpr._new(arrayClass);
        if (useGenericTypes) {
            newArrayExp = newArrayExp.arg(JExpr.cast(codeModel.INT, chunkLen)).arg(getSchemaExpr(arraySchema));
        }
        ifBlock.assign(arrayVar, newArrayExp);
        JBlock elseBlock = conditional._else();
        if (useGenericTypes) {
            elseBlock.assign(arrayVar, JExpr._new(arrayClass).arg(JExpr.lit(0)).arg(getSchemaExpr(arraySchema)));
        } else {
            elseBlock.assign(arrayVar, codeModel.ref(Collections.class).staticInvoke("emptyList"));
        }
    }

    JDoLoop doLoop = ifBlock._do(chunkLen.gt(JExpr.lit(0)));
    JForLoop forLoop = doLoop.body()._for();
    JVar counter = forLoop.init(codeModel.INT, getVariableName("counter"), JExpr.lit(0));
    forLoop.test(counter.lt(chunkLen));
    forLoop.update(counter.incr());
    JBlock forBody = forLoop.body();

    JVar elementSchemaVar = null;
    BiConsumer<JBlock, JExpression> putValueInArray = null;
    if (action.getShouldRead()) {
        putValueInArray = (block, expression) -> block.invoke(arrayVar, "add").arg(expression);
        if (useGenericTypes) {
            elementSchemaVar = declareSchemaVar(arraySchema.getElementType(), name + "ArrayElemSchema",
                    arraySchemaVar.invoke("getElementType"));
        }
    }

    if (SchemaAssistant.isComplexType(arraySchema.getElementType())) {
        String elemName = name + "Elem";
        Schema readerArrayElementSchema = action.getShouldRead() ? readerArraySchema.getElementType() : null;
        processComplexType(elementSchemaVar, elemName, arraySchema.getElementType(), readerArrayElementSchema,
                forBody, action, putValueInArray);
    } else {
        // to preserve reader string specific options use reader array schema
        if (action.getShouldRead() && Schema.Type.STRING.equals(arraySchema.getElementType().getType())) {
            processSimpleType(readerArraySchema.getElementType(), forBody, action, putValueInArray);
        } else {
            processSimpleType(arraySchema.getElementType(), forBody, action, putValueInArray);
        }
    }
    doLoop.body().assign(chunkLen, JExpr.direct(DECODER + ".arrayNext()"));

    if (action.getShouldRead()) {
        putArrayIntoParent.accept(parentBody, arrayVar);
    }
}
 
Example 9
Source File: FastDeserializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processMap(JVar mapSchemaVar, final String name, final Schema mapSchema, final Schema readerMapSchema,
        JBlock parentBody, FieldAction action, BiConsumer<JBlock, JExpression> putMapIntoParent) {

    if (action.getShouldRead()) {
        Symbol valuesActionSymbol = null;
        for (Symbol symbol : action.getSymbol().production) {
            if (Symbol.Kind.REPEATER.equals(symbol.kind)
                    && "map-end".equals(getSymbolPrintName(((Symbol.Repeater) symbol).end))) {
                valuesActionSymbol = symbol;
                break;
            }
        }

        if (valuesActionSymbol == null) {
            throw new FastDeserializerGeneratorException("unable to determine action for map: " + name);
        }

        action = FieldAction.fromValues(mapSchema.getValueType().getType(), action.getShouldRead(),
                valuesActionSymbol);
    } else {
        action = FieldAction.fromValues(mapSchema.getValueType().getType(), false, EMPTY_SYMBOL);
    }

    final JVar mapVar = action.getShouldRead() ? declareValueVar(name, readerMapSchema, parentBody) : null;
    JVar chunkLen = parentBody.decl(codeModel.LONG, getVariableName("chunkLen"),
            JExpr.direct(DECODER + ".readMapStart()"));

    JConditional conditional = parentBody._if(chunkLen.gt(JExpr.lit(0)));
    JBlock ifBlock = conditional._then();

    if (action.getShouldRead()) {
        ifBlock.assign(mapVar, JExpr._new(schemaAssistant.classFromSchema(readerMapSchema, false)));
        JBlock elseBlock = conditional._else();
        elseBlock.assign(mapVar, codeModel.ref(Collections.class).staticInvoke("emptyMap"));
    }

    JDoLoop doLoop = ifBlock._do(chunkLen.gt(JExpr.lit(0)));
    JForLoop forLoop = doLoop.body()._for();
    JVar counter = forLoop.init(codeModel.INT, getVariableName("counter"), JExpr.lit(0));
    forLoop.test(counter.lt(chunkLen));
    forLoop.update(counter.incr());
    JBlock forBody = forLoop.body();

    JClass keyClass = schemaAssistant.keyClassFromMapSchema(action.getShouldRead() ? readerMapSchema : mapSchema);
    JExpression keyValueExpression = (string.equals(keyClass)) ?
            JExpr.direct(DECODER + ".readString()")
            : JExpr.direct(DECODER + ".readString(null)");

    if (SchemaAssistant.hasStringableKey(mapSchema)) {
        keyValueExpression = JExpr._new(keyClass).arg(keyValueExpression.invoke("toString"));
    }

    JVar key = forBody.decl(keyClass, getVariableName("key"), keyValueExpression);
    JVar mapValueSchemaVar = null;
    if (action.getShouldRead() && useGenericTypes) {
        mapValueSchemaVar = declareSchemaVar(mapSchema.getValueType(), name + "MapValueSchema",
                mapSchemaVar.invoke("getValueType"));
    }

    BiConsumer<JBlock, JExpression> putValueInMap = null;
    if (action.getShouldRead()) {
        putValueInMap = (block, expression) -> block.invoke(mapVar, "put").arg(key).arg(expression);
    }

    if (SchemaAssistant.isComplexType(mapSchema.getValueType())) {
        String valueName = name + "Value";
        Schema readerMapValueSchema = null;
        if (action.getShouldRead()) {
            readerMapValueSchema = readerMapSchema.getValueType();
        }
        processComplexType(mapValueSchemaVar, valueName, mapSchema.getValueType(), readerMapValueSchema, forBody,
                action, putValueInMap);
    } else {
        // to preserve reader string specific options use reader map schema
        if (action.getShouldRead() && Schema.Type.STRING.equals(mapSchema.getValueType().getType())) {
            processSimpleType(readerMapSchema.getValueType(), forBody, action, putValueInMap);
        } else {
            processSimpleType(mapSchema.getValueType(), forBody, action, putValueInMap);
        }
    }
    doLoop.body().assign(chunkLen, JExpr.direct(DECODER + ".mapNext()"));

    if (action.getShouldRead()) {
        putMapIntoParent.accept(parentBody, mapVar);
    }
}
 
Example 10
Source File: FastSerializerGenerator.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
private void processMap(final Schema mapSchema, JExpression mapExpr, JBlock body) {

        final JClass mapClass = schemaAssistant.classFromSchema(mapSchema);
        JClass keyClass = schemaAssistant.keyClassFromMapSchema(mapSchema);

        body.invoke(JExpr.direct(ENCODER), "writeMapStart");

        final JExpression emptyMapCondition = mapExpr.eq(JExpr._null())
                .cor(JExpr.invoke(mapExpr, "isEmpty"));
        final JConditional emptyMapIf = body._if(emptyMapCondition);
        final JBlock emptyMapBlock = emptyMapIf._then();
        emptyMapBlock.invoke(JExpr.direct(ENCODER), "setItemCount").arg(JExpr.lit(0));

        final JBlock nonEmptyMapBlock = emptyMapIf._else();
        nonEmptyMapBlock.invoke(JExpr.direct(ENCODER), "setItemCount")
                .arg(JExpr.invoke(mapExpr, "size"));

        final JForEach mapKeysLoop = nonEmptyMapBlock.forEach(keyClass, getVariableName("key"),
                JExpr.invoke(JExpr.cast(mapClass, mapExpr), "keySet"));

        final JBlock forBody = mapKeysLoop.body();
        forBody.invoke(JExpr.direct(ENCODER), "startItem");

        JVar keyStringVar;
        if (SchemaAssistant.hasStringableKey(mapSchema)) {
            keyStringVar = forBody.decl(string, getVariableName("keyString"),
                    mapKeysLoop.var().invoke("toString"));
        } else {
            keyStringVar = mapKeysLoop.var();
        }

        final Schema valueSchema = mapSchema.getValueType();

        forBody.invoke(JExpr.direct(ENCODER), "writeString").arg(keyStringVar);

        JVar containerVar;
        if (SchemaAssistant.isComplexType(valueSchema)) {
            containerVar = declareValueVar(valueSchema.getName(), valueSchema, forBody);
            forBody.assign(containerVar, JExpr.invoke(JExpr.cast(mapClass, mapExpr), "get").arg(mapKeysLoop.var()));

            processComplexType(valueSchema, containerVar, forBody);
        } else {
            processSimpleType(valueSchema, mapExpr.invoke("get").arg(mapKeysLoop.var()), forBody);
        }
        body.invoke(JExpr.direct(ENCODER), "writeMapEnd");
    }
 
Example 11
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 12
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
private void createReportingMethod(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	String name = String.valueOf(executableElement.getSimpleName());

	JMethod method = clazz.method(JMod.PUBLIC, clazz, name);
	method.annotate(Override.class);

	List<JVar> params = new ArrayList<>();

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		TypeMirror paramType = parameterElement.asType();
		Name paramName = parameterElement.getSimpleName();

		JVar param;

		if((TypeKind.ARRAY).equals(paramType.getKind())){
			ArrayType arrayType = (ArrayType)paramType;

			param = method.varParam(toType(codeModel, arrayType.getComponentType()), String.valueOf(paramName));
		} else

		{
			param = method.param(toType(codeModel, paramType), String.valueOf(paramName));
		}

		params.add(param);
	}

	String valueMethod;

	if((codeModel.DOUBLE).equals(type)){
		valueMethod = "doubleValue";
	} else

	if((codeModel.FLOAT).equals(type)){
		valueMethod = "floatValue";
	} else

	{
		throw new IllegalArgumentException();
	}

	boolean checkChange;

	switch(name){
		case "add":
		case "subtract":
		case "multiply":
		case "divide":
			checkChange = (clazz.name()).endsWith("Value");
			break;
		default:
			checkChange = false;
			break;
	}

	JBlock body = method.body();

	JVar oldValueVar = null;
	if(checkChange){
		oldValueVar = body.decl(type, "oldValue", JExpr.invoke(valueMethod));
	}

	JVar resultVariable = body.decl(clazz, "result", JExpr.cast(clazz, createSuperInvocation(clazz, method)));

	JVar newValueVar = null;
	if(checkChange){
		newValueVar = body.decl(type, "newValue", JExpr.invoke(valueMethod));
	}

	JBlock block = body;
	if(checkChange){
		block = body._if((oldValueVar).ne(newValueVar))._then();
	}

	if(initialOperation != null){
		JConditional ifStatement = block._if(JExpr.invoke("hasExpression"));

		JBlock trueBlock = ifStatement._then();

		trueBlock.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, params, type)));

		JBlock falseBlock = ifStatement._else();

		falseBlock.add(JExpr.invoke("report").arg(createReportInvocation(clazz, initialOperation, params, type)));
	} else

	{
		block.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, params, type)));
	}

	body._return(resultVariable);
}