1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package com.highdatas.mdm.controller;
 
import com.alibaba.fastjson.JSONObject;
import com.highdatas.mdm.entity.*;
import com.highdatas.mdm.mapper.SysViewMapper;
import com.highdatas.mdm.mapper.TableInfoMapper;
import com.highdatas.mdm.pojo.CodeMsg;
import com.highdatas.mdm.pojo.Result;
import com.highdatas.mdm.pojo.Segment;
import com.highdatas.mdm.pojo.kettle.UnBigDataDataSourceInfo;
import com.highdatas.mdm.service.*;
import com.highdatas.mdm.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * @author kimi
 * @description
 * @date 2019-12-18 10:22
 */
 
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    ISysAssembleDbService dbService;
    @Autowired
    ISysAssembleService assembleService;
    @Autowired
    ISysAssembleParamsService paramsService;
    @Autowired
    RedisClient redisClient;
    @Autowired
    ISysViewService viewService;
    @Autowired
    IMenuMappingService menuMappingService;
    @Autowired
    TableInfoMapper tableInfoMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    UnBigDataDataSourceInfo unBigDataDataSourceInfo;
 
    @RequestMapping(value = "/loadSqlTable", method = RequestMethod.POST)
    @ResponseBody
    public Result loadSqlTable(@RequestParam("file")MultipartFile file,@RequestParam String dbId, HttpServletRequest request) {
        try {
            byte[] bytes = file.getBytes();
 
            String sql = new String (bytes);
            sql = DbUtils.replaceEscape(sql);
            String[] split = sql.split(Constant.SEMICOLON);
            if (split.length > 1) {
                return Result.error(new CodeMsg(6001 , "sql脚本上传错误,仅能支持一条语句"));
            }
            String sqlId = DbUtils.getUUID();
            boolean b = redisClient.putRedisVal(sqlId, sql);
            if (!b){
                return Result.error(new CodeMsg(6002, "sql保存失败"));
            }
            // 暂不校验是不是select语句了  后续需要再校验
            List<String> fieldsBySql = dbService.getFieldsBySql(dbId, sql);
            JSONObject object = new JSONObject();
            object.fluentPut("fields", fieldsBySql);
            object.fluentPut("sqlId",sqlId);
 
            return Result.success(object);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(new CodeMsg(6002, e.getMessage()));
        }
 
    }
 
    @RequestMapping(value = "/loadPurgeSql", method = RequestMethod.POST)
    @ResponseBody
    public Result loadPurgeSql(@RequestParam("file")MultipartFile file,@RequestParam String id, HttpServletRequest request) {
        // 暂不校验是不是select语句了  后续需要再校验
        SysAssemble assemble = assembleService.selectById(id);
        if (assemble == null){
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        try {
            byte[] bytes = file.getBytes();
 
            String sql = new String (bytes);
            sql = DbUtils.replaceEscape(sql);
            //TODO 校验sql 暂不进行
            assemble.setPurgeSql(sql);
            boolean update = assemble.updateById();
            if (update) {
                return Result.success(assemble);
            }else {
                return Result.error(CodeMsg.UPDATE_ERROR);
            }
 
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(new CodeMsg(6002, e.getMessage()));
        }
 
    }
 
    @RequestMapping(value = "/loadParamsUpdateSql", method = RequestMethod.POST)
    @ResponseBody
    public Result loadParamsUpdateSql(@RequestParam("file")MultipartFile file,@RequestParam String id, HttpServletRequest request) {
        // 暂不校验是不是select语句了  后续需要再校验
        SysAssembleParams sysAssembleParams = paramsService.selectById(id);
        if (sysAssembleParams == null){
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        try {
            byte[] bytes = file.getBytes();
 
            String sql = new String (bytes);
            sql = DbUtils.replaceEscape(sql);
            //TODO 校验sql 暂不进行
            sysAssembleParams.setUpdateSql(sql).setUpdateTime(new Date()).updateById();
 
            return Result.success(sysAssembleParams);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(new CodeMsg(6002, e.getMessage()));
        }
 
    }
 
 
    @RequestMapping(value = "/loadMappingFile", method = RequestMethod.POST)
    @ResponseBody
    public Result loadMappingFile(@RequestParam("file")MultipartFile file,@RequestParam String id, @RequestParam String menuId, @RequestParam String field, HttpServletRequest request) {
 
        SysView sysView = viewService.selectById(id);
        if (sysView == null){
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        String mappingTable = sysView.getMappingTable();
        if (StringUtils.isEmpty(mappingTable)){
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        boolean exists = unBigDataDataSourceInfo.checkTableExists(mappingTable);
        if (!exists) {
            ArrayList<String> fields = new ArrayList<>();
            fields.add(Constant.ID);
            fields.add(Constant.Code);
            fields.add("pre");
            fields.add("fix");
            boolean created = unBigDataDataSourceInfo.createTable(mappingTable, fields);
            if (!created) {
                return Result.error(CodeMsg.CREATE_ERROR);
            }
        }
 
        SqlSession session = null;
        try {
            String name = file.getOriginalFilename();
            List<ViewMappingItem> viewMappingByExcel = ExcelUtil.getViewMappingByExcel(file.getInputStream(), name);
            if (viewMappingByExcel.isEmpty()) {
                return Result.error(CodeMsg.EMPTY_ERROR);
            }
            Maintain maintainByMenu = viewService.getMaintainByMenu(sysView, menuId);
            if (maintainByMenu == null) {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
            String changeFieldName = viewService.changeFieldName(maintainByMenu.getTableName(), field);
            Segment segment = new Segment(Constant.Code, changeFieldName);
            tableInfoMapper.delete(mappingTable, segment.toString());
            session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//关闭session的自动提交
 
            SysViewMapper mapper = session.getMapper(SysViewMapper.class);
            AtomicInteger idx = new AtomicInteger(0);
            ContentBuilder builder = new ContentBuilder(Constant.COMMA);
            for (ViewMappingItem viewMappingItem : viewMappingByExcel) {
                builder.clear();
                builder.append(DbUtils.quotedStr(changeFieldName));
                builder.append(DbUtils.quotedStr(viewMappingItem.getPre())).append(DbUtils.quotedStr(viewMappingItem.getFix()));
                mapper.insertViewMapping(mappingTable, builder.toString());
                int i = idx.get();
                if (i % 1000 == 0 || i == viewMappingByExcel.size()-1) {
                    //手动每1000个一提交,提交后无法回滚
                    session.commit();
                    session.clearCache();//注意,如果没有这个动作,可能会导致内存崩溃。
                }
                idx.getAndIncrement();
            }
 
        }catch (Exception e) {
            e.printStackTrace();
            if (session != null) {
                session.rollback();
            }
 
            return Result.error(new CodeMsg(6002, e.getMessage()));
        }finally {
            if (session != null) {
                session.close();
            }
        }
        return Result.success(null);
    }
}