com.sccl.attech.generate.Generate.java Source code

Java tutorial

Introduction

Here is the source code for com.sccl.attech.generate.Generate.java

Source

/**
 * @(#)Generate.java     1.0 2015-7-15 16:41:49
 * Copyright 2015 bjth, Inc. All rights reserved.
 * myattech PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sccl.attech.generate;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sccl.attech.common.utils.DateUtils;
import com.sccl.attech.common.utils.FileUtils;
import com.sccl.attech.common.utils.FreeMarkers;
import com.sccl.attech.common.utils.IdGen;

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

/**
 * ??.
 * 
 * @author sccl
 * @version 2013-06-21
 */
public class Generate {

    /** The logger. */
    private static Logger logger = LoggerFactory.getLogger(Generate.class);

    /**
     * The main method.
     * 
     * @param args the arguments
     * @throws Exception the exception
     */
    public static void main(String[] args) throws Exception {

        // ==========  ?? ====================1412914

        // ??????
        // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}

        // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?
        String packageName = "com.sccl.attech.modules";

        String moduleName = "mobil"; // ???sys
        String subModuleName = ""; // ????? 
        String className = "updateApp"; // ??user
        List<GenerateField> fields = Lists.newArrayList();
        fields.add(new GenerateField("name", "??"));
        fields.add(new GenerateField("type", ""));
        fields.add(new GenerateField("version", ""));
        fields.add(new GenerateField("path", ""));

        String classAuthor = "zzz"; // zhaozz
        String functionName = "App?"; // ??

        // ???
        //Boolean isEnable = false;
        Boolean isEnable = true;

        // ==========  ?? ====================

        if (!isEnable) {
            logger.error("????isEnable = true");
            return;
        }

        if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className)
                || StringUtils.isBlank(functionName)) {
            logger.error("??????????????");
            return;
        }

        // ?
        String separator = File.separator;

        // ?
        File projectPath = new DefaultResourceLoader().getResource("").getFile();
        while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) {
            projectPath = projectPath.getParentFile();
        }
        logger.info("Project Path: {}", projectPath);

        // ?
        String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/sccl/attech/generate/template", "/",
                separator);
        logger.info("Template Path: {}", tplPath);

        // Java
        String javaPath = StringUtils.replaceEach(
                projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." },
                new String[] { separator, separator });
        logger.info("Java Path: {}", javaPath);

        // 
        String viewPath = StringUtils.replace(projectPath + "/WebRoot/pages", "/", separator);
        logger.info("View Path: {}", viewPath);
        String resPath = StringUtils.replace(projectPath + "/WebRoot/assets/js", "/", separator);
        logger.info("Res Path: {}", resPath);

        // ???
        Configuration cfg = new Configuration();
        cfg.setDefaultEncoding("UTF-8");
        cfg.setDirectoryForTemplateLoading(new File(tplPath));

        // ???
        Map<String, Object> model = Maps.newHashMap();
        model.put("packageName", StringUtils.lowerCase(packageName));
        model.put("moduleName", StringUtils.lowerCase(moduleName));
        model.put("fields", fields);
        model.put("subModuleName",
                StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : "");
        model.put("className", StringUtils.uncapitalize(className));
        model.put("ClassName", StringUtils.capitalize(className));
        model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools");
        model.put("classVersion", DateUtils.getDate());
        model.put("functionName", functionName);
        model.put("tableName",
                model.get("moduleName")
                        + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "")
                        + "_" + model.get("className"));
        model.put("urlPrefix",
                model.get("moduleName")
                        + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "")
                        + "/" + model.get("className"));
        model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
                model.get("urlPrefix"));
        model.put("permissionPrefix",
                model.get("moduleName")
                        + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "")
                        + ":" + model.get("className"));

        // ? Entity
        Template template = cfg.getTemplate("entity.ftl");
        String content = FreeMarkers.renderTemplate(template, model);
        String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator
                + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java";
        writeFile(content, filePath);
        logger.info("Entity: {}", filePath);

        // ? Dao
        template = cfg.getTemplate("dao.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator
                + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java";
        writeFile(content, filePath);
        logger.info("Dao: {}", filePath);

        // ? Service
        template = cfg.getTemplate("service.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator
                + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java";
        writeFile(content, filePath);
        logger.info("Service: {}", filePath);

        // ? Controller
        createJavaFile(subModuleName, separator, javaPath, cfg, model);

        // ? ViewForm
        template = cfg.getTemplate("viewForm.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
                + model.get("className") + "Form.html";
        writeFile(content, filePath);
        logger.info("ViewForm: {}", filePath);

        // ? ViewFormJs
        template = cfg.getTemplate("viewFormJs.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
                + model.get("className") + "FormCtrl.js";
        writeFile(content, filePath);
        logger.info("ViewFormJs: {}", filePath);

        // ? ViewList
        template = cfg.getTemplate("viewList.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
                + model.get("className") + "List.html";
        writeFile(content, filePath);
        logger.info("ViewList: {}", filePath);

        // ? ViewListJs
        template = cfg.getTemplate("viewListJs.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
                + model.get("className") + "ListCtrl.js";
        writeFile(content, filePath);
        logger.info("ViewList: {}", filePath);

        // ? ??sql
        template = cfg.getTemplate("sql.ftl");
        model.put("uid", IdGen.uuid());
        model.put("uid1", IdGen.uuid());
        content = FreeMarkers.renderTemplate(template, model);
        filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator
                + model.get("className") + ".sql";
        writeFile(content, filePath);
        logger.info("ViewList: {}", filePath);

        logger.info("Generate Success.");
    }

    /**
     *  java file.
     * 
     * @param subModuleName the sub module name
     * @param separator the separator
     * @param javaPath the java 
     * @param cfg the cfg
     * @param model the model
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private static void createJavaFile(String subModuleName, String separator, String javaPath, Configuration cfg,
            Map<String, Object> model) throws IOException {
        Template template;
        String content;
        String filePath;
        template = cfg.getTemplate("controller.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator
                + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java";
        writeFile(content, filePath);
        logger.info("Controller: {}", filePath);
    }

    /**
     * .
     * 
     * @param content the content
     * @param filePath the file 
     */
    public static void writeFile(String content, String filePath) {
        try {
            if (FileUtils.createFile(filePath)) {
                FileOutputStream fos = new FileOutputStream(filePath);
                Writer writer = new OutputStreamWriter(fos, "UTF-8");
                BufferedWriter bufferedWriter = new BufferedWriter(writer);
                bufferedWriter.write(content);
                bufferedWriter.close();
                writer.close();
            } else {
                logger.info("??");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}