Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

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

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private Vector uploadTmpAttachmentFile(HttpServletRequest request, HttpSession session) {
    String tmpFoler = request.getParameter("folder");
    String uploadPath = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
            + File.separator + "CommentReference" + File.separator + "tmp" + File.separator + tmpFoler;
    try {/*from w w  w .jav  a  2  s . com*/
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);

            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    String fileName = item.getFieldName();
                    String filePath = uploadPath + File.separator + fileName;
                    File f = new File(filePath);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }
    return new Vector();
}

From source file:com.look.UploadPostServlet.java

/***************************************************************************
 * Processes request data and saves into instance variables
 * @param request HttpServletRequest from client
 * @return True if successfully handled, false otherwise
 *//*from   w  ww.j  a v a 2  s  .  c  o m*/
private boolean handleRequest(HttpServletRequest request) {
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            boolean success = true;
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String filename = item.getName();
                    if (filename.equals("")) {
                        //only update responseMessage if there isn't one yet
                        if (responseMessage.equals("")) {
                            responseMessage = "Please choose an image";
                        }
                        success = false;
                    }
                    String clientFileName = FilenameUtils.getName("TEMP_" + item.getName().replaceAll(" ", ""));

                    imageExtension = FilenameUtils.getExtension(clientFileName);
                    imageURL = clientFileName + "." + imageExtension;
                    fileContent = item.getInputStream();
                } else {
                    String fieldName = item.getFieldName();
                    String value = item.getString();
                    //only title is required
                    if (value.equals("") && (fieldName.equals("title"))) {
                        responseMessage = "Please enter a title";
                        success = false;
                    }
                    switch (fieldName) {
                    case TITLE_FIELD_NAME:
                        title = value;
                        break;
                    case DESCRIPTION_FIELD_NAME:
                        description = value;
                        break;
                    case TAGS_FIELD_NAME:
                        tags = value;
                        if (!tags.equals("")) {
                            tagList = new LinkedList<>(Arrays.asList(tags.split(" ")));
                            for (int i = 0; i < tagList.size(); i++) {
                                String tag = tagList.get(i);
                                if (tag.charAt(0) != '#') {
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must begin with #";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else if (!StringUtils.isAlphanumeric(tag.substring(1))) {
                                    log.info(tag.substring(1));
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must only contain numbers and letters";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else if (tag.length() > 20) {
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must be 20 characters or less";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else {
                                    //tag is valid, remove the '#' for storage
                                    tagList.set(i, tag.substring(1));
                                }
                            }
                        }
                        //now have list of alphanumeric tags of 20 chars or less
                        break;
                    }
                }
            }
            if (!success) {
                return false;
            }
        } catch (FileUploadException | IOException ex) {
            Logger.getLogger(UploadPostServlet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        request.setAttribute("message", "File upload request not found");
        return false;
    }

    return true;
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyServiceImpl.java

/**
 * Performs an HTTP request//from w  w w .  j av  a  2  s .c  o  m
 * 
 * @param httpServletRequest The {@link HttpServletRequest} object passed in by the servlet engine representing the client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which we can send a proxied response to the client
 */
public void doMethod(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    ProxyMethodConfig methodConfig = proxyHelper.prepareProxyMethod(httpServletRequest, httpServletResponse,
            this);

    if (methodConfig != null) {

        // //////////////////////////////
        // Create a request
        // //////////////////////////////

        HttpMethod methodProxyRequest = methodConfig.getMethod();

        // //////////////////////////////
        // Forward the request headers
        // //////////////////////////////

        final ProxyInfo proxyInfo = setProxyRequestHeaders(methodConfig.getUrl(), httpServletRequest,
                methodProxyRequest);

        // //////////////////////////////////////////////////
        // Check if this is a mulitpart (file upload) PUT | POST
        // //////////////////////////////////////////////////

        if (methodProxyRequest instanceof EntityEnclosingMethod) {
            if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
                this.handleMultipart((EntityEnclosingMethod) methodProxyRequest, httpServletRequest);
            } else {
                this.handleStandard((EntityEnclosingMethod) methodProxyRequest, httpServletRequest);
            }
        }

        // //////////////////////////////
        // Execute the proxy request
        // //////////////////////////////

        this.executeProxyRequest(methodProxyRequest, httpServletRequest, httpServletResponse,
                methodConfig.getUser(), methodConfig.getPassword(), proxyInfo);

    }
}

From source file:com.britesnow.snow.web.RequestContext.java

private void initParamsIfNeeded() {
    if (!isParamInitialized) {
        isMultipart = ServletFileUpload.isMultipartContent(getReq());
        if (isMultipart) {
            try {
                fileItems = fileUploader.parseRequest(getReq());
                paramMap = new HashMap<String, Object>();

                Map<String, Class> paramBaseClasses = new HashMap<String, Class>();
                boolean hasMultivalues = false;

                for (Object item : fileItems) {
                    FileItem fileItem = (FileItem) item;
                    String paramName = fileItem.getFieldName();

                    // in case of normal fields, take the string value. otherwise
                    // put the whole file item into the map.
                    Object value;
                    Class paramBaseClass;
                    if (fileItem.isFormField()) {
                        try {
                            value = fileItem.getString("UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            value = fileItem.getString();
                        }/*from w w  w . ja  v a 2s. co m*/
                        paramBaseClass = String.class;
                    } else {
                        value = fileItem;
                        paramBaseClass = FileItem.class;
                    }

                    // make sure that the client isn't calling something that is mixing and
                    // matching parameter types...
                    // todo - could support this as Object arrays or arrays of most specific shared super class.
                    Class prevBaseClass = paramBaseClasses.put(paramName, paramBaseClass);
                    if (prevBaseClass != null && !prevBaseClass.equals(paramBaseClass)) {
                        throw new IllegalArgumentException("parameter " + paramName
                                + " has mixed parameter types (expected all file or all string)");
                    }

                    // if there is already a value, then, create a list
                    if (paramMap.containsKey(paramName)) {
                        hasMultivalues = true;
                        Object prevValue = paramMap.get(paramName);
                        if (prevValue instanceof List) {
                            ((List) prevValue).add(value);
                        } else {
                            List values = new ArrayList(2);
                            values.add(prevValue);
                            values.add(value);
                            paramMap.put(paramName, values);
                        }
                    } else {
                        paramMap.put(paramName, value);
                    }
                }

                // if we had multivalues, need to change the list to arrays
                if (hasMultivalues) {
                    for (String name : paramMap.keySet()) {
                        Object value = paramMap.get(name);
                        if (value instanceof List) {
                            List valueList = (List) value;
                            Object[] valueArray = (Object[]) Array.newInstance(paramBaseClasses.get(name),
                                    valueList.size());
                            valueList.toArray(valueArray);
                            paramMap.put(name, valueArray);
                        }
                    }
                }
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage());
            }
        } else {
            paramMap = new HashMap<String, Object>();
            // By the httpServletRequest spect, we can assume the type of
            // the return Map (name and values)
            Map<String, String[]> reqMap = getReq().getParameterMap();
            // now, simplify the map, by replacing single string array to
            // the string itself.
            for (String paramName : reqMap.keySet()) {
                String[] values = reqMap.get(paramName);
                if (values.length == 1) {
                    paramMap.put(paramName, values[0]);
                } else {
                    paramMap.put(paramName, values);
                }
            }
        }
        isParamInitialized = true;
    }
}

From source file:com.groupon.odo.Proxy.java

/**
 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse
 * response)/*from   w ww  .jav  a  2 s.  c o m*/
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // create thread specific session data
    requestInformation.set(new RequestInformation());

    History history = new History();
    logOriginalRequestHistory("PUT", request, history);

    try {
        PutMethod putMethodProxyRequest = new PutMethod(
                this.getProxyURL(request, history, Constants.REQUEST_TYPE_PUT));
        // Forward the request headers
        setProxyRequestHeaders(request, putMethodProxyRequest);
        // Check if this is a multipart (file upload) POST
        if (ServletFileUpload.isMultipartContent(request)) {
            logger.info("PUT:: Multipart");
            DiskFileItemFactory diskFactory = createDiskFactory();
            HttpUtilities.handleMultipartPost(putMethodProxyRequest, request, diskFactory);
        } else {
            logger.info("PUT:: Not Multipart");
            HttpUtilities.handleStandardPost(putMethodProxyRequest, request, history);
        }

        // use body filter to filter paths
        this.cullPathsByBodyFilter(history);

        // Execute the proxy request
        this.executeProxyRequest(putMethodProxyRequest, request, response, history);
    } catch (Exception e) {
        // TODO log to history
        logger.info("ERROR: cannot execute request: {}", e.getMessage());
    }
}

From source file:com.google.zxing.web.DecodeServlet.java

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

    if (!ServletFileUpload.isMultipartContent(request)) {
        log.info("File upload was not multipart");
        response.sendRedirect("badimage.jspx");
        return;//from  w ww  .  ja v a  2  s . c  o  m
    }

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
    upload.setFileSizeMax(MAX_IMAGE_SIZE);

    // Parse the request
    try {
        for (FileItem item : upload.parseRequest(request)) {
            if (!item.isFormField()) {
                if (item.getSize() <= MAX_IMAGE_SIZE) {
                    log.info("Decoding uploaded file");
                    try (InputStream is = item.getInputStream()) {
                        processStream(is, request, response);
                    }
                } else {
                    log.info("Too large");
                    response.sendRedirect("badimage.jspx");
                }
                break;
            }
        }
    } catch (FileUploadException fue) {
        log.info(fue.toString());
        response.sendRedirect("badimage.jspx");
    }

}

From source file:com.ms.commons.summer.web.multipart.CommonsMultipartEngancedResolver.java

public boolean isMultipart(HttpServletRequest request) {
    if (request == null) {
        return false;
    } else if (commonsFileUpload12Present) {
        return ServletFileUpload.isMultipartContent(request);
    } else {/*from  www .j  a v a 2 s  .c  o m*/
        return ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
    }
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void createFile(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws IndelibleWebAccessException, IOException, ServletException, FileUploadException {
    boolean completedOK = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    if (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fieldName = item.getFieldName();
        FilePath dirPath = null;//  ww  w  . ja va2 s.c  o m
        if (fieldName.equals("upfile")) {
            try {
                connection.startTransaction();
                String path = req.getPathInfo();
                String fileName = item.getName();
                if (fileName.indexOf('/') >= 0)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
                dirPath = FilePath.getFilePath(path);
                FilePath reqPath = dirPath.getChild(fileName);
                if (reqPath == null || reqPath.getNumComponents() < 2)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

                // Should be an absolute path
                reqPath = reqPath.removeLeadingComponent();
                String fsIDStr = reqPath.getComponent(0);
                IndelibleFSVolumeIF volume = getVolume(fsIDStr);
                if (volume == null)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError,
                            null);
                FilePath createPath = reqPath.removeLeadingComponent();
                FilePath parentPath = createPath.getParent();
                FilePath childPath = createPath.getPathRelativeTo(parentPath);
                if (childPath.getNumComponents() != 1)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
                IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute());
                if (!parentNode.isDirectory())
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
                IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode;
                IndelibleFileNodeIF childNode = null;
                childNode = parentDirectory.getChildNode(childPath.getName());
                if (childNode == null) {
                    try {
                        CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true);
                        childNode = childInfo.getCreatedNode();
                    } catch (FileExistsException e) {
                        // Probably someone else beat us to it...
                        childNode = parentDirectory.getChildNode(childPath.getName());
                    }
                } else {

                }
                if (childNode.isDirectory())
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null);

                IndelibleFSForkIF dataFork = childNode.getFork("data", true);
                dataFork.truncate(0);
                InputStream readStream = item.openStream();
                byte[] writeBuffer = new byte[1024 * 1024];
                int readLength;
                long bytesCopied = 0;
                int bufOffset = 0;
                while ((readLength = readStream.read(writeBuffer, bufOffset,
                        writeBuffer.length - bufOffset)) > 0) {
                    if (bufOffset + readLength == writeBuffer.length) {
                        dataFork.appendDataDescriptor(
                                new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length));
                        bufOffset = 0;
                    } else
                        bufOffset += readLength;
                    bytesCopied += readLength;
                }
                if (bufOffset != 0) {
                    // Flush out the final stuff
                    dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset));
                }
                connection.commit();
                completedOK = true;
            } catch (PermissionDeniedException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
            } catch (IOException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
            } catch (ObjectNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
            } catch (ForkNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e);
            } finally {
                if (!completedOK)
                    try {
                        connection.rollback();
                    } catch (IOException e) {
                        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
                    }
            }
            listPath(dirPath, buildDoc);
            return;
        }
    }
    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
}

From source file:de.zib.gndms.kit.monitor.GroovyMonitor.java

/**
 * Evaluate the multiparts of a http multipart request as groovy shell script code.
 *
 * @param servletRequest/*from ww w.  j  a  v a  2  s  .  c om*/
 * @param args to the script/command (plain string)
 *@param b64 if true, the content is asumed to be encoded in base64 @throws IOException
 */
synchronized void evalParts(@NotNull HttpServletRequest servletRequest, @NotNull String args, boolean b64)
        throws IOException {
    try {
        if (isRemainingOpen()) {
            boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequest);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                try {
                    List<FileItem> items = upload.parseRequest(servletRequest);
                    for (FileItem fi : items)
                        handlePart(b64, args, fi);
                } catch (FileUploadException fue) {
                    throw new RuntimeException(fue);
                }
            } else
                throw new RuntimeException("Non-multipart content received");
        } else {
            throw new RuntimeException("Processing of multiple requests on a monitor in " + " mode " + runMode
                    + " is either invalid " + " or monitor was closed down in the middle of processing");
        }
    } finally {
        postDone();
        notifyAll();
    }
}