Java 类com.sun.codemodel.JVar 实例源码

项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) {
    JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME);
    JTypeVar returnType = method.generify("T");
    method.type(returnType);
    Models.suppressWarnings(method, "unchecked");
    JVar nameParam = method.param(String.class, "name");
    JBlock body = method.body();
    JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value",
            invoke(internalGetMethod).arg(nameParam).arg(notFoundValue));
    JConditional found = method.body()._if(notFoundValue.ne(valueVar));
    found._then()._return(cast(returnType, valueVar));
    JBlock notFound = found._else();

    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam)));
    } else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }

    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addPublicSetMethod(JDefinedClass jclass, JMethod internalSetMethod) {
    JMethod method = jclass.method(PUBLIC, jclass.owner().VOID, SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

    // if we have additional properties, then put value.
    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
        notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                .arg(cast(additionalPropertiesType, valueParam)));
    }
    // else throw exception.
    else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }

    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) {
    JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

    // if we have additional properties, then put value.
    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
        notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                .arg(cast(additionalPropertiesType, valueParam)));
    }
    // else throw exception.
    else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }
    body._return(_this());

    return method;
}
项目:GitHub    文件:EnumRule.java   
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(fromValue);
}
项目:beanvalidation-benchmark    文件:Generator.java   
/**
 * Recursive method that handles the creation of reference beans at
 * different depth levels.
 * 
 * @param mjb
 *            The target bean to create an instance of.
 * @param body
 *            The current block of code.
 * @param level
 *            The current depth level.
 * @return A generated variable referencing the created bean.
 */
private JVar generateBeanNonStaticInitCode(MetaJavaBean mjb, JBlock body, int level) {

    JVar beanDecl = body.decl(mjb.getGeneratedClass(), "lvl" + level + mjb.getName() + "_" + Config.CFG.nextUniqueNum());
    body.assign(beanDecl, JExpr._new(mjb.getGeneratedClass()));

    for (AbstractMetaField amf : mjb.getFields()) {
        if (amf instanceof JavaBeanRefField) {

            JavaBeanRefField jbrf = (JavaBeanRefField) amf;

            // Should a nested bean be created?
            if (Config.CFG.shouldAddNestedBean(level)) {
                JVar nestedBeanDecl = generateBeanNonStaticInitCode(jbrf.getRefBean(), body, level + 1);
                jbrf.generateAssignCode(body, beanDecl, nestedBeanDecl);
            }
        }

    }

    return beanDecl;
}
项目:beanvalidation-benchmark    文件:JavaBeanBasicField.java   
/**
 * Creates a random MetaField
 * 
 * @param owner
 *            The class that owns this field.
 * @param name
 *            The name of the meta field.
 */
public JavaBeanBasicField(MetaJavaBean owner, String name) {

    super(owner, name);

    this.basicType = BasicType.getRandom();

    // Generate the field declaration
    JDefinedClass ownerClass = owner.getGeneratedClass();
    this.generatedField = ownerClass.field(JMod.PRIVATE, basicType.getTypeClass(), name);

    // The getter
    getter = ownerClass.method(JMod.PUBLIC, basicType.getTypeClass(), "get" + name.substring(0, 1).toUpperCase() + name.substring(1));
    getter.body()._return(this.generatedField);

    // And the setter
    setter = ownerClass.method(JMod.PUBLIC, void.class, "set" + name.substring(0, 1).toUpperCase() + name.substring(1));
    JVar setterParam = setter.param(basicType.getTypeClass(), name);
    setter.body().assign(JExpr._this().ref(this.generatedField), setterParam);
}
项目:beanvalidation-benchmark    文件:JavaBeanRefField.java   
public JavaBeanRefField(MetaJavaBean owner, String name, MetaJavaBean refBean) {
    super(owner, name);

    this.refBean = refBean;

    // Generate the field declaration
    JDefinedClass ownerClass = owner.getGeneratedClass();
    this.generatedField = ownerClass.field(JMod.PRIVATE, refBean.getGeneratedClass(), name);

    // The getter
    getter = ownerClass.method(JMod.PUBLIC, refBean.getGeneratedClass(), "get"+name.substring(0, 1).toUpperCase()+name.substring(1));
    getter.body()._return(this.generatedField);

    // The setter
    setter = ownerClass.method(JMod.PUBLIC, void.class, "set"+name.substring(0, 1).toUpperCase()+name.substring(1));
    JVar setterParam = setter.param(refBean.getGeneratedClass(), name);
    setter.body().assign(JExpr._this().ref(this.generatedField), setterParam);
}
项目:QDrill    文件:WindowFunction.java   
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
  final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
  final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);

  cg.setMappingSet(mappingSet);
  final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
  final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
  JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex)
    .arg(JExpr.direct("partition.ntile(" + numTiles + ")"));
  cg.getEvalBlock().add(setMethod);
}
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holderExpr,
    ClassGenerator<?> generator) throws RuntimeException {

  AbstractFuncHolder holder = (AbstractFuncHolder) holderExpr.getHolder();

  JVar[] workspaceVars = holder.renderStart(generator, null);

  if (holder.isNested()) {
    generator.getMappingSet().enterChild();
  }

  HoldingContainer[] args = new HoldingContainer[holderExpr.args.size()];
  for (int i = 0; i < holderExpr.args.size(); i++) {
    args[i] = holderExpr.args.get(i).accept(this, generator);
  }

  holder.renderMiddle(generator, args, workspaceVars);

  if (holder.isNested()) {
    generator.getMappingSet().exitChild();
  }

  return holder.renderEnd(generator, args, workspaceVars);
}
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitDecimal9Constant(Decimal9Expression e, ClassGenerator<?> generator)
    throws RuntimeException {
  MajorType majorType = e.getMajorType();
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = generator.getHolderType(majorType);
  JVar var = generator.declareClassField("dec9", holderType);
  JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal());
  JExpression scaleLiteral = JExpr.lit(e.getScale());
  JExpression precisionLiteral = JExpr.lit(e.getPrecision());
  setup.assign(
      var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal9Holder").arg(valueLiteral)
          .arg(scaleLiteral).arg(precisionLiteral));
  return new HoldingContainer(majorType, var, null, null);
}
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitDecimal18Constant(Decimal18Expression e, ClassGenerator<?> generator)
    throws RuntimeException {
  MajorType majorType = e.getMajorType();
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = generator.getHolderType(majorType);
  JVar var = generator.declareClassField("dec18", holderType);
  JExpression valueLiteral = JExpr.lit(e.getLongFromDecimal());
  JExpression scaleLiteral = JExpr.lit(e.getScale());
  JExpression precisionLiteral = JExpr.lit(e.getPrecision());
  setup.assign(
      var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal18Holder").arg(valueLiteral)
          .arg(scaleLiteral).arg(precisionLiteral));
  return new HoldingContainer(majorType, var, null, null);
}
项目:QDrill    文件:DrillAggFuncHolder.java   
@Override
public HoldingContainer renderEnd(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[]  workspaceJVars) {
  HoldingContainer out = g.declare(returnValue.type, false);
  JBlock sub = new JBlock();
  g.getEvalBlock().add(sub);
  JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValue.type), returnValue.name, JExpr._new(g.getHolderType(returnValue.type)));
  addProtectedBlock(g, sub, output, null, workspaceJVars, false);
  sub.assign(out.getHolder(), internalOutput);
      //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
      if (!g.getMappingSet().isHashAggMapping()) {
        generateBody(g, BlockType.RESET, reset, null, workspaceJVars, false);
      }
     generateBody(g, BlockType.CLEANUP, cleanup, null, workspaceJVars, false);

  return out;
}
项目:QDrill    文件:DrillAggFuncHolder.java   
private JVar[] declareWorkspaceVectors(ClassGenerator<?> g) {
  JVar[] workspaceJVars = new JVar[workspaceVars.length];

  for(int i =0 ; i < workspaceVars.length; i++){
    if (workspaceVars[i].isInject() == true) {
      workspaceJVars[i] = g.declareClassField("work", g.getModel()._ref(workspaceVars[i].type));
      g.getBlock(BlockType.SETUP).assign(workspaceJVars[i], g.getMappingSet().getIncoming().invoke("getContext").invoke("getManagedBuffer"));
    } else {
      Preconditions.checkState(Types.isFixedWidthType(workspaceVars[i].majorType), String.format("Workspace variable '%s' in aggregation function '%s' is not allowed to have variable length type.", workspaceVars[i].name, registeredNames[0]));
      Preconditions.checkState(workspaceVars[i].majorType.getMode()==DataMode.REQUIRED, String.format("Workspace variable '%s' in aggregation function '%s' is not allowed to have null or repeated type.", workspaceVars[i].name, registeredNames[0]));

      //workspaceJVars[i] = g.declareClassField("work", g.getHolderType(workspaceVars[i].majorType), JExpr._new(g.getHolderType(workspaceVars[i].majorType)));
      workspaceJVars[i] = g.declareClassField("work", g.getHolderType(workspaceVars[i].majorType));

      //Declare a workspace vector for the workspace var.
      TypedFieldId typedFieldId = new TypedFieldId(workspaceVars[i].majorType, g.getWorkspaceTypes().size());
      JVar vv  = g.declareVectorValueSetupAndMember(g.getMappingSet().getWorkspace(), typedFieldId);

      g.getWorkspaceTypes().add(typedFieldId);
      g.getWorkspaceVectors().put(workspaceVars[i], vv);
    }
  }
  return workspaceJVars;
}
项目:dremio-oss    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holderExpr,
    ClassGenerator<?> generator) throws RuntimeException {
  CompleteType resolvedOutput = holderExpr.getCompleteType();
  AbstractFunctionHolder holder = (AbstractFunctionHolder) holderExpr.getHolder();

  JVar[] workspaceVars = holder.renderStart(generator, resolvedOutput, null);

  if (holder.isNested()) {
    generator.getMappingSet().enterChild();
  }

  HoldingContainer[] args = new HoldingContainer[holderExpr.args.size()];
  for (int i = 0; i < holderExpr.args.size(); i++) {
    args[i] = holderExpr.args.get(i).accept(this, generator);
  }

  holder.renderMiddle(generator, resolvedOutput, args, workspaceVars);

  if (holder.isNested()) {
    generator.getMappingSet().exitChild();
  }

  return holder.renderEnd(generator, resolvedOutput, args, workspaceVars);
}
项目:dremio-oss    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitDecimalConstant(DecimalExpression e, ClassGenerator<?> generator)
    throws RuntimeException {
  CompleteType majorType= e.getCompleteType();
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = majorType.getHolderType(generator.getModel());
  JVar var = generator.declareClassField("dec", holderType);
  JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal());
  JExpression scaleLiteral = JExpr.lit(e.getScale());
  JExpression precisionLiteral = JExpr.lit(e.getPrecision());
  setup.assign(
      var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getNullableDecimalHolder").arg(valueLiteral)
          .arg(scaleLiteral).arg(precisionLiteral));
  return new HoldingContainer(majorType, var, var.ref("value"), var.ref("isSet"));
}
项目:dremio-oss    文件:ClassGenerator.java   
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
  final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);

  final Class<?> valueVectorClass = fieldId.getIntermediateClass();
  final JClass vvClass = model.ref(valueVectorClass);
  final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;

  final JVar vv = declareClassField("vv", retClass);
  final JBlock b = getSetupBlock();
  int[] fieldIndices = fieldId.getFieldIds();
  JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
      .arg(batchName)
      .arg(vvClass.dotclass());

  for(int i = 0; i < fieldIndices.length; i++){
    invoke.arg(JExpr.lit(fieldIndices[i]));
  }

  // we have to cast here since Janino doesn't handle generic inference well.
  JExpression casted = JExpr.cast(retClass, invoke);
  b.assign(vv, casted);
  vvDeclaration.put(setup, vv);

  return vv;
}
项目:dremio-oss    文件:AggrFunctionHolder.java   
@Override
public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[]  workspaceJVars) {
  HoldingContainer out = g.declare(resolvedOutput, false);
  JBlock sub = new JBlock();
  g.getEvalBlock().add(sub);
  JVar internalOutput = sub.decl(JMod.FINAL, resolvedOutput.getHolderType(g.getModel()), getReturnName(), JExpr._new(resolvedOutput.getHolderType(g.getModel())));
  addProtectedBlock(g, sub, output(), null, workspaceJVars, false);
  sub.assign(out.getHolder(), internalOutput);
      //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
      if (!g.getMappingSet().isHashAggMapping()) {
        generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false);
      }
     generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
项目:dremio-oss    文件:AggrFunctionHolder.java   
private JVar[] declareWorkspaceVectors(ClassGenerator<?> g) {
  JVar[] workspaceJVars = new JVar[workspaceVars.length];


  for(int i =0 ; i < workspaceVars.length; i++){
    if (workspaceVars[i].isInject() == true) {
      workspaceJVars[i] = g.declareClassField("work", g.getModel()._ref(workspaceVars[i].type));
      g.getBlock(BlockType.SETUP).assign(workspaceJVars[i], JExpr.direct("context").invoke("getManagedBuffer"));
    } else {
      Preconditions.checkState(workspaceVars[i].completeType.isFixedWidthScalar(), "Workspace variable '%s' in aggregation function '%s' is not allowed to have variable length type.", workspaceVars[i].name, registeredNames[0]);

      //workspaceJVars[i] = g.declareClassField("work", g.getHolderType(workspaceVars[i].majorType), JExpr._new(g.getHolderType(workspaceVars[i].majorType)));
      workspaceJVars[i] = g.declareClassField("work", workspaceVars[i].completeType.getHolderType(g.getModel()));

      //Declare a workspace vector for the workspace var.
      TypedFieldId typedFieldId = new TypedFieldId(workspaceVars[i].completeType, g.getWorkspaceTypes().size());
      JVar vv  = g.declareVectorValueSetupAndMember(g.getMappingSet().getWorkspace(), typedFieldId);

      g.getWorkspaceTypes().add(typedFieldId);
      g.getWorkspaceVectors().put(workspaceVars[i], vv);
    }
  }
  return workspaceJVars;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addInternalGetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
    JBlock body = method.body();
    JSwitch propertySwitch = body._switch(nameParam);
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            addGetPropertyCase(jclass, propertySwitch, propertyName, propertyType, node);
        }
    }
    JClass extendsType = jclass._extends();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        propertySwitch._default().body()
        ._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
    } else {
        propertySwitch._default().body()
        ._return(notFoundParam);
    }

    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
    JBlock body = method.body();
    JConditional propertyConditional = null;

    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
            if (propertyConditional == null) {
                propertyConditional = body._if(condition);
            } else {
                propertyConditional = propertyConditional._elseif(condition);
            }
            JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {});
            propertyConditional._then()._return(invoke(propertyGetter));
        }
    }

    JClass extendsType = jclass._extends();
    JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
    } else {
        lastBlock._return(notFoundParam);
    }

    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addInternalSetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JSwitch propertySwitch = body._switch(nameParam);
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            addSetPropertyCase(jclass, propertySwitch, propertyName, propertyType, valueParam, node);
        }
    }
    JBlock defaultBlock = propertySwitch._default().body();
    JClass extendsType = jclass._extends();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        defaultBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
    } else {
        defaultBlock._return(FALSE);
    }
    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addInternalSetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JConditional propertyConditional = null;
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();
            JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
            propertyConditional = propertyConditional == null ? propertyConditional = body._if(condition)
                    : propertyConditional._elseif(condition);

            JBlock callSite = propertyConditional._then();
            addSetProperty(jclass, callSite, propertyName, propertyType, valueParam, node);
            callSite._return(TRUE);
        }
    }
    JClass extendsType = jclass._extends();
    JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();

    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
    } else {
        lastBlock._return(FALSE);
    }
    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private void addSetProperty(JDefinedClass jclass, JBlock callSite, String propertyName, JType propertyType, JVar valueVar, JsonNode node) {
    JMethod propertySetter = jclass.getMethod(getSetterName(propertyName, node), new JType[] { propertyType });
    JConditional isInstance = callSite._if(valueVar._instanceof(propertyType.boxify().erasure()));
    isInstance._then()
    .invoke(propertySetter).arg(cast(propertyType.boxify(), valueVar));
    isInstance._else()
    ._throw(illegalArgumentInvocation(jclass, propertyName, propertyType, valueVar));
}
项目:GitHub    文件:EnumRule.java   
private JFieldVar addValueField(JDefinedClass _enum, JType type) {
    JFieldVar valueField = _enum.field(JMod.PRIVATE | JMod.FINAL, type, VALUE_FIELD_NAME);

    JMethod constructor = _enum.constructor(JMod.PRIVATE);
    JVar valueParam = constructor.param(type, VALUE_FIELD_NAME);
    JBlock body = constructor.body();
    body.assign(JExpr._this().ref(valueField), valueParam);

    return valueField;
}
项目:GitHub    文件:PropertyRule.java   
private JMethod addSetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) {
    JMethod setter = c.method(JMod.PUBLIC, void.class, getSetterName(jsonPropertyName, node));

    JVar param = setter.param(field.type(), field.name());
    JBlock body = setter.body();
    body.assign(JExpr._this().ref(field), param);

    return setter;
}
项目:GitHub    文件:PropertyRule.java   
private JMethod addBuilder(JDefinedClass c, JFieldVar field) {
    JMethod builder = c.method(JMod.PUBLIC, c, getBuilderName(field.name()));

    JVar param = builder.param(field.type(), field.name());
    JBlock body = builder.body();
    body.assign(JExpr._this().ref(field), param);
    body._return(JExpr._this());

    return builder;
}
项目:GitHub    文件:PropertiesRule.java   
private void addOverrideBuilder(JDefinedClass thisJDefinedClass, JMethod parentBuilder, JVar parentParam) {

        if (thisJDefinedClass.getMethod(parentBuilder.name(), new JType[] {parentParam.type()}) == null) {

            JMethod builder = thisJDefinedClass.method(parentBuilder.mods().getValue(), thisJDefinedClass, parentBuilder.name());
            builder.annotate(Override.class);

            JVar param = builder.param(parentParam.type(), parentParam.name());
            JBlock body = builder.body();
            body.invoke(JExpr._super(), parentBuilder).arg(param);
            body._return(JExpr._this());

        }
    }
项目:GitHub    文件:AdditionalPropertiesRule.java   
private void addSetter(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    JMethod setter = jclass.method(JMod.PUBLIC, void.class, "setAdditionalProperty");

    ruleFactory.getAnnotator().anySetter(setter);

    JVar nameParam = setter.param(String.class, "name");
    JVar valueParam = setter.param(propertyType, "value");

    JInvocation mapInvocation = setter.body().invoke(JExpr._this().ref(field), "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
}
项目:GitHub    文件:AdditionalPropertiesRule.java   
private void addBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    JMethod builder = jclass.method(JMod.PUBLIC, jclass, "withAdditionalProperty");

    JVar nameParam = builder.param(String.class, "name");
    JVar valueParam = builder.param(propertyType, "value");

    JBlock body = builder.body();
    JInvocation mapInvocation = body.invoke(JExpr._this().ref(field), "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
    body._return(JExpr._this());
}
项目:GitHub    文件:ObjectRule.java   
private void addEquals(JDefinedClass jclass, JsonNode node) {
    Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);

    JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals");
    JVar otherObject = equals.param(Object.class, "other");

    Class<?> equalsBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.EqualsBuilder.class : org.apache.commons.lang.builder.EqualsBuilder.class;

    JBlock body = equals.body();

    body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
    body._if(otherObject._instanceof(jclass).eq(JExpr.FALSE))._then()._return(JExpr.FALSE);

    JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject));
    JClass equalsBuilderClass = jclass.owner().ref(equalsBuilder);
    JInvocation equalsBuilderInvocation = JExpr._new(equalsBuilderClass);

    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        equalsBuilderInvocation = equalsBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("equals").arg(otherObject));
    }

    for (JFieldVar fieldVar : fields.values()) {
        if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        equalsBuilderInvocation = equalsBuilderInvocation.invoke("append")
                .arg(fieldVar)
                .arg(rhsVar.ref(fieldVar.name()));
    }

    JInvocation reflectionEquals = jclass.owner().ref(equalsBuilder).staticInvoke("reflectionEquals");
    reflectionEquals.arg(JExpr._this());
    reflectionEquals.arg(otherObject);

    body._return(equalsBuilderInvocation.invoke("isEquals"));

    equals.annotate(Override.class);
}
项目:beanvalidation-benchmark    文件:Generator.java   
/**
 * Generates a Holder class that will hold an {@link ArrayList} with all the
 * first level beans in the graph (contents of {@link #beans}) on it.
 */
private void generatePopulationCode() {
    try {
        // Generate the holder class
        JDefinedClass holderClass = cm._class(Config.CFG.getBasePackageName() + ".Holder");
        JClass alObject = (JClass) cm._ref(ArrayList.class);
        alObject = alObject.narrow(Object.class);
        JFieldVar beansField = holderClass.field(JMod.PUBLIC, alObject, "beans", JExpr._new(alObject));
        JMethod defConstructor = holderClass.constructor(JMod.PUBLIC);
        JBlock body = defConstructor.body();

        // Init the beans and add them to the array
        for (MetaJavaBean mjb : beans) {
            mjb.generateStaticInitCode();
            JVar beanDecl = generateBeanNonStaticInitCode(mjb, body, 0);
            body.add(beansField.invoke("add").arg(beanDecl));
        }

        // Init the base beans but don't add them to the array
        for (MetaJavaBean bmjb : baseBeans) {
            bmjb.generateStaticInitCode();
        }

    } catch (JClassAlreadyExistsException e) {
        throw new RuntimeException("Error generating the holder class.", e);
    }
}
项目:QDrill    文件:CopyUtil.java   
public static void generateCopies(ClassGenerator g, VectorAccessible batch, boolean hyper){
  // we have parallel ids for each value vector so we don't actually have to deal with managing the ids at all.
  int fieldId = 0;

  JExpression inIndex = JExpr.direct("inIndex");
  JExpression outIndex = JExpr.direct("outIndex");
  for(VectorWrapper<?> vv : batch) {
    String copyMethod;
    if (!Types.isFixedWidthType(vv.getField().getType()) || Types.isRepeated(vv.getField().getType()) || Types.isComplex(vv.getField().getType())) {
      copyMethod = "copyFromSafe";
    } else {
      copyMethod = "copyFrom";
    }
    g.rotateBlock();
    JVar inVV = g.declareVectorValueSetupAndMember("incoming", new TypedFieldId(vv.getField().getType(), vv.isHyper(), fieldId));
    JVar outVV = g.declareVectorValueSetupAndMember("outgoing", new TypedFieldId(vv.getField().getType(), false, fieldId));

    if(hyper){

      g.getEvalBlock().add(
              outVV
                      .invoke(copyMethod)
                      .arg(
                              inIndex.band(JExpr.lit((int) Character.MAX_VALUE)))
                      .arg(outIndex)
                      .arg(
                              inVV.component(inIndex.shrz(JExpr.lit(16)))
                      )
      );
    }else{
      g.getEvalBlock().add(outVV.invoke(copyMethod).arg(inIndex).arg(outIndex).arg(inVV));
    }

    g.rotateBlock();
    fieldId++;
  }
}
项目:QDrill    文件:WindowFunction.java   
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
  final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
  final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);

  cg.setMappingSet(mappingSet);
  final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
  final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
  JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex).arg(JExpr.direct("partition." + getName()));

  cg.getEvalBlock().add(setMethod);
}
项目:QDrill    文件:EvaluationVisitor.java   
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {

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

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

      // Only when the input is a reader, use writer interface to copy value.
      // Otherwise, input is a holder and we use vv mutator to set value.
      if (inputContainer.isReader()) {
        JType writerImpl = generator.getModel()._ref(
            TypeHelper.getWriterImpl(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JType writerIFace = generator.getModel()._ref(
            TypeHelper.getWriterInterface(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
        JVar writer = generator.declareClassField("writer", writerIFace);
        generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv).arg(JExpr._null()));
        generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));
        String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
        generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
        if (e.isSafe()) {
          HoldingContainer outputContainer = generator.declare(Types.REQUIRED_BIT);
          generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
          return outputContainer;
        }
      } else {

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

      }

      return null;
    }
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitQuotedStringConstant(QuotedString e, ClassGenerator<?> generator)
    throws RuntimeException {
  MajorType majorType = Types.required(MinorType.VARCHAR);
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = generator.getHolderType(majorType);
  JVar var = generator.declareClassField("string", holderType);
  JExpression stringLiteral = JExpr.lit(e.value);
  JExpression buffer = generator.getMappingSet().getIncoming().invoke("getContext").invoke("getManagedBuffer");
  setup.assign(var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getVarCharHolder").arg(buffer).arg(stringLiteral));
  return new HoldingContainer(majorType, var, null, null);
}
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitIntervalDayConstant(IntervalDayExpression e, ClassGenerator<?> generator)
    throws RuntimeException {
  MajorType majorType = Types.required(MinorType.INTERVALDAY);
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = generator.getHolderType(majorType);
  JVar var = generator.declareClassField("intervalday", holderType);
  JExpression dayLiteral = JExpr.lit(e.getIntervalDay());
  JExpression millisLiteral = JExpr.lit(e.getIntervalMillis());
  setup.assign(
      var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getIntervalDayHolder").arg(dayLiteral)
          .arg(millisLiteral));
  return new HoldingContainer(majorType, var, null, null);
}
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitDecimal28Constant(Decimal28Expression e, ClassGenerator<?> generator)
    throws RuntimeException {
  MajorType majorType = e.getMajorType();
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = generator.getHolderType(majorType);
  JVar var = generator.declareClassField("dec28", holderType);
  JExpression stringLiteral = JExpr.lit(e.getBigDecimal().toString());
  setup.assign(var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal28Holder").arg(stringLiteral));
  return new HoldingContainer(majorType, var, null, null);
}
项目:QDrill    文件:EvaluationVisitor.java   
@Override
public HoldingContainer visitDecimal38Constant(Decimal38Expression e, ClassGenerator<?> generator)
    throws RuntimeException {
  MajorType majorType = e.getMajorType();
  JBlock setup = generator.getBlock(BlockType.SETUP);
  JType holderType = generator.getHolderType(majorType);
  JVar var = generator.declareClassField("dec38", holderType);
  JExpression stringLiteral = JExpr.lit(e.getBigDecimal().toString());
  setup.assign(var,
      generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getVarCharHolder").arg(stringLiteral));
  return new HoldingContainer(majorType, var, null, null);
}
项目:QDrill    文件:EvaluationVisitor.java   
private HoldingContainer renderConstantExpression(ClassGenerator<?> generator, HoldingContainer input) {
  JVar fieldValue = generator.declareClassField("constant", generator.getHolderType(input.getMajorType()));
  generator.getEvalBlock().assign(fieldValue, input.getHolder());
  generator.getMappingSet().exitConstant();
  return new HoldingContainer(input.getMajorType(), fieldValue, fieldValue.ref("value"), fieldValue.ref("isSet"))
      .setConstant(true);
}
项目:dremio-oss    文件:BaseFunctionHolder.java   
protected void generateBody(ClassGenerator<?> g, BlockType bt, String body, HoldingContainer[] inputVariables,
    JVar[] workspaceJVars, boolean decConstantInputOnly) {
  if (!Strings.isNullOrEmpty(body) && !body.trim().isEmpty()) {
    JBlock sub = new JBlock(true, true);
    if (decConstantInputOnly) {
      addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, true);
    } else {
      addProtectedBlock(g, sub, body, null, workspaceJVars, false);
    }
    g.getBlock(bt).directStatement(String.format("/** start %s for function %s **/ ", bt.name(), registeredNames[0]));
    g.getBlock(bt).add(sub);
    g.getBlock(bt).directStatement(String.format("/** end %s for function %s **/ ", bt.name(), registeredNames[0]));
  }
}