package com.vst.webapp.action;
import com.vst.Constants;
import com.vst.util.FileHelper;
import com.vst.model.Hint;
import com.vst.service.HintManager;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.ResourceBundle;
public class HintController implements Controller {
private final Log log = LogFactory.getLog(HintController.class);
private HintManager hintManager = null;
public void setHintManager(HintManager hintManager) {
this.hintManager = hintManager;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering 'handleRequest' method...");
}
if (request.getParameter("edited") != null) {
request.setAttribute("addition", "?edited=1");
}
String pageNumber = request.getParameter("d-4004615-p");
if (pageNumber != null) {
request.setAttribute("pageNumber", "d-4004615-p=" + pageNumber);
}
if (request.getParameter("delete") != null) {
String hintId = request.getParameter("id");
ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources");
boolean hasFatalError = false;
try {
hintManager.removeHint(hintId);
request.setAttribute("message", bundle.getString("hint.deleted"));
} catch (Exception e) {
hasFatalError = true;
}
if (hasFatalError) {
request.setAttribute("errormessage", bundle.getString("commonMistake"));
}
}
List hints;
if (request.getParameter("isSearched") == null) {
hints = hintManager.getHints(null);
request.setAttribute("searchWord", "Укажите текст подсказки");
} else {
request.setAttribute("searchWord", request.getParameter("searchWord"));
Hint hint = new Hint();
hint.setContents(request.getParameter("searchWord"));
if (("1".equals(request.getParameter("byFragments")))) {
hint.setByFragments(true);
request.setAttribute("byFragments", "true");
}
hints = hintManager.findHintsByName(hint);
}
//retrieving all smal photoes from the DB blobs to the files on HD
for (int i = 0; i < hints.size(); i++) {
Hint curHint = (Hint) hints.get(i);
if (curHint.getWayToSmallPhoto() != null && !curHint.getWayToSmallPhoto().trim().equals("")) {
FileOutputStream fileOutputStream = new FileOutputStream(FileHelper.getCurrentPath(request) + curHint.getWayToSmallPhoto());
int c;
InputStream inputStream = curHint.getPhotoSmallBlob().getBinaryStream();
while ((c = inputStream.read()) != -1) {
fileOutputStream.write(c);
}
fileOutputStream.close();
}
}
return new ModelAndView("hintList", Constants.HINT_LIST, hints);
}
}