Example usage for org.apache.commons.fileupload FileUploadBase isMultipartContent

List of usage examples for org.apache.commons.fileupload FileUploadBase isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadBase isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest req) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

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

/**
 *
 * @param req/*ww  w .j a  v a2s  .co m*/
 * @param rpcRequest
 * @param service
 * @return
 * @throws Exception
 */
private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service)
        throws Exception {
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) {
        return null;
    }
    int streamsNumber = getInputStreamsNumber(rpcRequest, service);
    boolean isResponseStreamed = service.isBinaryResponse();
    FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR);
    int count = 0;
    final Map<String, InputStream> map = new HashMap();
    final File tempDirectory;
    if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) {
        tempDirectory = createTempUploadDirectory();
        req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory);
    } else {
        tempDirectory = null;
    }
    FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM);
    long availableLength = RpcConfig.getInstance().getMaxRequestSize();
    while (item != null) {
        count++;
        long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize());
        if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first
            File file = new File(tempDirectory, item.getFieldName());
            FileOutputStream fos = new FileOutputStream(file);
            try {
                Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength),
                        fos);
            } catch (MaxLengthExceededException ex) {
                if (maxLength == RpcConfig.getInstance().getMaxFileSize()) {
                    throw new MaxLengthExceededException(
                            "Upload part '" + item.getFieldName() + "' exceeds maximum length ("
                                    + RpcConfig.getInstance().getMaxFileSize() + " bytes)",
                            RpcConfig.getInstance().getMaxFileSize());
                } else {
                    throw new MaxLengthExceededException("Request exceeds maximum length ("
                            + RpcConfig.getInstance().getMaxRequestSize() + " bytes)",
                            RpcConfig.getInstance().getMaxRequestSize());
                }
            }
            map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(),
                    item.getContentType(), file.length(), null));
            availableLength -= file.length();
        } else if (count == streamsNumber) {
            map.put(item.getFieldName(),
                    new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength),
                            item.getName(), item.getContentType(), null, null));
            break;
        }
        req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
        if (iter.hasNext()) {
            item = iter.next();
        } else {
            item = null;
        }
    }
    if (count != streamsNumber) {
        throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files ("
                + count + ") does not match expected (" + streamsNumber + ")");
    }
    return map;
}

From source file:org.chiba.web.servlet._HttpRequestHandler.java

/**
 * Parses a HTTP request. Returns an array containing maps for upload
 * controls, other controls, repeat indices, and trigger. The individual
 * maps may be null in case no corresponding parameters appear in the
 * request.// ww w.  j ava2s  .  c  o m
 *
 * @param request a HTTP request.
 * @return an array of maps containing the parsed request parameters.
 * @throws FileUploadException if an error occurred during file upload.
 * @throws UnsupportedEncodingException if an error occurred during
 * parameter value decoding.
 */
protected Map[] parseRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map[] parameters = new Map[4];

    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        UploadListener uploadListener = new UploadListener(request, this.sessionKey);
        DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener);
        factory.setRepository(new File(this.uploadRoot));
        ServletFileUpload upload = new ServletFileUpload(factory);

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

        Iterator iterator = upload.parseRequest(request).iterator();
        FileItem item;
        while (iterator.hasNext()) {
            item = (FileItem) iterator.next();

            if (item.isFormField()) {
                LOGGER.info("request param: " + item.getFieldName() + " - value='" + item.getString() + "'");
            } else {
                LOGGER.info("file in request: " + item.getName());
            }

            parseMultiPartParameter(item, encoding, parameters);
        }
    } else {
        Enumeration enumeration = request.getParameterNames();
        String name;
        String[] values;
        while (enumeration.hasMoreElements()) {
            name = (String) enumeration.nextElement();
            values = request.getParameterValues(name);

            parseURLEncodedParameter(name, values, parameters);
        }
    }

    return parameters;
}

From source file:org.exoplatform.services.xmpp.rest.FileExchangeService.java

@POST
public Response upload() throws IOException {
    EnvironmentContext env = EnvironmentContext.getCurrent();
    HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class);
    HttpServletResponse resp = (HttpServletResponse) env.get(HttpServletResponse.class);
    String description = req.getParameter("description");
    String username = req.getParameter("username");
    String requestor = req.getParameter("requestor");
    String isRoom = req.getParameter("isroom");
    boolean isMultipart = FileUploadBase.isMultipartContent(req);
    if (isMultipart) {
        // FileItemFactory factory = new DiskFileUpload();
        // Create a new file upload handler
        // ServletFileUpload upload = new ServletFileUpload(factory);
        DiskFileUpload upload = new DiskFileUpload();
        // Parse the request
        try {//from  ww w.  j  av a2 s  .  c o m
            List<FileItem> items = upload.parseRequest(req);
            XMPPMessenger messenger = (XMPPMessenger) PortalContainer.getInstance()
                    .getComponentInstanceOfType(XMPPMessenger.class);
            for (FileItem fileItem : items) {
                XMPPSessionImpl session = (XMPPSessionImpl) messenger.getSession(username);
                String fileName = fileItem.getName();
                String fileType = fileItem.getContentType();
                if (session != null) {
                    if (fileName != null) {
                        // TODO Check this for compatible or not
                        // It's necessary because IE posts full path of uploaded files
                        fileName = FilenameUtils.getName(fileName);
                        fileType = FilenameUtils.getExtension(fileName);
                        File file = new File(tmpDir);
                        if (file.isDirectory()) {
                            String uuid = UUID.randomUUID().toString();
                            boolean success = (new File(tmpDir + "/" + uuid)).mkdir();
                            if (success) {
                                String path = tmpDir + "/" + uuid + "/" + fileName;
                                File f = new File(path);
                                success = f.createNewFile();
                                if (success) {
                                    // File did not exist and was created
                                    InputStream inputStream = fileItem.getInputStream();
                                    OutputStream out = new FileOutputStream(f);
                                    byte buf[] = new byte[1024];
                                    int len;
                                    while ((len = inputStream.read(buf)) > 0)
                                        out.write(buf, 0, len);
                                    out.close();
                                    inputStream.close();
                                    if (log.isDebugEnabled())
                                        log.debug("File " + path + "is created");
                                    session.sendFile(requestor, path, description,
                                            Boolean.parseBoolean(isRoom));
                                }
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("File already exists");
                            }
                        }
                    }
                } else {
                    if (log.isDebugEnabled())
                        log.debug("XMPPSession for user " + username + " is null!");
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled())
                e.printStackTrace();
            return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build();
        }
    }
    return Response.ok().build();
}

From source file:org.exoplatform.wiki.service.impl.WikiRestServiceImpl.java

@POST
@Path("/upload/{wikiType}/{wikiOwner:.+}/{pageId}/")
public Response upload(@PathParam("wikiType") String wikiType, @PathParam("wikiOwner") String wikiOwner,
        @PathParam("pageId") String pageId) {
    EnvironmentContext env = EnvironmentContext.getCurrent();
    HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class);
    boolean isMultipart = FileUploadBase.isMultipartContent(req);
    if (isMultipart) {
        DiskFileUpload upload = new DiskFileUpload();
        // Parse the request
        try {// ww  w  .ja v a2s  .  c  om
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem fileItem : items) {
                InputStream inputStream = fileItem.getInputStream();
                byte[] imageBytes;
                if (inputStream != null) {
                    imageBytes = new byte[inputStream.available()];
                    inputStream.read(imageBytes);
                } else {
                    imageBytes = null;
                }
                String fileName = fileItem.getName();
                String fileType = fileItem.getContentType();
                if (fileName != null) {
                    // It's necessary because IE posts full path of uploaded files
                    fileName = FilenameUtils.getName(fileName);
                    fileType = FilenameUtils.getExtension(fileName);
                }
                String mimeType = new MimeTypeResolver().getMimeType(fileName);
                WikiResource attachfile = new WikiResource(mimeType, "UTF-8", imageBytes);
                attachfile.setName(fileName);
                if (attachfile != null) {
                    WikiService wikiService = (WikiService) PortalContainer.getComponent(WikiService.class);
                    Page page = wikiService.getExsitedOrNewDraftPageById(wikiType, wikiOwner, pageId);
                    if (page != null) {
                        AttachmentImpl att = ((PageImpl) page).createAttachment(attachfile.getName(),
                                attachfile);
                        ConversationState conversationState = ConversationState.getCurrent();
                        String creator = null;
                        if (conversationState != null && conversationState.getIdentity() != null) {
                            creator = conversationState.getIdentity().getUserId();
                        }
                        att.setCreator(creator);
                        Utils.reparePermissions(att);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build();
        }
    }
    return Response.ok().build();
}

From source file:org.jasig.portlet.cms.controller.EditPostController.java

private void processPostAttachments(final ActionRequest request, final Post post) throws Exception {
    if (FileUploadBase.isMultipartContent(new PortletRequestContext(request))) {

        /*//from www.  j a v  a 2s .c o m
         * Attachments may have been removed in the edit mode. We must
         * refresh the session-bound post before updating attachments.
         */
        final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);
        final Post originalPost = getRepositoryDao().getPost(pref.getPortletRepositoryRoot());

        if (originalPost != null) {
            post.getAttachments().clear();
            post.getAttachments().addAll(originalPost.getAttachments());
        }

        final MultipartActionRequest multipartRequest = (MultipartActionRequest) request;

        for (int index = 0; index < multipartRequest.getFileMap().size(); index++) {
            final MultipartFile file = multipartRequest.getFile("attachment" + index);

            if (!file.isEmpty()) {

                logDebug("Uploading attachment file: " + file.getOriginalFilename());
                logDebug("Attachment file size: " + file.getSize());

                final Calendar cldr = Calendar.getInstance(request.getLocale());
                cldr.setTime(new Date());
                final Attachment attachment = Attachment.fromFile(file.getOriginalFilename(),
                        file.getContentType(), cldr, file.getBytes());

                final String title = multipartRequest.getParameter("attachmentTitle" + index);
                attachment.setTitle(title);
                post.getAttachments().add(attachment);
            }

        }
    }
}

From source file:org.jasig.springframework.web.portlet.upload.Portlet2FileUpload.java

public static final boolean isMultipartContent(ResourceRequest request) {
    return FileUploadBase.isMultipartContent(new PortletResourceRequestContext(request));
}

From source file:org.opencms.ugc.CmsUgcEditService.java

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  w w w.  j  av a  2 s .co  m*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultiPart = FileUploadBase.isMultipartContent(new ServletRequestContext(request));

    if (isMultiPart) {
        try {
            handleUpload(request, response);
        } finally {
            clearThreadStorage();
        }
    } else {
        super.service(request, response);
    }
}

From source file:org.origin.common.servlet.WebConsoleUtil.java

/**
 * An utility method, that is used to filter out simple parameter from file parameter when multipart transfer encoding is used.
 *
 * This method processes the request and sets a request attribute {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map}
 * where the key is a String specifying the field name and the value is a {@link org.apache.commons.fileupload.FileItem}.
 *
 * @param request//from  w w  w  . j ava2s. c  o  m
 *            the HTTP request coming from the user
 * @param name
 *            the name of the parameter
 * @return if not multipart transfer encoding is used - the value is the parameter value or <code>null</code> if not set. If multipart is used, and the
 *         specified parameter is field - then the value of the parameter is returned.
 */
public static final String getParameter(HttpServletRequest request, String name) {
    // just get the parameter if not a multipart/form-data POST
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        return request.getParameter(name);
    }

    // check, whether we already have the parameters
    Map params = (Map) request.getAttribute(ATTR_FILEUPLOAD);
    if (params == null) {
        // parameters not read yet, read now
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(256000);
        // See https://issues.apache.org/jira/browse/FELIX-4660
        final Object repo = request.getAttribute(ATTR_FILEUPLOAD_REPO);
        if (repo instanceof File) {
            factory.setRepository((File) repo);
        }

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);

        // Parse the request
        params = new HashMap();
        try {
            List items = upload.parseRequest(request);
            for (Iterator fiter = items.iterator(); fiter.hasNext();) {
                FileItem fi = (FileItem) fiter.next();
                FileItem[] current = (FileItem[]) params.get(fi.getFieldName());
                if (current == null) {
                    current = new FileItem[] { fi };
                } else {
                    FileItem[] newCurrent = new FileItem[current.length + 1];
                    System.arraycopy(current, 0, newCurrent, 0, current.length);
                    newCurrent[current.length] = fi;
                    current = newCurrent;
                }
                params.put(fi.getFieldName(), current);
            }
        } catch (FileUploadException fue) {
            // TODO: log
        }
        request.setAttribute(ATTR_FILEUPLOAD, params);
    }

    FileItem[] param = (FileItem[]) params.get(name);
    if (param != null) {
        for (int i = 0; i < param.length; i++) {
            if (param[i].isFormField()) {
                return param[i].getString();
            }
        }
    }

    // no valid string parameter, fail
    return null;
}

From source file:org.seasar.cadhelin.ControllerServlet.java

protected HttpServletRequest createHttpRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    ServletRequestContext context = new ServletRequestContext(request);
    if (FileUploadBase.isMultipartContent(context)) {
        MultipartRequestWrapper wrapper = new MultipartRequestWrapper(request);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List list = upload.parseRequest(context);
        wrapper.setFileItems(list);//  w ww.j a  va 2  s  .c  o  m
        return wrapper;
    } else {
        return request;
    }
}

From source file:org.seasar.cubby.controller.impl.MultipartRequestParser.java

/**
 * {@inheritDoc}/*from  www.j av a  2 s.co m*/
 * <p>
 * ??????? (contentType ? "multipart/" ??) ???
 * <code>true</code> ???
 * </p>
 * 
 * @see FileUpload#isMultipartContent(RequestContext)
 */
public boolean isParsable(final HttpServletRequest request) {
    final Container container = ProviderFactory.get(ContainerProvider.class).getContainer();
    try {
        final RequestContext requestContext = container.lookup(RequestContext.class);
        return FileUploadBase.isMultipartContent(requestContext);
    } catch (final LookupException e) {
        return false;
    }
}