Example usage for org.apache.commons.fileupload FileItemIterator hasNext

List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator hasNext.

Prototype

boolean hasNext() throws FileUploadException, IOException;

Source Link

Document

Returns, whether another instance of FileItemStream is available.

Usage

From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//  w w w . ja v a2 s  .  co m

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(500000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();
        byte[] image = null;

        Tag tag = new Tag();
        TagImage tagImage = new TagImage();
        TagThumbnail tagThumbnail = new TagThumbnail();
        String contentType = null;
        boolean bLandscape = false;

        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        tag.setName(IOUtils.toString(in));
                    }
                    if (Constants.PARAMATER_LAT.equals(item.getFieldName())) {
                        tag.setLat(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LON.equals(item.getFieldName())) {
                        tag.setLon(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) {
                        bLandscape = IOUtils.toString(in).equals("on");
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    try {
                        image = IOUtils.toByteArray(in);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
        } catch (SizeLimitExceededException e) {
            out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        }

        contentType = (contentType != null) ? contentType : "image/jpeg";

        if (bLandscape) {
            image = rotate(image);
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        tagThumbnail.setImage(createThumbnail(image));
        tagThumbnail.setContentType(contentType);

        TagImageDAO daoImage = new TagImageDAO();
        daoImage.create(tagImage);

        TagThumbnailDAO daoThumbnail = new TagThumbnailDAO();
        daoThumbnail.create(tagThumbnail);

        TagDAO dao = new TagDAO();
        tag.setKeyImage(tagImage.getKey());
        tag.setKeyThumbnail(tagThumbnail.getKey());
        tag.setDate(new Date().getTime());
        dao.create(tag);

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:kg12.Ex12_2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w.ja  v a 2s  .  com
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Ex12_2</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>???</h1>");

        // multipart/form-data ??
        if (ServletFileUpload.isMultipartContent(request)) {
            out.println("???<br>");
        } else {
            out.println("?????<br>");
            out.close();
            return;
        }

        // ServletFileUpload??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        // ???
        int fileSizeMax = 1024000;
        factory.setSizeThreshold(1024);
        sfu.setSizeMax(fileSizeMax);
        sfu.setHeaderEncoding("UTF-8");

        // ?
        String format = "%s:%s<br>%n";

        // ???????
        FileItemIterator fileIt = sfu.getItemIterator(request);

        while (fileIt.hasNext()) {
            FileItemStream item = fileIt.next();

            if (item.isFormField()) {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getFieldName());
                InputStream is = item.openStream();

                // ? byte ??
                byte[] b = new byte[255];

                // byte? b ????
                is.read(b, 0, b.length);

                // byte? b ? "UTF-8" ??String??? result ?
                String result = new String(b, "UTF-8");
                out.printf(format, "", result);
            } else {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getName());
                InputStream is = item.openStream();

                String fileName = item.getName();
                int len = 0;
                byte[] buffer = new byte[fileSizeMax];

                FileOutputStream fos = new FileOutputStream(
                        "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName);
                try {
                    while ((len = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                } finally {
                    fos.close();
                }

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } catch (Exception e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } finally {
        out.close();
    }
}

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  w  w  w.  jav a 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;
}

From source file:com.boundlessgeo.geoserver.api.controllers.WorkspaceController.java

@RequestMapping(value = "/{wsName}/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(value = HttpStatus.OK)//  w w w .  j av  a  2s  .  co m
public void inport(@PathVariable String wsName, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Catalog cat = geoServer.getCatalog();

    WorkspaceInfo ws = findWorkspace(wsName, cat);

    // grab the uploaded file
    FileItemIterator files = doFileUpload(request);
    if (!files.hasNext()) {
        throw new BadRequestException("Request must contain a single file");
    }
    Path zip = Files.createTempFile(null, null);
    FileItemStream item = files.next();
    try (InputStream stream = item.openStream()) {
        IOUtils.copy(stream, zip.toFile());
    }
    BundleImporter importer = new BundleImporter(cat, new ImportOpts(ws));
    importer.unzip(zip);
    importer.run();
}

From source file:freedots.web.MusicXML2BrailleServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Score score = null;//from  w  w  w. j a v  a 2  s . c  o  m
    BrailleEncoding brailleEncoding = BrailleEncoding.UnicodeBraille;
    int width = 40, height = 25;
    InputStream stream = null;
    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            final FileItemStream item = iterator.next();
            if (item.getFieldName().compareTo("file.xml") == 0) {
                String extension = "xml";
                if (item.getName().endsWith(".mxl"))
                    extension = "mxl";
                score = parseMusicXML(item.openStream(), extension);
            } else if (item.getFieldName().compareTo("encoding") == 0) {
                final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
                final String line = reader.readLine();
                if (line != null) {
                    try {
                        brailleEncoding = Enum.valueOf(BrailleEncoding.class, line);
                    } catch (IllegalArgumentException e) {
                        LOG.info("Unknown encoding " + line + ", falling back to default");
                    }
                }
            } else if (item.getFieldName().compareTo("width") == 0) {
                final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
                final String line = reader.readLine();
                if (line != null && !line.isEmpty()) {
                    try {
                        final int value = Integer.parseInt(line);
                        if (value >= MIN_COLUMNS_PER_LINE && value <= MAX_COLUMNS_PER_LINE)
                            width = value;
                    } catch (NumberFormatException e) {
                        LOG.info("Not a proper number: " + line + ", falling back to default");
                    }
                }
            } else if (item.getFieldName().compareTo("height") == 0) {
                final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream()));
                final String line = reader.readLine();
                if (line != null && !line.isEmpty()) {
                    try {
                        final int value = Integer.parseInt(line);
                        if (value >= MIN_LINES_PER_PAGE && value <= MAX_LINES_PER_PAGE)
                            height = value;
                    } catch (NumberFormatException e) {
                        LOG.info("Not a proper number: " + line + ", falling back to default");
                    }
                }
            }
        }
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        LOG.info("FileUploadException error");
        resp.sendError(500);
    }

    if (score != null) {
        writeResult(score, width, height, Method.SectionBySection, brailleEncoding, resp);
    } else {
        resp.sendRedirect("/");
    }
}

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  ww  .j  a  v a2s  .co  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:controllers.PictureController.java

@FilterWith(SecureFilter.class)
public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception {
    String fileLocation = "";
    // Make sure the context really is a multipart context...
    if (context.isMultipart()) {
        Picture pic = new Picture();
        // This is the iterator we can use to iterate over the
        // contents of the request.
        FileItemIterator fileItemIterator = context.getFileItemIterator();

        while (fileItemIterator.hasNext()) {

            FileItemStream item = fileItemIterator.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();

            String contentType = item.getContentType();

            if (item.isFormField()) {
                String value = Streams.asString(stream);
                switch (name) {
                case "name":
                    pic.setName(value);//  w ww  .  j  a v a2s. co  m
                    break;
                case "about":
                    pic.setAbout(value);
                    break;
                }

            } else {
                OutputStream outputStream = null;

                try {
                    fileLocation = "public/pictures/" + item.getName();
                    outputStream = new FileOutputStream(new File(fileLocation));

                    int read = 0;
                    byte[] bytes = new byte[1024];

                    while ((read = stream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, read);
                    }
                    pic.setFile(item.getName());

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (outputStream != null) {
                        try {
                            // outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
        pictureDao.postArticlePicture(username, pic);
    }

    reziseImage(fileLocation);
    // We always return ok. You don't want to do that in production ;)
    return Results.redirect("/picture/all");

}

From source file:de.mpg.imeji.presentation.upload.UploadBean.java

public void upload() throws Exception {
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from  w  w  w  . ja  va  2 s . c o m
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (!item.isFormField()) {
                title = item.getName();
                StringTokenizer st = new StringTokenizer(title, ".");
                while (st.hasMoreTokens()) {
                    format = st.nextToken();
                }
                mimetype = "image/" + format;
                // TODO remove static image description
                description = "";
                try {
                    UserController uc = new UserController(null);
                    User user = uc.retrieve(getUser().getEmail());
                    try {
                        DepositController controller = new DepositController();
                        Item escidocItem = controller.createEscidocItem(stream, title, mimetype, format);
                        controller.createImejiImage(collection, user, escidocItem.getOriginObjid(), title,
                                URI.create(EscidocHelper.getOriginalResolution(escidocItem)),
                                URI.create(EscidocHelper.getThumbnailUrl(escidocItem)),
                                URI.create(EscidocHelper.getWebResolutionUrl(escidocItem)));
                        // controller.createImejiImage(collection, user, "escidoc:123", title,
                        // URI.create("http://imeji.org/test"), URI.create("http://imeji.org/test"),
                        // URI.create("http://imeji.org/test"));
                        sNum += 1;
                        sFiles.add(title);
                    } catch (Exception e) {
                        fNum += 1;
                        fFiles.add(title);
                        logger.error("Error uploading image: ", e);
                        // throw new RuntimeException(e);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        logger.info("Upload finished");
    }
}

From source file:com.google.reducisaurus.servlets.BaseServlet.java

private String collectFromFileUpload(final HttpServletRequest req) throws IOException, ServletException {
    StringBuilder collector = new StringBuilder();
    try {/*w  ww  .ja v  a  2  s.  com*/
        ServletFileUpload sfu = new ServletFileUpload();
        FileItemIterator it = sfu.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            if (!item.isFormField()) {
                InputStream stream = item.openStream();
                collector.append(IOUtils.toString(stream, "UTF-8"));
                collector.append("\n");
                IOUtils.closeQuietly(stream);
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    return collector.toString();
}

From source file:com.runwaysdk.web.WebFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    // capture the session id
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }//from  w w w.j  a  v  a2 s.  c o  m

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);

        String fileName = null;
        String extension = null;
        InputStream stream = null;
        String uploadPath = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream input = item.openStream();
            if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) {
                uploadPath = Streams.asString(input);
            } else if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                fileName = fullName.substring(0, extensionInd);
                extension = fullName.substring(extensionInd + 1);
                stream = input;
            }
        }

        if (stream != null) {
            clientRequest.newFile(uploadPath, fileName, extension, stream);
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    }
}