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.daxplore.presenter.server.servlets.AdminUploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {/*  ww  w  .  j a  v a2s .  c  o  m*/
        long time = System.nanoTime();
        int statusCode = HttpServletResponse.SC_OK;
        response.setContentType("text/html; charset=UTF-8");

        ServletFileUpload upload = new ServletFileUpload();
        PersistenceManager pm = null;
        String prefix = null;
        try {
            FileItemIterator fileIterator = upload.getItemIterator(request);
            String fileName = "";
            byte[] fileData = null;
            while (fileIterator.hasNext()) {
                FileItemStream item = fileIterator.next();
                try (InputStream stream = item.openStream()) {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("prefix")) {
                            prefix = Streams.asString(stream);
                        } else {
                            throw new BadRequestException("Form contains extra fields");
                        }
                    } else {
                        fileName = item.getName();
                        fileData = IOUtils.toByteArray(stream);
                    }
                }
            }
            if (SharedResourceTools.isSyntacticallyValidPrefix(prefix)) {
                if (fileData != null && !fileName.equals("")) {
                    pm = PMF.get().getPersistenceManager();
                    unzipAll(pm, prefix, fileData);
                } else {
                    throw new BadRequestException("No file uploaded");
                }
            } else {
                throw new BadRequestException("Request made with invalid prefix: '" + prefix + "'");
            }
            logger.log(Level.INFO, "Unpacked new data for prefix '" + prefix + "' in "
                    + ((System.nanoTime() - time) / 1000000000.0) + " seconds");
        } catch (FileUploadException | IOException | BadRequestException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
            statusCode = HttpServletResponse.SC_BAD_REQUEST;
        } catch (InternalServerException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        } catch (DeadlineExceededException e) {
            logger.log(Level.SEVERE, "Timeout when uploading new data for prefix '" + prefix + "'", e);
            // the server is currently unavailable because it is overloaded (hopefully)
            statusCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
        } finally {
            if (pm != null) {
                pm.close();
            }
        }

        response.setStatus(statusCode);
        try (PrintWriter resWriter = response.getWriter()) {
            if (resWriter != null) {
                resWriter.write(Integer.toString(statusCode));
                resWriter.close();
            }
        }
    } catch (IOException | RuntimeException e) {
        logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.dspace.rest.providers.AbstractBaseProvider.java

public Object translateFormattedData(EntityReference ref, String format, InputStream input,
        Map<String, Object> params) {
    String IS = "";
    if (format.equals("xml") || format.equals("json")) {
        try {/*from  ww  w  . j a  va2  s  .  co  m*/
            IS = readIStoString(input);
            //                System.out.println("is+= " + IS);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    Map<String, Object> decodedInput = null;
    EntityEncodingManager em = new EntityEncodingManager(null, null);
    if (format.equals("xml")) {
        decodedInput = em.decodeData(IS, Formats.XML);
    } else if (format.equals("json")) {
        decodedInput = em.decodeData(IS, Formats.JSON);
    } else if (format.equals("stream")) {
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(requestGetter.getRequest());
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                return item.openStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    System.out.println("== translate formated data called");
    System.out.println("got: \n" + IS + "\ndecoded " + decodedInput);
    return decodedInput;
}

From source file:org.duracloud.common.rest.RestUtilImpl.java

/**
 * Retrieves the contents of the HTTP Request.
 *
 * @return InputStream from the request/*w ww .  ja  v  a  2s  .  co  m*/
 */
@Override
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 = Long.parseLong(contentLength);
                    }
                }

                break;
            }
        }
    } else {
        // If the content stream was not found as a multipart,
        // try to use the stream from the request directly
        rContent = new RequestContent();
        rContent.contentStream = request.getInputStream();
        if (request.getContentLength() >= 0) {
            rContent.size = request.getContentLength();
        }
    }

    // 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 = Long.parseLong(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:org.duracloud.duradmin.spaces.controller.ContentItemUploadController.java

@RequestMapping(value = "/spaces/content/upload", method = RequestMethod.POST)
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {//from www.j a  v  a 2  s  .c  o  m
        log.debug("handling request...");

        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        String spaceId = null;
        String storeId = null;
        String contentId = null;
        List<ContentItem> results = new ArrayList<ContentItem>();

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                String value = Streams.asString(item.openStream(), "UTF-8");
                if (item.getFieldName().equals("spaceId")) {
                    log.debug("setting spaceId: {}", value);
                    spaceId = value;
                } else if (item.getFieldName().equals("storeId")) {
                    storeId = value;
                } else if (item.getFieldName().equals("contentId")) {
                    contentId = value;
                }
            } else {
                log.debug("setting fileStream: {}", item);

                if (StringUtils.isBlank(spaceId)) {
                    throw new IllegalArgumentException("space id required.");
                }

                ContentItem ci = new ContentItem();
                if (StringUtils.isBlank(contentId)) {
                    contentId = item.getName();
                }

                ci.setContentId(contentId);
                ci.setSpaceId(spaceId);
                ci.setStoreId(storeId);
                ci.setContentMimetype(item.getContentType());
                ContentStore contentStore = contentStoreManager.getContentStore(ci.getStoreId());
                ContentItemUploadTask task = new ContentItemUploadTask(ci, contentStore, item.openStream(),
                        request.getUserPrincipal().getName());

                task.execute();
                ContentItem result = new ContentItem();
                Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication();
                SpaceUtil.populateContentItem(ContentItemController.getBaseURL(request), result,
                        ci.getSpaceId(), ci.getContentId(), contentStore, auth);
                results.add(result);
                contentId = null;
            }
        }

        return new ModelAndView("javascriptJsonView", "results", results);

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    }

}

From source file:org.ebayopensource.turmeric.policy.adminui.server.PlcImportServlet.java

/**
 * Parses the input stream./*  w  ww . j a  v  a 2 s.  c  om*/
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the byte array output stream
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public ByteArrayOutputStream parseInputStream(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            // Process the input stream
            int len;
            byte[] buffer = new byte[8192];
            while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }

            int maxFileSize = 10 * (1024 * 1024); // 10 megs max
            if (out.size() > maxFileSize) {
                response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                        "Max allowed file size: 10 Mb");
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return out;
}

From source file:org.eclipse.rap.addons.fileupload.internal.FileUploadProcessor.java

private void receive(FileItemStream item) throws IOException {
    InputStream stream = item.openStream();
    try {//from  w w w  .ja  v  a 2  s.c o m
        String fileName = stripFileName(item.getName());
        String contentType = item.getContentType();
        FileDetails details = new FileDetailsImpl(fileName, contentType, -1);
        FileUploadReceiver receiver = handler.getReceiver();
        receiver.receive(stream, details);
        tracker.addFile(details);
    } finally {
        stream.close();
    }
}

From source file:org.eclipse.rap.fileupload.internal.FileUploadProcessor.java

private void receive(FileItemStream item) throws IOException {
    InputStream stream = item.openStream();
    try {// ww  w.  ja v  a2 s  .  c  om
        String fileName = stripFileName(item.getName());
        String contentType = item.getContentType();
        FileDetails details = new FileDetailsImpl(fileName, contentType);
        FileUploadReceiver receiver = handler.getReceiver();
        receiver.receive(stream, details);
        tracker.addFile(details);
    } finally {
        stream.close();
    }
}

From source file:org.eclipse.rdf4j.workbench.util.WorkbenchRequest.java

private String firstLine(FileItemStream item) throws IOException {
    InputStream stream = item.openStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    try {/*from  w  w  w  .  jav  a2s .  c o  m*/
        return reader.readLine();
    } finally {
        reader.close();
    }
}

From source file:org.eclipse.rdf4j.workbench.util.WorkbenchRequest.java

private Map<String, String> getMultipartParameterMap()
        throws RepositoryException, IOException, FileUploadException {
    Map<String, String> parameters = new HashMap<String, String>();
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(this);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        if ("content".equals(name)) {
            content = item.openStream();
            contentFileName = item.getName();
            break;
        } else {/*from w w  w.  j  a  va 2  s  .  c  o m*/
            parameters.put(name, firstLine(item));
        }
    }
    return parameters;
}

From source file:org.eclipse.scout.rt.ui.html.json.UploadRequestHandler.java

protected void readUploadData(HttpServletRequest httpReq, long maxSize, Map<String, String> uploadProperties,
        List<BinaryResource> uploadResources) throws FileUploadException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
    upload.setSizeMax(maxSize);/*from   w  ww .j  a  va 2  s .  c  om*/
    for (FileItemIterator it = upload.getItemIterator(httpReq); it.hasNext();) {
        FileItemStream item = it.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
            // Handle non-file fields (interpreted as properties)
            uploadProperties.put(name, Streams.asString(stream, StandardCharsets.UTF_8.name()));
        } else {
            // Handle files
            String filename = item.getName();
            if (StringUtility.hasText(filename)) {
                String[] parts = StringUtility.split(filename, "[/\\\\]");
                filename = parts[parts.length - 1];
            }
            String contentType = item.getContentType();
            byte[] content = IOUtility.getContent(stream);
            // Info: we cannot set the charset property for uploaded files here, because we simply don't know it.
            // the only thing we could do is to guess the charset (encoding) by reading the byte contents of
            // uploaded text files (for binary file types the encoding is not relevant). However: currently we
            // do not set the charset at all.
            uploadResources.add(new BinaryResource(filename, contentType, content));
        }
    }
}