Java Code Examples for com.sun.codemodel.JBlock#directStatement()

The following examples show how to use com.sun.codemodel.JBlock#directStatement() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private void processBytes(JBlock body, FieldAction action, BiConsumer<JBlock, JExpression> putValueIntoParent,
    Supplier<JExpression> reuseSupplier) {
  if (action.getShouldRead()) {
    if (reuseSupplier.get().equals(JExpr._null())) {
      putValueIntoParent.accept(body, JExpr.invoke(JExpr.direct(DECODER), "readBytes").arg(JExpr.direct("null")));
    } else {
      ifCodeGen(body,
          reuseSupplier.get()._instanceof(codeModel.ref("java.nio.ByteBuffer")),
          thenBlock -> putValueIntoParent.accept(thenBlock, JExpr.invoke(JExpr.direct(DECODER), "readBytes")
              .arg(JExpr.cast(codeModel.ref(ByteBuffer.class), reuseSupplier.get()))),
          elseBlock -> putValueIntoParent.accept(elseBlock,
              JExpr.invoke(JExpr.direct(DECODER), "readBytes").arg(JExpr.direct("null")))
      );
    }
  } else {
    body.directStatement(DECODER + ".skipBytes()");
  }
}
 
Example 2
private void processString(Schema schema, JBlock body, FieldAction action,
    BiConsumer<JBlock, JExpression> putValueIntoParent, Supplier<JExpression> reuseSupplier) {
  if (action.getShouldRead()) {
    JClass stringClass = schemaAssistant.findStringClass(schema);
    if (stringClass.equals(codeModel.ref(Utf8.class))) {
      if (reuseSupplier.equals(EMPTY_SUPPLIER)) {
        putValueIntoParent.accept(body, JExpr.invoke(JExpr.direct(DECODER), "readString").arg(JExpr._null()));
      } else {
        ifCodeGen(body, reuseSupplier.get()._instanceof(codeModel.ref(Utf8.class)),
            thenBlock -> putValueIntoParent.accept(thenBlock, JExpr.invoke(JExpr.direct(DECODER), "readString").arg(JExpr.cast(codeModel.ref(Utf8.class), reuseSupplier.get()))),
            elseBlock -> putValueIntoParent.accept(elseBlock,
                JExpr.invoke(JExpr.direct(DECODER), "readString").arg(JExpr._null())));
      }
    } else if (stringClass.equals(codeModel.ref(String.class))) {
      putValueIntoParent.accept(body, JExpr.invoke(JExpr.direct(DECODER), "readString"));
    } else {
      putValueIntoParent.accept(body, readStringableExpression(stringClass));
    }
  } else {
    body.directStatement(DECODER + ".skipString();");
  }
}
 
Example 3
Source Project: Bats   File: DrillAggFuncHolder.java    License: Apache License 2.0 5 votes vote down vote up
private JBlock generateInitWorkspaceBlockHA(ClassGenerator<?> g, BlockType bt, String body, JVar[] workspaceJVars, JExpression wsIndexVariable){
  JBlock initBlock = new JBlock(true, true);
  if(!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()){
    JBlock sub = new JBlock(true, true);
    addProtectedBlockHA(g, sub, body, null, workspaceJVars, wsIndexVariable);
    initBlock.directStatement(String.format("/** start %s for function %s **/ ", bt.name(), getRegisteredNames()[0]));
    initBlock.add(sub);
    initBlock.directStatement(String.format("/** end %s for function %s **/ ", bt.name(), getRegisteredNames()[0]));
  }
  return initBlock;
}
 
Example 4
private void processPrimitive(final Schema schema, JBlock body, FieldAction action,
    BiConsumer<JBlock, JExpression> putValueIntoParent, Supplier<JExpression> reuseSupplier) {

  String readFunction;
  switch (schema.getType()) {
    case STRING:
      processString(schema, body, action, putValueIntoParent, reuseSupplier);
      return;
    case BYTES:
      processBytes(body, action, putValueIntoParent, reuseSupplier);
      return;
    case INT:
      readFunction = "readInt()";
      break;
    case LONG:
      readFunction = "readLong()";
      break;
    case FLOAT:
      readFunction = "readFloat()";
      break;
    case DOUBLE:
      readFunction = "readDouble()";
      break;
    case BOOLEAN:
      readFunction = "readBoolean()";
      break;
    default:
      throw new FastDeserializerGeneratorException("Unsupported primitive schema of type: " + schema.getType());
  }

  JExpression primitiveValueExpression = JExpr.direct("decoder." + readFunction);
  if (action.getShouldRead()) {
    putValueIntoParent.accept(body, primitiveValueExpression);
  } else {
    body.directStatement(DECODER + "." + readFunction + ";");
  }
}
 
Example 5
private void renderBuilderCreateContract(JDefinedClass builderClass, JClass literalBuilderClass, List<FieldModel> fields, Class<?> contractInterface) {
	JMethod createContractMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JVar contractParam = createContractMethod.param(contractInterface, "contract");
	JBlock body = createContractMethod.body();
	JConditional nullContractCheck = body._if(contractParam.eq(JExpr._null()));
	nullContractCheck._then().directStatement("throw new IllegalArgumentException(\"contract was null\");");
	body.directStatement("// TODO if create() is modified to accept required parameters, this will need to be modified");
	body.directStatement("Builder builder = create();");
	for (FieldModel fieldModel : fields) {
		String fieldName = fieldModel.fieldName;
		body.directStatement("builder." + Util.generateSetter(fieldName, "contract." + Util.generateGetter(fieldName, isBoolean(fieldModel.fieldType))) + ";");
	}
	body.directStatement("return builder;");
}
 
Example 6
Source Project: dremio-oss   File: AggrFunctionHolder.java    License: Apache License 2.0 5 votes vote down vote up
private JBlock generateInitWorkspaceBlockHA(ClassGenerator<?> g, BlockType bt, String body, JVar[] workspaceJVars, JExpression wsIndexVariable){
  JBlock initBlock = new JBlock(true, true);
  if(!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()){
    JBlock sub = new JBlock(true, true);
    addProtectedBlockHA(g, sub, body, null, workspaceJVars, wsIndexVariable);
    initBlock.directStatement(String.format("/** start %s for function %s **/ ", bt.name(), registeredNames[0]));
    initBlock.add(sub);
    initBlock.directStatement(String.format("/** end %s for function %s **/ ", bt.name(), registeredNames[0]));
  }
  return initBlock;
}
 
Example 7
Source Project: dremio-oss   File: BaseFunctionHolder.java    License: Apache License 2.0 5 votes vote down vote up
protected void addProtectedBlock(ClassGenerator<?> g, JBlock sub, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstInputOnly) {
  if (inputVariables != null) {
    for (int i = 0; i < inputVariables.length; i++) {
      if (decConstInputOnly && !inputVariables[i].isConstant()) {
        continue;
      }

      ValueReference parameter = parameters[i];
      HoldingContainer inputVariable = inputVariables[i];
      if (parameter.isFieldReader && !inputVariable.isReader() && inputVariable.getCompleteType().isScalar()) {
        JType singularReaderClass = g.getModel()._ref(TypeHelper.getHolderReaderImpl(getArrowMinorType(inputVariable.getCompleteType().toMinorType())));
        JType fieldReadClass = g.getModel()._ref(FieldReader.class);
        sub.decl(fieldReadClass, parameter.name, JExpr._new(singularReaderClass).arg(inputVariable.getHolder()));
      } else {
        sub.decl(inputVariable.getHolder().type(), parameter.name, inputVariable.getHolder());
      }
    }
  }

  JVar[] internalVars = new JVar[workspaceJVars.length];
  for (int i = 0; i < workspaceJVars.length; i++) {
    if (decConstInputOnly) {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    } else {
      internalVars[i] = sub.decl(g.getModel()._ref(workspaceVars[i].type), workspaceVars[i].name, workspaceJVars[i]);
    }

  }

  Preconditions.checkNotNull(body);
  sub.directStatement(body);

  // reassign workspace variables back to global space.
  for (int i = 0; i < workspaceJVars.length; i++) {
    sub.assign(workspaceJVars[i], internalVars[i]);
  }
}
 
Example 8
public void generateCloseClient(){
  JMethod jmCreate = method(JMod.PUBLIC, void.class, "close");
  jmCreate.javadoc().add("Close the client. Closing will close down any "
      + "pooled connections. Clients should always be closed after use.");
  JBlock body = jmCreate.body();

  body.directStatement("httpClient.close();");
}
 
Example 9
private void processListParameter(JBlock b, ParameterDetails details) {
  b.directStatement(new StringBuilder("if(")
    .append(details.valueName)
    .append(".getClass().isArray())")
    .append("{queryParams.append(String.join(\"&")
    .append(details.valueName)
    .append("=\",")
    .append(details.valueName)
    .append("));}")
    .toString());
}
 
Example 10
private void renderPrivateJaxbConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = " + getInitString(fieldModel.fieldType) + ";");
	}
	method.javadoc().add("Private constructor used only by JAXB.");
}
 
Example 11
private void renderBuilderConstructor(JDefinedClass classModel, List<FieldModel> fields) {
	JMethod method = classModel.constructor(JMod.PRIVATE);
	method.param(codeModel.ref("Builder"), "builder");
	JBlock body = method.body();
	for (FieldModel fieldModel : fields) {
		body.directStatement("this." + fieldModel.fieldName + " = builder." + Util.generateGetter(fieldModel.fieldName, isBoolean(fieldModel.fieldType)) + ";");
	}
}
 
Example 12
private void renderGetters(JDefinedClass classModel, List<FieldModel> fields) {
          for (FieldModel fieldModel : fields) {
              JMethod getterMethod = classModel.method(JMod.PUBLIC, fieldModel.fieldType, Util.generateGetterName(fieldModel.fieldName, isBoolean(fieldModel.fieldType)));
		JBlock methodBody = getterMethod.body();
		methodBody.directStatement("return this." + fieldModel.fieldName + ";");
		getterMethod.annotate(Override.class);
	}
}
 
Example 13
private void processEnum(final Schema schema, final JBlock body, FieldAction action,
    BiConsumer<JBlock, JExpression> putEnumIntoParent) {

  if (action.getShouldRead()) {

    Symbol.EnumAdjustAction enumAdjustAction = null;
    if (action.getSymbol() instanceof Symbol.EnumAdjustAction) {
      enumAdjustAction = (Symbol.EnumAdjustAction) action.getSymbol();
    } else {
      for (Symbol symbol : action.getSymbol().production) {
        if (symbol instanceof Symbol.EnumAdjustAction) {
          enumAdjustAction = (Symbol.EnumAdjustAction) symbol;
        }
      }
    }

    boolean enumOrderCorrect = true;
    for (int i = 0; i < enumAdjustAction.adjustments.length; i++) {
      Object adjustment = enumAdjustAction.adjustments[i];
      if (adjustment instanceof String) {
        throw new FastDeserializerGeneratorException(
            schema.getName() + " enum label impossible to deserialize: " + adjustment.toString());
      } else if (!adjustment.equals(i)) {
        enumOrderCorrect = false;
      }
    }

    JExpression newEnum;
    JExpression enumValueExpr = JExpr.direct(DECODER + ".readEnum()");

    if (enumOrderCorrect) {
      newEnum = schemaAssistant.getEnumValueByIndex(schema, enumValueExpr, getSchemaExpr(schema));
    } else {
      JVar enumIndex = body.decl(codeModel.INT, getUniqueName("enumIndex"), enumValueExpr);
      JClass enumClass = schemaAssistant.classFromSchema(schema);
      newEnum = body.decl(enumClass, getUniqueName("enumValue"), JExpr._null());

      for (int i = 0; i < enumAdjustAction.adjustments.length; i++) {
        JExpression ithVal =
            schemaAssistant.getEnumValueByIndex(schema, JExpr.lit((Integer) enumAdjustAction.adjustments[i]),
                getSchemaExpr(schema));
        body._if(enumIndex.eq(JExpr.lit(i)))._then().assign((JVar) newEnum, ithVal);
      }
    }
    putEnumIntoParent.accept(body, newEnum);
  } else {
    body.directStatement(DECODER + ".readEnum();");
  }
}
 
Example 14
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 15
private void processEnum(final Schema schema, final JBlock body, FieldAction action,
        BiConsumer<JBlock, JExpression> putEnumIntoParent) {

    if (action.getShouldRead()) {

        Symbol.EnumAdjustAction enumAdjustAction = null;
        if (action.getSymbol() instanceof Symbol.EnumAdjustAction) {
            enumAdjustAction = (Symbol.EnumAdjustAction) action.getSymbol();
        } else {
            for (Symbol symbol : action.getSymbol().production) {
                if (symbol instanceof Symbol.EnumAdjustAction) {
                    enumAdjustAction = (Symbol.EnumAdjustAction) symbol;
                }
            }
        }

        boolean enumOrderCorrect = true;
        for (int i = 0; i < enumAdjustAction.adjustments.length; i++) {
            Object adjustment = enumAdjustAction.adjustments[i];
            if (adjustment instanceof String) {
                throw new FastDeserializerGeneratorException(
                        schema.getName() + " enum label impossible to deserialize: " + adjustment.toString());
            } else if (!adjustment.equals(i)) {
                enumOrderCorrect = false;
            }
        }

        JExpression newEnum;
        JExpression enumValueExpr = JExpr.direct(DECODER + ".readEnum()");

        if (enumOrderCorrect) {
            newEnum = schemaAssistant.getEnumValueByIndex(schema, enumValueExpr, getSchemaExpr(schema));
        } else {
            JVar enumIndex = body.decl(codeModel.INT, getVariableName("enumIndex"), enumValueExpr);
            JClass enumClass = schemaAssistant.classFromSchema(schema);
            newEnum = body.decl(enumClass, getVariableName("enumValue"), JExpr._null());

            for (int i = 0; i < enumAdjustAction.adjustments.length; i++) {
                JExpression ithVal = schemaAssistant
                        .getEnumValueByIndex(schema, JExpr.lit((Integer) enumAdjustAction.adjustments[i]),
                                getSchemaExpr(schema));
                body._if(enumIndex.eq(JExpr.lit(i)))._then().assign((JVar) newEnum, ithVal);
            }
        }
        putEnumIntoParent.accept(body, newEnum);
    } else {
        body.directStatement(DECODER + ".readEnum();");
    }

}
 
Example 16
private void processPrimitive(final Schema schema, JBlock body, FieldAction action,
        BiConsumer<JBlock, JExpression> putValueIntoParent) {

    String readFunction;
    switch (schema.getType()) {
    case STRING:
        if (action.getShouldRead()) {
            if (string.equals(schemaAssistant.classFromSchema(schema))) {
                readFunction = "readString()";
            } else {
                // reads as Utf8
                readFunction = "readString(null)";
            }
        } else {
            readFunction = "skipString()";
        }
        break;
    case BYTES:
        readFunction = "readBytes(null)";
        break;
    case INT:
        readFunction = "readInt()";
        break;
    case LONG:
        readFunction = "readLong()";
        break;
    case FLOAT:
        readFunction = "readFloat()";
        break;
    case DOUBLE:
        readFunction = "readDouble()";
        break;
    case BOOLEAN:
        readFunction = "readBoolean()";
        break;
    default:
        throw new FastDeserializerGeneratorException(
                "Unsupported primitive schema of type: " + schema.getType());
    }

    JExpression primitiveValueExpression = JExpr.direct("decoder." + readFunction);
    if (action.getShouldRead()) {
        if (schema.getType().equals(Schema.Type.STRING) && SchemaAssistant.isStringable(schema)) {
            primitiveValueExpression = JExpr._new(schemaAssistant.classFromSchema(schema))
                    .arg(primitiveValueExpression.invoke("toString"));
        }
        putValueIntoParent.accept(body, primitiveValueExpression);
    } else {
        body.directStatement(DECODER + "." + readFunction + ";");
    }
}
 
Example 17
Source Project: dremio-oss   File: HiveFuncHolder.java    License: Apache License 2.0 4 votes vote down vote up
private void generateSetup(ClassGenerator<?> g, JVar[] workspaceJVars) {
  JCodeModel m = g.getModel();
  JBlock sub = new JBlock(true, true);

  // declare and instantiate argument ObjectInspector's
  JVar oiArray = sub.decl(
    m._ref(ObjectInspector[].class),
    "argOIs",
    JExpr.newArray(m._ref(ObjectInspector.class), argTypes.length));

  JClass oih = m.directClass(ObjectInspectorHelper.class.getCanonicalName());
  JClass mt = m.directClass(MinorType.class.getCanonicalName());
  JClass mode = m.directClass(DataMode.class.getCanonicalName());
  for(int i=0; i<argTypes.length; i++) {
    sub.assign(
      oiArray.component(JExpr.lit(i)),
      oih.staticInvoke("getObjectInspector")
        .arg(mode.staticInvoke("valueOf").arg(JExpr.lit("OPTIONAL")))
        .arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].toMinorType().name())))
        .arg((((PrimitiveObjectInspector) returnOI).getPrimitiveCategory() ==
            PrimitiveObjectInspector.PrimitiveCategory.STRING) ? JExpr.lit(true) : JExpr.lit(false)));
  }

  // declare and instantiate DeferredObject array
  sub.assign(workspaceJVars[2], JExpr.newArray(m._ref(DeferredObject.class), argTypes.length));

  for(int i=0; i<argTypes.length; i++) {
    sub.assign(
      workspaceJVars[2].component(JExpr.lit(i)),
      JExpr._new(m.directClass(DeferredObject.class.getCanonicalName())));
  }

  // declare empty array for argument deferred objects
  sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DeferredObject.class), argTypes.length));

  // create new instance of the UDF class
  sub.assign(workspaceJVars[1], getUDFInstance(m));

  // create try..catch block to initialize the UDF instance with argument OIs
  JTryBlock udfInitTry = sub._try();
  udfInitTry.body().assign(
    workspaceJVars[0],
    workspaceJVars[1].invoke("initialize")
    .arg(oiArray));

  JCatchBlock udfInitCatch = udfInitTry._catch(m.directClass(Exception.class.getCanonicalName()));
  JVar exVar = udfInitCatch.param("ex");
  udfInitCatch.body()
    ._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName()))
      .arg(JExpr.lit(String.format("Failed to initialize GenericUDF"))).arg(exVar));

  sub.add(ObjectInspectorHelper.initReturnValueHolder(g, m, workspaceJVars[4], returnOI, returnType.toMinorType()));

  // now add it to the doSetup block in Generated class
  JBlock setup = g.getBlock(ClassGenerator.BlockType.SETUP);
  setup.directStatement(String.format("/** start %s for function %s **/ ",
    ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));

  setup.add(sub);

  setup.directStatement(String.format("/** end %s for function %s **/ ",
    ClassGenerator.BlockType.SETUP.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));
}
 
Example 18
Source Project: dremio-oss   File: HiveFuncHolder.java    License: Apache License 2.0 4 votes vote down vote up
private HoldingContainer generateEval(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) {

    HoldingContainer out = g.declare(returnType);

    JCodeModel m = g.getModel();
    JBlock sub = new JBlock(true, true);

    // initialize DeferredObject's. For an optional type, assign the value holder only if it is not null
    for(int i=0; i<argTypes.length; i++) {
      sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
      JBlock conditionalBlock = new JBlock(false, false);
      JConditional jc = conditionalBlock._if(inputVariables[i].getIsSet().ne(JExpr.lit(0)));
      jc._then().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
      jc._else().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), JExpr._null());
      sub.add(conditionalBlock);
    }

    // declare generic object for storing return value from GenericUDF.evaluate
    JVar retVal = sub.decl(m._ref(Object.class), "ret");

    // create try..catch block to call the GenericUDF instance with given input
    JTryBlock udfEvalTry = sub._try();
    udfEvalTry.body().assign(retVal,
      workspaceJVars[1].invoke("evaluate").arg(workspaceJVars[3]));

    JCatchBlock udfEvalCatch = udfEvalTry._catch(m.directClass(Exception.class.getCanonicalName()));
    JVar exVar = udfEvalCatch.param("ex");
    udfEvalCatch.body()
      ._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName()))
        .arg(JExpr.lit(String.format("GenericUDF.evaluate method failed"))).arg(exVar));

    // get the ValueHolder from retVal and return ObjectInspector
    sub.add(ObjectInspectorHelper.getObject(m, returnOI, workspaceJVars[0], workspaceJVars[4], retVal));
    sub.assign(out.getHolder(), workspaceJVars[4]);

    // now add it to the doEval block in Generated class
    JBlock setup = g.getBlock(ClassGenerator.BlockType.EVAL);
    setup.directStatement(String.format("/** start %s for function %s **/ ",
      ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));
    setup.add(sub);
    setup.directStatement(String.format("/** end %s for function %s **/ ",
      ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "("+udfName+")" : "")));

    return out;
  }
 
Example 19
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 20
private void renderBuilderDefaultCreate(JDefinedClass builderClass, JClass literalBuilderClass) {
	JMethod createMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JBlock createMethodBody = createMethod.body();
	createMethodBody.directStatement("// TODO modify as needed to pass any required values and add them to the signature of the 'create' method");
	createMethodBody.directStatement("return new Builder();");
}