Example usage for org.apache.commons.fileupload FileItemIterator hasNext

List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator hasNext.

Prototype

boolean hasNext() throws FileUploadException, IOException;

Source Link

Document

Returns, whether another instance of FileItemStream is available.

Usage

From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    boolean isGWT = true;
    try {/*from  www  . jav  a 2s . c o m*/
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);
                // upload requests can come from smartGWT (args) or
                // FCKEditor (request)
                String contextName = args.get("context");
                String model = args.get("model");
                String path = args.get("path");
                if (contextName == null) {
                    isGWT = false;
                    contextName = request.getParameter("context");
                    model = request.getParameter("model");
                    path = request.getParameter("path");
                    if (log.isDebugEnabled())
                        log.debug("query=" + request.getQueryString());
                } else if (log.isDebugEnabled())
                    log.debug(args);
                // the following code stores the file based on your parameters
                /*               ProjectContext context = ContextService.get().getContext(
                                     contextName);
                               ProjectState state = (ProjectState) request.getSession()
                                     .getAttribute(contextName);
                               InputStream in = null;
                               try {
                                  in = item.openStream();
                                  state.getFileManager().storeFile(
                context.getModel(model), path + fileName, in);
                               } catch (Exception e) {
                                  e.printStackTrace();
                                  log.error("Fail to upload " + fileName + " to " + path);
                               } finally {
                                  if (in != null)
                                     try {
                in.close();
                                     } catch (Exception e) {
                                     }
                               }
                */
            }
        }
        // TODO: need to handle conversion options and error reporting
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        if (isGWT) {
            out.println("<script type=\"text/javascript\">");
            out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
        } else
            out.println(getEditorResponse());
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.glaf.core.web.servlet.FileUploadServlet.java

public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return;//from   w  w  w.jav a  2  s  .  co  m
    }
    String serviceKey = request.getParameter("serviceKey");
    String type = request.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    String rootDir = SystemProperties.getConfigRootPath();

    InputStream inputStream = null;
    try {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold ???? 8M
        diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE);
        // repository 
        diskFactory.setRepository(new File(rootDir + "/temp"));
        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
        if (maxUploadSize == 0) {
            maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
        }
        maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
        logger.debug("maxUploadSize:" + maxUploadSize);

        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxUploadSize);
        upload.setFileSizeMax(maxUploadSize);
        String uploadDir = Constants.UPLOAD_PATH;

        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("#################start upload process#########################");
            FileItemIterator iter = upload.getItemIterator(request);
            PrintWriter out = response.getWriter();
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    // ????
                    String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                    String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                            autoCreatedDateDirByParttern);

                    File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    String fileId = UUID32.getUUID();
                    String fileName = savePath + "/" + fileId;

                    BlobItem dataFile = new BlobItemEntity();
                    dataFile.setLastModified(System.currentTimeMillis());
                    dataFile.setCreateBy(loginContext.getActorId());
                    dataFile.setFileId(fileId);
                    dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                    dataFile.setFilename(item.getName());
                    dataFile.setName(item.getName());
                    dataFile.setContentType(item.getContentType());
                    dataFile.setType(type);
                    dataFile.setStatus(0);
                    dataFile.setServiceKey(serviceKey);
                    getBlobService().insertBlob(dataFile);

                    inputStream = item.openStream();

                    FileUtils.save(fileName, inputStream);

                    logger.debug(fileName + " save ok.");

                    out.print(fileId);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:graphql.servlet.GraphQLServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    GraphQLContext context = createContext(Optional.of(req), Optional.of(resp));
    InputStream inputStream = null;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//w  w w .  j  a  v  a 2 s  .  com
            FileItemIterator it = upload.getItemIterator(req);
            context.setFiles(Optional.of(it));
            while (inputStream == null && it.hasNext()) {
                FileItemStream stream = it.next();
                if (stream.getFieldName().contentEquals("graphql")) {
                    inputStream = stream.openStream();
                }
            }
            if (inputStream == null) {
                throw new ServletException("no query found");
            }
        } catch (FileUploadException e) {
            throw new ServletException("no query found");
        }
    } else {
        // this is not a multipart request
        inputStream = req.getInputStream();
    }
    Request request = new ObjectMapper().readValue(inputStream, Request.class);
    Map<String, Object> variables = request.variables;
    if (variables == null) {
        variables = new HashMap<>();
    }
    query(request.query, request.operationName, variables, getSchema(), req, resp, context);
}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {/*from   ww  w  . j av  a 2s  .  c  o m*/
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        FileItemStream fileItem = null;
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                fileItem = item;
            }
        }
        if (fileItem != null) {
            args.put("contentType", fileItem.getContentType());
            args.put("fileName", FileUtils.filename(fileItem.getName()));
            System.out.println("uploading args " + args);
            String context = args.get("context");
            String model = args.get("model");
            String xq = args.get("xq");
            System.out.println(context + "," + model + "," + xq);
            File f = new File(args.get("fileName"));
            System.out.println(f.getAbsolutePath());
            /*
             * TODO: pboysen get the state, context and fileManager and store the
             * stream in fileName.  Parameters should be passed to locate state 
             * and conversion options.
             */
            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script>");
            out.println("top.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();
        } else {
            //TODO: add error code
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.priocept.jcr.server.UploadServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {//from  w w  w .  j  a  v  a2s. c om
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);

                if (log.isDebugEnabled())
                    log.debug(args);

                InputStream in = null;
                try {
                    in = item.openStream();
                    writeToFile(request.getSession().getId() + "/" + fileName, in, true,
                            request.getSession().getServletContext().getRealPath("/"));
                } catch (Exception e) {
                    //                  e.printStackTrace();
                    log.error("Fail to upload " + fileName);

                    response.setContentType("text/html");
                    response.setHeader("Pragma", "No-cache");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Cache-Control", "no-cache");
                    PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<body>");
                    out.println("<script type=\"text/javascript\">");
                    out.println("if (parent.uploadFailed) parent.uploadFailed('"
                            + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');");
                    out.println("</script>");
                    out.println("</body>");
                    out.println("</html>");
                    out.flush();
                    return;
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                }

            }
        }
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<script type=\"text/javascript\">");
        out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java

/**
 * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from:
 * /*from   www .  ja va  2  s. co m*/
 *      http://code.google.com/appengine/kb/java.html#fileforms
 * 
 * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption"
 * target="_blank">GaeVFS path</a>. All directories within the path hierarchy
 * are created (if they don't already exist) when the file is saved.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data");
    }
    try {
        String path = "/";
        int blockSize = 0;
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("path")) {
                    path = asString(item.openStream());
                    if (!path.endsWith("/")) {
                        path = path + "/";
                    }
                } else if (item.getFieldName().equalsIgnoreCase("blocksize")) {
                    String s = asString(item.openStream());
                    if (s.length() > 0) {
                        blockSize = Integer.parseInt(s);
                    }
                }
            } else {
                Path filePath = Paths.get(path + item.getName());
                Path parent = filePath.getParent();
                if (parent.notExists()) {
                    createDirectories(parent);
                }
                if (blockSize > 0) {
                    filePath.createFile(withBlockSize(blockSize));
                } else {
                    filePath.createFile();
                }
                // IOUtils.copy() buffers the InputStream internally
                OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE);
                copy(item.openStream(), out);
                out.close();
            }
        }

        // redirect to the configured response, or to this servlet for a
        // directory listing
        res.sendRedirect(uploadRedirect != null ? uploadRedirect : path);

    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files//from ww  w . j a va2  s .  c  o  m
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java

private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException {
    Task task = null;/*from   www.j a  va2  s . c o  m*/

    ServletFileUpload fileUpload = new ServletFileUpload();
    FileItemIterator iterator = null;
    InputStream itemStream = null;

    try {
        ImageReplicationType replicationType = null;

        iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            itemStream = item.openStream();

            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                switch (fieldName.toUpperCase()) {
                case "IMAGEREPLICATION":
                    replicationType = ImageReplicationType.valueOf(Streams.asString(itemStream).toUpperCase());
                    break;
                default:
                    logger.warn(String.format("The parameter '%s' is unknown in image upload.", fieldName));
                }
            } else {
                if (replicationType == null) {
                    throw new ImageUploadException(
                            "ImageReplicationType is required and should be encoded before image data in the upload request.");
                }

                task = imageFeClient.create(itemStream, item.getName(), replicationType);
            }

            itemStream.close();
            itemStream = null;
        }
    } catch (IllegalArgumentException ex) {
        throw new ImageUploadException("Image upload receives invalid parameter", ex);
    } catch (IOException ex) {
        throw new ImageUploadException("Image upload IOException", ex);
    } catch (FileUploadException ex) {
        throw new ImageUploadException("Image upload FileUploadException", ex);
    } finally {
        flushRequest(iterator, itemStream);
    }

    if (task == null) {
        throw new ImageUploadException("There is no image stream data in the image upload request.");
    }

    return task;
}

From source file:fi.helsinki.lib.simplerest.ItemsResource.java

@Post
public Representation addItem(InputRepresentation rep)
        throws AuthorizeException, SQLException, IdentifierException {
    Collection collection = null;
    Context addItemContext = null;
    try {//from www  . ja  va 2  s  .co  m
        //Get Context and make sure the user has the rights to add items.
        addItemContext = getAuthenticatedContext();
        collection = Collection.find(addItemContext, this.collectionId);
        if (collection == null) {
            addItemContext.abort();
            return errorNotFound(addItemContext, "Could not find the collection.");
        }
    } catch (SQLException e) {
        log.log(Priority.ERROR, e);
        return errorInternal(addItemContext, "SQLException");
    } catch (NullPointerException e) {
        log.log(Priority.ERROR, e);
        return errorInternal(addItemContext, "NullPointerException");
    }
    String title = null;
    String lang = null;

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("title")) {
                    title = value;
                } else if (key.equals("lang")) {
                    lang = value;
                } else if (key.equals("in_archive")) {
                    ;
                } else if (key.equals("withdrawn")) {
                    ;
                } else {
                    return error(addItemContext, "Unexpected attribute: " + key,
                            Status.CLIENT_ERROR_BAD_REQUEST);
                }
            }
        }
    } catch (FileUploadException e) {
        return errorInternal(addItemContext, e.toString());
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e);
        return errorInternal(context, e.toString());
    } catch (IOException e) {
        return errorInternal(context, e.toString());
    }

    if (title == null) {
        return error(addItemContext, "There was no title given.", Status.CLIENT_ERROR_BAD_REQUEST);
    }

    Item item = null;
    try {
        WorkspaceItem wsi = WorkspaceItem.create(addItemContext, collection, false);
        item = InstallItem.installItem(addItemContext, wsi);
        item.addMetadata("dc", "title", null, lang, title);
        item.update();
    } catch (AuthorizeException ae) {
        return error(addItemContext, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (SQLException e) {
        log.log(Priority.FATAL, e, e);
        return errorInternal(addItemContext, e.toString());
    } catch (IOException e) {
        log.log(Priority.FATAL, e, e);
        return errorInternal(addItemContext, e.toString());
    } finally {
        if (addItemContext != null) {
            addItemContext.complete();
        }
    }

    return successCreated("Created a new item.", baseUrl() + ItemResource.relativeUrl(item.getID()));
}

From source file:com.fullmetalgalaxy.server.AdminServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_resp)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    Map<String, String> params = new HashMap<String, String>();
    ModelFmpInit modelInit = null;/*from  w w w.  ja va  2  s  .  c o m*/

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8"));
            } else if (item.getFieldName().equalsIgnoreCase("gamefile")) {
                ObjectInputStream in = new ObjectInputStream(item.openStream());
                modelInit = ModelFmpInit.class.cast(in.readObject());
                in.close();
            }
        }
    } catch (FileUploadException e) {
        log.error(e);
    } catch (ClassNotFoundException e2) {
        log.error(e2);
    }

    // import game from file
    if (modelInit != null) {
        // set transient to avoid override data
        modelInit.getGame().setTrancient();

        // search all accounts in database to correct ID
        for (EbRegistration registration : modelInit.getGame().getSetRegistration()) {
            if (registration.haveAccount()) {
                EbAccount account = FmgDataStore.dao().find(EbAccount.class, registration.getAccount().getId());
                if (account == null) {
                    // corresponding account from this player doesn't exist in database
                    try {
                        // try to find corresponding pseudo
                        account = FmgDataStore.dao().query(EbAccount.class).filter("m_compactPseudo ==",
                                ServerUtil.compactTag(registration.getAccount().getPseudo())).get();
                    } catch (Exception e) {
                    }
                }
                registration.setAccount(account);
            }
        }

        // then save game
        FmgDataStore dataStore = new FmgDataStore(false);
        dataStore.put(modelInit.getGame());
        dataStore.close();

    }

}