Package com.adaptrex.tools.webapp

Source Code of com.adaptrex.tools.webapp.GenerateService

package com.adaptrex.tools.webapp;

import static com.adaptrex.tools.Tools.CR;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.adaptrex.tools.Tools;
import com.adaptrex.tools.environment.Environment;
import com.adaptrex.tools.environment.IEnvironmentService;
import com.adaptrex.tools.framework.javascript.AdaptrexJS;
import com.adaptrex.tools.framework.javascript.ExtJS;
import com.adaptrex.tools.framework.javascript.JavaScriptFramework;
import com.adaptrex.tools.framework.javascript.SenchaTouch;
import com.adaptrex.tools.framework.orm.ORM;
import com.adaptrex.tools.framework.presentation.PresentationFramework;
import com.adaptrex.tools.log.ILogService;
import com.adaptrex.tools.log.Log;
import com.google.common.io.Files;
import com.google.inject.Inject;
import com.google.inject.Singleton;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Singleton
public class GenerateService implements IGenerateService {

  private IEnvironmentService environmentService;
  private ILogService logService;
  private IWebappService webappService;
 
  @Inject
  public GenerateService(IEnvironmentService environmentService, ILogService logService,
      IWebappService webappService) {
    this.environmentService = environmentService;
    this.logService = logService;
    this.webappService = webappService;
  }
 
  /*
   * Generate Page
   */
  @Override
  public boolean generatePage(Webapp webapp, String path, String namespace, String framework) throws IOException, TemplateException {
    if (path.endsWith(Tools.SLASH)) path = path.substring(0, path.length()-1);
    path = path.replace("\\", "/");
    String smwPath = webapp.getFullPath() + "/src/main/webapp";
   
    /*
     * Make sure we don't already have a page at the path
     */
    File pageFolder = new File(smwPath + "/" + path);
    if (pageFolder.exists()) {
      logService.log(Log.ERROR, "Page already exists", "A page at " + CR + path + " already exists");
      return false;
    }
   
    /*
     * Make sure we have a valid framework
     */
    if (!framework.equals(JavaScriptFramework.EXTJS) && !framework.equals(JavaScriptFramework.SENCHA_TOUCH)) {
      logService.log(Log.ERROR, "Invalid Framework",
          "You must specify either ext-js or sencha-touch for this page's framework");
      return false;
    }
    boolean isTouch = framework.equals(JavaScriptFramework.SENCHA_TOUCH);
   
    /*
     * Make sure the page uses a valid name
     */
    if (namespace.contains(".")) {
      logService.log(Log.ERROR, "Invalid Namespace",
          "The namespace must not contain a dot ( . )");
      return false;
    }
   
    /*
     * Create the app folder and template target
     */
    pageFolder.mkdirs();
    PageTemplateTarget target =
        new PageTemplateTarget(
          namespace, path,
          webapp.getName(), webapp.getBasePackage(), webapp.getGlobalNamespace(), webapp.getGlobalFolder(),
          webapp.getAdaptrex().getFolderName(), webapp.getExt().getFolderName(), webapp.getSenchaTouch().getFolderName(),
          webapp.getOrm(), webapp.getPresentation(), webapp.getDi()
        );
   
   
    /*
     * Add the page (first, figure out what type of presentation layer we have)
     */
    String view = webapp.getPresentation();
    if (view.equals("jsp")) {
      String tpl = "src/main/webapp/" + (isTouch ? "t/generic-touch" : "generic") + "-index.jsp.ftl";
      Files.write(processTemplate(tpl, target),
          new File(path + "/src/main/webapp/" + path + "index.jsp"));
    } else if (view.equals("jsf")) {
      String tpl = "src/main/webapp/" + (isTouch ? "t/generic-touch" : "generic") + "-index.xhtml.ftl";
      Files.write(processTemplate(tpl, target),
          new File(path + "/src/main/webapp/" + path + "index.xhtml"));
    } else if (view.equals("tapestry")) {
      String tml = "src/main/resources/package/pages/Generic" + (isTouch ? "Touch" : "") + "Page.tml.ftl";
      String java = "src/main/java/package/pages/GenericPage.java.ftl";
     
      String packagePath = webapp.getFullPath() + "/src/main/java/" + StringUtils.replace(webapp.getBasePackage(), ".", "/");
      String resourcePackagePath = webapp.getFullPath() + "/src/main/resources/" + StringUtils.replace(webapp.getBasePackage(), ".", "/");
     
      String basePath = path.contains(Tools.SLASH) ?
          StringUtils.substringBeforeLast(path, Tools.SLASH) + "/" : "";
      String className = StringUtils.capitalize(path.contains(Tools.SLASH) ?
          StringUtils.substringAfterLast(path, Tools.SLASH) : path);
     
      (new File(resourcePackagePath + "/pages/" + basePath)).mkdirs();
      (new File(packagePath + "/pages/" + basePath)).mkdirs();
     
      Files.write(processTemplate(tml, target),
          new File(resourcePackagePath + "/pages/" + basePath + className + ".tml"));
      Files.write(processTemplate(java, target),
          new File(packagePath + "/pages/" + basePath + className + ".java"));
    }
   
   
    /*
     * Add the app javascript
     */
    String appTpl = isTouch ? "t/generic-touch" : "index/generic";
    Files.write(processTemplate("src/main/webapp/" + appTpl + "-app.js.ftl", target),
        new File(smwPath + "/" + path + "/app.js"))
    (new File(smwPath + "/" + path + "/app/view")).mkdirs();
    (new File(smwPath + "/" + path + "/app/controller")).mkdirs();
   
    /*
     * Add the page to the webapp
     */
    webappService.importPage(webapp, path, namespace, framework);
    webappService.saveWebapp(webapp);
   
    logService.log(Log.SUCCESS, "Page Successfully Generated");
    return true;
  }
 
 
 
  /*
   * Generate Webapp
   */
  @Override
  public boolean generateWebapp(
      String title, String path, String basePackage, String globalNamespace, String globalFolder,
      String adaptrexVersion, String extFolder, String senchaTouchFolder,
      String ormFramework, String presentationFramework, String diFramework,
      String extTheme, String senchaTouchTheme)
          throws IOException, TemplateException {
    if (globalFolder == null) globalFolder = "common";
   
    /*
     * Process default frameworks
     */
    Environment env = environmentService.getEnvironment();
    if (adaptrexVersion.equals(JavaScriptFramework.DEFAULT)) {
      Map<String,AdaptrexJS> fw = env.getAdaptrexFrameworks();
      if (fw.size() == 1) {
        AdaptrexJS adaptrex = (AdaptrexJS) fw.get(fw.keySet().iterator().next());
        adaptrexVersion = adaptrex.getFolderName();
      }
    }
   
    if (extFolder.equals(JavaScriptFramework.DEFAULT)) {
      Map<String,ExtJS> fw = env.getExtFrameworks();
      if (fw.size() == 1) {
        ExtJS ext = (ExtJS) fw.get(fw.keySet().iterator().next());
        extFolder = ext.getFolderName();
      }
    }
   
    if (senchaTouchFolder.equals(JavaScriptFramework.DEFAULT)) {
      Map<String,SenchaTouch> fw = env.getSenchaTouchFrameworks();
      if (fw.size() == 1) {
        SenchaTouch senchaTouch = (SenchaTouch) fw.get(fw.keySet().iterator().next());
        senchaTouchFolder = senchaTouch.getFolderName();
      }
    }
   
   
    /*
     * Make sure we've got the required frameworks
     */
    List<String> missing = new ArrayList<String>();
    String missingString = StringUtils.join(missing, " and ");
    if (adaptrexVersion == null) missing.add("AdaptrexJS");
    if (extFolder == null && senchaTouchFolder == null) missing.add("ExtJS/Sencha Touch");
    if (missing.size() > 0) {
      logService.log(Log.ERROR, "Missing frameworks",
        "New webapps require" + CR + missingString + " folder(s)"
      );
      return false;
    }
   
   
    /*
     * Create the pojo to pass to the templates
     */
    WebappTemplateTarget target =
      new WebappTemplateTarget(title, basePackage, globalNamespace, globalFolder,
        adaptrexVersion, extFolder, senchaTouchFolder,
        ormFramework, presentationFramework, diFramework
      );
    String packagePath = "/src/main/java/" + StringUtils.replace(basePackage, ".", "/");
    String resourcePackagePath = "/src/main/resources/" + StringUtils.replace(basePackage, ".", "/");
   
   
    /*
     * Make sure existing folder doesn't already exist
     */
    File webappFolder = new File(path);
    if (webappFolder.exists()) {
      logService.log(Log.ERROR, "Webapp already exists at " + path);
      return false;
    }
   
    /*
     * Create folder structure
     */
    new File(path + "/src/main/webapp/WEB-INF").mkdirs();
    new File(path + "/src/main/webapp/adaptrex").mkdirs();
    new File(path + "/src/main/webapp/resources").mkdirs();
   
    new File(path + "/src/main/resources").mkdirs();
    new File(path + packagePath).mkdirs();
    new File(path + packagePath + "/rest").mkdirs();
    new File(path + packagePath + "/entities").mkdirs();
   
   
    /*
     * Create files
     */
    Files.write(processTemplate("pom.xml.ftl", target),
        new File(path + "/pom.xml"));
    Files.write(processTemplate(".project.ftl", target),
        new File(path + "/.project"));
    Files.write(processTemplate(".classpath.ftl", target),
        new File(path + "/.classpath"));

    Files.write(processTemplate("src/main/webapp/WEB-INF/web.xml.ftl", target),
        new File(path + "/src/main/webapp/WEB-INF/web.xml"));

    Files.write(processTemplate("src/main/resources/adaptrex.properties.ftl", target),
        new File(path + "/src/main/resources/adaptrex.properties"));
   
    /*
     * Create REST API
     */
    for (String rest : Arrays.asList("DirectorApi", "MovieApi", "PersonApi", "GenericRestBase", "TheaterApi")) {
      String targetRest = rest.contains("Generic") ? (title.replace(" ", "") + "RestBase") : rest;
      Files.write(processTemplate("src/main/java/package/rest/" + rest + ".java.ftl", target),
          new File(path + packagePath + "/rest/" + targetRest + ".java"));
    }
   
    /*
     * Tapestry
     */
    if (presentationFramework.equals(PresentationFramework.TAPESTRY)) {
      new File(path + packagePath + "/services").mkdirs();
      Files.write(processTemplate("src/main/java/package/services/GenericWebappModule.java.ftl", target),
          new File(path + packagePath + "/services/" +
              StringUtils.capitalize(target.getAppShortName()) + "Module.java"
          )
      );
    }
   
    /*
     * Tapestry Dependency Injection
     */
    if (diFramework != null && diFramework.equals(PresentationFramework.TAPESTRY)) {
      Files.write(processTemplate("src/main/java/package/services/AdaptrexService.java.ftl", target),
          new File(path + packagePath + "/services/AdaptrexService.java"));
      Files.write(processTemplate("src/main/java/package/services/IAdaptrexService.java.ftl", target),
          new File(path + packagePath + "/services/IAdaptrexService.java"));
    }   
   
    /*
     * Cayenne
     */
    if (ormFramework.equals(ORM.CAYENNE)) {
      Files.write(processTemplate("src/main/resources/cayenne-generic.xml.ftl", target),
          new File(path + "/src/main/resources/cayenne-" + target.getAppShortName() + ".xml"));
      Files.write(processTemplate("src/main/resources/generic.map.xml.ftl", target),
          new File(path + "/src/main/resources/" + target.getAppShortName() + ".map.xml"));
     
      new File(path + packagePath + "/entities/auto").mkdirs();
      for (String entity : Arrays.asList("Person", "Director", "GenericDatamap", "Movie", "Theater")) {
        String targetEntity = entity.contains("Generic") ? (title.replace(" ", "") + "Datamap") : entity;
       
        Files.write(processTemplate("src/main/java/package/entities/cayenne/" + entity + ".java.ftl", target),
            new File(path + packagePath + "/entities/" + targetEntity + ".java"));
        Files.write(processTemplate("src/main/java/package/entities/cayenne/auto/_" + entity + ".java.ftl", target),
            new File(path + packagePath + "/entities/auto/_" + targetEntity + ".java"));
      }
    }
   
    /*
     * JPA
     */
    if (ormFramework.equals(ORM.JPA)) {
      new File(path + "/src/main/resources/META-INF").mkdirs();
      Files.write(processTemplate("src/main/resources/META-INF/persistence.xml.ftl", target),
          new File(path + "/src/main/resources/META-INF/persistence.xml"));
     
      for (String entity : Arrays.asList("Person", "Director", "Movie", "Theater")) {
        Files.write(processTemplate("src/main/java/package/entities/jpa/" + entity + ".java.ftl", target),
            new File(path + packagePath + "/entities/" + entity + ".java"));
      }
    }

    /*
     * Copy common javascript
     */
    new File(path + "/src/main/webapp/" + globalFolder + "/view").mkdirs();
    for (String tpl : Arrays.asList("Utilities", "view/CommonHeader")) {
      Files.write(processTemplate("src/main/webapp/common/" + tpl + ".js.ftl", target),
          new File(path + "/src/main/webapp/" + globalFolder + "/" + tpl + ".js"));
    }
   
    /*
     * Copy favicon
     */
    URL srcIco = this.getClass().getClassLoader().getResource("templates/webapp/src/main/webapp/favicon.ico");
    File destIco = new File(path + "/src/main/webapp/favicon.ico");
    FileUtils.copyURLToFile(srcIco, destIco);
   
    /*
     * Create index page
     */
    if (extFolder != null) {
      new File(path + "/src/main/webapp/index/app/controller").mkdirs();
      new File(path + "/src/main/webapp/index/app/view").mkdirs();
     
      Files.write(processTemplate("src/main/webapp/index/app.js.ftl", target),
          new File(path + "/src/main/webapp/index/app.js"));
      Files.write(processTemplate("src/main/webapp/resources/sample.css.ftl", target),
          new File(path + "/src/main/webapp/resources/sample.css"));
     
      for (String tpl : Arrays.asList("controller/IndexController", "view/GrossSalesChart",
          "view/MovieFormPanel", "view/MovieGrid")) {
        Files.write(processTemplate("src/main/webapp/index/app/" + tpl + ".js.ftl", target),
            new File(path + "/src/main/webapp/index/app/" + tpl + ".js"));
      }
     
      /*
       * Tapestry
       */
      if (presentationFramework.equals(PresentationFramework.TAPESTRY)) {
        new File(path + packagePath + "/pages").mkdirs();
        new File(path + packagePath + "/components").mkdirs();
        new File(path + resourcePackagePath + "/pages").mkdirs();
        new File(path + resourcePackagePath + "/components").mkdirs();
       
        Files.write(processTemplate("src/main/java/package/pages/Index.java.ftl", target),
            new File(path + packagePath + "/pages/Index.java"));
        Files.write(processTemplate("src/main/resources/package/pages/Index.tml.ftl", target),
            new File(path + resourcePackagePath + "/pages/Index.tml"));
       
        Files.write(processTemplate("src/main/java/package/components/GenericLayout.java.ftl", target),
            new File(path + packagePath + "/components/" + target.getAppName() + "Layout.java"));
        Files.write(processTemplate("src/main/resources/package/components/GenericLayout.tml.ftl", target),
            new File(path + resourcePackagePath + "/components/" + target.getAppName() + "Layout.tml"));
     
      /*
       * JSP
       */
      } else if (presentationFramework.equals(PresentationFramework.JSP)) {
        Files.write(processTemplate("src/main/webapp/index.jsp.ftl", target),
            new File(path + "/src/main/webapp/index.jsp"));
       
      /*
       * JSF
       */
      } else if (presentationFramework.equals(PresentationFramework.JSF)) {
        Files.write(processTemplate("src/main/webapp/index.xhtml.ftl", target),
            new File(path + "/src/main/webapp/index.xhtml"))
      }
    }
   
    /*
     * Create touch page if we have sencha touch specified
     */
    if (senchaTouchFolder != null) {
      new File(path + "/src/main/webapp/t/app/profile").mkdirs();
      new File(path + "/src/main/webapp/t/app/controller/phone").mkdirs();
      new File(path + "/src/main/webapp/t/app/controller/tablet").mkdirs();
      new File(path + "/src/main/webapp/t/app/view/phone").mkdirs();
      new File(path + "/src/main/webapp/t/app/view/tablet").mkdirs();

      new File(path + "/src/main/webapp/" + globalFolder + "/view/phone").mkdirs();
      new File(path + "/src/main/webapp/" + globalFolder + "/view/tablet").mkdirs();
     
      for (String tpl : Arrays.asList("view/phone/TitleBar", "view/tablet/TitleBar")) {
        Files.write(processTemplate("src/main/webapp/common/" + tpl + ".js.ftl", target),
            new File(path + "/src/main/webapp/" + globalFolder + "/" + tpl + ".js"));
      }
     
      Files.write(processTemplate("src/main/webapp/t/app.js.ftl", target),
          new File(path + "/src/main/webapp/t/app.js"));
     
      for (String tpl : Arrays.asList(
          "controller/TouchController",
          "controller/phone/PhoneController", "controller/tablet/TabletController",
          "profile/Phone", "profile/Tablet", "view/phone/PhoneUI", "view/tablet/TabletUI",
          "view/GrossSalesChart", "view/MainUI", "view/MovieFormPanel", "view/MovieList"
        )) {
        Files.write(processTemplate("src/main/webapp/t/app/" + tpl + ".js.ftl", target),
            new File(path + "/src/main/webapp/t/app/" + tpl + ".js"));
      }
     
      /*
       * Tapestry
       */
      if (presentationFramework.equals(PresentationFramework.TAPESTRY)) {
        Files.write(processTemplate("src/main/java/package/pages/T.java.ftl", target),
            new File(path + packagePath + "/pages/T.java"));
        Files.write(processTemplate("src/main/resources/package/pages/T.tml.ftl", target),
            new File(path + resourcePackagePath + "/pages/T.tml"));
     
      /*
       * JSP
       */
      } else if (presentationFramework.equals(PresentationFramework.JSP)) {
        Files.write(processTemplate("src/main/webapp/t/index.jsp.ftl", target),
            new File(path + "/src/main/webapp/t/index.jsp"));
       
      /*
       * JSF
       */
      } else if (presentationFramework.equals(PresentationFramework.JSF)) {
        Files.write(processTemplate("src/main/webapp/t/index.xhtml.ftl", target),
            new File(path + "/src/main/webapp/t/index.xhtml"))
      }
    }
   
    /*
     * Import test data listener
     */
    new File(path + packagePath + "/servlet").mkdirs();
    Files.write(processTemplate("src/main/java/package/servlet/SampleDataContextListener.java.ftl", target),
        new File(path + packagePath + "/servlet/SampleDataContextListener.java"));
   
   
    /*
     * Import the webapp into our environment
     */
    Webapp webapp = environmentService.importWebapp(path, title,
        globalFolder, globalNamespace, basePackage,
        adaptrexVersion, extFolder, senchaTouchFolder,
        presentationFramework, ormFramework, diFramework, extTheme, senchaTouchTheme
        );
    if (webapp == null) return false;
   
   
    /*
     * Add framework and other webapp settings
     */
    webapp.setBasePackage(basePackage);
    webapp.setOrm(ormFramework);
    webapp.setPresentation(presentationFramework);
    webapp.setDi(diFramework);

    /*
     * Add our global framework to the webapp
     */
    if (globalNamespace == null) globalNamespace = target.getAppName();
    webapp.setGlobalNamespace(globalNamespace);
    webapp.setGlobalFolder(globalFolder);
   
   
    /*
     * Add the pages to the webapp
     */
    if (extFolder != null)
      webappService.importPage(webapp, "index", target.getAppName() + "Index", "extjs");
    if (senchaTouchFolder != null)
      webappService.importPage(webapp, "t", target.getAppName() + "Touch", "sencha-touch");

   
   
    /*
     * Save the webapp
     */
    webappService.saveWebapp(webapp);
   
   
    /*
     * Success log
     */
    logService.log(Log.SUCCESS, "Webapp \"" + title + "\" successfully generated");
   
    return true;
  }

 
 
 
 
  private byte[] processTemplate(String tpl, Object target) throws TemplateException, IOException {
    InputStream pomStream = this.getClass().getClassLoader().getResourceAsStream("templates/webapp/" + tpl);
    Scanner scanner = new Scanner(pomStream).useDelimiter("\\A");
      String tplString = scanner.hasNext() ? scanner.next() : "";
      Template template = new Template(tpl, new StringReader(tplString), new Configuration());
      Writer out = new StringWriter();
      template.process(target, out);
      return out.toString().getBytes();
  }
 
}
TOP

Related Classes of com.adaptrex.tools.webapp.GenerateService

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.