001/**
002 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
003 *
004 * This file is part of Dicoogle/dicoogle.
005 *
006 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package pt.ua.dicoogle.server.web.servlets;
020
021import java.io.BufferedInputStream;
022import java.io.BufferedOutputStream;
023import java.io.File;
024import java.io.FileInputStream;
025import java.io.FileOutputStream;
026import java.io.IOException;
027import java.nio.file.Path;
028import java.util.*;
029
030import javax.servlet.ServletException;
031import javax.servlet.http.HttpServlet;
032import javax.servlet.http.HttpServletRequest;
033import javax.servlet.http.HttpServletResponse;
034
035import org.apache.commons.io.IOUtils;
036
037import net.sf.json.JSONArray;
038import net.sf.json.JSONException;
039import net.sf.json.JSONObject;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042import pt.ua.dicoogle.core.QueryExpressionBuilder;
043import pt.ua.dicoogle.core.query.ExportToCSVQueryTask;
044import pt.ua.dicoogle.plugins.PluginController;
045
046public class ExportCSVToFILEServlet extends HttpServlet {
047        private static final Logger logger = LoggerFactory.getLogger(ExportCSVToFILEServlet.class);
048
049        private final Path tempDirectory;
050        public ExportCSVToFILEServlet(Path tempDirectory) {
051                super();
052                this.tempDirectory = tempDirectory;
053        }
054
055        private static final long serialVersionUID = 1L;
056
057        @Override
058        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
059                        throws ServletException, IOException {
060                String uid = req.getParameter("UID");
061                if(uid == null){
062                        resp.sendError(401, "No Query UID Supplied: Please fill the field \"UID\"");
063                        return;
064                }
065                
066                File tmpFile = this.getCsvFile(uid);
067                if(!tmpFile.exists()){
068                        resp.sendError(402, "The file for the given uid was not found. Please try again...");
069                        return; 
070                }
071                
072                // Find this file id in database to get file name, and file type
073
074        // You must tell the browser the file type you are going to send
075        // for example application/pdf, text/plain, text/html, image/jpg
076        resp.setContentType("application/csv");
077        // Make sure to show the download dialog
078        resp.setHeader("Content-disposition","attachment; filename=QueryResultsExport.csv");            
079                
080                try (BufferedInputStream bi = new BufferedInputStream(new FileInputStream(tmpFile))) {
081
082                        IOUtils.copy(bi, resp.getOutputStream());
083                        resp.getOutputStream().flush();
084                }
085        }
086
087        @Override
088        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
089                        throws ServletException, IOException {
090                List<String> orderedFields = new ArrayList<>();
091                Map<String, String> fields = new HashMap<>();
092                String queryString = null;
093                String[] arr;           
094                boolean keyword;
095                
096                try {
097                        queryString = req.getParameter("query");
098                        if (queryString == null) {
099                                resp.sendError(402,
100                                                "QueryString not supplied: Please fill the field \"query\"");
101                                return;
102                        }
103
104                        System.out.println(req.getParameter("fields"));
105                        JSONArray jsonObj = new JSONArray().fromObject(req.getParameter("fields"));
106                        if (jsonObj.size()== 0) {
107                                resp.sendError(403,
108                                                "No fields supplied: Please fill the field \"extraFields\" in \"JSON\"");
109                                return;
110                        }
111
112                        for (Object f : jsonObj) {
113                                fields.put(f.toString(), f.toString());
114                                orderedFields.add(f.toString());
115                        }
116                        keyword = Boolean.parseBoolean(req.getParameter("keyword"));
117
118                        arr = req.getParameterValues("providers");
119                } catch (JSONException ex) {
120                        resp.sendError(400, "Invalid JSON content");
121                        return;
122                }
123                
124                if (!keyword) {
125            QueryExpressionBuilder q = new QueryExpressionBuilder(queryString);
126            queryString = q.getQueryString();
127        }
128
129                String uid = UUID.randomUUID().toString();
130                //File tempFile = File.createTempFile("QueryResultsExport-", uid, tempDirectory);
131                
132                File tempFile = this.getCsvFile(uid);
133                tempFile.deleteOnExit();
134                logger.debug("UID: {}", uid);
135                logger.debug("FilePath: {}", tempFile.getAbsolutePath());
136                
137                try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile))) {
138                        ExportToCSVQueryTask task = new ExportToCSVQueryTask(orderedFields,
139                                        bos);
140                        
141                        if (arr == null || arr.length ==0) {
142                                PluginController.getInstance().queryAll(task, queryString, fields);
143                        } else {
144                                List<String> providers = new ArrayList<>();
145                                for (Object f : arr) {
146                                        providers.add(f.toString());
147                                }
148                                PluginController.getInstance().query(task, providers, queryString,
149                                                fields);
150                        }
151
152                        task.await();
153                }
154                
155                JSONObject obj = new JSONObject();
156                obj.put("uid", uid);
157                resp.getWriter().write(obj.toString());
158                resp.getWriter().flush();
159        }
160
161        private File getCsvFile(String uid) {
162                return this.tempDirectory.resolve("QueryResultsExport-" + uid).toFile();
163        }
164}