Java Code Examples for com.sun.codemodel.JType

The following are top voted examples for showing how to use com.sun.codemodel.JType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: Jsonschema2PojoRuleTest.java   View source code 9 votes vote down vote up
@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;
        }
    };
}
 
Example 2
Project: GitHub   File: EnumRule.java   View source code 7 votes vote down vote up
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

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

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

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

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

    // if string no need to add ""
    if(!isString(backingType)){
        expr = expr.plus(JExpr.lit(""));
    }

    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);

    ruleFactory.getAnnotator().enumCreatorMethod(fromValue);
}
 
Example 3
Project: GitHub   File: DefaultRule.java   View source code 7 votes vote down vote up
/**
 * 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;

}
 
Example 4
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
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;
}
 
Example 5
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: GitHub   File: EnumRule.java   View source code 6 votes vote down vote up
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());
        }
    }
}
 
Example 8
Project: GitHub   File: DefaultRule.java   View source code 6 votes vote down vote up
/**
 * 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;

}
 
Example 9
Project: QDrill   File: EvaluationVisitor.java   View source code 6 votes vote down vote up
@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);
}
 
Example 10
Project: dremio-oss   File: PartitionSenderOperator.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: QDrill   File: EvaluationVisitor.java   View source code 6 votes vote down vote up
@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);
}
 
Example 12
Project: GitHub   File: TypeRuleTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 13
Project: dremio-oss   File: EvaluationVisitor.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 14
Project: GitHub   File: SchemaMapper.java   View source code 5 votes vote down vote up
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));
    }
 
Example 15
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
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;
}
 
Example 16
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
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;
}
 
Example 17
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
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;
}
 
Example 18
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
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;
}
 
Example 19
Project: GitHub   File: CustomRuleFactoryIT.java   View source code 5 votes vote down vote up
@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);
        }
    };
}
 
Example 20
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
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));
}
 
Example 21
Project: GitHub   File: EnumRule.java   View source code 5 votes vote down vote up
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;
}
 
Example 22
Project: GitHub   File: DefaultRule.java   View source code 5 votes vote down vote up
/**
 * @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;

}
 
Example 23
Project: dremio-oss   File: TypeHelper.java   View source code 5 votes vote down vote up
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)));
  }
 
Example 24
Project: dremio-oss   File: BaseFunctionHolder.java   View source code 5 votes vote down vote up
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;
}
 
Example 25
Project: beanvalidation-benchmark   File: Util.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 26
Project: QDrill   File: ClassGenerator.java   View source code 5 votes vote down vote up
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);
}
 
Example 27
Project: GitHub   File: TypeRule.java   View source code 5 votes vote down vote up
private JType unboxIfNecessary(JType type, GenerationConfig config) {
    if (config.isUsePrimitives()) {
        return type.unboxify();
    } else {
        return type;
    }
}
 
Example 28
Project: GitHub   File: TypeRule.java   View source code 5 votes vote down vote up
/**
 * 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);
    }

}
 
Example 29
Project: GitHub   File: TypeRule.java   View source code 5 votes vote down vote up
/**
 * 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);
    }

}
 
Example 30
Project: GitHub   File: AdditionalPropertiesRule.java   View source code 5 votes vote down vote up
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);
}
 
Example 31
Project: QDrill   File: PartitionSenderRootExec.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 32
Project: QDrill   File: EvaluationVisitor.java   View source code 5 votes vote down vote up
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {

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

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

      // Only when the input is a reader, use writer interface to copy value.
      // Otherwise, input is a holder and we use vv mutator to set value.
      if (inputContainer.isReader()) {
        JType writerImpl = generator.getModel()._ref(
            TypeHelper.getWriterImpl(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;
    }
 
Example 33
Project: GitHub   File: ObjectRule.java   View source code 5 votes vote down vote up
private boolean isFinal(JType superType) {
    try {
        Class<?> javaClass = Class.forName(superType.fullName());
        return Modifier.isFinal(javaClass.getModifiers());
    } catch (ClassNotFoundException e) {
        return false;
    }
}
 
Example 34
Project: GitHub   File: ObjectRule.java   View source code 5 votes vote down vote up
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());
}
 
Example 35
Project: GitHub   File: NameHelper.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 36
Project: QDrill   File: EvaluationVisitor.java   View source code 5 votes vote down vote up
@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);
}
 
Example 37
Project: QDrill   File: EvaluationVisitor.java   View source code 5 votes vote down vote up
@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);
}
 
Example 38
Project: dremio-oss   File: ClassGenerator.java   View source code 5 votes vote down vote up
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"));
}
 
Example 39
Project: dremio-oss   File: BaseFunctionHolder.java   View source code 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 40
Project: GitHub   File: FormatRuleTest.java   View source code 5 votes vote down vote up
@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()));
}