package com.vst.webapp.action;
import com.vst.model.BuildingObject;
import com.vst.model.Loader;
import com.vst.service.BuildingObjectManager;
import com.vst.util.FileHelper;
import org.hibernate.Hibernate;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ResourceBundle;
/**
* Created by IntelliJ IDEA.
* User: ALEXEI
* Date: 03.11.2017
* Time: 14:26:40
* To change this template use File | Settings | File Templates.
*/
public class LoadTechnicalTaskController extends BaseFormController {
private BuildingObjectManager buildingObjectManager;
public void setBuildingObjectManager(BuildingObjectManager buildingObjectManager) {
this.buildingObjectManager = buildingObjectManager;
}
public LoadTechnicalTaskController() {
setCommandName("loader");
setCommandClass(Loader.class);
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
Loader loader = new Loader();
return loader;
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,
BindException errors)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering 'onSubmit' method...");
}
String buildingObjectId = request.getParameter("buildingObjectId");
// Loader loader = (Loader) command;
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
CommonsMultipartFile file =
(CommonsMultipartFile) multipartRequest.getFile("file");
if (file.getSize() > 0) {
InputStream inputStream = file.getInputStream();
String filename = FileHelper.getUniqueFileName(request);
OutputStream outputStream = new FileOutputStream(FileHelper.getCurrentPath(request) + filename);
int c;
while ((c = (inputStream.read())) != -1) {
outputStream.write(c);
}
BuildingObject buildingObject = buildingObjectManager.getBuildingObject(buildingObjectId);
buildingObject.setTechnicalTask(Hibernate.createBlob(new FileInputStream(FileHelper.getCurrentPath(request) + filename)));
File fileObject = new File(FileHelper.getCurrentPath(request) + filename);
buildingObject.setWayToTechnicalTask(fileObject.getName());
buildingObjectManager.saveBuildingObject(buildingObject);
} else {
request.setAttribute("noFile", "true");
return new ModelAndView("loadTechnicalTaskForm");
}
ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources");
request.setAttribute("message", bundle.getString("buildingObject.taskLoaded"));
return new ModelAndView("redirect:buildingObjects.html?objectId=" + buildingObjectId);
}
}