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

The following examples show how to use com.sun.codemodel.JConditional#_else . 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: 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 2
Source File: DrillSimpleFuncHolder.java    From Bats with Apache License 2.0 4 votes vote down vote up
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, HoldingContainer[] inputVariables, String body,
                                            JVar[] workspaceJVars, FieldReference ref) {

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

  JBlock sub = new JBlock(true, true);
  JBlock topSub = sub;
  HoldingContainer out = null;
  MajorType returnValueType = getReturnType();

  // add outside null handling if it is defined.
  if (getNullHandling() == NullHandling.NULL_IF_NULL) {
    JExpression e = null;
    for (HoldingContainer v : inputVariables) {
      if (v.isOptional()) {
        JExpression isNullExpr;
        if (v.isReader()) {
         isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }
    }

    if (e != null) {
      // if at least one expression must be checked, set up the conditional.
      returnValueType = getReturnType().toBuilder().setMode(DataMode.OPTIONAL).build();
      out = g.declare(returnValueType);
      e = e.eq(JExpr.lit(0));
      JConditional jc = sub._if(e);
      jc._then().assign(out.getIsSet(), JExpr.lit(0));
      sub = jc._else();
    }
  }

  if (out == null) {
    out = g.declare(returnValueType);
  }

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


  JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValueType), getReturnValue().getName(), JExpr._new(g.getHolderType(returnValueType)));
  addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);

  List<String> holderFields = ValueHolderHelper.getHolderParams(returnValueType);
  for (String holderField : holderFields) {
    sub.assign(out.f(holderField), internalOutput.ref(holderField));
  }

  if (sub != topSub) {
    sub.assign(out.f("isSet"),JExpr.lit(1));  // Assign null if NULL_IF_NULL mode
  }

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

  return out;
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: SimpleFunctionHolder.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
protected HoldingContainer generateEvalBody(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) {

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

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;
    HoldingContainer out = null;


    // add outside null handling if it is defined.
    if (nullHandling == NullHandling.NULL_IF_NULL) {
      JExpression e = null;
      for (HoldingContainer v : inputVariables) {
        final JExpression isNullExpr;
        if (v.isReader()) {
          isNullExpr = JOp.cond(v.getHolder().invoke("isSet"), JExpr.lit(1), JExpr.lit(0));
        } else {
          isNullExpr = v.getIsSet();
        }
        if (e == null) {
          e = isNullExpr;
        } else {
          e = e.mul(isNullExpr);
        }
      }

      if (e != null) {
        // if at least one expression must be checked, set up the conditional.
        out = g.declare(resolvedOutput);
        e = e.eq(JExpr.lit(0));
        JConditional jc = sub._if(e);
        jc._then().assign(out.getIsSet(), JExpr.lit(0));
        sub = jc._else();
      }
    }

    if (out == null) {
      out = g.declare(resolvedOutput);
    }

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


    JVar internalOutput = sub.decl(JMod.FINAL, CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel()), getReturnName(), JExpr._new(CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel())));
    addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);

    if (sub != topSub || inputVariables.length == 0) {
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1));// Assign null if NULL_IF_NULL mode
    }
    sub.assign(out.getHolder(), internalOutput);

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

    return out;
  }
 
Example 8
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);
}