コード例 #1
0
ファイル: ScanHtml.java プロジェクト: InnovTeam/HtmlConverter
  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");
     */
  }
コード例 #2
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;
  }
コード例 #3
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;
  }
コード例 #4
0
ファイル: ScanHtml.java プロジェクト: InnovTeam/HtmlConverter
  /** @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();
    }
  }
コード例 #5
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;
  }