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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

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   ww  w  .  j ava 2s  . 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.eclipse.rap.addons.fileupload.internal.FileUploadProcessor.java

private void receive(FileItemStream item) throws IOException {
    InputStream stream = item.openStream();
    try {/*w w w . j  ava 2 s  .c om*/
        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 {//from w  ww  .  j  ava 2  s  .c o  m
        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 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 {/* w w  w.j  av  a 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  www .  j a  v a2 s.  c  o  m
    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));
        }
    }
}

From source file:org.elfinder.servlets.AbstractConnectorServlet.java

/**
 * Parse request parameters and files.//w ww.  j  a  va2s  .com
 * @param request
 * @param response
 */
protected void parseRequest(HttpServletRequest request, HttpServletResponse response) {
    requestParams = new HashMap<String, Object>();
    listFiles = new ArrayList<FileItemStream>();
    listFileStreams = new ArrayList<ByteArrayOutputStream>();

    // Parse the request
    if (ServletFileUpload.isMultipartContent(request)) {
        // multipart request
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);

            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    requestParams.put(name, Streams.asString(stream));
                } else {
                    String fileName = item.getName();
                    if (fileName != null && !"".equals(fileName.trim())) {
                        listFiles.add(item);

                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        IOUtils.copy(stream, os);
                        listFileStreams.add(os);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Unexpected error parsing multipart content", e);
        }
    } else {
        // not a multipart
        for (Object mapKey : request.getParameterMap().keySet()) {
            String mapKeyString = (String) mapKey;

            if (mapKeyString.endsWith("[]")) {
                // multiple values
                String values[] = request.getParameterValues(mapKeyString);
                List<String> listeValues = new ArrayList<String>();
                for (String value : values) {
                    listeValues.add(value);
                }
                requestParams.put(mapKeyString, listeValues);
            } else {
                // single value
                String value = request.getParameter(mapKeyString);
                requestParams.put(mapKeyString, value);
            }
        }
    }
}

From source file:org.epics.archiverappliance.mgmt.bpl.UploadChannelArchiverConfigAction.java

@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, ConfigService configService)
        throws IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        throw new IOException("HTTP request is not sending multipart content; therefore we cannnot process");
    }/*  www  .  j av a 2  s .  co  m*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    List<String> fieldsAsPartOfStream = ArchivePVAction.getFieldsAsPartOfStream(configService);
    try (PrintWriter out = new PrintWriter(new NullOutputStream())) {
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                logger.debug("Form field " + name + " detected.");
            } else {
                logger.debug("File field " + name + " with file name " + item.getName() + " detected.");
                try (InputStream is = new BufferedInputStream(item.openStream())) {
                    is.mark(1024);
                    logger.info((new LineNumberReader(new InputStreamReader(is))).readLine());
                    is.reset();
                    LinkedList<PVConfig> pvConfigs = EngineConfigParser.importEngineConfig(is);
                    for (PVConfig pvConfig : pvConfigs) {
                        boolean scan = !pvConfig.isMonitor();
                        float samplingPeriod = pvConfig.getPeriod();
                        if (logger.isDebugEnabled())
                            logger.debug("Adding " + pvConfig.getPVName() + " using "
                                    + (scan ? SamplingMethod.SCAN : SamplingMethod.MONITOR)
                                    + " and a period of " + samplingPeriod);
                        ArchivePVAction.archivePV(out, pvConfig.getPVName(), true,
                                scan ? SamplingMethod.SCAN : SamplingMethod.MONITOR, samplingPeriod, null, null,
                                null, false, configService, fieldsAsPartOfStream);
                    }
                } catch (Exception ex) {
                    logger.error("Error importing configuration", ex);
                    resp.sendRedirect("../ui/integration.html?message=Error importing config file "
                            + item.getName() + " " + ex.getMessage());
                    return;
                }
            }
        }
        resp.sendRedirect("../ui/integration.html?message=Successfully imported configuration files");
    } catch (FileUploadException ex) {
        throw new IOException(ex);
    }

}

From source file:org.fcrepo.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request/*  w  w  w. j av  a 2  s. c  o m*/
 */
public static 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)) {

        logger.debug("processing multipart content...");
        // 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 {
                logger.trace("ignoring form field \"{}\" \"{}\"", item.getFieldName(), item.getName());
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            String contentLength = request.getHeader("Content-Length");
            long size = 0;
            if (contentLength != null) {
                size = Long.parseLong(contentLength);
            } else
                size = request.getContentLength();
            if (size > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = size;
            } 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;
                    }
                } else {
                    logger.warn(
                            "Expected chunked data not found- " + "Transfer-Encoding : {}, Content-Length: {}",
                            transferEncoding, size);
                }
            }
        }
    }

    // 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.gatein.wsrp.consumer.handlers.MultiPartUtil.java

public static MultiPartResult getMultiPartContent(RequestContext requestContext) {
    RequestContextWrapper requestContextWrapper = new RequestContextWrapper(requestContext);
    MultiPartResult result = null;//www .j a  va  2s .  c om

    try {
        if (FileUpload.isMultipartContent(requestContextWrapper)) {
            result = new MultiPartResult();
            // content is multipart, we need to parse it (that includes form parameters)
            FileUpload upload = new FileUpload();
            FileItemIterator iter = upload.getItemIterator(requestContextWrapper);
            List<UploadContext> uploadContexts = new ArrayList<UploadContext>(7);
            List<NamedString> formParameters = new ArrayList<NamedString>(7);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    if (log.isDebugEnabled()) {
                        log.debug("File field " + item.getFieldName() + " with file name " + item.getName()
                                + " and content type " + contentType + " detected.");
                    }

                    BufferedInputStream bufIn = new BufferedInputStream(stream);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    BufferedOutputStream bos = new BufferedOutputStream(baos);

                    int c = bufIn.read();
                    while (c != -1) {
                        bos.write(c);
                        c = bufIn.read();
                    }

                    bos.flush();
                    baos.flush();
                    bufIn.close();
                    bos.close();

                    final byte[] uploadData = baos.toByteArray();
                    if (uploadData.length != 0) {
                        UploadContext uploadContext = WSRPTypeFactory.createUploadContext(contentType,
                                uploadData);

                        List<NamedString> mimeAttributes = new ArrayList<NamedString>(2);

                        String value = FileUpload.FORM_DATA + ";" + " name=\"" + item.getFieldName() + "\";"
                                + " filename=\"" + item.getName() + "\"";
                        NamedString mimeAttribute = WSRPTypeFactory
                                .createNamedString(FileUpload.CONTENT_DISPOSITION, value);
                        mimeAttributes.add(mimeAttribute);

                        mimeAttribute = WSRPTypeFactory.createNamedString(FileUpload.CONTENT_TYPE,
                                item.getContentType());
                        mimeAttributes.add(mimeAttribute);

                        uploadContext.getMimeAttributes().addAll(mimeAttributes);

                        uploadContexts.add(uploadContext);
                    } else {
                        log.debug("Ignoring empty file " + item.getName());
                    }
                } else {
                    NamedString formParameter = WSRPTypeFactory.createNamedString(item.getFieldName(),
                            Streams.asString(stream));
                    formParameters.add(formParameter);
                }
            }

            result.getUploadContexts().addAll(uploadContexts);
            result.getFormParameters().addAll(formParameters);
        }
    } catch (Exception e) {
        log.debug("Couldn't create UploadContext", e);
    }
    return result;
}

From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java

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

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    SettingsBean settingsBean = SettingsBean.getInstance();
    final long fileSizeLimit = settingsBean.getJahiaFileUploadMaxSize();
    upload.setHeaderEncoding("UTF-8");
    Map<String, FileItem> uploads = new HashMap<String, FileItem>();
    String location = null;//from ww  w. ja  v a 2  s  .c  o  m
    String type = null;
    boolean unzip = false;
    response.setContentType("text/plain; charset=" + settingsBean.getCharacterEncoding());
    final PrintWriter printWriter = response.getWriter();
    try {
        FileItemIterator itemIterator = upload.getItemIterator(request);
        FileSizeLimitExceededException sizeLimitExceededException = null;
        while (itemIterator.hasNext()) {
            final FileItemStream item = itemIterator.next();
            if (sizeLimitExceededException != null) {
                continue;
            }
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            long contentLength = getContentLength(item.getHeaders());

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

            InputStream limitedInputStream = null;
            try {
                limitedInputStream = fileSizeLimit > 0 ? new LimitedInputStream(itemStream, fileSizeLimit) {

                    @Override
                    protected void raiseError(long pSizeMax, long pCount) throws IOException {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted size of "
                                        + fileSizeLimit + " bytes.",
                                pCount, pSizeMax));
                    }
                } : itemStream;

                Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                if (e.getCause() instanceof FileSizeLimitExceededException) {
                    if (sizeLimitExceededException == null) {
                        sizeLimitExceededException = (FileSizeLimitExceededException) e.getCause();
                    }
                } else {
                    throw e;
                }
            } finally {
                IOUtils.closeQuietly(limitedInputStream);
            }

            if ("unzip".equals(fileItem.getFieldName())) {
                unzip = true;
            } else if ("uploadLocation".equals(fileItem.getFieldName())) {
                location = fileItem.getString("UTF-8");
            } else if ("asyncupload".equals(fileItem.getFieldName())) {
                String name = fileItem.getName();
                if (name.trim().length() > 0) {
                    uploads.put(extractFileName(name, uploads), fileItem);
                }
                type = "async";
            } else if (!fileItem.isFormField() && fileItem.getFieldName().startsWith("uploadedFile")) {
                String name = fileItem.getName();
                if (name.trim().length() > 0) {
                    uploads.put(extractFileName(name, uploads), fileItem);
                }
                type = "sync";
            }
        }
        if (sizeLimitExceededException != null) {
            throw sizeLimitExceededException;
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, e, request) + "\n");
        return;
    } catch (FileUploadIOException e) {
        if (e.getCause() != null && (e.getCause() instanceof FileSizeLimitExceededException)) {
            printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit,
                    (FileSizeLimitExceededException) e.getCause(), request) + "\n");
        } else {
            logger.error("UPLOAD-ISSUE", e);
            printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
        }
        return;
    } catch (FileUploadException e) {
        logger.error("UPLOAD-ISSUE", e);
        printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
        return;
    }

    if (type == null || type.equals("sync")) {
        response.setContentType("text/plain");

        final JahiaUser user = (JahiaUser) request.getSession().getAttribute(Constants.SESSION_USER);

        final List<String> pathsToUnzip = new ArrayList<String>();
        for (String fileName : uploads.keySet()) {
            final FileItem fileItem = uploads.get(fileName);
            try {
                StringBuilder name = new StringBuilder(fileName);
                final int saveResult = saveToJcr(user, fileItem, location, name);
                switch (saveResult) {
                case OK:
                    if (unzip && fileName.toLowerCase().endsWith(".zip")) {
                        pathsToUnzip.add(
                                new StringBuilder(location).append("/").append(name.toString()).toString());
                    }
                    printWriter.write("OK: " + UriUtils.encode(name.toString()) + "\n");
                    break;
                case EXISTS:
                    storeUploadedFile(request.getSession().getId(), fileItem);
                    printWriter.write("EXISTS: " + UriUtils.encode(fileItem.getFieldName()) + " "
                            + UriUtils.encode(fileItem.getName()) + " " + UriUtils.encode(fileName) + "\n");
                    break;
                case READONLY:
                    printWriter.write("READONLY: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                    break;
                default:
                    printWriter.write("UPLOAD-FAILED: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                    break;
                }
            } catch (IOException e) {
                logger.error("Upload failed for file \n", e);
            } finally {
                fileItem.delete();
            }
        }

        // direct blocking unzip
        if (unzip && pathsToUnzip.size() > 0) {
            try {
                ZipHelper zip = ZipHelper.getInstance();
                //todo : in which workspace do we upload ?
                zip.unzip(pathsToUnzip, true, JCRSessionFactory.getInstance().getCurrentUserSession(),
                        (Locale) request.getSession().getAttribute(Constants.SESSION_UI_LOCALE));
            } catch (RepositoryException e) {
                logger.error("Auto-unzipping failed", e);
            } catch (GWTJahiaServiceException e) {
                logger.error("Auto-unzipping failed", e);
            }
        }
    } else {
        response.setContentType("text/html");
        for (FileItem fileItem : uploads.values()) {
            storeUploadedFile(request.getSession().getId(), fileItem);
            printWriter.write("<html><body>");
            printWriter.write("<div id=\"uploaded\" key=\"" + fileItem.getName() + "\" name=\""
                    + fileItem.getName() + "\"></div>\n");
            printWriter.write("</body></html>");
        }
    }
}