/*
* 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.io.UnsupportedEncodingException;
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 display the cyclone development forecast web form.
* @author serch
*/
public class Pronostico implements Processor {
/** 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));
//System.out.println("colocando: "+key+" : "+datos.get(key));
}
}
//Put nhcLinks in map
BasicDBObject advice = MongoInterface.getInstance().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 pronostico saved and for tracking
if (advice != null && advice.get("pronostico") == null) {
if (prevIssue != null) {
BasicDBObject previous = MongoInterface.getInstance().getAdvice(prevIssue);
if (previous != null) {
//System.out.println("Putting previous data from "+prevIssue);
BasicDBObject forecastSection = (BasicDBObject) previous.get("pronostico");
if (forecastSection != null) {
//Set current values to previous values
datos.put("issueSateliteLocationImgFooter", forecastSection.getString("issueSateliteLocationImgFooter", ""));
}
}
}
}
request.setAttribute("data", datos);
request.setAttribute("bulletinType", parts[2]);
String url = "/jsp/forecast.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);
parametros.put(item.getFieldName(), filename);
} else {
//System.out.println("item:" + item.getFieldName() + "=" + item.getString());
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"), "UTF-8"));
} catch (UnsupportedEncodingException ue) {
//No debe llegar a este punto
assert false;
}
}
}
BasicDBObject anterior = (BasicDBObject)MongoInterface.getInstance().getAdvice(currentId).get(parts[3]);
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 {
GridFS gridfs = MongoInterface.getInstance().getImagesFS();
GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
gfsFile.setFilename(filename);
gfsFile.setContentType(item.getContentType());
gfsFile.save();
return filename;
}
/**
* 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("issueSateliteLocationImg")||"".equals(parametros.get("issueSateliteLocationImg").trim())){
if(null!=anterior && null!=anterior.getString("issueSateliteLocationImg")){
parametros.put("issueSateliteLocationImg", anterior.getString("issueSateliteLocationImg"));
}
}
}
}