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.threewks.thundr.bind.http.MultipartHttpBinderTest.java

@Before
public void before() throws FileUploadException, IOException {
    parameterBinderRegistry = new ParameterBinderRegistry(TransformerManager.createWithDefaults());
    ParameterBinderRegistry.addDefaultBinders(parameterBinderRegistry);
    binder = new MultipartHttpBinder(parameterBinderRegistry);
    parameterDescriptions = new LinkedHashMap<ParameterDescription, Object>();
    pathVariables = new HashMap<String, String>();

    multipartData = new ArrayList<FileItemStream>();
    ServletFileUpload mockUpload = mock(ServletFileUpload.class);
    when(mockUpload.getItemIterator(request)).thenAnswer(new Answer<FileItemIterator>() {

        @Override//from  ww  w  . j  a v  a2  s.  com
        public FileItemIterator answer(InvocationOnMock invocation) throws Throwable {
            return new FileItemIterator() {
                Iterator<FileItemStream> iterator = multipartData.iterator();

                @Override
                public FileItemStream next() throws FileUploadException, IOException {
                    return iterator.next();
                }

                @Override
                public boolean hasNext() throws FileUploadException, IOException {
                    return iterator.hasNext();
                }
            };
        }
    });
    TestSupport.setField(binder, "upload", mockUpload);
}

From source file:com.lemania.sis.server.servlet.GcsServlet.java

/**
 * Writes the payload of the incoming post as the contents of a file to GCS.
 * If the request path is /gcs/Foo/Bar this will be interpreted as a request
 * to create a GCS file named Bar in bucket Foo.
 * /*  w  w w .j  a va 2 s .  com*/
 * @throws ServletException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    //
    GcsOutputChannel outputChannel = gcsService.createOrReplace(getFileName(req),
            GcsFileOptions.getDefaultInstance());

    ServletFileUpload upload = new ServletFileUpload();
    resp.setContentType("text/plain");
    //
    InputStream fileContent = null;
    FileItemIterator iterator;
    try {
        iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            if (item.isFormField()) {
                //
            } else {
                fileContent = stream;
                break;
            }
        }
    } catch (FileUploadException e) {
        //
        e.printStackTrace();
    }
    //
    copy(fileContent, Channels.newOutputStream(outputChannel));
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files//from w ww  .j a va2 s  .com
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * Creates a new {@link DynamicInputImpl}
 * @param request from which to read the request parameters
 *//*w  ww .j  ava2 s.co m*/
public DynamicInputImpl(HttpServletRequest request) {
    @SuppressWarnings("unchecked")
    Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap());
    this.inputParams = reqParams;
    if (ServletFileUpload.isMultipartContent(request)) {
        this.fileUploads = Maps.newHashMap();
        Multimap<String, String> inputParamsWithList = ArrayListMultimap.create();

        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name()));
                } else {
                    final String filename = item.getName();
                    final byte[] bytes = ByteStreams.toByteArray(stream);
                    fileUploads.put(fieldName, new UploadedFile() {
                        @Override
                        public String getFilename() {
                            return filename;
                        }

                        @Override
                        public byte[] getBytes() {
                            return bytes;
                        }

                        @Override
                        public int getSize() {
                            return bytes.length;
                        }
                    });
                }
            }
            for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) {
                inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0]));
            }
        } catch (IOException | FileUploadException e) {
            throw new IllegalArgumentException("Failed to parse multipart", e);
        }
    } else {
        this.fileUploads = Collections.emptyMap();
    }
}

From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java

private void parseReq(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from   w  w  w .ja  va  2  s .co m*/

        MF mf = MF.getFactory();

        req.setCharacterEncoding("UTF-8");

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(req);

        HashMap<String, String> map = new HashMap<String, String>();

        while (iterator.hasNext()) {

            FileItemStream item = iterator.next();

            InputStream stream = item.openStream();

            if (item.isFormField()) {

                String field = item.getFieldName();

                String value = Streams.asString(stream);

                map.put(field, value);

                stream.close();

            } else {

                String filename = item.getName();

                String[] extension = filename.split("\\.");

                String mail = map.get("mail");

                if (mail != null) {

                    filename = mail + "_" + String.valueOf(filename.hashCode()) + "."
                            + extension[extension.length - 1];

                } else {

                    filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1];

                }

                map.put("filename", filename);

                byte[] buffer = IOUtils.toByteArray(stream);

                mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer,

                        filename);

                stream.close();

            }

        }

        String email = map.get("mail");

        String firstName = map.get("firstName");

        String lastName = map.get("lastName");

        String dayS = map.get("day");

        String monthS = map.get("month");

        String yearS = map.get("year");

        String password = map.get("password");

        String filename = map.get("filename");

        String date = yearS + "-" + monthS + "-" + dayS;

        char gender = map.get("gender").charAt(0);

        RequestDispatcher disp;

        Connection c = mf.getSQLService().getConnection();

        String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName
                + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')";

        Statement statement = c.createStatement();

        statement.executeUpdate(stm);

        statement.close();

        c.close();

        req.getSession(true).setAttribute("actualUser", email);

        req.getSession(true).setAttribute("edit", "false");

        disp = req.getRequestDispatcher("SelectTopic.jsp");

        disp.forward(req, response);

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (FileUploadException e) {

        e.printStackTrace();

    }

}

From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java

/**
 * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from:
 * //from   ww  w.ja v a2  s  .c om
 *      http://code.google.com/appengine/kb/java.html#fileforms
 * 
 * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption"
 * target="_blank">GaeVFS path</a>. All directories within the path hierarchy
 * are created (if they don't already exist) when the file is saved.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data");
    }
    try {
        String path = "/";
        int blockSize = 0;
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("path")) {
                    path = asString(item.openStream());
                    if (!path.endsWith("/")) {
                        path = path + "/";
                    }
                } else if (item.getFieldName().equalsIgnoreCase("blocksize")) {
                    String s = asString(item.openStream());
                    if (s.length() > 0) {
                        blockSize = Integer.parseInt(s);
                    }
                }
            } else {
                Path filePath = Paths.get(path + item.getName());
                Path parent = filePath.getParent();
                if (parent.notExists()) {
                    createDirectories(parent);
                }
                if (blockSize > 0) {
                    filePath.createFile(withBlockSize(blockSize));
                } else {
                    filePath.createFile();
                }
                // IOUtils.copy() buffers the InputStream internally
                OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE);
                copy(item.openStream(), out);
                out.close();
            }
        }

        // redirect to the configured response, or to this servlet for a
        // directory listing
        res.sendRedirect(uploadRedirect != null ? uploadRedirect : path);

    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
}

From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java

private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException {
    Task task = null;//from w  w w.ja  va  2  s  .c  o m

    ServletFileUpload fileUpload = new ServletFileUpload();
    FileItemIterator iterator = null;
    InputStream itemStream = null;

    try {
        ImageReplicationType replicationType = null;

        iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            itemStream = item.openStream();

            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                switch (fieldName.toUpperCase()) {
                case "IMAGEREPLICATION":
                    replicationType = ImageReplicationType.valueOf(Streams.asString(itemStream).toUpperCase());
                    break;
                default:
                    logger.warn(String.format("The parameter '%s' is unknown in image upload.", fieldName));
                }
            } else {
                if (replicationType == null) {
                    throw new ImageUploadException(
                            "ImageReplicationType is required and should be encoded before image data in the upload request.");
                }

                task = imageFeClient.create(itemStream, item.getName(), replicationType);
            }

            itemStream.close();
            itemStream = null;
        }
    } catch (IllegalArgumentException ex) {
        throw new ImageUploadException("Image upload receives invalid parameter", ex);
    } catch (IOException ex) {
        throw new ImageUploadException("Image upload IOException", ex);
    } catch (FileUploadException ex) {
        throw new ImageUploadException("Image upload FileUploadException", ex);
    } finally {
        flushRequest(iterator, itemStream);
    }

    if (task == null) {
        throw new ImageUploadException("There is no image stream data in the image upload request.");
    }

    return task;
}

From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java

/**
 * Receive an upload book assest//  w ww.  ja v  a2  s . c  om
 * 
 * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest)
 */
@Override
@POST
@Path("/upload2")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process2(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String description = null;
            String descriptionDetail = null;
            String hoursOfWorkStr = null;
            String bookId = null;
            String action = null;
            String dataType = null;
            String contentType = null;
            //String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // description
                    if (item.getFieldName().equals("description")) {
                        description = Streams.asString(stream);
                    }

                    // detail
                    if (item.getFieldName().equals("descriptionDetail")) {
                        descriptionDetail = Streams.asString(stream);
                    }

                    // Work hours
                    if (item.getFieldName().equals("hoursOfWork")) {
                        hoursOfWorkStr = Streams.asString(stream);
                    }

                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }

                    // action
                    if (item.getFieldName().equals("action")) {
                        action = Streams.asString(stream);
                    }

                    // datatype
                    if (item.getFieldName().equals("dataType")) {
                        dataType = Streams.asString(stream);
                    }

                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray();
                        size = bytes.length;
                    }
                }
            }

            // convert the hoursOfWork
            int hoursOfWork = 0;
            if (hoursOfWorkStr != null) {
                try {
                    hoursOfWork = Integer.parseInt(hoursOfWorkStr);
                } catch (Exception e) {
                    log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr
                            + " to an int in BookAssetUploadServiceImpl. Converting to 0.");
                    hoursOfWork = 0;
                }
            }

            // Verify that the session user is the author or co-author of
            // the book. They would be the only ones who could add to the
            // book.
            String userId = userToken.getUserId();
            boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId);
            if (isAuthor == false) {
                throw new Exception("The user " + userId + " is not the author or co-author of the book.");
            }

            // Add to the database
            bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType,
                    BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size,
                    hoursOfWork, userId);

            // Tell Solr about the update
            queueBookEvent.fire(new QueueBookEvent(bookId, userId));
        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}

From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResource.java

@Post
@Put/*from www . j a va  2  s . co m*/
public void accept(final Representation payload) throws Exception {
    if ((payload != null) && MediaType.MULTIPART_FORM_DATA.equals(payload.getMediaType(), true)) {
        // The Apache FileUpload project parses HTTP requests which
        // conform to RFC 1867, "Form-based File Upload in HTML". That
        // is, if an HTTP request is submitted using the POST method,
        // and with a content type of "multipart/form-data", then
        // FileUpload can parse that request, and get all uploaded files
        // as FileItem.

        // Obtain the file upload Representation as an iterator.
        final ServletFileUpload upload = parseRepresentation();

        final FileItemIterator fileItemIterator = upload.getItemIterator(ServletUtils.getRequest(getRequest()));

        if (!fileItemIterator.hasNext()) {
            // Some problem occurs, sent back a simple line of text.
            uploadError(Status.CLIENT_ERROR_BAD_REQUEST, "Unable to upload corrupted or incompatible data.");
        } else {
            upload(fileItemIterator);
        }
    } else {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        getResponse().setEntity("Nothing to upload or invalid data.", MediaType.TEXT_PLAIN);
    }
}

From source file:es.eucm.mokap.backend.server.MokapBackend.java

/**
 * Iterates the whole request in search for a file. When it finds it, it
 * creates a FileItemStream which contains it.
 * /*from   ww  w.ja va  2s  .  co  m*/
 * @param req
 *            The request to process
 * @return Returns THE FIRST file found in the upload request or null if no
 *         file could be found
 */
private FileItemStream getUploadedFile(HttpServletRequest req) throws IOException, FileUploadException {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    // Set the UTF-8 encoding to grab the correct uploaded filename,
    // especially for Chinese
    upload.setHeaderEncoding("UTF-8");

    FileItemStream file = null;

    /* Parse the request */
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        if (!item.isFormField()) {
            file = item;
            break;
        }
    }
    return file;
}