疯狂的狮子li
2020-07-20 1e79d6f56fbd9a054800f1c62fd95bacda37c6b3
ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,345 @@
package com.ruoyi.generator.service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.mapper.GenTableColumnMapper;
import com.ruoyi.generator.mapper.GenTableMapper;
import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
/**
 * ä¸šåŠ¡ æœåŠ¡å±‚å®žçŽ°
 *
 * @author ruoyi
 */
@Service
public class GenTableServiceImpl implements IGenTableService
{
    private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);
    @Autowired
    private GenTableMapper genTableMapper;
    @Autowired
    private GenTableColumnMapper genTableColumnMapper;
    /**
     * æŸ¥è¯¢ä¸šåŠ¡ä¿¡æ¯
     *
     * @param id ä¸šåŠ¡ID
     * @return ä¸šåŠ¡ä¿¡æ¯
     */
    @Override
    public GenTable selectGenTableById(Long id)
    {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }
    /**
     * æŸ¥è¯¢ä¸šåŠ¡åˆ—è¡¨
     *
     * @param genTable ä¸šåŠ¡ä¿¡æ¯
     * @return ä¸šåŠ¡é›†åˆ
     */
    @Override
    public List<GenTable> selectGenTableList(GenTable genTable)
    {
        return genTableMapper.selectGenTableList(genTable);
    }
    /**
     * æŸ¥è¯¢æ®åº“列表
     *
     * @param genTable ä¸šåŠ¡ä¿¡æ¯
     * @return æ•°æ®åº“表集合
     */
    @Override
    public List<GenTable> selectDbTableList(GenTable genTable)
    {
        return genTableMapper.selectDbTableList(genTable);
    }
    /**
     * æŸ¥è¯¢æ®åº“列表
     *
     * @param tableNames è¡¨åç§°ç»„
     * @return æ•°æ®åº“表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames)
    {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }
    /**
     * ä¿®æ”¹ä¸šåŠ¡
     *
     * @param genTable ä¸šåŠ¡ä¿¡æ¯
     * @return ç»“æžœ
     */
    @Override
    @Transactional
    public void updateGenTable(GenTable genTable)
    {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = genTableMapper.updateGenTable(genTable);
        if (row > 0)
        {
            for (GenTableColumn cenTableColumn : genTable.getColumns())
            {
                genTableColumnMapper.updateGenTableColumn(cenTableColumn);
            }
        }
    }
    /**
     * åˆ é™¤ä¸šåŠ¡å¯¹è±¡
     *
     * @param tableIds éœ€è¦åˆ é™¤çš„æ•°æ®ID
     * @return ç»“æžœ
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(Long[] tableIds)
    {
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }
    /**
     * å¯¼å…¥è¡¨ç»“æž„
     *
     * @param tableList å¯¼å…¥è¡¨åˆ—表
     */
    @Override
    @Transactional
    public void importGenTable(List<GenTable> tableList)
    {
        String operName = SecurityUtils.getUsername();
        try
        {
            for (GenTable table : tableList)
            {
                String tableName = table.getTableName();
                GenUtils.initTable(table, operName);
                int row = genTableMapper.insertGenTable(table);
                if (row > 0)
                {
                    // ä¿å­˜åˆ—信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns)
                    {
                        GenUtils.initColumnField(column, table);
                        genTableColumnMapper.insertGenTableColumn(column);
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new CustomException("导入失败:" + e.getMessage());
        }
    }
    /**
     * é¢„览代码
     *
     * @param tableId è¡¨ç¼–号
     * @return é¢„览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId)
    {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // æŸ¥è¯¢è¡¨ä¿¡æ¯
        GenTable table = genTableMapper.selectGenTableById(tableId);
        // æŸ¥è¯¢åˆ—信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(table);
        // èŽ·å–æ¨¡æ¿åˆ—è¡¨
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // æ¸²æŸ“模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }
    /**
     * ç”Ÿæˆä»£ç 
     *
     * @param tableName è¡¨åç§°
     * @return æ•°æ®
     */
    @Override
    public byte[] generatorCode(String tableName)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
    /**
     * æ‰¹é‡ç”Ÿæˆä»£ç 
     *
     * @param tableNames è¡¨æ•°ç»„
     * @return æ•°æ®
     */
    @Override
    public byte[] generatorCode(String[] tableNames)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames)
        {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
    /**
     * æŸ¥è¯¢è¡¨ä¿¡æ¯å¹¶ç”Ÿæˆä»£ç 
     */
    private void generatorCode(String tableName, ZipOutputStream zip)
    {
        // æŸ¥è¯¢è¡¨ä¿¡æ¯
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // æŸ¥è¯¢åˆ—信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(table);
        // èŽ·å–æ¨¡æ¿åˆ—è¡¨
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // æ¸²æŸ“模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                // æ·»åŠ åˆ°zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
            zip.flush();
                zip.closeEntry();
            }
            catch (IOException e)
            {
                log.error("渲染模板失败,表名:" + table.getTableName(), e);
            }
        }
    }
    /**
     * ä¿®æ”¹ä¿å­˜å‚数校验
     *
     * @param genTable ä¸šåŠ¡ä¿¡æ¯
     */
    @Override
    public void validateEdit(GenTable genTable)
    {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSONObject.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
            {
                throw new CustomException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
            {
                throw new CustomException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
            {
                throw new CustomException("树名称字段不能为空");
            }
        }
    }
    /**
     * è®¾ç½®ä¸»é”®åˆ—信息
     *
     * @param table ä¸šåŠ¡è¡¨ä¿¡æ¯
     * @param columns ä¸šåŠ¡å­—æ®µåˆ—è¡¨
     */
    public void setPkColumn(GenTable table, List<GenTableColumn> columns)
    {
        for (GenTableColumn column : columns)
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(columns.get(0));
        }
    }
    /**
     * è®¾ç½®ä»£ç ç”Ÿæˆå…¶ä»–选项值
     *
     * @param genTable è®¾ç½®åŽçš„生成对象
     */
    public void setTableFromOptions(GenTable genTable)
    {
        JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj))
        {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
        }
    }
}