001package jmri.web.servlet.roster;
002
003import java.io.IOException;
004import java.util.Collection;
005import java.util.LinkedList;
006import java.util.List;
007import javax.servlet.MultipartConfigElement;
008import javax.servlet.ServletException;
009import javax.servlet.http.HttpServletRequest;
010import javax.servlet.http.Part;
011import org.eclipse.jetty.server.Request;
012
013/**
014 * helper class for getting uploaded files which are returned as a list object
015 * based on examples at http://hmkcode.com/java-servlet-jquery-file-upload/ 
016 *
017 */
018public class MultipartRequestHandler {
019
020    private static final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement(System.getProperty("java.io.tmpdir"));
021
022    public static List<FileMeta> uploadByJavaServletAPI(HttpServletRequest request) throws IOException, ServletException {
023
024        List<FileMeta> files = new LinkedList<>();
025
026        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) {
027            request.setAttribute(Request.MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
028        }
029
030        // 1. Get all parts and the flag
031        Collection<Part> parts = request.getParts();
032        //set replace flag from parameter
033        boolean fileReplace = request.getParameter("fileReplace").equals("true");
034        //set replace flag from parameter
035        String rosterGroup = request.getParameter("rosterGroup");
036
037        // deal with each each part
038        FileMeta temp;
039        for (Part part : parts) {
040
041            // if part is multiparts "file"
042            if (part.getContentType() != null) {
043                
044                // populate a new FileMeta object
045                temp = new FileMeta();
046                temp.setFileName(getFilename(part));
047                temp.setFileSize(part.getSize() / 1024 + " Kb");
048                temp.setFileType(part.getContentType());
049                temp.setContent(part.getInputStream());
050                temp.setFileReplace(fileReplace);
051                temp.setRosterGroup(rosterGroup);
052
053                // 3.3 Add created FileMeta object to List<FileMeta> files
054                files.add(temp);
055
056            }
057        }
058        return files;
059    }
060
061    // this method is used to get file name out of request headers
062    // 
063    private static String getFilename(Part part) {
064        for (String cd : part.getHeader("content-disposition").split(";")) {
065            if (cd.trim().startsWith("filename")) {
066                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
067                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
068            }
069        }
070        return null;
071    }
072}