BController.java
10.3 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package com.bsth.controller.schedule;
import com.bsth.common.Constants;
import com.bsth.common.ResponseCode;
import com.bsth.entity.schedule.BEntity;
import com.bsth.entity.sys.SysUser;
import com.bsth.service.schedule.BService;
import com.bsth.service.schedule.exception.ScheduleException;
import com.bsth.service.schedule.utils.DataToolsFile;
import com.bsth.service.sys.SysUserService;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;
/**
* 基础控制器。
*/
public class BController<T, ID extends Serializable> {
@Autowired
protected BService<T, ID> bService;
@Autowired
private SysUserService sysUserService;
//---------------- CRUD 操作 ----------------//
// Create操作
@RequestMapping(method = RequestMethod.POST)
public Map<String, Object> save(@RequestBody T t, HttpSession httpSession) {
// 判定T是否是BEntity的子类,增加新的字段
String userName = String.valueOf(httpSession.getAttribute(Constants.SESSION_USERNAME));
SysUser sysUser = sysUserService.findByUserName(userName);
BEntity t_b = null;
if (t instanceof BEntity) {
Date cdate = new Date();
t_b = (BEntity) t;
t_b.setCreateBy(sysUser);
t_b.setCreateDate(cdate);
t_b.setUpdateBy(sysUser);
t_b.setUpdateDate(cdate);
}
T t_saved = bService.save(t_b == null ? t : (T) t_b);
Map<String, Object> rtn = new HashMap<>();
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("data", t_saved);
return rtn;
}
// Update操作
@RequestMapping(value="/{id}", method = RequestMethod.POST)
public Map<String, Object> update(@RequestBody T t, HttpSession httpSession) {
String userName = String.valueOf(httpSession.getAttribute(Constants.SESSION_USERNAME));
SysUser sysUser = sysUserService.findByUserName(userName);
BEntity t_b = null;
if (t instanceof BEntity) {
t_b = (BEntity) t;
t_b.setUpdateBy(sysUser);
t_b.setUpdateDate(new Date());
}
T t_updated = bService.save(t_b == null ? t : (T) t_b);
Map<String, Object> rtn = new HashMap<>();
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("data", t_updated);
return rtn;
}
// Research操作
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Map<String, Object> findById(@PathVariable("id") ID id) {
T t = bService.findById(id);
Map<String, Object> rtn = new HashMap<>();
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("data", t);
return rtn;
}
// 查询所有操作
@RequestMapping(value = "/all", method = RequestMethod.GET)
public Map<String, Object> list(@RequestParam Map<String, Object> param) {
List<T> tList = bService.list(param);
Map<String, Object> rtn = new HashMap<>();
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("data", tList);
return rtn;
}
// 分页查询操作
@RequestMapping(method = RequestMethod.GET)
public Map<String, Object> list(
@RequestParam Map<String, Object> map,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String order,
@RequestParam(defaultValue = "DESC") String direction) {
// 允许多个字段排序,order可以写单个字段,也可以写多个字段
// 多个字段格式:{col1},{col2},{col3},....,{coln}
if(StringUtils.isBlank(order)){
order = map.get("order").toString();
direction = map.get("direction").toString();
}
List<String> order_columns = Splitter.on(",").trimResults().splitToList(order);
// 多字段排序:DESC,ASC...
List<String> order_dirs = Splitter.on(",").trimResults().splitToList(direction);
Map<String, Object> rtn = new HashMap<>();
if (order_dirs.size() == 1) { // 所有字段采用一种排序
rtn.put("status", ResponseCode.SUCCESS);
if (order_dirs.get(0).equals("ASC")) {
rtn.put("data", bService.list(map, new PageRequest(page, size, new Sort(Sort.Direction.ASC, order_columns))));
} else {
rtn.put("data", bService.list(map, new PageRequest(page, size, new Sort(Sort.Direction.DESC, order_columns))));
}
} else if (order_columns.size() == order_dirs.size()) {
List<Sort.Order> orderList = new ArrayList<>();
for (int i = 0; i < order_columns.size(); i++) {
if (null != order_dirs.get(i) && order_dirs.get(i).equals("ASC")) {
orderList.add(new Sort.Order(Sort.Direction.ASC, order_columns.get(i)));
} else {
orderList.add(new Sort.Order(Sort.Direction.DESC, order_columns.get(i)));
}
}
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("data", bService.list(map, new PageRequest(page, size, new Sort(orderList))));
} else {
throw new RuntimeException("多字段排序参数格式问题,排序顺序和字段数不一致");
}
return rtn;
}
// Delete操作
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Map<String, Object> delete(@PathVariable("id") ID id, HttpSession httpSession) {
Map<String, Object> rtn = new HashMap<>();
try {
// 由于种种原因,这里不保存用户和操作时间了
bService.delete(id);
rtn.put("status", ResponseCode.SUCCESS);
} catch (ScheduleException exp) {
rtn.put("status", ResponseCode.ERROR);
rtn.put("msg", exp.getMessage());
}
return rtn;
}
//---------------- 数据服务操作 ----------------//
// 上传excel文件
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public Map<String, Object> uploadFile(MultipartFile file) {
Map<String, Object> rtn = new HashMap<>();
try {
DataToolsFile dataToolsFile = bService.uploadFile(file.getOriginalFilename(), file.getBytes());
// excel文件名
String fileName = dataToolsFile.getFile().getAbsolutePath();
Workbook wb = dataToolsFile.getFileType().getWorkBook(dataToolsFile.getFile());
// excel文件sheet
List<String> sheetnames = new ArrayList<>();
for (int i = 0; i < wb.getNumberOfSheets(); i ++) {
sheetnames.add(wb.getSheetAt(i).getSheetName());
}
wb.close();
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("filename", fileName);
rtn.put("sheetnames", StringUtils.join(sheetnames, ","));
} catch (Exception exp) {
exp.printStackTrace();
rtn.put("status", ResponseCode.ERROR);
rtn.put("msg", exp.getMessage());
}
return rtn;
}
// 导入excel文件
@RequestMapping(value = "/importFile", method = RequestMethod.POST)
public Map<String, Object> importFile(@RequestParam Map<String, Object> params) {
Map<String, Object> rtn = new HashMap<>();
try {
File file = new File(String.valueOf(params.get("filename")));
if (!file.exists()) {
throw new Exception("导入文件不存在!");
}
bService.importData(file, params);
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("msg", "导入文件成功");
} catch (Exception exp) {
rtn.put("status", ResponseCode.ERROR);
rtn.put("msg", exp.getMessage());
}
return rtn;
}
// 上传并导入excel文件
@RequestMapping(value = "/uploadAndImportFile", method = RequestMethod.POST)
public Map<String, Object> uploadAndImportFile(MultipartFile file) {
Map<String, Object> rtn = new HashMap<>();
try {
DataToolsFile dataToolsFile = bService.uploadFile(file.getOriginalFilename(), file.getBytes());
Map<String, Object> params = new HashMap<>();
bService.importData(dataToolsFile.getFile(), params);
rtn.put("status", ResponseCode.SUCCESS);
rtn.put("msg", "上传&导入文件成功");
} catch (Exception exp) {
exp.printStackTrace();
rtn.put("status", ResponseCode.ERROR);
rtn.put("msg", exp.getMessage());
}
return rtn;
}
// 导出数据到xls文件
@RequestMapping(value = "/exportFile", method = RequestMethod.GET)
public void exportFile(HttpServletResponse response,
@RequestParam Map<String, Object> params) throws Exception {
DataToolsFile dataToolsFile = bService.exportData(params);
// 流输出导出文件
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + dataToolsFile.getFile().getName());
response.setContentType("application/octet-stream");
OutputStream os = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
InputStream is = new FileInputStream(dataToolsFile.getFile());
BufferedInputStream bis = new BufferedInputStream(is);
int length = 0;
byte[] temp = new byte[1 * 1024 * 10];
while ((length = bis.read(temp)) != -1) {
bos.write(temp, 0, length);
}
bos.flush();
bis.close();
bos.close();
is.close();
}
}