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:fedora.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request/*from  w w  w  .ja v  a2s  . com*/
 */
public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception {
    RequestContent rContent = null;

    // See if the request is a multi-part file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, use the first available File item
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                rContent = new RequestContent();
                rContent.contentStream = item.openStream();
                rContent.mimeType = item.getContentType();

                FileItemHeaders itemHeaders = item.getHeaders();
                if (itemHeaders != null) {
                    String contentLength = itemHeaders.getHeader("Content-Length");
                    if (contentLength != null) {
                        rContent.size = Integer.parseInt(contentLength);
                    }
                }

                break;
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            if (request.getContentLength() > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = request.getContentLength();
            } else {
                String transferEncoding = request.getHeader("Transfer-Encoding");
                if (transferEncoding != null && transferEncoding.contains("chunked")) {
                    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                    bis.mark(2);
                    if (bis.read() > 0) {
                        bis.reset();
                        rContent = new RequestContent();
                        rContent.contentStream = bis;
                    }
                }
            }
        }
    }

    // Attempt to set the mime type and size if not already set
    if (rContent != null) {
        if (rContent.mimeType == null) {
            MediaType mediaType = headers.getMediaType();
            if (mediaType != null) {
                rContent.mimeType = mediaType.toString();
            }
        }

        if (rContent.size == 0) {
            List<String> lengthHeaders = headers.getRequestHeader("Content-Length");
            if (lengthHeaders != null && lengthHeaders.size() > 0) {
                rContent.size = Integer.parseInt(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

@Override
public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//w  w w .  j a  v a 2s .  c  om
        // We always return xhtml in utf-8
        response.setContentType("application/xhtml+xml");
        response.setCharacterEncoding("utf-8");

        // Default filename just in case none is found in form
        String filename = defaultFilename;

        // Commons file upload
        ServletFileUpload upload = new ServletFileUpload();

        // Go through upload items
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Parse form fields
                String fieldname = item.getFieldName();

                if ("chartFilename".equals(fieldname)) {
                    // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default
                    // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
                    //   "The parts are sent to the processing agent in the same order the
                    //    corresponding controls appear in the document stream."
                    filename = Streams.asString(stream, "utf-8");
                } else if ("chartDataXML".equals(fieldname)) {
                    log.info("Doing form bounce");
                    String filenameAscii = formSafeAscii(filename);
                    String fileNameUtf = formSafeUtfName(filename);
                    String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''"
                            + fileNameUtf;
                    response.setHeader("Content-Disposition", cdh);
                    ServletOutputStream out = response.getOutputStream();
                    Streams.copy(stream, out, false);
                    out.flush();
                    // No more processing needed (prevent BOTH form AND upload from happening)
                    return;
                }
            } else {
                // Handle upload
                log.info("Doing file bounce");
                ServletOutputStream out = response.getOutputStream();
                Streams.copy(stream, out, false);
                out.flush();
                // No more processing needed (prevent BOTH form AND upload from happening)
                return;
            }
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public String processarArquivo(HttpServletRequest request, String nameToSave)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from ww w. j  a  v  a  2  s. com
            FileItemIterator itr = upload.getItemIterator(request);

            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (!item.isFormField()) {
                    //                        pode ser tb sem a barra ????
                    //                        String path = request.getServletContext().getRealPath("");
                    String contextPath = request.getServletContext().getRealPath("/");

                    //refatorar aqui apenas para salvarimagem receber um pasta, inputStream e o nome
                    //aqui, criar um inputStream atravs do arquivo item antes de enviar
                    //diminuir 1 mtodo, deixando salvarImagem mais genrico
                    if (salvarImagem(contextPath + File.separator + folder, item, nameToSave)) {
                        return folder + "/" + nameToSave;
                    }
                }
            }

        } catch (FileUploadException ex) {
            System.out.println("erro ao obter informaoes sobre o arquivo");
        }

    } else {
        System.out.println("Erro no formulario!");
    }

    return null;
}

From source file:edu.ucla.loni.pipeline.server.Upload.Uploaders.FileUploadServlet.java

/**
 * Handles Request to Upload File, Builds a Response
 * // w w w . j  a  v a2s .c om
 * @param req
 * @param respBuilder
 */
private void handleFileUpload(HttpServletRequest req, ResponseBuilder respBuilder) {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

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

            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                handleUploadedFile(item, respBuilder);
            }
        } catch (FileUploadException e) {
            respBuilder.appendRespMessage("The file was not uploaded successfully.");
        } catch (IOException e) {
            respBuilder.appendRespMessage("The file was not uploaded successfully.");
        }
    } else {
        respBuilder.appendRespMessage("Your form of request is not supported by this upload servlet.");
    }
}

From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java

/**
 * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection ,
 *      FileUploadSelector, String, UploadProgress)
 *//*from   w  w w  .j a  va  2 s.  com*/
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex,
        final UploadProgress progress) throws Exception {
    final ApplicationInstance app = conn.getUserInstance().getApplicationInstance();

    final DiskFileItemFactory itemFactory = new DiskFileItemFactory();
    itemFactory.setRepository(getDiskCacheLocation());
    itemFactory.setSizeThreshold(getMemoryCacheThreshold());

    String encoding = conn.getRequest().getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }

    final ServletFileUpload upload = new ServletFileUpload(itemFactory);
    upload.setHeaderEncoding(encoding);
    upload.setProgressListener(new UploadProgressListener(progress));

    long sizeLimit = uploadSelect.getUploadSizeLimit();
    if (sizeLimit == 0)
        sizeLimit = getFileUploadSizeLimit();
    if (sizeLimit != NO_SIZE_LIMIT) {
        upload.setSizeMax(sizeLimit);
    }

    String fileName = null;
    String contentType = null;

    try {
        final FileItemIterator iter = upload.getItemIterator(conn.getRequest());
        if (iter.hasNext()) {
            final FileItemStream stream = iter.next();

            if (!stream.isFormField()) {
                fileName = FilenameUtils.getName(stream.getName());
                contentType = stream.getContentType();

                final Set<String> types = uploadSelect.getContentTypeFilter();
                if (!types.isEmpty()) {
                    if (!types.contains(contentType)) {
                        app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable(
                                uploadSelect, uploadIndex, fileName, contentType, progress));
                        return;
                    }
                }

                progress.setStatus(Status.inprogress);
                final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName());
                item.getOutputStream(); // initialise DiskFileItem internals

                uploadSelect.notifyCallback(
                        new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize()));

                IOUtils.copy(stream.openStream(), item.getOutputStream());

                app.enqueueTask(uploadSelect.getTaskQueue(),
                        new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress));

                return;
            }
        }

        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new RuntimeException("No multi-part content!"), progress));
    } catch (final FileUploadBase.SizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final FileUploadBase.FileSizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final MultipartStream.MalformedStreamException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(),
                new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress));
    }
}

From source file:fi.helsinki.lib.simplerest.CollectionLogoResource.java

@Put
public Representation put(Representation logoRepresentation) {
    Context c = null;//from ww w . j a va  2  s.com
    Collection collection;
    try {
        c = getAuthenticatedContext();
        collection = Collection.find(c, this.collectionId);
        if (collection == null) {
            return errorNotFound(c, "Could not find the collection.");
        }
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(logoRepresentation);
        if (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();

                collection.setLogo(inputStream);
                Bitstream logo = collection.getLogo();
                BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType());
                logo.setFormat(bf);
                logo.update();
                collection.update();
            }
        }
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successOk("Logo set.");
}

From source file:fi.helsinki.lib.simplerest.CommunityLogoResource.java

@Put
public Representation put(Representation logoRepresentation) {
    Context c = null;/*from   ww  w .  j a v a  2 s  .co  m*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(logoRepresentation);
        if (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();

                community.setLogo(inputStream);
                Bitstream logo = community.getLogo();
                BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType());
                logo.setFormat(bf);
                logo.update();
                community.update();
            }
        }
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successOk("Logo set.");
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {/* w  w w . j a va2  s.c om*/
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    byte[] filecontent = null;
    ServletFileUpload upload = new ServletFileUpload();
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    boolean isFirstLineHeader = false;
    String delimiter = ",";

    writeUploadInfo(request);/*from w ww .  j a v a  2s. c  o m*/
    log(request.getHeader("User-Agent"));

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
        FileItemIterator fileItemIterator = upload.getItemIterator(request);
        while (fileItemIterator.hasNext()) {
            FileItemStream item = fileItemIterator.next();
            inputStream = item.openStream();
            // Read the file into a byte array.
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int len = 0;
            while (-1 != (len = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, len);
            }
            if (filecontent == null) {
                filecontent = outputStream.toByteArray();
            }
            if (FORM_PARAMETER_DELIMITER.equals(item.getFieldName())) {
                delimiter = outputStream.toString();
            } else if (FORM_PARAMETER_ISFIRSTLINEHEADER.equals(item.getFieldName())) {
                if ("on".equals(outputStream.toString())) {
                    isFirstLineHeader = true;
                }
            }
        }
        inputStream.close();
        outputStream.close();
    } catch (FileUploadException e) {
        ExceptionHelper.printStackTrace(e);
    } catch (RuntimeException e) {
        out.print("Conversion failed. Please check the file. Message :" + e.getMessage());
    }

    DocumentParameter dp = new DocumentParameter();
    dp.setDelimiter(delimiter);
    dp.setFirstFieldHeader(isFirstLineHeader);
    dp.setData(filecontent);
    try {
        DocumentOutput dout = documentService.processExcelUpload(dp);
        String uploadUUID = DataStore.KEY_LOOKUP_DATA + dout.getUuid();
        ApplicationLocalStore.getInstance().store(uploadUUID, uploadUUID, dout.getData());
        out.print("UUID=" + uploadUUID);
    } catch (Exception e) {
        out.print("Conversion failed. Please check the file (" + e.getMessage() + ")");
    }
}

From source file:controllers.UploadController.java

/**
 * //from w  w  w.j av  a  2 s .com
 * This upload method expects a file and simply displays the file in the
 * multipart upload again to the user (in the correct mime encoding).
 * 
 * @param context
 * @return
 * @throws Exception
 */
public Result uploadFinish(Context context) throws Exception {

    // we are using a renderable inner class to stream the input again to
    // the user
    Renderable renderable = new Renderable() {

        @Override
        public void render(Context context, Result result) {

            try {
                // make sure the context really is a multipart context...
                if (context.isMultipart()) {

                    // 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 (contentType != null) {
                            result.contentType(contentType);
                        } else {
                            contentType = mimeTypes.getMimeType(name);
                        }

                        ResponseStreams responseStreams = context.finalizeHeaders(result);

                        if (item.isFormField()) {
                            System.out.println("Form field " + name + " with value " + Streams.asString(stream)
                                    + " detected.");
                        } else {
                            System.out.println(
                                    "File field " + name + " with file name " + item.getName() + " detected.");
                            // Process the input stream

                            ByteStreams.copy(stream, responseStreams.getOutputStream());

                        }
                    }

                }

            } catch (IOException | FileUploadException exception) {

                throw new InternalServerErrorException(exception);

            }

        }
    };

    return new Result(200).render(renderable);

}