예제 #1
0
  @Override
  public void generate(JDefinedClass cls, GenerationContext context) {
    if (classSpec.getFields().isEmpty()) {
      return; // No equals needed.
    }

    // Import the objects class, for hash coding.
    JClass objects = context.getTypeManager().getClassDirect("java.util.Objects");

    // Create the equals method.
    JMethod hashMethod = cls.method(JMod.PUBLIC, int.class, "hashCode");
    hashMethod.annotate(Override.class);
    JBlock body = hashMethod.body();

    // Check if the object is null.
    JVar hash = body.decl(JType.parse(context.getCodeModel(), "int"), "hash", JExpr.lit(3));

    // Do check for each field.
    for (DataFieldSpecification fieldSpec : classSpec.getFields()) {
      List<String> parts = NameFormat.namesToList(fieldSpec.getFieldName());
      String camelCaseFieldName = NameFormat.camelCase(parts, false);
      // Get the field value.
      JExpression thisField = JExpr.refthis(camelCaseFieldName);
      // Accumulate the hash code.
      JExpression fieldHashCode = objects.staticInvoke("hashCode").arg(thisField);

      body.assign(hash, JExpr.lit(79).mul(hash).plus(fieldHashCode));
    }

    // Return the processed hash value.
    body._return(hash);
  }
예제 #2
0
  private static void generateEnum() throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();
    JDefinedClass enumClass = codeModel._class("com.foo.Bar", ClassType.ENUM);
    // This code creates field within the enum class
    JFieldVar columnField = enumClass.field(JMod.PRIVATE | JMod.FINAL, String.class, "column");
    JFieldVar filterableField =
        enumClass.field(JMod.PRIVATE | JMod.FINAL, codeModel.BOOLEAN, "filterable");

    // Define the enum constructor
    JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE);
    enumConstructor.param(String.class, "column");
    enumConstructor.param(codeModel.BOOLEAN, "filterable");
    enumConstructor.body().assign(JExpr._this().ref("column"), JExpr.ref("column"));
    enumConstructor.body().assign(JExpr._this().ref("filterable"), JExpr.ref("filterable"));

    JMethod getterColumnMethod = enumClass.method(JMod.PUBLIC, String.class, "getColumn");
    getterColumnMethod.body()._return(columnField);
    JMethod getterFilterMethod = enumClass.method(JMod.PUBLIC, codeModel.BOOLEAN, "isFilterable");
    getterFilterMethod.body()._return(filterableField);

    JEnumConstant enumConst = enumClass.enumConstant("FOO_BAR");
    enumConst.arg(JExpr.lit("fooBar"));
    enumConst.arg(JExpr.lit(true));
    codeModel.build(new File("src"));
    /*
     * //creating an enum class within our main class JDefinedClass enumClass =
     * codeModel._class(JMod.PUBLIC, "REPORT_COLUMNS"); //This code creates
     * field within the enum class JFieldVar columnField =
     * enumClass.field(JMod.PRIVATE|JMod.FINAL, String.class, "column");
     * JFieldVar filterableField = enumClass.field(JMod.PRIVATE|JMod.FINAL,
     * codeModel.BOOLEAN, "filterable");
     */
  }
  /**
   * Sets up projection that will transfer all of the columns in batch, and also populate the
   * partition column based on which partition a record falls into in the partition table
   *
   * @param batch
   * @throws SchemaChangeException
   */
  protected void setupNewSchema(VectorAccessible batch) throws SchemaChangeException {
    container.clear();
    final ErrorCollector collector = new ErrorCollectorImpl();
    final List<TransferPair> transfers = Lists.newArrayList();

    final ClassGenerator<OrderedPartitionProjector> cg =
        CodeGenerator.getRoot(
            OrderedPartitionProjector.TEMPLATE_DEFINITION, context.getFunctionRegistry());

    for (VectorWrapper<?> vw : batch) {
      TransferPair tp = vw.getValueVector().getTransferPair();
      transfers.add(tp);
      container.add(tp.getTo());
    }

    cg.setMappingSet(mainMapping);

    int count = 0;
    for (Ordering od : popConfig.getOrderings()) {
      final LogicalExpression expr =
          ExpressionTreeMaterializer.materialize(
              od.getExpr(), batch, collector, context.getFunctionRegistry());
      if (collector.hasErrors())
        throw new SchemaChangeException(
            "Failure while materializing expression. " + collector.toErrorString());
      cg.setMappingSet(incomingMapping);
      ClassGenerator.HoldingContainer left = cg.addExpr(expr, false);
      cg.setMappingSet(partitionMapping);
      ClassGenerator.HoldingContainer right =
          cg.addExpr(
              new ValueVectorReadExpression(new TypedFieldId(expr.getMajorType(), count++)), false);
      cg.setMappingSet(mainMapping);

      LogicalExpression fh =
          FunctionGenerationHelper.getComparator(left, right, context.getFunctionRegistry());
      ClassGenerator.HoldingContainer out = cg.addExpr(fh, false);
      JConditional jc = cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      if (od.getDirection() == Direction.ASCENDING) {
        jc._then()._return(out.getValue());
      } else {
        jc._then()._return(out.getValue().minus());
      }
    }

    cg.getEvalBlock()._return(JExpr.lit(0));

    container.add(this.partitionKeyVector);
    container.buildSchema(batch.getSchema().getSelectionVectorMode());

    try {
      this.projector = context.getImplementationClass(cg);
      projector.setup(
          context, batch, this, transfers, partitionVectors, partitions, popConfig.getRef());
    } catch (ClassTransformationException | IOException e) {
      throw new SchemaChangeException("Failure while attempting to load generated class", e);
    }
  }
  protected HoldingContainer generateEvalBody(
      ClassGenerator<?> g, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) {

    // g.getBlock().directStatement(String.format("//---- start of eval portion of %s function.
    // ----//", functionName));

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;
    HoldingContainer out = null;
    MajorType returnValueType = returnValue.type;

    // add outside null handling if it is defined.
    if (nullHandling == NullHandling.NULL_IF_NULL) {
      JExpression e = null;
      for (HoldingContainer v : inputVariables) {
        if (v.isOptional()) {
          if (e == null) {
            e = v.getIsSet();
          } else {
            e = e.mul(v.getIsSet());
          }
        }
      }

      if (e != null) {
        // if at least one expression must be checked, set up the conditional.
        returnValueType = returnValue.type.toBuilder().setMode(DataMode.OPTIONAL).build();
        out = g.declare(returnValueType);
        e = e.eq(JExpr.lit(0));
        JConditional jc = sub._if(e);
        jc._then().assign(out.getIsSet(), JExpr.lit(0));
        sub = jc._else();
      }
    }

    if (out == null) out = g.declare(returnValueType);

    // add the subblock after the out declaration.
    g.getEvalBlock().add(topSub);

    JVar internalOutput =
        sub.decl(
            JMod.FINAL,
            g.getHolderType(returnValueType),
            returnValue.name,
            JExpr._new(g.getHolderType(returnValueType)));
    addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);
    if (sub != topSub)
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode
    sub.assign(out.getHolder(), internalOutput);
    if (sub != topSub)
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode
    return out;
  }
예제 #5
0
  private MSorter createNewMSorter(
      FragmentContext context,
      List<Ordering> orderings,
      VectorAccessible batch,
      MappingSet mainMapping,
      MappingSet leftMapping,
      MappingSet rightMapping)
      throws ClassTransformationException, IOException, SchemaChangeException {
    CodeGenerator<MSorter> cg =
        CodeGenerator.get(
            MSorter.TEMPLATE_DEFINITION, context.getFunctionRegistry(), context.getOptions());
    ClassGenerator<MSorter> g = cg.getRoot();
    g.setMappingSet(mainMapping);

    for (Ordering od : orderings) {
      // first, we rewrite the evaluation stack for each side of the comparison.
      ErrorCollector collector = new ErrorCollectorImpl();
      final LogicalExpression expr =
          ExpressionTreeMaterializer.materialize(
              od.getExpr(), batch, collector, context.getFunctionRegistry());
      if (collector.hasErrors()) {
        throw new SchemaChangeException(
            "Failure while materializing expression. " + collector.toErrorString());
      }
      g.setMappingSet(leftMapping);
      HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
      g.setMappingSet(rightMapping);
      HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
      g.setMappingSet(mainMapping);

      // next we wrap the two comparison sides and add the expression block for the comparison.
      LogicalExpression fh =
          FunctionGenerationHelper.getOrderingComparator(
              od.nullsSortHigh(), left, right, context.getFunctionRegistry());
      HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
      JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      if (od.getDirection() == Direction.ASCENDING) {
        jc._then()._return(out.getValue());
      } else {
        jc._then()._return(out.getValue().minus());
      }
      g.rotateBlock();
    }

    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));

    return context.getImplementationClass(cg);
  }
  public void build() {
    declareMethod();

    ExceptionWrapper mainTryBlock = new ExceptionWrapper(codeModel, method.body(), context);
    for (Integer arity : primitive.getArity()) {
      JInvocation invocation = invoke("doApply").arg(context).arg(environment);

      for (int i = 0; i < arity; ++i) {
        invocation.arg(args.component(lit(i)));
      }
      mainTryBlock
          .body()
          ._if(JExpr.direct("args.length").eq(JExpr.lit(arity)))
          ._then()
          ._return(invocation);
    }

    mainTryBlock.catchEvalExceptions();
    mainTryBlock.catchRuntimeExceptions();
    mainTryBlock.catchExceptions();

    method
        .body()
        ._throw(
            JExpr._new(codeModel.ref(EvalException.class))
                .arg(lit(primitive.getName() + ": max arity is " + primitive.getMaxArity())));
  }
예제 #7
0
  private void addResourcePath(JDefinedClass cls, Feed feed) {
    JFieldVar field = cls.field(privateStaticFinal, String.class, "RESOURCE_PATH");
    field.init(JExpr.lit(feed.getHref()));

    JMethod method = cls.method(JMod.PROTECTED | JMod.FINAL, String.class, "resourcePath");
    method.annotate(Override.class);
    method.body()._return(field);
  }
예제 #8
0
  private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls)
      throws JClassAlreadyExistsException, ClassNotFoundException {
    JDefinedClass bldrCls = cls._class(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, "Builder");
    JVar paramBuilder =
        bldrCls
            .field(JMod.PRIVATE | JMod.FINAL, immutableMapBldr, "params")
            .init(immutableMap.staticInvoke("builder"));

    for (Filter filter : feed.getFilters().getFilter()) {
      if (!Boolean.TRUE.equals(filter.isDeprecated())) {
        addWithersFor(filter, bldrCls, paramBuilder);
      }
    }

    if (feed.getMixins() != null && feed.getMixins().getMixin() != null) {
      JDefinedClass mixinEnum = getMixinEnum(feed);
      for (Mixin mixin : feed.getMixins().getMixin()) {
        String mixinName = mixin.getName().toUpperCase().replace(' ', '_');
        JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName);
        mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+')));
      }
      JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXIN");
      field.init(JExpr.lit("mixin"));
      JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins");
      JVar param = iterWither.param(iterable(mixinEnum), "mixins");
      JBlock mthdBody = iterWither.body();
      mthdBody.add(
          paramBuilder
              .invoke("put")
              .arg(field)
              .arg(immutableList.staticInvoke("copyOf").arg(param)));
      mthdBody._return(JExpr._this());
      JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins");
      param = varArgWither.varParam(mixinEnum, "mixins");
      varArgWither
          .body()
          ._return(JExpr.invoke(iterWither).arg(immutableList.staticInvoke("copyOf").arg(param)));
    }

    JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build");
    bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build")));

    // TODO: add sorts
    return bldrCls;
  }
예제 #9
0
 private void addWither(
     Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType)
     throws JClassAlreadyExistsException {
   JMethod method = createWitherMethod(filter, bldrCls);
   if (filter.getTitle() != null) {
     method.javadoc().add(String.format("<p>%s</p>", filter.getTitle()));
   }
   JVar param = addParam(filter, method, paramType);
   JBlock mthdBody = method.body();
   boolean needsNullCheck = true;
   if (filter.getMinValue() != null) {
     mthdBody.add(precs.staticInvoke("checkNotNull").arg(param));
     needsNullCheck = false;
     int min = filter.getMinValue().intValue();
     mthdBody.add(
         precs
             .staticInvoke("checkArgument")
             .arg(JExpr.lit(min).lte(param))
             .arg(JExpr.lit(param.name() + ": %s < " + min))
             .arg(param));
   }
   if (filter.getMaxValue() != null) {
     if (needsNullCheck) {
       mthdBody.add(precs.staticInvoke("checkNotNull").arg(param));
       needsNullCheck = false;
     }
     int max = filter.getMaxValue().intValue();
     mthdBody.add(
         precs
             .staticInvoke("checkArgument")
             .arg(JExpr.lit(max).gte(param))
             .arg(JExpr.lit(param.name() + ": %s > " + max))
             .arg(param));
   }
   JInvocation putIntoMap = paramBuilder.invoke("put").arg(field);
   if (needsNullCheck) {
     putIntoMap.arg(precs.staticInvoke("checkNotNull").arg(param));
   } else {
     putIntoMap.arg(param);
   }
   mthdBody.add(putIntoMap);
   mthdBody._return(JExpr._this());
 }
  private JInvocation buildScopeKey(InjectionNode injectionNode) {
    InjectionSignature signature = injectionNode.getTypeSignature();

    JClass injectionNodeClassRef = generationUtil.ref(injectionNode.getASTType());

    return codeModel
        .ref(ScopeKey.class)
        .staticInvoke(ScopeKey.GET_METHOD)
        .arg(injectionNodeClassRef.dotclass())
        .arg(JExpr.lit(signature.buildScopeKeySignature()));
  }
예제 #11
0
 /**
  * Creates the hashCode method on the supplied class. Leverages {@link
  * org.ldaptive.LdapUtils#computeHashCode(int, Object...)}.
  *
  * @param clazz to put hashCode method on
  */
 private void createHashCode(final JDefinedClass clazz) {
   final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class);
   final JInvocation computeHashCode = ldapUtilsClass.staticInvoke("computeHashCode");
   final JMethod hashCode = clazz.method(JMod.PUBLIC, int.class, "hashCode");
   hashCode.annotate(java.lang.Override.class);
   // CheckStyle:MagicNumber OFF
   computeHashCode.arg(JExpr.lit(7919));
   // CheckStyle:MagicNumber ON
   for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) {
     computeHashCode.arg(JExpr._this().ref(entry.getValue()));
   }
   hashCode.body()._return(computeHashCode);
 }
예제 #12
0
  private void generateComparisons(ClassGenerator<?> g, VectorAccessible batch)
      throws SchemaChangeException {
    g.setMappingSet(MAIN_MAPPING);

    for (Ordering od : popConfig.getOrderings()) {
      // first, we rewrite the evaluation stack for each side of the comparison.
      ErrorCollector collector = new ErrorCollectorImpl();
      final LogicalExpression expr =
          ExpressionTreeMaterializer.materialize(
              od.getExpr(), batch, collector, context.getFunctionRegistry());
      if (collector.hasErrors()) {
        throw new SchemaChangeException(
            "Failure while materializing expression. " + collector.toErrorString());
      }
      g.setMappingSet(LEFT_MAPPING);
      HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
      g.setMappingSet(RIGHT_MAPPING);
      HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
      g.setMappingSet(MAIN_MAPPING);

      // next we wrap the two comparison sides and add the expression block for the comparison.
      LogicalExpression fh =
          FunctionGenerationHelper.getOrderingComparator(
              od.nullsSortHigh(), left, right, context.getFunctionRegistry());
      HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
      JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));

      if (od.getDirection() == Direction.ASCENDING) {
        jc._then()._return(out.getValue());
      } else {
        jc._then()._return(out.getValue().minus());
      }
      g.rotateBlock();
    }

    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));
  }
  /**
   * Creates a copier that does a project for every Nth record from a VectorContainer incoming into
   * VectorContainer outgoing. Each Ordering in orderings generates a column, and evaluation of the
   * expression associated with each Ordering determines the value of each column. These records
   * will later be sorted based on the values in each column, in the same order as the orderings.
   *
   * @param sv4
   * @param incoming
   * @param outgoing
   * @param orderings
   * @return
   * @throws SchemaChangeException
   */
  private SampleCopier getCopier(
      SelectionVector4 sv4,
      VectorContainer incoming,
      VectorContainer outgoing,
      List<Ordering> orderings,
      List<ValueVector> localAllocationVectors)
      throws SchemaChangeException {
    final ErrorCollector collector = new ErrorCollectorImpl();
    final ClassGenerator<SampleCopier> cg =
        CodeGenerator.getRoot(SampleCopier.TEMPLATE_DEFINITION, context.getFunctionRegistry());

    int i = 0;
    for (Ordering od : orderings) {
      final LogicalExpression expr =
          ExpressionTreeMaterializer.materialize(
              od.getExpr(), incoming, collector, context.getFunctionRegistry());
      SchemaPath schemaPath = SchemaPath.getSimplePath("f" + i++);
      TypeProtos.MajorType.Builder builder =
          TypeProtos.MajorType.newBuilder()
              .mergeFrom(expr.getMajorType())
              .clearMode()
              .setMode(TypeProtos.DataMode.REQUIRED);
      TypeProtos.MajorType newType = builder.build();
      MaterializedField outputField = MaterializedField.create(schemaPath, newType);
      if (collector.hasErrors()) {
        throw new SchemaChangeException(
            String.format(
                "Failure while trying to materialize incoming schema.  Errors:\n %s.",
                collector.toErrorString()));
      }

      ValueVector vector = TypeHelper.getNewVector(outputField, oContext.getAllocator());
      localAllocationVectors.add(vector);
      TypedFieldId fid = outgoing.add(vector);
      ValueVectorWriteExpression write = new ValueVectorWriteExpression(fid, expr, true);
      HoldingContainer hc = cg.addExpr(write);
      cg.getEvalBlock()._if(hc.getValue().eq(JExpr.lit(0)))._then()._return(JExpr.FALSE);
    }
    cg.rotateBlock();
    cg.getEvalBlock()._return(JExpr.TRUE);
    outgoing.buildSchema(BatchSchema.SelectionVectorMode.NONE);
    try {
      SampleCopier sampleCopier = context.getImplementationClass(cg);
      sampleCopier.setupCopier(context, sv4, incoming, outgoing);
      return sampleCopier;
    } catch (ClassTransformationException | IOException e) {
      throw new SchemaChangeException(e);
    }
  }
예제 #14
0
  private static void processPacket(
      PacketType packet, JPackage dirPackage, JCodeModel codeModel, boolean fromClient)
      throws JClassAlreadyExistsException {
    // get the packet info
    String packetName =
        (packet.getInfo() == null || packet.getInfo().getName() == null)
            ? "Unknown"
            : packet.getInfo().getName();
    String packetNamePrefixed = "P" + String.format("%03d", packet.getHeader()) + "_" + packetName;
    String packetDescription =
        (packet.getInfo() == null
                || packet.getInfo().getDescription() == null
                || packet.getInfo().getDescription().isEmpty())
            ? ""
            : "\n" + WordUtils.wrap(packet.getInfo().getDescription(), /* maximumLength */ 50);

    JDefinedClass packetClass =
        dirPackage._class(JMod.FINAL | JMod.PUBLIC, packetNamePrefixed)._extends(GWMessage.class);

    LOGGER.info("+-Processing packet: {}", packetNamePrefixed);
    LOGGER.debug("|+-Packet description: {}", packetDescription);

    StringBuilder packetJavadoc =
        new StringBuilder("Auto-generated by PacketCodeGen.").append(packetDescription);

    JDocComment jDocComment = packetClass.javadoc();
    jDocComment.add(packetJavadoc.toString());

    AtomicInteger numberOfUnknowns = new AtomicInteger(); // unknown field number

    // get all fields in this packet
    for (FieldType field : packet.getField()) {
      processField(field, packetClass, codeModel, numberOfUnknowns, fromClient);
    }

    // generate the header method
    JMethod headerMeth = packetClass.method(JMod.PUBLIC, short.class, "getHeader");
    headerMeth.annotate(Override.class);
    headerMeth.body()._return(JExpr.lit(packet.getHeader().intValue()));

    // generate getters, setters
    for (JFieldVar fieldVar : packetClass.fields().values()) {
      processAccessors(fieldVar, packetClass, fromClient);
    }

    // generate the toString method
    processToString(packetClass, codeModel);
  }
예제 #15
0
  private void addWithersFor(Filter filter, JDefinedClass bldrCls, JVar paramBuilder)
      throws ClassNotFoundException, JClassAlreadyExistsException {
    JDefinedClass cls = (JDefinedClass) bldrCls.parentContainer();

    JFieldVar field =
        cls.field(privateStaticFinal, String.class, sanitize(filter.getName().toUpperCase()));
    field.init(JExpr.lit(filter.getName()));

    JClass paramType = mapType(filter);
    if (Boolean.TRUE.equals(filter.isMultipleValues())) {
      JMethod iterableWither = addIterableWither(filter, bldrCls, paramBuilder, field, paramType);
      addVarArgsWither(filter, iterableWither, bldrCls, paramType);
    } else {
      addWither(filter, bldrCls, paramBuilder, field, paramType);
    }
  }
예제 #16
0
  private void setupIsSame(ClassGenerator<StreamingAggregator> cg, LogicalExpression[] keyExprs) {
    cg.setMappingSet(IS_SAME_I1);
    for (final LogicalExpression expr : keyExprs) {
      // first, we rewrite the evaluation stack for each side of the comparison.
      cg.setMappingSet(IS_SAME_I1);
      final HoldingContainer first = cg.addExpr(expr, false);
      cg.setMappingSet(IS_SAME_I2);
      final HoldingContainer second = cg.addExpr(expr, false);

      final LogicalExpression fh =
          FunctionGenerationHelper.getOrderingComparatorNullsHigh(
              first, second, context.getFunctionRegistry());
      final HoldingContainer out = cg.addExpr(fh, false);
      cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE);
    }
    cg.getEvalBlock()._return(JExpr.TRUE);
  }
예제 #17
0
  private JClass getParamTypeEnum(Filter filter) throws JClassAlreadyExistsException {
    String enumName = camel(filter.getName(), true) + "Option";
    if (pkg.isDefined(enumName)) {
      return pkg._getClass(enumName);
    }
    List<Option> options = filter.getOption();
    if (options.size() == 1) {
      /*turn into '*Only' method?*/
    }
    if (options.size() == 2) {
      if (ImmutableSet.of("true", "false")
          .equals(
              ImmutableSet.of(
                  options.get(0).getValue().toLowerCase(),
                  options.get(1).getValue().toLowerCase()))) {
        return model.ref(Boolean.class);
      }
    }

    JDefinedClass valueEnum = pkg._enum(enumName);

    JFieldVar valField = valueEnum.field(JMod.PRIVATE | JMod.FINAL, String.class, "value");
    JMethod ctor = valueEnum.constructor(JMod.PRIVATE);
    JVar param = ctor.param(String.class, "val");
    ctor.body().assign(valField, param);

    JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString");
    toString.annotate(Override.class);
    toString.body()._return(valField);

    for (Option option : options) {
      String optionName = option.getValue().toUpperCase().replace(' ', '_');
      JEnumConstant optionCst = valueEnum.enumConstant(optionName);
      optionCst.arg(JExpr.lit(option.getValue().replace(' ', '+')));
    }
    return valueEnum;
  }
예제 #18
0
  /** @param args */
  public static void main(String[] args) {
    // Freemarker configuration object
    Configuration cfg = new Configuration();
    try {
      Document doc = Jsoup.parse(new File("./src/identification.html"), "UTF-8");

      // Load template from source folder
      Template template = cfg.getTemplate("src/com/convert/template/jsp/struts2.ftl");

      // Build the data-model
      Map<String, Object> data = new HashMap<String, Object>();
      final String pageName = "identification";

      data.put("pageName", pageName);

      // get select tags

      Elements selectTags = doc.getElementsByTag("select");
      for (Element selectTag : selectTags) {
        JCodeModel codeModel = new JCodeModel();
        String enumName = StringUtils.capitalize(selectTag.attr("id") + "Type");
        // String enumName=selectTag.attr("id")+"Type";
        System.out.println(enumName);
        JDefinedClass enumClass = codeModel._class("com.foo." + enumName, ClassType.ENUM);
        JFieldVar field1 = enumClass.field(JMod.PRIVATE | JMod.FINAL, String.class, "column");
        JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE);
        enumConstructor.param(String.class, "column");
        enumConstructor.body().assign(JExpr._this().ref("column"), JExpr.ref("column"));
        Elements options = selectTag.select("option");
        for (Element element : options) {
          String text = element.text();
          if (!text.contains("GenerateSelectHtml")) {

            JEnumConstant enumConst = enumClass.enumConstant(text.toUpperCase());
            enumConst.arg(JExpr.lit(text));
          }
        }
        String mehtodName = "get" + enumName;
        JMethod jmCreate =
            enumClass.method(
                JMod.PUBLIC | JMod.STATIC, java.util.ArrayList.class, "create" + mehtodName);
        JBlock jBlock = jmCreate.body();
        jBlock.directStatement(
            "List<String> list = new ArrayList<String>();"
                + " for (SalutationsType value : SalutationsType.values()) {"
                + "list.add(value.getSalutation());"
                + "} "
                + "return list");
        codeModel.build(new File("src"));
      }

      // generateEnum();

      Elements links = doc.getElementsByTag("script");
      data.put("javascripts", links);
      Elements styles = doc.getElementsByTag("link");
      data.put("styles", styles);
      // links.remove();
      Elements labels = doc.select("label");
      Properties prop = new Properties();
      OutputStream output = null;
      output = new FileOutputStream("config.properties");
      Template templateLabels = cfg.getTemplate("src/com/convert/template/label/struts2.ftl");
      for (Element label : labels) {
        if (label.hasText()) {
          String labelName = label.attr("for");
          String pageNameText = pageName + ".label." + labelName;
          prop.setProperty(pageNameText, label.text());
          data.put("labelName", label.text());
          StringWriter writer = new StringWriter();
          // Writer out = new OutputStreamWriter(System.out);
          templateLabels.process(data, writer);
          // out.flush();
          label.html(writer.getBuffer().toString());
        }
      }

      // save properties to project root folder
      prop.store(output, null);

      doc.select("script, style, meta, link, comment, CDATA, #comment").remove();
      // removeComments(doc);
      // doc.body().html().replaceAll("<body>", "").replaceAll("</body>",
      // "");

      data.put("body", doc.body().html().replaceAll("<body>", "").replaceAll("</body>", ""));
      /*
       * for (Element link : links) { System.out.println(link); }
       */

      // Console output
      /*
       * Writer out = new OutputStreamWriter(System.out); template.process(data,
       * out); out.flush();
       */
      // File output
      Writer file = new FileWriter(new File("FTL_helloworld.jsp"));
      template.process(data, file);
      file.flush();
      file.close();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TemplateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JClassAlreadyExistsException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 public void addDescribeContents(JDefinedClass jclass) {
   JMethod method = jclass.method(JMod.PUBLIC, int.class, "describeContents");
   method.body()._return(JExpr.lit(0));
 }
  public List<JVar> readIntent(
      List<? extends VariableElement> parameters,
      JBlock body,
      JVar intentParam,
      BaseAnnotationHandler handler)
      throws Exception {
    List<JVar> vars = new ArrayList<JVar>();

    for (VariableElement variableElement : parameters) {
      String type = variableElement.asType().toString();
      LOGGER.debug("var type:{} {}", variableElement.getSimpleName().toString(), type);
      JVar var = null;
      if (type.equals("java.lang.String")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getStringExtra")
                    .arg(variableElement.getSimpleName().toString()));
      } else if (type.equals("int")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getIntExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));

      } else if (type.equals("float")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getFloatExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));
      }
      if (type.equals("double")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getDoubleExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));
      }
      if (type.equals("char")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getCharExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit((char) 0)));
      } else if (type.equals("java.util.ArrayList<java.lang.Integer>")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getIntegerArrayListExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("java.util.ArrayList<java.lang.String>")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getStringArrayListExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("float[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getFloatArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("double[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getDoubleArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("char[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getCharArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("java.lang.String[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getStringArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("boolean[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getBooleanArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("boolean")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getBooleanExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(false)));

      } else if (type.equals("int[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getIntArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("long[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getLongArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("long")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getLongExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));

      } else if (type.equals("byte[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getByteArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("byte")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getByteExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));

      } else if (type.endsWith("[]")) {
        if (EntityHandler.isInterface(
            type.substring(0, type.length() - 2), "android.os.Parcelable")) {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getParcelableArrayExtra")
                          .arg(variableElement.getSimpleName().toString())));
        } else {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getSerializableExtra")
                          .arg(variableElement.getSimpleName().toString())));
        }
        // JConditional
        // parcel=body._if(JExpr._new(handler.refClass(type.substring(0,type.length()-2)))._instanceof(handler.refClass("android.os.Parcelable")));
        // parcel._then().assign(var,JExpr.cast(handler.refClass(type),
        //
        // intentParam.invoke("getParcelableArrayExtra").arg(variableElement.getSimpleName().toString())));
        // JConditional serializable=
        // parcel._else()._if(JExpr._new(handler.refClass(type.substring(0,type.length()-2)))._instanceof(handler.refClass("java.io.Serializable")));
        // serializable._then().assign(var,
        // JExpr.cast(handler.refClass(variableElement.asType().toString()),
        //
        // intentParam.invoke("getSerializableExtra").arg(variableElement.getSimpleName().toString())));

      } else if (type.startsWith("java.util.ArrayList")) {

        String clz = type.substring(type.indexOf('<') + 1, type.lastIndexOf('>'));
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                JExpr.cast(
                    handler.refClass("java.util.ArrayList").narrow(handler.refClass(clz)),
                    intentParam
                        .invoke("getSerializableExtra")
                        .arg(variableElement.getSimpleName().toString())));
      }
      if (var == null) {
        if (EntityHandler.isInterface(type, "android.os.Parcelable")) {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getParcelableExtra")
                          .arg(variableElement.getSimpleName().toString())));
        } else {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getSerializableExtra")
                          .arg(variableElement.getSimpleName().toString())));
        }
        // var=body.decl(handler.refClass(type),variableElement.getSimpleName().toString(),JExpr._new(handler.refClass(type)));
        // JConditional parcel=body._if(var._instanceof(handler.refClass("android.os.Parcelable")));
        // parcel._then().assign(var,JExpr.cast(handler.refClass(variableElement.asType().toString()),
        //
        // intentParam.invoke("getParcelableExtra").arg(variableElement.getSimpleName().toString())));

        // JConditional serializable=
        // parcel._else()._if(var._instanceof(handler.refClass("java.io.Serializable")));
        // serializable._then().assign(var,
        // JExpr.cast(handler.refClass(variableElement.asType().toString()),
        //
        // intentParam.invoke("getSerializableExtra").arg(variableElement.getSimpleName().toString())));
      }
      vars.add(var);
    }
    return vars;
  }
예제 #21
0
  public GeneratedClass createEnum(
      String namespace, String name, List<String> values, EnumBinding enumBinding)
      throws JClassAlreadyExistsException, NoSuchMethodException, IllegalAccessException,
          InvocationTargetException, InstantiationException {

    String className = NameConverter.smart.toClassName(name);
    if (enumBinding != null && !Utils.isEmpty(enumBinding.getClassName())) {
      className = enumBinding.getClassName();
    }

    String qualifiedClassName = targetPackage + "." + className;
    GeneratedClass generatedClass = generatedClasses.get(qualifiedClassName);
    if (generatedClass != null) {
      return generatedClass;
    }

    JDefinedClass enumClass = codeModel._class(JMod.PUBLIC, qualifiedClassName, ClassType.ENUM);
    generatedClass = new GeneratedClass(codeModel, enumClass);
    enumClass.annotate(Root.class).param("name", name);
    enumClass.annotate(Namespace.class).param("reference", namespace);

    if (enumBinding == null) {

      // create enumeration without any customization

      for (String enumConstant : values) {
        enumClass.enumConstant(enumConstant);
      }
    } else {

      // create enumeration with the bindings provided

      JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE);

      for (EnumAttribute enumAttribute : enumBinding.getAttributes()) {

        // constructor
        enumConstructor.param(enumAttribute.getTypeClz(), enumAttribute.getName());
        enumConstructor
            .body()
            .assign(JExpr._this().ref(enumAttribute.getName()), JExpr.ref(enumAttribute.getName()));

        // property
        JFieldVar attributeVar =
            enumClass.field(
                JMod.PRIVATE | JMod.FINAL, enumAttribute.getTypeClz(), enumAttribute.getName());

        // getter
        JMethod attributeMethod =
            enumClass.method(JMod.PUBLIC, enumAttribute.getTypeClz(), enumAttribute.getName());
        attributeMethod.body()._return(attributeVar);
      }

      for (EnumAttributeValue attributeValue : enumBinding.getAttributeValues()) {

        JEnumConstant enumConstant = enumClass.enumConstant(attributeValue.getKey());
        List<Object> attributeValues = attributeValue.getAttributes();
        int index = 0;
        for (Object attributeVal : attributeValues) {
          EnumAttribute enumAttribute = enumBinding.getAttributes().get(index);

          // todo - need to find a better way.
          if (enumAttribute.getTypeClz() == String.class) {

            enumConstant.arg(JExpr.lit((String) attributeVal));

          } else if (enumAttribute.getTypeClz() == Integer.class) {

            enumConstant.arg(JExpr.lit((Integer) attributeVal));

          } else if (enumAttribute.getTypeClz() == Float.class) {

            enumConstant.arg(JExpr.lit((Float) attributeVal));

          } else if (enumAttribute.getTypeClz() == Double.class) {

            enumConstant.arg(JExpr.lit((Double) attributeVal));

          } else if (enumAttribute.getTypeClz() == Short.class) {

            enumConstant.arg(JExpr.lit((Short) attributeVal));

          } else if (enumAttribute.getTypeClz() == Boolean.class) {

            enumConstant.arg(JExpr.lit((Boolean) attributeVal));

          } else if (enumAttribute.getTypeClz() == Character.class) {

            enumConstant.arg(JExpr.lit((Character) attributeVal));
          }

          index++;
        }
      }
    }

    generatedClasses.put(qualifiedClassName, generatedClass);
    return generatedClass;
  }
예제 #22
0
  private void createResponseBuilderInResourceMethodReturnType(
      final JDefinedClass responseClass,
      final int statusCode,
      final Response response,
      final MimeType responseMimeType)
      throws Exception {
    final String responseBuilderMethodName =
        Names.buildResponseMethodName(statusCode, responseMimeType);

    final JMethod responseBuilderMethod =
        responseClass.method(PUBLIC + STATIC, responseClass, responseBuilderMethodName);

    final JDocComment javadoc = responseBuilderMethod.javadoc();

    if (isNotBlank(response.getDescription())) {
      javadoc.add(response.getDescription());
    }

    if ((responseMimeType != null) && (isNotBlank(responseMimeType.getExample()))) {
      javadoc.add(EXAMPLE_PREFIX + responseMimeType.getExample());
    }

    JInvocation builderArgument =
        types
            .getGeneratorClass(javax.ws.rs.core.Response.class)
            .staticInvoke("status")
            .arg(JExpr.lit(statusCode));

    if (responseMimeType != null) {
      builderArgument =
          builderArgument
              .invoke("header")
              .arg(HttpHeaders.CONTENT_TYPE)
              .arg(responseMimeType.getType());
    }

    final StringBuilder freeFormHeadersDescription = new StringBuilder();

    for (final Entry<String, Header> namedHeaderParameter : response.getHeaders().entrySet()) {
      final String headerName = namedHeaderParameter.getKey();
      final Header header = namedHeaderParameter.getValue();

      if (headerName.contains(RESPONSE_HEADER_WILDCARD_SYMBOL)) {
        appendParameterJavadocDescription(header, freeFormHeadersDescription);
        continue;
      }

      final String argumentName = Names.buildVariableName(headerName);

      builderArgument =
          builderArgument.invoke("header").arg(headerName).arg(JExpr.ref(argumentName));

      addParameterJavaDoc(header, argumentName, javadoc);

      responseBuilderMethod.param(types.buildParameterType(header, argumentName), argumentName);
    }

    final JBlock responseBuilderMethodBody = responseBuilderMethod.body();

    final JVar builderVariable =
        responseBuilderMethodBody.decl(
            types.getGeneratorType(ResponseBuilder.class), "responseBuilder", builderArgument);

    if (freeFormHeadersDescription.length() > 0) {
      // generate a Map<String, List<Object>> argument for {?} headers
      final JClass listOfObjectsClass = types.getGeneratorClass(List.class).narrow(Object.class);
      final JClass headersArgument =
          types
              .getGeneratorClass(Map.class)
              .narrow(types.getGeneratorClass(String.class), listOfObjectsClass);

      builderArgument =
          responseBuilderMethodBody
              .invoke("headers")
              .arg(JExpr.ref(MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME))
              .arg(builderVariable);

      final JVar param =
          responseBuilderMethod.param(headersArgument, MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME);

      javadoc.addParam(param).add(freeFormHeadersDescription.toString());
    }

    if (responseMimeType != null) {
      responseBuilderMethodBody
          .invoke(builderVariable, "entity")
          .arg(JExpr.ref(GENERIC_PAYLOAD_ARGUMENT_NAME));
      responseBuilderMethod.param(
          types.getResponseEntityClass(responseMimeType), GENERIC_PAYLOAD_ARGUMENT_NAME);
      javadoc
          .addParam(GENERIC_PAYLOAD_ARGUMENT_NAME)
          .add(defaultString(responseMimeType.getExample()));
    }

    responseBuilderMethodBody._return(
        JExpr._new(responseClass).arg(builderVariable.invoke("build")));
  }