Example usage for org.apache.commons.fileupload FileItemStream openStream

List of usage examples for org.apache.commons.fileupload FileItemStream openStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream openStream.

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

From source file:org.apache.myfaces.webapp.filter.servlet.ServletChacheFileSizeErrorsFileUpload.java

/**
 * Similar to {@link ServletFileUpload#parseRequest(RequestContext)} but will
 * catch and swallow FileSizeLimitExceededExceptions in order to return as
 * many usable items as possible.//  ww  w  .  ja  va 2  s . c om
 * 
 * @param fileUpload
 * @return List of {@link FileItem} excluding any that exceed max size.  
 * @throws FileUploadException
 */
public List parseRequestCatchingFileSizeErrors(HttpServletRequest request, FileUpload fileUpload)
        throws FileUploadException {
    try {
        List items = new ArrayList();

        // The line below throws a SizeLimitExceededException (wrapped by a
        // FileUploadIOException) if the request is longer than the max size
        // allowed by fileupload requests (FileUpload.getSizeMax)
        // But note that if the request does not send proper headers this check
        // just will not do anything and we still have to check it again.
        FileItemIterator iter = fileUpload.getItemIterator(new ServletRequestContext(request));

        FileItemFactory fac = fileUpload.getFileItemFactory();
        if (fac == null) {
            throw new NullPointerException("No FileItemFactory has been set.");
        }

        long maxFileSize = this.getFileSizeMax();
        long maxSize = this.getSizeMax();
        boolean checkMaxSize = false;

        if (maxFileSize == -1L) {
            //The max allowed file size should be approximate to the maxSize
            maxFileSize = maxSize;
        }
        if (maxSize != -1L) {
            checkMaxSize = true;
        }

        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(),
                    item.getName());

            long allowedLimit = 0L;
            try {
                if (maxFileSize != -1L || checkMaxSize) {
                    if (checkMaxSize) {
                        allowedLimit = maxSize > maxFileSize ? maxFileSize : maxSize;
                    } else {
                        //Just put the limit
                        allowedLimit = maxFileSize;
                    }

                    long contentLength = getContentLength(item.getHeaders());

                    //If we have a content length in the header we can use it
                    if (contentLength != -1L && contentLength > allowedLimit) {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                        + " size of " + allowedLimit + " characters.",
                                contentLength, allowedLimit));
                    }

                    //Otherwise we must limit the input as it arrives (NOTE: we cannot rely
                    //on commons upload to throw this exception as it will close the 
                    //underlying stream
                    final InputStream itemInputStream = item.openStream();

                    InputStream limitedInputStream = new LimitedInputStream(itemInputStream, allowedLimit) {
                        protected void raiseError(long pSizeMax, long pCount) throws IOException {
                            throw new FileUploadIOException(new FileSizeLimitExceededException(
                                    "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                            + " size of " + pSizeMax + " characters.",
                                    pCount, pSizeMax));
                        }
                    };

                    //Copy from the limited stream
                    long bytesCopied = Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);

                    // Decrement the bytesCopied values from maxSize, so the next file copied 
                    // takes into account this value when allowedLimit var is calculated
                    // Note the invariant before the line is maxSize >= bytesCopied, since if this
                    // is not true a FileUploadIOException is thrown first.
                    maxSize -= bytesCopied;
                } else {
                    //We can just copy the data
                    Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                }
            } catch (FileUploadIOException e) {
                try {
                    throw (FileUploadException) e.getCause();
                } catch (FileUploadBase.FileSizeLimitExceededException se) {
                    request.setAttribute("org.apache.myfaces.custom.fileupload.exception",
                            "fileSizeLimitExceeded");
                    String fieldName = fileItem.getFieldName();
                    request.setAttribute("org.apache.myfaces.custom.fileupload." + fieldName + ".maxSize",
                            new Integer((int) allowedLimit));
                }
            } catch (IOException e) {
                throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                        + " request failed. " + e.getMessage(), e);
            }
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }
            if (fileItem != null) {
                items.add(fileItem);
            }
        }
        return items;
    } catch (FileUploadIOException e) {
        throw (FileUploadException) e.getCause();
    } catch (IOException e) {
        throw new FileUploadException(e.getMessage(), e);
    }
}

From source file:org.apache.olio.webapp.fileupload.FileUploadHandler.java

/**
 * Handle upload of a standard form item
 *
 * @param item The Commons Fileupload item being loaded
 * @param htUpload The Status Hashtable that contains the items that have been uploaded for post-processing use
 *//*from w w w  .  j  a  v a  2s. c  om*/
protected int formItemFound(FileItemStream item, Hashtable<String, String> htUpload) {
    int size = 0;
    InputStream is = null;
    try {
        String key = item.getFieldName();
        StringBuilder strb = new StringBuilder();
        byte[] buf = new byte[128];
        is = item.openStream();

        // Read from the stream
        int i = 0;
        while ((i = is.read(buf)) != -1) {
            strb.append(new String(buf, 0, i));
            size += i;
        }
        String value = strb.toString();

        // put in Hashtable for later access
        logger.fine("Inserting form item in map " + key + " = " + value);
        htUpload.put(key, value);
    } catch (IOException ex) {
        Logger.getLogger(FileUploadHandler.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            is.close();
        } catch (IOException ex) {
            Logger.getLogger(FileUploadHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return size;
}

From source file:org.apache.olio.webapp.fileupload.FileUploadHandler.java

/**
 * write out file item to a file using the Apache Commons FileUpload FileItem.write method as a guide,
 * so the output could be monitored/*from w  w w .ja v  a 2s  . c o  m*/
 *
 * @param item The Commons Fileupload item being loaded
 * @param fileName File name to write uploaded data.
 * @throws Exception Exceptions propagated from Apache Commons Fileupload classes
 */
public void write(FileItemStream item, String fileName) throws Exception {
    // use name for update of session
    String itemName = item.getName();

    ServiceLocator locator = ServiceLocator.getInstance();

    FileSystem fs = locator.getFileSystem();

    logger.fine("Getting fileItem from memory - " + itemName);

    OutputStream fout = fs.create(fileName);

    // It would have been more efficient to use NIO if we are writing to 
    // the local filesystem. However, since we need to support DFS, 
    // a simple solution is provided. 
    // TO DO: Optimize write if required.

    try {
        byte[] buf = new byte[8192];
        int count, size = 0;
        InputStream is = item.openStream();
        while ((count = is.read(buf)) != -1) {
            fout.write(buf, 0, count);
            size += count;
        }
        updateSessionStatus("", size);
    } finally {
        if (fout != null) {
            fout.close();
        }
    }
}

From source file:org.apache.olio.webapp.fileupload.FileUploadHandler.java

/**
 * /*from   w w  w. ja  v  a 2s  .  co m*/
 * @param item FileItemStream from the file upload handler
 * @param imageName name to save the image.
 * @param thumbnailName name to save the thumbnail. Extension is appended.
 * @throws java.lang.Exception
 */
public void writeWithThumbnail(FileItemStream item, String imageName, String thumbnailName) throws Exception {
    // use name for update of session
    String itemName = item.getName();

    ServiceLocator locator = ServiceLocator.getInstance();

    FileSystem fs = locator.getFileSystem();

    logger.fine("Getting fileItem from memory - " + itemName);

    OutputStream imgOut = null;
    OutputStream thumbOut = null;
    InputStream is = null;
    try {
        imgOut = fs.create(imageName);
        thumbOut = fs.create(thumbnailName);
        // It would have been more efficient to use NIO if we are writing to
        // the local filesystem. However, since we need to support DFS,
        // a simple solution is provided.
        // TO DO: Optimize write if required.

        is = item.openStream();
        FileUploadStatus status = getFileUploadStatus();
        status.setCurrentItem(itemName);

        WebappUtil.saveImageWithThumbnail(is, imgOut, thumbOut, status);
    } finally {
        if (imgOut != null)
            try {
                imgOut.close();
            } catch (IOException e) {
            }
        if (thumbOut != null)
            try {
                thumbOut.close();
            } catch (IOException e) {
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
            }
    }
}

From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java

/**
 * Processes the FileItemStream as a Form Field.
 *
 * @param itemStream//w ww.j  ava2 s .co  m
 */
private void processFileItemStreamAsFormField(FileItemStream itemStream) {
    String fieldName = itemStream.getFieldName();
    try {
        List<String> values = null;
        String fieldValue = Streams.asString(itemStream.openStream());
        if (!parameters.containsKey(fieldName)) {
            values = new ArrayList<String>();
            parameters.put(fieldName, values);
        } else {
            values = parameters.get(fieldName);
        }
        values.add(fieldValue);
    } catch (IOException e) {
        e.printStackTrace();
        LOG.warn("Failed to handle form field '#0'.", fieldName);
    }
}

From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java

/**
 * Streams the file upload stream to the specified file.
 *
 * @param itemStream/* w  ww.j av  a 2  s .c o  m*/
 * @param file
 * @return
 * @throws IOException
 */
private boolean streamFileToDisk(FileItemStream itemStream, File file) throws IOException {
    boolean result = false;
    InputStream input = itemStream.openStream();
    OutputStream output = null;
    try {
        output = new BufferedOutputStream(new FileOutputStream(file), bufferSize);
        byte[] buffer = new byte[bufferSize];
        LOG.debug("Streaming file using buffer size #0.", bufferSize);
        for (int length = 0; ((length = input.read(buffer)) > 0);)
            output.write(buffer, 0, length);
        result = true;
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:org.artags.server.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*from ww w . jav a2s .  co  m*/
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(1000000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();

        byte[] image = null;
        byte[] thumbnail = 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()) {
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        String name = IOUtils.toString(in, "UTF-8");
                        tag.setName(name);
                    }
                    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();

                    try {
                        if (fieldName.equals("thumbnail")) {
                            thumbnail = IOUtils.toByteArray(in);
                        } else {
                            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);
            if (thumbnail != null) {
                thumbnail = rotate(thumbnail);
            }
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        if (thumbnail != null) {
            tagThumbnail.setImage(thumbnail);
        } else {
            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());
        tag.setDateUpdate(new Date().getTime());
        Tag newTag = dao.create(tag);
        out.print("" + newTag.getKey().getId());
        out.close();
        CacheService.instance().invalidate();

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:org.bimserver.servlets.UploadServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getHeader("Origin") != null
            && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
        response.setStatus(403);//from w w  w  .ja  v a  2 s.c o m
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");

    String token = (String) request.getSession().getAttribute("token");

    ObjectNode result = OBJECT_MAPPER.createObjectNode();
    response.setContentType("text/json");
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        long poid = -1;
        String comment = null;
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            InputStream in = null;
            String name = "";
            long deserializerOid = -1;
            boolean merge = false;
            boolean sync = false;
            String compression = null;
            String action = null;
            long topicId = -1;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    if ("action".equals(item.getFieldName())) {
                        action = Streams.asString(item.openStream());
                    } else if ("token".equals(item.getFieldName())) {
                        token = Streams.asString(item.openStream());
                    } else if ("poid".equals(item.getFieldName())) {
                        poid = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("comment".equals(item.getFieldName())) {
                        comment = Streams.asString(item.openStream());
                    } else if ("topicId".equals(item.getFieldName())) {
                        topicId = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("sync".equals(item.getFieldName())) {
                        sync = Streams.asString(item.openStream()).equals("true");
                    } else if ("merge".equals(item.getFieldName())) {
                        merge = Streams.asString(item.openStream()).equals("true");
                    } else if ("compression".equals(item.getFieldName())) {
                        compression = Streams.asString(item.openStream());
                    } else if ("deserializerOid".equals(item.getFieldName())) {
                        deserializerOid = Long.parseLong(Streams.asString(item.openStream()));
                    }
                } else {
                    name = item.getName();
                    in = item.openStream();

                    if ("file".equals(action)) {
                        ServiceInterface serviceInterface = getBimServer().getServiceFactory()
                                .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                        SFile file = new SFile();
                        byte[] data = IOUtils.toByteArray(in);
                        file.setData(data);
                        file.setSize(data.length);
                        file.setFilename(name);
                        file.setMime(item.getContentType());
                        result.put("fileId", serviceInterface.uploadFile(file));
                    } else if (poid != -1) {
                        InputStream realStream = null;
                        if ("gzip".equals(compression)) {
                            realStream = new GZIPInputStream(in);
                        } else if ("deflate".equals(compression)) {
                            realStream = new InflaterInputStream(in);
                        } else {
                            realStream = in;
                        }
                        InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(realStream);
                        inputStreamDataSource.setName(name);
                        DataHandler ifcFile = new DataHandler(inputStreamDataSource);

                        if (token != null) {
                            if (topicId == -1) {
                                ServiceInterface service = getBimServer().getServiceFactory()
                                        .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name,
                                        ifcFile, merge, sync);
                                result.put("topicId", newTopicId);
                            } else {
                                ServiceInterface service = getBimServer().getServiceFactory()
                                        .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                long newTopicId = service.checkinInitiated(topicId, poid, comment,
                                        deserializerOid, -1L, name, ifcFile, merge, true);
                                result.put("topicId", newTopicId);
                            }
                        }
                    } else {
                        result.put("exception", "No poid");
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
        sendException(response, e);
        return;
    }
    response.getWriter().write(result.toString());
}

From source file:org.bonitasoft.engine.api.internal.servlet.ServletCall.java

/**
 * Default constructor./*from  w w  w .  ja  va 2  s . co m*/
 * 
 * @param request
 *        The request made to access this servletCall.
 * @param response
 *        The response to return.
 * @throws IOException
 * @throws FileUploadException
 */
public ServletCall(final HttpServletRequest request, final HttpServletResponse response)
        throws FileUploadException, IOException {
    super();
    this.request = request;
    this.response = response;
    parameters = new HashMap<String, String>();
    binaryParameters = new ArrayList<byte[]>();
    if (ServletFileUpload.isMultipartContent(request)) {
        final ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        final FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            try {
                final FileItemStream item = iter.next();
                final InputStream stream = item.openStream();
                String fieldName = item.getFieldName();
                if (fieldName.startsWith(BINARY_PARAMETER)) {
                    binaryParameters.add(IOUtil.getAllContentFrom(stream));
                } else {
                    String read = IOUtil.read(stream);
                    parameters.put(fieldName, read);
                }
                stream.close();
            } catch (final Exception t) {
                throw new IOException(t);
            }
        }
    } else {
        final Map<String, String[]> parameterMap = this.request.getParameterMap();
        final Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
        for (final Entry<String, String[]> entry : entrySet) {
            parameters.put(entry.getKey(), entry.getValue()[0]);
        }
    }
}

From source file:org.brutusin.rpc.http.RpcServlet.java

/**
 *
 * @param req//from w w w .  j  a  v a  2 s .c  om
 * @return
 * @throws IOException
 */
private static Map<String, String[]> parseMultipartParameters(HttpServletRequest req) throws IOException {
    if (isMultipartContent(req)) {
        Map<String, String[]> multipartParameters = new HashMap();
        Map<String, List<String>> map = new HashMap();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            req.setAttribute(REQ_ATT_MULTIPART_ITERATOR, iter);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
                    break;
                }
                List<String> list = map.get(item.getFieldName());
                if (list == null) {
                    list = new ArrayList();
                    map.put(item.getFieldName(), list);
                }
                String encoding = req.getCharacterEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                list.add(Miscellaneous.toString(item.openStream(), encoding));
            }
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        }
        for (Map.Entry<String, List<String>> entrySet : map.entrySet()) {
            String key = entrySet.getKey();
            List<String> value = entrySet.getValue();
            multipartParameters.put(key, value.toArray(new String[value.size()]));
        }
        return multipartParameters;
    }
    return null;
}