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

项目:GitHub    文件:Jsonschema2PojoRuleTest.java   
@Override
public org.jsonschema2pojo.rules.Rule<JPackage, JType> getObjectRule() {
    final org.jsonschema2pojo.rules.Rule<JPackage, JType> workingRule = super.getObjectRule();

    return new org.jsonschema2pojo.rules.Rule<JPackage, JType>() {
        @Override
        public JType apply(String nodeName, JsonNode node, JPackage generatableType, Schema currentSchema) {
            JType objectType = workingRule.apply(nodeName, node, generatableType, currentSchema);
            if( objectType instanceof JDefinedClass ) {
                JDefinedClass jclass = (JDefinedClass)objectType;
                jclass.method(JMod.PUBLIC, jclass.owner().BOOLEAN, "brokenMethod").body();
            }
            return objectType;
        }
    };
}
项目:GitHub    文件:DefaultRule.java   
/**
 * Creates a default value for a set property by:
 * <ol>
 * <li>Creating a new {@link LinkedHashSet} with the correct generic type
 * <li>Using {@link Arrays#asList(Object...)} to initialize the set with the
 * correct default values
 * </ol>
 *
 * @param fieldType
 *            the java type that applies for this field ({@link Set} with
 *            some generic type argument)
 * @param node
 *            the node containing default values for this set
 * @return an expression that creates a default value that can be assigned
 *         to this field
 */
private JExpression getDefaultSet(JType fieldType, JsonNode node) {

    JClass setGenericType = ((JClass) fieldType).getTypeParameters().get(0);

    JClass setImplClass = fieldType.owner().ref(LinkedHashSet.class);
    setImplClass = setImplClass.narrow(setGenericType);

    JInvocation newSetImpl = JExpr._new(setImplClass);

    if (node instanceof ArrayNode && node.size() > 0) {
        JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList");
        for (JsonNode defaultValue : node) {
            invokeAsList.arg(getDefaultValue(setGenericType, defaultValue));
        }
        newSetImpl.arg(invokeAsList);
    } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) {
        return JExpr._null();
    }

    return newSetImpl;

}
项目: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);
}
项目:GitHub    文件:EnumRule.java   
private void addEnumConstants(JsonNode node, JDefinedClass _enum, JsonNode customNames, JType type) {
    Collection<String> existingConstantNames = new ArrayList<String>();
    for (int i = 0; i < node.size(); i++) {
        JsonNode value = node.path(i);

        if (!value.isNull()) {
            String constantName = getConstantName(value.asText(), customNames.path(i).asText());
            constantName = makeUnique(constantName, existingConstantNames);
            existingConstantNames.add(constantName);

            JEnumConstant constant = _enum.enumConstant(constantName);
            constant.arg(DefaultRule.getDefaultValue(type, value));
            ruleFactory.getAnnotator().enumConstant(constant, value.asText());
        }
    }
}
项目:GitHub    文件:DefaultRule.java   
/**
 * Creates a default value for a list property by:
 * <ol>
 * <li>Creating a new {@link ArrayList} with the correct generic type
 * <li>Using {@link Arrays#asList(Object...)} to initialize the list with
 * the correct default values
 * </ol>
 *
 * @param fieldType
 *            the java type that applies for this field ({@link List} with
 *            some generic type argument)
 * @param node
 *            the node containing default values for this list
 * @return an expression that creates a default value that can be assigned
 *         to this field
 */
private JExpression getDefaultList(JType fieldType, JsonNode node) {

    JClass listGenericType = ((JClass) fieldType).getTypeParameters().get(0);

    JClass listImplClass = fieldType.owner().ref(ArrayList.class);
    listImplClass = listImplClass.narrow(listGenericType);

    JInvocation newListImpl = JExpr._new(listImplClass);

    if (node instanceof ArrayNode && node.size() > 0) {
        JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList");
        for (JsonNode defaultValue : node) {
            invokeAsList.arg(getDefaultValue(listGenericType, defaultValue));
        }
        newListImpl.arg(invokeAsList);
    } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) {
        return JExpr._null();
    }

    return newListImpl;

}
项目: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);
}
项目:dremio-oss    文件:PartitionSenderOperator.java   
private List<Partitioner> createClassInstances(int actualPartitions) throws SchemaChangeException {
  // set up partitioning function
  final LogicalExpression expr = config.getExpr();
  final ClassGenerator<Partitioner> cg = context.getClassProducer().createGenerator(Partitioner.TEMPLATE_DEFINITION).getRoot();
  ClassGenerator<Partitioner> cgInner = cg.getInnerGenerator("OutgoingRecordBatch");

  final LogicalExpression materializedExpr = context.getClassProducer().materialize(expr, incoming);

  // generate code to copy from an incoming value vector to the destination partition's outgoing value vector
  JExpression bucket = JExpr.direct("bucket");

  // generate evaluate expression to determine the hash
  ClassGenerator.HoldingContainer exprHolder = cg.addExpr(materializedExpr);
  cg.getEvalBlock().decl(JType.parse(cg.getModel(), "int"), "bucket", exprHolder.getValue().mod(JExpr.lit(outGoingBatchCount)));
  cg.getEvalBlock()._return(cg.getModel().ref(Math.class).staticInvoke("abs").arg(bucket));

  CopyUtil.generateCopies(cgInner, incoming, incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.FOUR_BYTE);

  // compile and setup generated code
  List<Partitioner> subPartitioners = cg.getCodeGenerator().getImplementationClass(actualPartitions);
  return subPartitioners;
}
项目: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);
}
项目:GitHub    文件:TypeRuleTest.java   
@Test
public void applyGeneratesDate() {

    JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());

    ObjectNode objectNode = new ObjectMapper().createObjectNode();
    objectNode.put("type", "string");

    TextNode formatNode = TextNode.valueOf("date-time");
    objectNode.set("format", formatNode);

    JType mockDateType = mock(JType.class);
    FormatRule mockFormatRule = mock(FormatRule.class);
    when(mockFormatRule.apply(eq("fooBar"), eq(formatNode), Mockito.isA(JType.class), isNull(Schema.class))).thenReturn(mockDateType);
    when(ruleFactory.getFormatRule()).thenReturn(mockFormatRule);

    JType result = rule.apply("fooBar", objectNode, jpackage, null);

    assertThat(result, equalTo(mockDateType));
}
项目: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"));
}
项目:GitHub    文件:SchemaMapper.java   
public JType generate(JCodeModel codeModel, String className, String packageName, String json) throws IOException {

        JPackage jpackage = codeModel._package(packageName);

        JsonNode schemaNode = null;
        if (ruleFactory.getGenerationConfig().getSourceType() == SourceType.JSON) {
            JsonNode jsonNode = objectMapper().readTree(json);
            schemaNode = schemaGenerator.schemaFromExample(jsonNode);
        } else {
            schemaNode = objectMapper().readTree(json);
        }

        return ruleFactory.getSchemaRule().apply(className, schemaNode, jpackage, new Schema(null, schemaNode, schemaNode));
    }
项目: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    文件:CustomRuleFactoryIT.java   
@Override
public Rule<JType, JType> getFormatRule() {
    return new FormatRule(this) {
        @Override
        public JType apply(String nodeName, JsonNode node, JType baseType, Schema schema) {
            if (node.asText().equals("date")) {
                return baseType.owner().ref(LocalDate.class);
            }

            return super.apply(nodeName, node, baseType, schema);
        }
    };
}
项目: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    文件:DefaultRule.java   
/**
 * @see EnumRule
 */
private static JExpression getDefaultEnum(JType fieldType, JsonNode node) {

    JDefinedClass enumClass = (JDefinedClass) fieldType;
    JType backingType = enumClass.fields().get("value").type();
    JInvocation invokeFromValue = enumClass.staticInvoke("fromValue");
    invokeFromValue.arg(getDefaultValue(backingType, node));

    return invokeFromValue;

}
项目:dremio-oss    文件:TypeHelper.java   
public static JType getHolderType(JCodeModel model, com.dremio.common.types.TypeProtos.MinorType type, com.dremio.common.types.TypeProtos.DataMode mode){
    switch (type) {
    case UNION:
      return model._ref(UnionHolder.class);
    case MAP:
    case LIST:
      return model._ref(ComplexHolder.class);

<#list vv.types as type>
  <#list type.minor as minor>
    <#assign typeMapping = TypeMappings[minor.class]!{}>
      <#assign supported = typeMapping.supported!true>
      <#assign dremioMinorType = typeMapping.minor_type!minor.class?upper_case>
      <#if supported>
      case ${dremioMinorType}:
        switch (mode) {
          case REQUIRED:
            return model._ref(${minor.class}Holder.class);
          case OPTIONAL:
            return model._ref(Nullable${minor.class}Holder.class);
        }
    </#if>
  </#list>
</#list>
    case GENERIC_OBJECT:
      return model._ref(ObjectHolder.class);
      default:
        break;
      }
    throw new UnsupportedOperationException(buildErrorMessage("get holder type", com.dremio.common.util.MajorTypeHelper.getArrowMinorType(type)));
  }
项目:dremio-oss    文件:BaseFunctionHolder.java   
protected JVar[] declareWorkspaceVariables(ClassGenerator<?> g) {
  JVar[] workspaceJVars = new JVar[workspaceVars.length];
  for (int i = 0; i < workspaceVars.length; i++) {
    WorkspaceReference ref = workspaceVars[i];
    JType jtype = g.getModel()._ref(ref.type);

    if (ScalarReplacementTypes.CLASSES.contains(ref.type)) {
      workspaceJVars[i] = g.declareClassField("work", jtype);
      JBlock b = g.getBlock(SignatureHolder.INIT_METHOD);
      b.assign(workspaceJVars[i], JExpr._new(jtype));
    } else {
      workspaceJVars[i] = g.declareClassField("work", jtype);
    }

    if (ref.isInject()) {
      if (FunctionContext.INJECTABLE_GETTER_METHODS.get(ref.getType()) != null) {
        g.getBlock(BlockType.SETUP).assign(
            workspaceJVars[i],
            JExpr.direct("context").invoke(
                FunctionContext.INJECTABLE_GETTER_METHODS.get(ref.getType())
            ));
      } else {
        // Invalid injectable type provided, this should have been caught in FunctionConverter
        throw new IllegalArgumentException("Invalid injectable type requested in UDF: " + ref.getType().getSimpleName());
      }
    } else {
      //g.getBlock(BlockType.SETUP).assign(workspaceJVars[i], JExpr._new(jtype));
    }
  }
  return workspaceJVars;
}
项目:beanvalidation-benchmark    文件:Util.java   
private static void addAnnotArrayParam(JAnnotationArrayMember aux, Object value) {
    if (value instanceof JType) {
        aux.param((JType) value);
        // return aux.param((JType)value); ?? No Javadoc defining how to use the API
    } else {
        throw new RuntimeException("Impossible to construct annotation param array for: " + value);
    }
}
项目:QDrill    文件:ClassGenerator.java   
public HoldingContainer declare(MajorType t, boolean includeNewInstance) {
  JType holderType = getHolderType(t);
  JVar var;
  if (includeNewInstance) {
    var = getEvalBlock().decl(holderType, "out" + index, JExpr._new(holderType));
  } else {
    var = getEvalBlock().decl(holderType, "out" + index);
  }
  JFieldRef outputSet = null;
  if (t.getMode() == DataMode.OPTIONAL) {
    outputSet = var.ref("isSet");
  }
  index++;
  return new HoldingContainer(t, var, var.ref("value"), outputSet);
}
项目:GitHub    文件:TypeRule.java   
private JType unboxIfNecessary(JType type, GenerationConfig config) {
    if (config.isUsePrimitives()) {
        return type.unboxify();
    } else {
        return type;
    }
}
项目:GitHub    文件:TypeRule.java   
/**
 * Returns the JType for an integer field. Handles type lookup and unboxing.
 */
private JType getIntegerType(JCodeModel owner, JsonNode node, GenerationConfig config) {

    if (config.isUseBigIntegers()) {
        return unboxIfNecessary(owner.ref(BigInteger.class), config);
    } else if (config.isUseLongIntegers() ||
            node.has("minimum") && node.get("minimum").isLong() ||
            node.has("maximum") && node.get("maximum").isLong()) {
        return unboxIfNecessary(owner.ref(Long.class), config);
    } else {
        return unboxIfNecessary(owner.ref(Integer.class), config);
    }

}
项目:GitHub    文件:TypeRule.java   
/**
 * Returns the JType for a number field. Handles type lookup and unboxing.
 */
private JType getNumberType(JCodeModel owner, GenerationConfig config) {

    if (config.isUseBigDecimals()) {
        return unboxIfNecessary(owner.ref(BigDecimal.class), config);
    } else if (config.isUseDoubleNumbers()) {
        return unboxIfNecessary(owner.ref(Double.class), config);
    } else {
        return unboxIfNecessary(owner.ref(Float.class), config);
    }

}
项目: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);
}
项目:QDrill    文件:PartitionSenderRootExec.java   
private List<Partitioner> createClassInstances(int actualPartitions) throws SchemaChangeException {
  // set up partitioning function
  final LogicalExpression expr = operator.getExpr();
  final ErrorCollector collector = new ErrorCollectorImpl();
  final ClassGenerator<Partitioner> cg ;

  cg = CodeGenerator.getRoot(Partitioner.TEMPLATE_DEFINITION, context.getFunctionRegistry());
  ClassGenerator<Partitioner> cgInner = cg.getInnerGenerator("OutgoingRecordBatch");

  final LogicalExpression materializedExpr = ExpressionTreeMaterializer.materialize(expr, incoming, collector, context.getFunctionRegistry());
  if (collector.hasErrors()) {
    throw new SchemaChangeException(String.format(
        "Failure while trying to materialize incoming schema.  Errors:\n %s.",
        collector.toErrorString()));
  }

  // generate code to copy from an incoming value vector to the destination partition's outgoing value vector
  JExpression bucket = JExpr.direct("bucket");

  // generate evaluate expression to determine the hash
  ClassGenerator.HoldingContainer exprHolder = cg.addExpr(materializedExpr);
  cg.getEvalBlock().decl(JType.parse(cg.getModel(), "int"), "bucket", exprHolder.getValue().mod(JExpr.lit(outGoingBatchCount)));
  cg.getEvalBlock()._return(cg.getModel().ref(Math.class).staticInvoke("abs").arg(bucket));

  CopyUtil.generateCopies(cgInner, incoming, incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.FOUR_BYTE);

  try {
    // compile and setup generated code
    List<Partitioner> subPartitioners = context.getImplementationClass(cg, actualPartitions);
    return subPartitioners;

  } catch (ClassTransformationException | IOException e) {
    throw new SchemaChangeException("Failure while attempting to load generated class", e);
  }
}
项目: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;
    }
项目:GitHub    文件:ObjectRule.java   
private boolean isFinal(JType superType) {
    try {
        Class<?> javaClass = Class.forName(superType.fullName());
        return Modifier.isFinal(javaClass.getModifiers());
    } catch (ClassNotFoundException e) {
        return false;
    }
}
项目:GitHub    文件:ObjectRule.java   
private static JDefinedClass definedClassOrNullFromType(JType type)
{
    if (type == null || type.isPrimitive())
    {
        return null;
    }
    JClass fieldClass = type.boxify();
    JPackage jPackage = fieldClass._package();
    return jPackage._getClass(fieldClass.name());
}
项目:GitHub    文件:NameHelper.java   
/**
 * Generate getter method name for property.
 *
 * @param propertyName
 * @param type
 * @param node
 * @return
 */
public String getGetterName(String propertyName, JType type, JsonNode node) {
    propertyName = getFieldName(propertyName, node);

    String prefix = type.equals(type.owner()._ref(boolean.class)) ? "is" : "get";
    propertyName = replaceIllegalCharacters(propertyName);
    String getterName = prefix + capitalize(capitalizeTrailingWords(propertyName));

    if (getterName.equals("getClass")) {
        getterName = "getClass_";
    }

    return getterName;
}
项目: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);
}
项目:dremio-oss    文件:ClassGenerator.java   
public HoldingContainer declare(CompleteType t, boolean includeNewInstance) {
  JType holderType = t.getHolderType(model);
  JVar var;
  if (includeNewInstance) {
    var = getEvalBlock().decl(holderType, "out" + index, JExpr._new(holderType));
  } else {
    var = getEvalBlock().decl(holderType, "out" + index);
  }
  index++;
  return new HoldingContainer(t, var, var.ref("value"), var.ref("isSet"));
}
项目:dremio-oss    文件:BaseFunctionHolder.java   
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]);
  }
}
项目:GitHub    文件:FormatRuleTest.java   
@Test
public void applyGeneratesTypeFromFormatValue() {
    TextNode formatNode = TextNode.valueOf(formatValue);

    JType result = rule.apply("fooBar", formatNode, new JCodeModel().ref(String.class), null);

    assertThat(result.fullName(), equalTo(expectedType.getName()));
}