FileUploadController.java
20.1 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package com.myproject.webapp.controller;
import com.csvreader.CsvReader;
import com.myproject.Constants;
import com.myproject.bean.excel.BarcodeExcel;
import com.myproject.bean.excel.BomExcel;
import com.myproject.bean.excel.ComponentExcel;
import com.myproject.bean.excel.StoragePosExcel;
import com.myproject.bean.update.*;
import com.myproject.exception.ExcelParseException;
import com.myproject.exception.ValidateException;
import com.myproject.manager.*;
import com.myproject.poi.BarcodeXlsParser;
import com.myproject.poi.BomXlsParser;
import com.myproject.poi.ComponentXlsParser;
import com.myproject.util.PointUtil;
import com.myproject.util.StorageConstants;
import com.myproject.webapp.controller.webService.DataCache;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
/**
* Controller class to upload Files.
* <p/>
* <p>
* <a href="FileUploadFormController.java.html"><i>View Source</i></a>
* </p>
*
* @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
*/
@Controller
@RequestMapping("/storage/fileupload*")
public class FileUploadController extends BaseFormController {
@Autowired
private IComponentManager componentManager;
@Autowired
private IBarcodeManager barcodeManager;
@Autowired
private IStorageManager storageManager;
@Autowired
private IStoragePosManager storagePosManager;
@Autowired
private DataCache dataCache;
public FileUploadController() {
setCancelView("redirect:/home");
setSuccessView("uploadDisplay");
}
@ModelAttribute
@RequestMapping(method = RequestMethod.GET)
public FileUpload showForm() {
return new FileUpload();
}
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(
/** FileUpload fileUpload, BindingResult errors,*/ HttpServletRequest request) throws Exception {
String type = request.getParameter("type");
String param = request.getParameter("param");
if (request.getParameter("cancel") != null) {
return getCancelView();
}
// if (validator != null) { // validator is null during testing
// validator.validate(fileUpload, errors);
//
// if (errors.hasErrors()) {
// return "fileupload";
// }
// }
// validate a file was entered
// /*if (fileUpload.getFile().length == 0) {
// Object[] args = new Object[]{getText("uploadForm.file", request.getLocale())};
// errors.rejectValue("file", "errors.required", args, "File");
//
// return "fileupload";
// }*/
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
// the directory to upload to
String uploadDir = getServletContext().getRealPath("/resources");
// The following seems to happen when running jetty:run
if (uploadDir == null) {
uploadDir = new File("src/main/webapp/resources").getAbsolutePath();
}
uploadDir += "/" + request.getRemoteUser() + "/";
// Create the directory if it doesn't exist
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
//retrieve the file data
InputStream stream = file.getInputStream();
//write the file to the file specified
OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
//close the stream
stream.close();
// place the data into the request for retrieval on next page
request.setAttribute("friendlyName", request.getAttribute("name"));
request.setAttribute("fileName", file.getOriginalFilename());
request.setAttribute("contentType", file.getContentType());
request.setAttribute("size", file.getSize() + " bytes");
String fileURL = dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename();
request.setAttribute("location", fileURL);
String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
request.setAttribute("link", link + file.getOriginalFilename());
log.debug("Upload file is saved as: " + fileURL);
if (!StringUtils.isEmpty(type)) {
log.debug("Upload file type is: " + type);
try {
if (StorageConstants.COMPONENT.equals(type)) {
return handleComponent(fileURL);
} else if (StorageConstants.BARCODE_TYPE.equals(type)) {
return handleBarcode(fileURL);
} else if (StorageConstants.STORAGE_TYPE.equals(type)) {
String message = handleStoragePos(fileURL, param);
saveMessage(request,message);
}
} catch (ExcelParseException e) {
log.error(e);
log.error(e.getMessage());
saveError(request, e.getMessage());
} catch (IOException ioe) {
log.error(ioe);
log.error(ioe.getMessage());
saveError(request, getText("errors.upload.fileNotExist", request.getLocale()));
} catch (ValidateException ve) {
String errorMsg = getText(ve.getMessage(), ve.getParams(), request.getLocale());
log.error(ve);
log.error(errorMsg);
saveError(request, errorMsg);
} finally {
if (StorageConstants.COMPONENT.equals(type)) {
return StorageConstants.COMPONENT_SEARCH_VIEW;
} else if (StorageConstants.BARCODE_TYPE.equals(type)) {
return StorageConstants.BARCODE_SEARCH_VIEW;
} else if (StorageConstants.STORAGE_TYPE.equals(type)) {
return StorageConstants.STORAGE_UPDATE_VIEW + "?id=" + param;
}
}
}
return getSuccessView();
}
protected String handleComponent(String fileURL) throws ExcelParseException, IOException, ValidateException, IllegalAccessException, InvocationTargetException {
ComponentXlsParser componentXlsParser = new ComponentXlsParser();
List<ComponentExcel> list = componentXlsParser.readXls(fileURL);
log.debug("Parse component to list with size: " + list.size());
if (list != null && list.size() > 0) {
for (ComponentExcel componentExcel : list) {
Component component = componentManager.findOneByPn(componentExcel.getPartNumber());
if (component == null) {
component = new Component();
}
BeanUtils.copyProperties(component, componentExcel);
componentManager.save(component);
}
}
return StorageConstants.COMPONENT_SEARCH_VIEW;
}
protected String handleBarcode(String fileURL) throws ExcelParseException, IOException, ValidateException, IllegalAccessException, InvocationTargetException {
// BarcodeXlsParser barcodeXlsParser = new BarcodeXlsParser();
// List<BarcodeExcel> list = barcodeXlsParser.readXls(fileURL);
// log.debug("Parse barcode to list with size: " + list.size());
// if (list != null && list.size() > 0) {
// for (BarcodeExcel barcodeExcel : list) {
// Barcode barcode = barcodeManager.findByBarcode(barcodeExcel.getBarcode());
// if (barcode == null) {
// barcode = new Barcode();
// } else if (barcode.isUsed()) {
// log.error("Barcode: " + barcode.getBarcode() + " is already used, can't import again.");
// throw new ValidateException("barcode.error.used", new String[]{barcode.getBarcode()});
// }
// BeanUtils.copyProperties(barcode, barcodeExcel);
// barcode.setUsed(false);
// barcodeManager.save(barcode);
// }
// }
// return StorageConstants.BARCODE_SEARCH_VIEW;
log.info("开始更新条码信息");
// CsvReader csvRead = new CsvReader(fileURL);
// csvRead.setSkipEmptyRecords(true);//忽略空行
// csvRead.setTrimWhitespace(true);//去除空格
// csvRead.readHeaders();
CsvReader csvRead = CsvReader.newReader(fileURL,"PN");
int reelIdIndex = csvRead.getIndex("RI");
int partNumberIndex = csvRead.getIndex("PN");
if (partNumberIndex == -1){
log.info("未包含PN列");
return "必须包含PN列";
}
int qtyIndex = csvRead.getIndex("QTY");
if (qtyIndex == -1){
log.info("未包含【QTY】列");
return "必须包含【QTY】列";
}
int barcodeCount = 0;
while(csvRead.readRecord()){
String[] lineValues = csvRead.getValues();
String reelId = System.currentTimeMillis() + "";
if(reelIdIndex != -1){
String reelIdStr = lineValues[reelIdIndex];
if(reelIdStr != null && !reelIdStr.isEmpty()){
reelId = reelIdStr;
}
}
int qty = 1;
if(qtyIndex != -1){
try{
qty = Integer.valueOf(lineValues[qtyIndex]);
}catch (Exception e){
}
}
String partNumber = lineValues[partNumberIndex];
if(partNumber.isEmpty()){
log.warn("行[partNumber="+partNumber + ","+"reelId="+reelId+",qty="+qty+"]中PN 为空,此行忽略");
}else{
Component component = componentManager.findOneByPn(partNumber);
if(component == null){
log.info("未找到["+ partNumber+"]的档案,创建新的数量为["+qty+"]档案");
component = new Component();
component.setPartNumber(partNumber);
component.setAmount(qty);
component = componentManager.save(component);
}
Barcode barcode = barcodeManager.findByBarcode(reelId);
if(barcode == null){
barcode = new Barcode();
}
barcode.setBarcode(reelId);
barcode.setPartNumber(partNumber);
barcode.setInitialAmount(component.getAmount());
barcode.setAmount(qty);
barcodeManager.save(barcode);
barcodeCount++;
}
}
String msg = "操作完成,共保存["+barcodeCount+"]个条码信息";
log.info(msg);
return msg;
}
/**
*
* @param fileURL
* @param params
* @return
*/
protected String handleStoragePos(String fileURL, String params) throws ExcelParseException, IOException, ValidateException, IllegalAccessException, InvocationTargetException
{
log.info("开始更新料仓【"+params+"】的位置信息");
if (StringUtils.isEmpty(params)) {
log.error("Storage id is null");
throw new ValidateException("storage.error.notExist");
}
Storage storage = storageManager.get(params);
if (storage == null) {
log.error("Storage id is not exist");
throw new ValidateException("storage.error.notExist");
}
// CsvReader csvRead = new CsvReader(fileURL);
// csvRead.setSkipEmptyRecords(true);//忽略空行
// csvRead.setTrimWhitespace(true);//去除空格
// csvRead.readHeaders();
CsvReader csvRead = CsvReader.newReader(fileURL,"位置","pos");
int posIndex = csvRead.getIndex("位置");
if(posIndex == -1){
posIndex = csvRead.getIndex("pos");
if(posIndex == -1){
log.info("未包含【位置】或【pos】列");
return "必须包含[位置]列";
}
}
int priIndex = csvRead.getIndex("优先级");
if (priIndex == -1){
priIndex = csvRead.getIndex("pri");
if(priIndex == -1){
log.info("未包含【优先级】或【pri】列");
return "必须包含[优先级]列";
}
}
int hIndex = csvRead.getIndex("高度");
if (hIndex == -1){
hIndex = csvRead.getIndex("h");
if(hIndex == -1){
log.info("未包含【高度】或【h】列");
return "必须包含【高度】列";
}
}
int wIndex = csvRead.getIndex("宽度");
if (wIndex == -1){
wIndex = csvRead.getIndex("w");
if(wIndex == -1){
log.info("未包含【宽度】或【w】列");
return "必须包含【宽度】列";
}
}
List<StoragePosExcel> list = new ArrayList<StoragePosExcel>();
while(csvRead.readRecord()){
String[] lineValues = csvRead.getValues();
String posName = lineValues[posIndex];
String priorityStr = lineValues[priIndex];
String hStr = lineValues[hIndex];
String wStr = lineValues[wIndex];
if(posName.isEmpty() || priorityStr.isEmpty() || hStr.isEmpty() || wStr.isEmpty()){
log.warn("行[posName="+posName + ","+"priority="+priorityStr+",h="+hStr+",w="+wStr+"]中有空白内容,此行忽略");
}else{
StoragePosExcel posInfo = new StoragePosExcel();
posInfo.setPosName(posName);
posInfo.setPriority(Double.valueOf(priorityStr));
posInfo.setH(Integer.valueOf(hStr));
posInfo.setW(Integer.valueOf(wStr));
list.add(posInfo);
}
}
int newRowCount = 0;
int existRowCount=0;
int updateRowCount = 0;
List<StoragePos> storagePosList=storagePosManager.findByStorage(storage.getId());
List<StoragePos> newList=new ArrayList<>();
if (list != null && list.size() > 0) {
for (StoragePosExcel storagePosExcel : list) {
// StoragePos storagePos = storagePosManager.findByStorage(storage.getId(), storagePosExcel.getPosName());
StoragePos storagePos =findFormList(storagePosList,storage.getId(),storagePosExcel.getPosName());
if (storagePos == null) {
storagePos = new StoragePos();
newRowCount ++;
storagePos.setPosName(storagePosExcel.getPosName());
storagePos.setPriority(storagePosExcel.getPriority());
storagePos.setW(storagePosExcel.getW());
storagePos.setH(storagePosExcel.getH());
storagePos.setStorageId(storage.getId());
Point point= PointUtil.getPosPoint(storagePos.getPosName());
storagePos.setCoordinate(new double[]{point.getX(),point.getY()});
newList.add(storagePos);
}else{
boolean needUpdate=false;
if(!storagePos.getPosName().equals(storagePosExcel.getPosName())){
needUpdate=true;
storagePos.setPosName(storagePosExcel.getPosName());
}
// if(storagePos.getPriority()!=storagePosExcel.getPriority()) {
// needUpdate=true;
// storagePos.setPriority(storagePosExcel.getPriority());
// }
if(storagePos.getW()!=storagePosExcel.getW()) {
needUpdate=true;
storagePos.setW(storagePosExcel.getW());
}
if(storagePos.getH()!=storagePosExcel.getH()) {
needUpdate=true;
storagePos.setH(storagePosExcel.getH());
}
if(!storagePos.getStorageId().equals(storage.getId())){
needUpdate=true;
storagePos.setStorageId(storage.getId());
}
Point point= PointUtil.getPosPoint(storagePos.getPosName());
if(storagePos.getCoordinate()==null||storagePos.getCoordinate().length!=2||
(storagePos.getCoordinate()[0]!=point.getX()) ||(storagePos.getCoordinate()[1]!=point.getY())){
needUpdate=true;
storagePos.setCoordinate(new double[]{point.getX(),point.getY()});
}
if(needUpdate){
updateRowCount ++;
storagePosManager.save(storagePos);
}else{
existRowCount++;
}
}
}
if(newList.size()>0){
storagePosManager.insertAll(newList);
}
}
dataCache.reloadStorage(storage);
String msg = "读取到["+list.size()+"]个位置信息:新增【"+newRowCount+"】,已存在【"+existRowCount+"】,更新【" +updateRowCount +"】";
log.info(msg);
return msg;
}
private StoragePos findFormList(List<StoragePos> list,String storageId,String posName)
{
for (StoragePos pos :
list) {
if(pos.getStorageId().equals(storageId)&&pos.getPosName().equals(posName)){
return pos;
}
}
return null;
}
/*protected String handleStoragePos(String fileURL, String params) throws ExcelParseException, IOException, ValidateException, IllegalAccessException, InvocationTargetException {
if (StringUtils.isEmpty(params)) {
log.error("Storage id is null");
throw new ValidateException("storage.error.notExist");
}
Storage storage = storageManager.get(params);
if (storage == null) {
log.error("Storage id is not exist");
throw new ValidateException("storage.error.notExist");
}
StoragePosXlsParser storagePosXlsParser = new StoragePosXlsParser();
List<StoragePosExcel> list = storagePosXlsParser.readXls(fileURL);
log.debug("Parse storagePos to list with size: " + list.size());
if (list != null && list.size() > 0) {
for (StoragePosExcel storagePosExcel : list) {
StoragePos storagePos = storagePosManager.findByStorage(storage.getId(), storagePosExcel.getPosName());
if (storagePos == null) {
storagePos = new StoragePos();
}
BeanUtils.copyProperties(storagePos, storagePosExcel);
storagePos.setStorageId(storage.getId());
storagePosManager.save(storagePos);
}
}
return StorageConstants.STORAGE_UPDATE_VIEW + "?id=" + params;
}*/
public void setComponentManager(IComponentManager componentManager) {
this.componentManager = componentManager;
}
public void setBarcodeManager(IBarcodeManager barcodeManager) {
this.barcodeManager = barcodeManager;
}
public void setStorageManager(IStorageManager storageManager) {
this.storageManager = storageManager;
}
public void setStoragePosManager(IStoragePosManager storagePosManager) {
this.storagePosManager = storagePosManager;
}
}