/*
* The MIT License (MIT)
*
* Copyright (c) 2014 México Abierto
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* For more information visit https://github.com/mxabierto/avisos.
*/
package mx.org.cedn.avisosconagua.engine.processors;
import com.mongodb.BasicDBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mx.org.cedn.avisosconagua.engine.Processor;
import mx.org.cedn.avisosconagua.exceptions.AvisosException;
import mx.org.cedn.avisosconagua.mongo.MongoInterface;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Workflow processor to gather primary information for the advice (actual situation, winds, seas, distance, etc.).
* @author serch
*/
public class Init implements Processor {
/** Mongo Interface object to gather information from **/
private static final MongoInterface mi = MongoInterface.getInstance();
/** Max allowed size for uploaded files **/
private static final int MAX_SIZE = 2 * 1024 * 1024;
@Override
public void invokeForm(HttpServletRequest request, HttpServletResponse response, BasicDBObject data, String parts[]) throws ServletException, IOException {
HashMap<String, String> datos = new HashMap<>();
String prevIssue = null;
if (null != data) {
for (String key : data.keySet()) {
datos.put(key, data.getString(key));
}
}
//Put nhcLinks in map and get advisory for tracking
BasicDBObject advice = mi.getAdvice((String) request.getSession(true).getAttribute("internalId"));
if (null != advice) {
//Get nhcLinks
BasicDBObject section = (BasicDBObject) advice.get("precapture");
if (null != section) {
datos.put("nhcForecastLink", section.getString("nhcForecastLink"));
datos.put("nhcPublicLink", section.getString("nhcPublicLink"));
prevIssue = section.getString("previousIssue");
}
}
//Advice without init saved and for tracking
if (advice != null && advice.get("init") == null) {
if (prevIssue != null) {
BasicDBObject previous = mi.getAdvice(prevIssue);
if (previous != null) {
//System.out.println("Putting previous data from "+prevIssue);
BasicDBObject initSection = (BasicDBObject) previous.get("init");
if (initSection != null) {
//Set current values to previous values
datos.put("eventDescriptionHTML", initSection.getString("eventDescriptionHTML", ""));
datos.put("areaDescription", initSection.getString("areaDescription", ""));
datos.put("eventRisk", initSection.getString("eventRisk", ""));
datos.put("eventComments", initSection.getString("eventComments", ""));
}
}
}
}
request.setAttribute("data", datos);
request.setAttribute("bulletinType", parts[2]);
String url = "/jsp/init.jsp";
if (parts[2].endsWith("dp")) {
url = "/jsp/initdp.jsp";
}
RequestDispatcher rd = request.getRequestDispatcher(url);
rd.forward(request, response);
}
@Override
public void processForm(HttpServletRequest request, String[] parts, String currentId) throws ServletException, IOException {
HashMap<String, String> parametros = new HashMap<>();
boolean fileflag = false;
AvisosException aex = null;
if (ServletFileUpload.isMultipartContent(request)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MAX_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_SIZE);
List<FileItem> items = upload.parseRequest(request);
String filename = null;
for (FileItem item : items) {
if (!item.isFormField() && item.getSize() > 0) {
filename = processUploadedFile(item, currentId);
//System.out.println("poniendo: "+ item.getFieldName() + "=" +filename);
parametros.put(item.getFieldName(), filename);
} else {
// System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1")));
// parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1")));
// System.out.println("item:" + item.getFieldName() + "=" + item.getString());
// System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"),"UTF-8"));
// System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1")));
// System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("UTF-8"),"UTF-8"));
parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1"), "UTF-8"));
}
}
} catch (FileUploadException fue) {
fue.printStackTrace();
fileflag = true;
aex = new AvisosException("El archivo sobrepasa el tamaño de " + MAX_SIZE + " bytes", fue);
}
} else {
for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
// try {
// parametros.put(entry.getKey(), new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1")));
// } catch (UnsupportedEncodingException ue) {
// //No debe llegar a este punto
// assert false;
// }
parametros.put(entry.getKey(), request.getParameter(entry.getKey()));
}
}
BasicDBObject anterior = (BasicDBObject) mi.getAdvice(currentId).get(parts[3]);
procesaAreas(parametros, anterior);
procesaImagen(parametros, anterior);
MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros);
if (fileflag) {
throw aex;
}
}
/**
* Processes an uploaded file and stores it in MongoDB.
* @param item file item from the parsed servlet request
* @param currentId ID for the current MongoDB object for the advice
* @return file name
* @throws IOException
*/
private String processUploadedFile(FileItem item, String currentId) throws IOException {
System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
GridFS gridfs = mi.getImagesFS();
String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
gridfs.remove(filename);
GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
gfsFile.setFilename(filename);
gfsFile.setContentType(item.getContentType());
gfsFile.save();
return filename;
}
/**
* Updates selected areas in the google map displayed in the web form.
* @param nuevo new advice properties
* @param anterior previous advice properties
*/
private void procesaAreas(HashMap<String, String> nuevo, BasicDBObject anterior) {
if (null != anterior) {
HashMap<String, String> cambios = new HashMap<>();
for (String key : nuevo.keySet()) {
if (key.startsWith("area-")) {
String states = "states" + key.substring(4);
String municipalities = "municipalities" + key.substring(4);
if (null == nuevo.get(states) || null == nuevo.get(municipalities)) {
if (((String) nuevo.get(key)).equals(anterior.get(key))) {
if (null != anterior.get(states)) {
cambios.put(states, (String) anterior.get(states));
}
if (null != anterior.get(municipalities)) {
cambios.put(municipalities, (String) anterior.get(municipalities));
}
}
}
}
}
if (!cambios.isEmpty()) {
nuevo.putAll(cambios);
}
}
}
/**
* Updates uploaded images from the web form.
* @param parametros new advice properties
* @param anterior previous advice properties
*/
private void procesaImagen(HashMap<String, String> parametros, BasicDBObject anterior) {
if (null == parametros.get("issueSateliteImg") || "".equals(parametros.get("issueSateliteImg").trim())) {
if (null != anterior && null != anterior.getString("issueSateliteImg")) {
System.out.println("Arreglando: issueSateliteImg=" + anterior.getString("issueSateliteImg"));
parametros.put("issueSateliteImg", anterior.getString("issueSateliteImg"));
}
}
}
}