Example usage for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator.

Prototype

public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.google.phonenumbers.PhoneNumberParserServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String phoneNumber = null;/* w  ww. j  a  v  a 2 s . c  o m*/
    String defaultCountry = null;
    String languageCode = "en"; // Default languageCode to English if nothing is entered.
    String regionCode = "";
    String fileContents = null;
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("phoneNumber")) {
                    phoneNumber = Streams.asString(in, "UTF-8");
                } else if (fieldName.equals("defaultCountry")) {
                    defaultCountry = Streams.asString(in).toUpperCase();
                } else if (fieldName.equals("languageCode")) {
                    String languageEntered = Streams.asString(in).toLowerCase();
                    if (languageEntered.length() > 0) {
                        languageCode = languageEntered;
                    }
                } else if (fieldName.equals("regionCode")) {
                    regionCode = Streams.asString(in).toUpperCase();
                }
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

    StringBuilder output;
    if (fileContents.length() == 0) {
        output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println("<html><head>");
        resp.getWriter()
                .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />");
        resp.getWriter().println("</head>");
        resp.getWriter().println("<body>");
        resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>");
        resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>");
        resp.getWriter().println("Language entered: " + languageCode
                + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>"));
    } else {
        output = getOutputForFile(defaultCountry, fileContents);
        resp.setContentType("text/html");
    }
    resp.getWriter().println(output);
    resp.getWriter().println("</body></html>");
}

From source file:ca.nrc.cadc.rest.SyncInput.java

public void init() throws IOException, ResourceNotFoundException {
    if (request.getMethod().equals("GET") || request.getMethod().equals("HEAD")
            || request.getMethod().equals("DELETE")) {
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            processParameter(name, request.getParameterValues(name));
        }//from  w  w  w.  j  a  v a 2 s.  c o  m
    } else {
        String contentType = request.getContentType();
        if (contentType != null) {
            int i = contentType.indexOf(';');
            if (i > 0)
                contentType = contentType.substring(0, i);
        }
        log.debug("Content-Type: " + contentType);
        if (contentType != null && contentType.equalsIgnoreCase(RestAction.URLENCODED)) {
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                processParameter(name, request.getParameterValues(name));
            }
        } else if (contentType != null && contentType.startsWith(RestAction.MULTIPART)) {
            try {
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator itemIterator = upload.getItemIterator(request);
                processMultiPart(itemIterator);
            } catch (FileUploadException ex) {
                throw new IOException("Failed to process " + RestAction.MULTIPART, ex);
            }
        } else {
            processStream(null, contentType, request.getInputStream());
        }
    }
}

From source file:edu.umn.msi.tropix.webgui.server.UploadController.java

@ServiceMethod(secure = true)
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    LOG.debug("In UploadController.handleRequest");
    //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId"));
    //Preconditions.checkState(userId != null);
    final String userId = userSession.getGridId();
    LOG.debug("Upload by user with id " + userId);
    String clientId = request.getParameter("clientId");
    if (!StringUtils.hasText(clientId)) {
        clientId = UUID.randomUUID().toString();
    }//from w w  w .  j  a v a  2 s. c o  m
    final String endStr = request.getParameter("end");
    final String startStr = request.getParameter("start");
    final String zipStr = request.getParameter("zip");

    final String lastUploadStr = request.getParameter("lastUpload");
    final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false;
    final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true;

    LOG.trace("Upload request with startStr " + startStr);
    final StringWriter rawJsonWriter = new StringWriter();
    final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter);
    final FileItemFactory factory = new DiskFileItemFactory();

    final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr)
            : request.getContentLength();
    long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L;

    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8"); // Deal with international file names
    final FileItemIterator iter = upload.getItemIterator(request);

    // Setup message conditionalSampleComponent to track upload progress...
    final ProgressMessageSupplier supplier = new ProgressMessageSupplier();
    supplier.setId(userId + "/" + clientId);
    supplier.setName("Upload File(s) to Web Application");

    final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl();
    progressTracker.setUserGridId(userId);
    progressTracker.setCometPusher(cometPusher);
    progressTracker.setProgressMessageSupplier(supplier);

    jsonWriter.object();
    jsonWriter.key("result");
    jsonWriter.array();

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        if (item.isFormField()) {
            continue;
        }
        File destination;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        if (!isZip) {
            final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName();
            LOG.debug("Handling upload of file with name " + fileName);

            final TempFileInfo info = tempFileStore.getTempFileInfo(fileName);
            recordJsonInfo(jsonWriter, info);
            destination = info.getTempLocation();
        } else {
            destination = FILE_UTILS.createTempFile();
        }

        try {
            inputStream = item.openStream();
            outputStream = FILE_UTILS.getFileOutputStream(destination);
            bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength,
                    progressTracker);

            if (isZip) {
                ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() {
                    public File apply(final String fileName) {
                        final String cleanedUpFileName = FilenameUtils.getName(fileName);
                        final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName);
                        recordJsonInfo(jsonWriter, info);
                        return info.getTempLocation();
                    }
                });
            }
        } finally {
            IO_UTILS.closeQuietly(inputStream);
            IO_UTILS.closeQuietly(outputStream);
            if (isZip) {
                FILE_UTILS.deleteQuietly(destination);
            }
        }
    }
    if (lastUploads) {
        progressTracker.complete();
    }
    jsonWriter.endArray();
    jsonWriter.endObject();
    // response.setStatus(200);
    final String json = rawJsonWriter.getBuffer().toString();
    LOG.debug("Upload json response " + json);
    response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this
    response.getOutputStream().println(json);
    return null;
}

From source file:market.servlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  www  . java 2 s  . c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    response.setContentType("xml");
    PrintWriter out = response.getWriter();
    String user = request.getParameter("user");
    String fileContents = "";

    try {
        /*capture submitted data*/
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();

            if (item.isFormField()) {
                /*do nothing*/
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                    //                                        MarketParser parser = new MarketParser(fileContents);
                    new MarketHandler(fileContents, user);
                    response.sendRedirect("./home");
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (SizeLimitExceededException e) {
        out.println("You exceeded the maximu size (" + e.getPermittedSize() + ") of the file ("
                + e.getActualSize() + ")");
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sifiso.yazisa.util.PhotoUtil.java

public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil)
        throws FileUploadException {
    logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n");
    ResponseDTO resp = new ResponseDTO();
    InputStream stream = null;/*from   w w w. jav a  2 s  .c  o m*/
    File rootDir;
    try {
        rootDir = YazisaProperties.getImageDir();
        logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath());
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Properties file problem", ex);
        resp.setMessage("Server file unavailable. Please try later");
        resp.setStatusCode(114);

        return resp;
    }

    PhotoUploadDTO dto = null;
    Gson gson = new Gson();
    File schoolDir = null, classDir = null, parentDir = null, teacherDir = null, studentDir = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            stream = item.openStream();
            if (item.isFormField()) {
                if (name.equalsIgnoreCase("JSON")) {
                    String json = Streams.asString(stream);
                    if (json != null) {
                        logger.log(Level.INFO, "picture with associated json: {0}", json);
                        dto = gson.fromJson(json, PhotoUploadDTO.class);
                        if (dto != null) {
                            if (dto.getSchoolID() > 0) {
                                schoolDir = createSchoolDirectory(rootDir, schoolDir, dto.getSchoolID());
                            }

                            if (dto.getClassID() > 0) {
                                classDir = createClassDirectory(schoolDir, classDir, dto.getClassID());
                            }
                            if (dto.getParentID() > 0) {
                                parentDir = createParentDirectory(schoolDir, parentDir);
                            }
                            if (dto.getTeacherID() > 0) {
                                teacherDir = createTeacherDirectory(schoolDir, teacherDir);
                            }
                            if (dto.getStudentID() > 0) {
                                studentDir = createStudentDirectory(rootDir, studentDir);
                            }
                        }
                    } else {
                        logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL..");
                    }
                }
            } else {
                File imageFile = null;
                if (dto == null) {
                    continue;
                }
                DateTime dt = new DateTime();
                String fileName = "";
                if (dto.isIsFullPicture()) {
                    fileName = "f" + dt.getMillis() + ".jpg";
                } else {
                    fileName = "t" + dt.getMillis() + ".jpg";
                }
                if (dto.getSchoolID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getSchoolID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getSchoolID() + ".jpg";
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getTeacherID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getTeacherID() + ".jpg";
                        } else {
                            fileName = "t" + dto.getTeacherID() + ".jpg";
                        }
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getClassID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getClassID() + "-" + new Date().getYear() + ".jpg";
                        } else {
                            fileName = "t" + dto.getClassID() + "-" + new Date().getYear() + ".jpg";
                        }
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getParentID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getParentID() + ".jpg";
                        } else {
                            fileName = "t" + dto.getParentID() + ".jpg";
                        }
                    }
                }

                if (dto.getStudentID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getStudentID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getStudentID() + ".jpg";
                    }
                }

                //
                switch (dto.getPictureType()) {
                case PhotoUploadDTO.SCHOOL_IMAGE:
                    imageFile = new File(schoolDir, fileName);
                    break;
                case PhotoUploadDTO.CLASS_IMAGE:
                    imageFile = new File(classDir, fileName);
                    break;
                case PhotoUploadDTO.PARENT_IMAGE:
                    imageFile = new File(parentDir, fileName);
                    break;
                case PhotoUploadDTO.STUDENT_IMAGE:
                    imageFile = new File(studentDir, fileName);
                    break;
                }

                writeFile(stream, imageFile);
                resp.setStatusCode(0);
                resp.setMessage("Photo downloaded from mobile app ");
                //add database
                System.out.println("filepath: " + imageFile.getAbsolutePath());
                //create uri
                /*int index = imageFile.getAbsolutePath().indexOf("monitor_images");
                 if (index > -1) {
                 String uri = imageFile.getAbsolutePath().substring(index);
                 System.out.println("uri: " + uri);
                 dto.setUri(uri);
                 }
                 dto.setDateUploaded(new Date());
                 if (dto.isIsFullPicture()) {
                 dto.setThumbFlag(null);
                 } else {
                 dto.setThumbFlag(1);
                 }
                 dataUtil.addPhotoUpload(dto);*/

            }
        }

    } catch (FileUploadException | IOException | JsonSyntaxException ex) {
        logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex);
        throw new FileUploadException();
    }

    return resp;
}

From source file:com.oprisnik.semdroid.SemdroidServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("doPost");
    StringBuilder sb = new StringBuilder();
    try {//from  w  w  w . j  ava2 s .c o  m
        ServletFileUpload upload = new ServletFileUpload();
        // set max size (-1 for unlimited size)
        upload.setSizeMax(1024 * 1024 * 30); // 30MB
        upload.setHeaderEncoding("UTF-8");

        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                // Process regular form fields
                // String fieldname = item.getFieldName();
                // String fieldvalue = item.getString();
                // log.info("Got form field: " + fieldname + " " + fieldvalue);
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getBaseName(item.getName());
                log.info("Got file: " + filename);
                InputStream filecontent = null;
                try {
                    filecontent = item.openStream();
                    // analyze
                    String txt = analyzeApk(filecontent);
                    if (txt != null) {
                        sb.append(txt);
                    } else {
                        sb.append("Error. Could not analyze ").append(filename);
                    }
                    log.info("Analysis done!");
                } finally {
                    if (filecontent != null) {
                        filecontent.close();
                    }
                }
            }
        }
        response.getWriter().print(sb.toString());
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    } catch (Exception ex) {
        log.warning("Exception: " + ex.getMessage());
        log.throwing(this.getClass().getName(), "doPost", ex);
    }

}

From source file:de.egore911.reader.servlets.OpmlImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    User user = getUserOrRedirect(resp);
    if (user == null) {
        return;/*w ww.ja  v  a  2s. c  om*/
    }

    boolean success = false;
    String reason = null;
    ServletFileUpload upload = new ServletFileUpload();
    CategoryDao categoryDao = new CategoryDao();
    FeedUserDao feedUserDao = new FeedUserDao();
    FeedDao feedDao = new FeedDao();
    try {
        FileItemIterator iter = upload.getItemIterator(req);
        // Parse the request
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if ("subscriptions".equals(name) && !item.isFormField()
                    && "text/xml".equals(item.getContentType())) {
                try (InputStream stream = item.openStream()) {
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse(stream);

                    document.getDocumentElement().normalize();

                    Element opml = document.getDocumentElement();
                    if (!"opml".equals(opml.getTagName())) {
                        throw new ServletException("Invalid XML");
                    }

                    NodeList nodes = opml.getChildNodes();
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node node = nodes.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;
                            if ("body".equals(element.getTagName())) {
                                if (countFeeds(element.getChildNodes()) < 20) {
                                    importRecursive(categoryDao, feedUserDao, feedDao, user, Category.ROOT,
                                            element.getChildNodes());
                                    success = true;
                                } else {
                                    reason = "to_many_feeds";
                                }
                            }
                        }
                    }

                } catch (ParserConfigurationException | SAXException e) {
                    throw new ServletException(e.getMessage(), e);
                }
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException(e.getMessage(), e);
    }

    if (success) {
        resp.sendRedirect("/reader");
    } else {
        String redirectTo = "/import?msg=import_failed";
        if (reason != null) {
            redirectTo += "&reason=" + reason;
        }
        resp.sendRedirect(redirectTo);
    }
}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload2")
@POST/*from w ww .j a  v a2s  . co m*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(CHARSET);
    try {
        FileItemIterator fileIterator = upload.getItemIterator(request);
        while (fileIterator.hasNext()) {
            FileItemStream item = fileIterator.next();
            InputStream is = item.openStream();
            try {
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    String name = Calendar.getInstance().getTimeInMillis() + fileName;
                    String path = request.getServletContext().getRealPath("/");
                    path += File.separator + "data" + File.separator + name;
                    File file = new File(path);
                    FileUtils.copyInputStreamToFile(is, file);
                } else {
                    System.out.println(Streams.asString(is, CHARSET));
                }
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        return "{\"success\": true}";
    } catch (IOException | FileUploadException e) {
        return "{\"success\": false}";
    }
}

From source file:com.googlecode.npackdweb.RepUploadAction.java

@Override
public Page perform(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    List<String> messages = new ArrayList<String>();

    Found f = null;/*w  ww. j  av  a 2s . com*/
    String tag = "unknown";
    boolean overwrite = false;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                try {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tag")) {
                            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
                            tag = r.readLine();
                        } else if (item.getFieldName().equals("overwrite")) {
                            overwrite = true;
                        }
                    } else {
                        f = process(stream);
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (FileUploadException e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    } else {
        tag = req.getParameter("tag");
        String rep = req.getParameter("repository");
        overwrite = req.getParameter("overwrite") != null;
        f = process(new ByteArrayInputStream(rep.getBytes("UTF-8")));
    }

    if (f != null) {
        boolean isAdmin = NWUtils.isAdminLoggedIn();

        for (PackageVersion pv : f.pvs) {
            pv.tags.add(tag);
        }

        Objectify ofy = DefaultServlet.getObjectify();
        List<Key<?>> keys = new ArrayList<Key<?>>();
        for (License lic : f.lics) {
            keys.add(lic.createKey());
        }
        for (PackageVersion pv : f.pvs) {
            keys.add(pv.createKey());
        }
        for (Package p : f.ps) {
            keys.add(p.createKey());
        }

        Map<Key<Object>, Object> existing = ofy.get(keys);

        Stats stats = new Stats();
        Iterator<PackageVersion> it = f.pvs.iterator();
        while (it.hasNext()) {
            PackageVersion pv = it.next();
            PackageVersion found = (PackageVersion) existing.get(pv.createKey());
            if (found != null) {
                stats.pvExisting++;
                if (!overwrite)
                    it.remove();
            }
        }

        Iterator<License> itLic = f.lics.iterator();
        while (itLic.hasNext()) {
            License pv = itLic.next();
            License found = (License) existing.get(pv.createKey());
            if (found != null) {
                stats.licExisting++;
                if (!overwrite)
                    itLic.remove();
            }
        }

        Iterator<Package> itP = f.ps.iterator();
        while (itP.hasNext()) {
            Package p = itP.next();
            Package found = (Package) existing.get(p.createKey());
            if (found != null) {
                stats.pExisting++;
                if (!overwrite)
                    itP.remove();
            }
        }

        for (PackageVersion pv : f.pvs) {
            Package p = ofy.find(new Key<Package>(Package.class, pv.package_));
            if (p != null && !p.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + pv.package_);
        }

        for (Package p : f.ps) {
            Package p_ = ofy.find(new Key<Package>(Package.class, p.name));
            if (p_ != null && !p_.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + p.name);
        }

        if (f.lics.size() > 0) {
            if (isAdmin)
                ofy.put(f.lics);
            else
                messages.add("Only an administrator can change licenses");
        }

        ofy.put(f.pvs);

        for (Package p : f.ps) {
            NWUtils.savePackage(ofy, p, true);
        }

        if (overwrite) {
            stats.pOverwritten = stats.pExisting;
            stats.pvOverwritten = stats.pvExisting;
            stats.licOverwritten = stats.licExisting;
            stats.pAppended = f.ps.size() - stats.pOverwritten;
            stats.pvAppended = f.pvs.size() - stats.pvOverwritten;
            stats.licAppended = f.lics.size() - stats.licOverwritten;
        } else {
            stats.pAppended = f.ps.size();
            stats.pvAppended = f.pvs.size();
            stats.licAppended = f.lics.size();
        }
        messages.add(stats.pOverwritten + " packages overwritten, " + stats.pvOverwritten
                + " package versions overwritten, " + stats.licOverwritten + " licenses overwritten, "
                + stats.pAppended + " packages appended, " + stats.pvAppended + " package versions appended, "
                + stats.licAppended + " licenses appended");
    } else {
        messages.add("No data found");
    }

    return new MessagePage(messages);
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }/*from www. java  2  s. c  o  m*/
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}