Java Code Examples for com.sun.codemodel.JBlock#_if

The following examples show how to use com.sun.codemodel.JBlock#_if . 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: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(backingType, "value");

    JBlock body = fromValue.body();
    JVar constant = body.decl(_enum, "constant");
    constant.init(quickLookupMap.invoke("get").arg(valueParam));

    JConditional _if = body._if(constant.eq(JExpr._null()));

    JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
    JExpression expr = valueParam;

    // if string no need to add ""
    if(!isString(backingType)){
        expr = expr.plus(JExpr.lit(""));
    }
    
    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
 
Example 2
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) {
    // remove the old getter
    ownerClass.methods().remove(getter);
    // and create a new one
    JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name());
    JBlock block = newGetter.body();

    JVar ret = block.decl(getJavaType(field), "ret");
    JCodeModel codeModel = field.type().owner();
    JVar param = generateMethodParameter(getter, field);
    JConditional conditional = block._if(param.eq(JExpr._null()));
    conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param));
    conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param));
    block._return(ret);

    getter.javadoc().append("Returns unmodifiable collection.");
}
 
Example 3
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 4
Source File: FastSerializerGenerator.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processString(final Schema primitiveSchema, JExpression primitiveValueExpression, JBlock body) {
  String writeFunction = "writeString";
  JExpression encodeVar = JExpr.direct(ENCODER);
  if (!useGenericTypes && SchemaAssistant.isStringable(primitiveSchema)) {
    body.invoke(encodeVar, writeFunction).arg(primitiveValueExpression.invoke("toString"));
  } else {
    JConditional stringTypeCheck = body._if(primitiveValueExpression._instanceof(codeModel.ref(Utf8.class)));
    stringTypeCheck._then()
        .invoke(encodeVar, writeFunction)
        .arg(JExpr.cast(codeModel.ref(Utf8.class), primitiveValueExpression));
    stringTypeCheck._else().invoke(encodeVar, writeFunction).arg(primitiveValueExpression.invoke("toString"));
  }
}
 
Example 5
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 6
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 7
Source File: ClientGenerator.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
public void generateMethodMeta(String methodName, JsonObject params, String url,
    String httpVerb, JsonArray contentType, JsonArray accepts){

  /* Adding method to the Class which is public and returns void */

  JMethod jmCreate = method(JMod.PUBLIC, void.class, methodName);
  JBlock body = jmCreate.body();

  /* create the query parameter string builder */
  JVar queryParams = body.decl(jcodeModel._ref(StringBuilder.class), "queryParams",
          JExpr._new(jcodeModel.ref(StringBuilder.class)).arg("?"));


  ////////////////////////---- Handle place holders in the url  ----//////////////////
  /* create request */
  /* Handle place holders in the URL
    * replace {varName} with "+varName+" so that it will be replaced
    * in the url at runtime with the correct values */
  Matcher m = Pattern.compile("\\{.*?\\}").matcher(url);
  while(m.find()){
    String varName = m.group().replace("{","").replace("}", "");
    url = url.replace("{"+varName+"}", "\"+"+varName+"+\"");
  }

  url = "\""+url.substring(1)+"\"+queryParams.toString()";

  /* Adding java doc for method */
  jmCreate.javadoc().add("Service endpoint " + url);


  /* iterate on function params and add the relevant ones
   * --> functionSpecificQueryParamsPrimitives is populated by query parameters that are primitives
   * --> functionSpecificHeaderParams (used later on) is populated by header params
   * --> functionSpecificQueryParamsEnums is populated by query parameters that are enums */
  Iterator<Entry<String, Object>> paramList = params.iterator();

  boolean [] bodyContentExists = new boolean[]{false};
  paramList.forEachRemaining(entry -> {
    String valueName = ((JsonObject) entry.getValue()).getString("value");
    String valueType = ((JsonObject) entry.getValue()).getString("type");
    String paramType = ((JsonObject) entry.getValue()).getString("param_type");
    if(handleParams(jmCreate, queryParams, paramType, valueType, valueName)){
      bodyContentExists[0] = true;
    }
  });

  //////////////////////////////////////////////////////////////////////////////////////

  /* create the http client request object */
  body.directStatement("io.vertx.core.http.HttpClientRequest request = httpClient."+
      httpVerb.substring(httpVerb.lastIndexOf('.')+1).toLowerCase()+"Abs(okapiUrl+"+url+");");
  body.directStatement("request.handler(responseHandler);");

  /* add headers to request */
  functionSpecificHeaderParams.forEach(body::directStatement);
  //reset for next method usage
  functionSpecificHeaderParams = new ArrayList<>();

  /* add content and accept headers if relevant */
  if(contentType != null){
    String cType = contentType.toString().replace("\"", "").replace("[", "").replace("]", "");
    if(contentType.contains("multipart/form-data")){
      body.directStatement("request.putHeader(\"Content-type\", \""+cType+"; boundary=--BOUNDARY\");");
    }
    else{
      body.directStatement("request.putHeader(\"Content-type\", \""+cType+"\");");
    }
  }
  if(accepts != null){
    String aType = accepts.toString().replace("\"", "").replace("[", "").replace("]", "");
    //replace any/any with */* to allow declaring accpet */* which causes compilation issues
    //when declared in raml. so declare any/any in raml instead and replaced here
    aType = aType.replaceAll("any/any", "");
    body.directStatement("request.putHeader(\"Accept\", \""+aType+"\");");
  }

  /* push tenant id into x-okapi-tenant and authorization headers for now */
  JConditional ifClause = body._if(tenantId.ne(JExpr._null()));
  ifClause._then().directStatement("request.putHeader(\"X-Okapi-Token\", token);");
  ifClause._then().directStatement("request.putHeader(\""+OKAPI_HEADER_TENANT+"\", tenantId);");

  JConditional ifClause2 = body._if(this.okapiUrl.ne(JExpr._null()));
  ifClause2._then().directStatement("request.putHeader(\"X-Okapi-Url\", okapiUrl);");

  /* add response handler to each function */
  JClass handler = jcodeModel.ref(Handler.class).narrow(HttpClientResponse.class);
  jmCreate.param(handler, "responseHandler");

  /* if we need to pass data in the body */
  if(bodyContentExists[0]){
    body.directStatement("request.putHeader(\"Content-Length\", buffer.length()+\"\");");
    body.directStatement("request.setChunked(true);");
    body.directStatement("request.write(buffer);");
  }

  body.directStatement("request.end();");
}
 
Example 8
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 9
Source File: EvaluationVisitor.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitBooleanOr(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getCompleteType());

  JLabel label = generator.getEvalBlockLabel("OrOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);   // enter into nested block.

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "or" when one side is null
  //    p       q       p and q
  //    true    null     true
  //    false   null     null
  //    null    true     true
  //    null    false    null
  //    null    null     null

  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().eq(JExpr.lit(1))))._then();
    if (e == null) {
      e = arg.getIsSet();
    } else {
      e = e.mul(arg.getIsSet());
    }
    earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    earlyExit.assign(out.getValue(),  JExpr.lit(1));
    earlyExit._break(label);
  }

  assert (e != null);

  JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
  notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

  JBlock setBlock = notSetJC._else().block();
  setBlock.assign(out.getIsSet(), JExpr.lit(1));
  setBlock.assign(out.getValue(), JExpr.lit(0));

  generator.unNestEvalBlock();   // exit from nested block.

  return out;
}
 
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: 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 12
Source File: ObjectCodeGenerator.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void generate(final JBlock block, JType type,
		Collection<JType> possibleTypes, boolean isAlwaysSet, A arguments) {
	if (possibleTypes.size() <= 1) {
		getImplementor().onObject(arguments, block, isAlwaysSet);
	} else {
		final JClass jaxbElementClass = getCodeModel().ref(
				JAXBElement.class);
		final Set<JType> arrays = new HashSet<JType>();
		final Collection<JClass> jaxbElements = new HashSet<JClass>();
		final Set<JType> otherTypes = new HashSet<JType>();
		for (final JType possibleType : possibleTypes) {
			if (possibleType.isArray()) {
				arrays.add(possibleType);
			} else if (possibleType instanceof JClass
					&& jaxbElementClass
							.isAssignableFrom(((JClass) possibleType)
									.erasure())) {
				jaxbElements.add((JClass) possibleType);
			} else {
				otherTypes.add(possibleType);
			}
		}

		final JConditionable _if = new JConditionable() {

			private JConditional conditional = null;

			@Override
			public JBlock _ifThen(JExpression condition) {
				if (conditional == null) {
					conditional = block._if(condition);
				} else {
					conditional = conditional._elseif(condition);
				}
				return conditional._then();
			}

			@Override
			public JBlock _else() {
				if (conditional == null) {
					return block;
				} else {
					return conditional._else();
				}
			}
		};

		if (!jaxbElements.isEmpty()) {
			final Set<JType> valueTypes = getJAXBElementValueTypes(jaxbElements);
			final JType valueType = TypeUtil.getCommonBaseType(
					getCodeModel(), valueTypes);
			final JClass jaxbElementType = jaxbElementClass
					.narrow(valueType);

			final JBlock jaxbElementBlock = _if._ifThen(arguments
					._instanceof(jaxbElementClass));
			getCodeGenerator().generate(
					jaxbElementBlock,
					jaxbElementType,
					new HashSet<JType>(jaxbElements),
					true,
					arguments.cast("JAXBElement", jaxbElementBlock,
							jaxbElementType, true));

		}

		if (!arrays.isEmpty()) {
			for (JType arrayType : arrays) {
				final JBlock arrayBlock = _if._ifThen(arguments
						._instanceof(arrayType));
				getCodeGenerator().generate(
						arrayBlock,
						arrayType,
						Collections.singleton(arrayType),
						true,
						arguments.cast("Array", arrayBlock, arrayType,
								false));
			}
		}

		if (!otherTypes.isEmpty()) {
			getImplementor().onObject(arguments, _if._else(), false);
		}
	}
}
 
Example 13
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 14
Source File: PluginContext.java    From jaxb2-rich-contract-plugin with MIT License 4 votes vote down vote up
public JForEach loop(final JBlock block, final JExpression source, final JType sourceElementType, final JAssignmentTarget target, final JType targetElementType) {
	final JConditional ifNull = block._if(source.eq(JExpr._null()));
	ifNull._then().assign(target, JExpr._null());
	ifNull._else().assign(target, JExpr._new(this.arrayListClass.narrow(targetElementType)));
	return ifNull._else().forEach(sourceElementType, "_item", source);
}
 
Example 15
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 16
Source File: FastSerdeBase.java    From avro-util with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected void ifCodeGen(JBlock parentBody, JExpression condition, Consumer<JBlock> thenClosure,
    Consumer<JBlock> elseClosure) {
  JConditional ifCondition = parentBody._if(condition);
  thenClosure.accept(ifCondition._then());
  elseClosure.accept(ifCondition._else());
}
 
Example 17
Source File: FastSerdeBase.java    From avro-util with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected void ifCodeGen(JBlock parentBody, JExpression condition, Consumer<JBlock> thenClosure) {
  JConditional ifCondition = parentBody._if(condition);
  thenClosure.accept(ifCondition._then());
}
 
Example 18
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 19
Source File: EvaluationVisitor.java    From Bats with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitBooleanOr(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("OrOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);   // enter into nested block.

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "or" when one side is null
  //    p       q       p and q
  //    true    null     true
  //    false   null     null
  //    null    true     true
  //    null    false    null
  //    null    null     null

  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().eq(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().eq(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(1));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(0));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(0));
  }

  generator.unNestEvalBlock();   // exit from nested block.

  return out;
}
 
Example 20
Source File: EvaluationVisitor.java    From Bats with Apache License 2.0 4 votes vote down vote up
private HoldingContainer visitBooleanAnd(BooleanOperator op,
    ClassGenerator<?> generator) {

  HoldingContainer out = generator.declare(op.getMajorType());

  JLabel label = generator.getEvalBlockLabel("AndOP");
  JBlock eval = generator.createInnerEvalBlock();
  generator.nestEvalBlock(eval);  // enter into nested block

  HoldingContainer arg = null;

  JExpression e = null;

  //  value of boolean "and" when one side is null
  //    p       q     p and q
  //    true    null     null
  //    false   null     false
  //    null    true     null
  //    null    false    false
  //    null    null     null
  for (int i = 0; i < op.args.size(); i++) {
    arg = op.args.get(i).accept(this, generator);

    JBlock earlyExit = null;
    if (arg.isOptional()) {
      earlyExit = eval._if(arg.getIsSet().eq(JExpr.lit(1)).cand(arg.getValue().ne(JExpr.lit(1))))._then();
      if (e == null) {
        e = arg.getIsSet();
      } else {
        e = e.mul(arg.getIsSet());
      }
    } else {
      earlyExit = eval._if(arg.getValue().ne(JExpr.lit(1)))._then();
    }

    if (out.isOptional()) {
      earlyExit.assign(out.getIsSet(), JExpr.lit(1));
    }

    earlyExit.assign(out.getValue(),  JExpr.lit(0));
    earlyExit._break(label);
  }

  if (out.isOptional()) {
    assert (e != null);

    JConditional notSetJC = eval._if(e.eq(JExpr.lit(0)));
    notSetJC._then().assign(out.getIsSet(), JExpr.lit(0));

    JBlock setBlock = notSetJC._else().block();
    setBlock.assign(out.getIsSet(), JExpr.lit(1));
    setBlock.assign(out.getValue(), JExpr.lit(1));
  } else {
    assert (e == null);
    eval.assign(out.getValue(), JExpr.lit(1));
  }

  generator.unNestEvalBlock();     // exit from nested block

  return out;
}