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");
     */
  }
  private void createConstructorAndBuilder() {
    List<ExecutableElement> constructors = new ArrayList<ExecutableElement>();
    for (Element e : annotatedElement.getEnclosedElements()) {
      if (e.getKind() == CONSTRUCTOR) {
        constructors.add((ExecutableElement) e);
      }
    }

    for (ExecutableElement userConstructor : constructors) {
      JMethod copyConstructor = generatedClass.constructor(PUBLIC);
      JMethod staticHelper =
          generatedClass.method(PUBLIC | STATIC, generatedClass._extends(), "build");

      codeModelHelper.generifyStaticHelper(this, staticHelper, getAnnotatedElement());

      JBlock body = copyConstructor.body();
      JInvocation superCall = body.invoke("super");
      JInvocation newInvocation = JExpr._new(generatedClass);
      for (VariableElement param : userConstructor.getParameters()) {
        String paramName = param.getSimpleName().toString();
        JClass paramType = codeModelHelper.typeMirrorToJClass(param.asType(), this);
        copyConstructor.param(paramType, paramName);
        staticHelper.param(paramType, paramName);
        superCall.arg(JExpr.ref(paramName));
        newInvocation.arg(JExpr.ref(paramName));
      }

      JVar newCall = staticHelper.body().decl(generatedClass, "instance", newInvocation);
      staticHelper.body().invoke(newCall, getOnFinishInflate());
      staticHelper.body()._return(newCall);
      body.invoke(getInit());
    }
  }
Exemple #3
0
  /**
   * Creates the getter and setter methods on the supplied class for the supplied name.
   *
   * @param clazz to put getter and setter methods on
   * @param name of the property
   * @param syntaxType of the property
   * @param multivalue whether this property is a collection
   */
  protected void createMutators(
      final JDefinedClass clazz,
      final String name,
      final Class<?> syntaxType,
      final boolean multivalue) {
    final String upperName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
    if (multivalue) {
      final JClass detailClass = codeModel.ref(syntaxType);
      final JClass collectionClass = codeModel.ref(Collection.class);
      final JClass genericClass = collectionClass.narrow(detailClass);
      final JFieldVar field = clazz.field(JMod.PRIVATE, genericClass, name);
      final JMethod getterMethod = clazz.method(JMod.PUBLIC, genericClass, "get" + upperName);
      getterMethod.body()._return(field);

      final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName);
      setterMethod.param(genericClass, "c");
      setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("c"));

    } else {
      final JFieldVar field = clazz.field(JMod.PRIVATE, syntaxType, name);
      final JMethod getterMethod = clazz.method(JMod.PUBLIC, syntaxType, "get" + upperName);
      getterMethod.body()._return(field);

      final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName);
      setterMethod.param(syntaxType, "s");
      setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("s"));
    }
  }
Exemple #4
0
  private static JInvocation generateInvocation(Method method) {
    JInvocation generatedInvocation = JExpr.invoke(JExpr.invoke("getWrapped"), method.getName());

    for (Parameter parameter : method.getParameters()) {
      generatedInvocation.arg(JExpr.ref(parameter.getName()));
    }

    return generatedInvocation;
  }
  private static void processAccessors(
      JFieldVar fieldVar, JDefinedClass packetClass, boolean fromClient) {
    String name = WordUtils.capitalize(fieldVar.name());

    if (fromClient) {
      String methodName = "get" + name;
      JMethod getter = packetClass.method(JMod.PUBLIC, fieldVar.type(), methodName);
      getter.body()._return(fieldVar);
    } else {
      String methodName = "set" + name;
      JMethod setter = packetClass.method(JMod.PUBLIC, Void.TYPE, methodName);
      setter.param(fieldVar.type(), fieldVar.name());
      setter.body().assign(JExpr._this().ref(fieldVar.name()), JExpr.ref(fieldVar.name()));
    }
  }
  private JDefinedClass createResourceMethodReturnType(
      final String methodName, final Action action, final JDefinedClass resourceInterface)
      throws Exception {
    final JDefinedClass responseClass =
        resourceInterface
            ._class(capitalize(methodName) + "Response")
            ._extends(context.getResponseWrapperType());

    final JMethod responseClassConstructor = responseClass.constructor(JMod.PRIVATE);
    responseClassConstructor.param(javax.ws.rs.core.Response.class, "delegate");
    responseClassConstructor.body().invoke("super").arg(JExpr.ref("delegate"));

    for (final Entry<String, Response> statusCodeAndResponse : action.getResponses().entrySet()) {
      createResponseBuilderInResourceMethodReturnType(action, responseClass, statusCodeAndResponse);
    }

    return responseClass;
  }
  /** @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();
    }
  }
  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")));
  }
  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;
  }