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:ca.nrc.cadc.beacon.web.resources.FileItemServerResource.java

@Post
@Put/*www .j  a va  2s .com*/
public void accept(final Representation payload) throws Exception {
    if ((payload != null) && MediaType.MULTIPART_FORM_DATA.equals(payload.getMediaType(), true)) {
        // The Apache FileUpload project parses HTTP requests which
        // conform to RFC 1867, "Form-based File Upload in HTML". That
        // is, if an HTTP request is submitted using the POST method,
        // and with a content type of "multipart/form-data", then
        // FileUpload can parse that request, and get all uploaded files
        // as FileItem.

        // Obtain the file upload Representation as an iterator.
        final ServletFileUpload upload = parseRepresentation();

        final FileItemIterator fileItemIterator = upload.getItemIterator(ServletUtils.getRequest(getRequest()));

        if (!fileItemIterator.hasNext()) {
            // Some problem occurs, sent back a simple line of text.
            uploadError(Status.CLIENT_ERROR_BAD_REQUEST, "Unable to upload corrupted or incompatible data.");
        } else {
            upload(fileItemIterator);
        }
    } else {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        getResponse().setEntity("Nothing to upload or invalid data.", MediaType.TEXT_PLAIN);
    }
}

From source file:n3phele.backend.RepoProxy.java

@POST
@Path("{id}/upload/{bucket}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket,
        @QueryParam("name") String destination, @QueryParam("expires") long expires,
        @QueryParam("signature") String signature, @Context HttpServletRequest request)
        throws NotFoundException {
    Repository repo = Dao.repository().load(id);
    if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(),
            bucket + ":" + destination)) {
        log.severe("Expired temporary authorization");
        throw new NotFoundException();
    }//www .ja  v a  2s.  co m

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding "
                + upload.getHeaderEncoding());
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (item.isFormField()) {
                log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream()));
            } else {
                InputStream stream = item.openStream();
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()
                        + " content " + item.getContentType());
                URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination);
                Response.created(target).build();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Processing error", e);
    }

    return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build();
}

From source file:ca.nrc.cadc.rest.SyncInput.java

private void processMultiPart(FileItemIterator itemIterator)
        throws FileUploadException, IOException, ResourceNotFoundException {
    while (itemIterator.hasNext()) {
        FileItemStream item = itemIterator.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField())
            processParameter(name, new String[] { Streams.asString(stream) });
        else//from w  ww.  ja v a 2  s  .co  m
            processStream(name, item.getContentType(), stream);
    }
}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload2")
@POST//  w  ww  . j  av a 2 s .co m
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(CHARSET);
    try {
        FileItemIterator fileIterator = upload.getItemIterator(request);
        while (fileIterator.hasNext()) {
            FileItemStream item = fileIterator.next();
            InputStream is = item.openStream();
            try {
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    String name = Calendar.getInstance().getTimeInMillis() + fileName;
                    String path = request.getServletContext().getRealPath("/");
                    path += File.separator + "data" + File.separator + name;
                    File file = new File(path);
                    FileUtils.copyInputStreamToFile(is, file);
                } else {
                    System.out.println(Streams.asString(is, CHARSET));
                }
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        return "{\"success\": true}";
    } catch (IOException | FileUploadException e) {
        return "{\"success\": false}";
    }
}

From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java

private void parseReq(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {

    try {//w  w  w .  j a  v a2  s  .  c  o  m

        MF mf = MF.getFactory();

        req.setCharacterEncoding("UTF-8");

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(req);

        HashMap<String, String> map = new HashMap<String, String>();

        while (iterator.hasNext()) {

            FileItemStream item = iterator.next();

            InputStream stream = item.openStream();

            if (item.isFormField()) {

                String field = item.getFieldName();

                String value = Streams.asString(stream);

                map.put(field, value);

                stream.close();

            } else {

                String filename = item.getName();

                String[] extension = filename.split("\\.");

                String mail = map.get("mail");

                if (mail != null) {

                    filename = mail + "_" + String.valueOf(filename.hashCode()) + "."
                            + extension[extension.length - 1];

                } else {

                    filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1];

                }

                map.put("filename", filename);

                byte[] buffer = IOUtils.toByteArray(stream);

                mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer,

                        filename);

                stream.close();

            }

        }

        String email = map.get("mail");

        String firstName = map.get("firstName");

        String lastName = map.get("lastName");

        String dayS = map.get("day");

        String monthS = map.get("month");

        String yearS = map.get("year");

        String password = map.get("password");

        String filename = map.get("filename");

        String date = yearS + "-" + monthS + "-" + dayS;

        char gender = map.get("gender").charAt(0);

        RequestDispatcher disp;

        Connection c = mf.getSQLService().getConnection();

        String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName
                + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')";

        Statement statement = c.createStatement();

        statement.executeUpdate(stm);

        statement.close();

        c.close();

        req.getSession(true).setAttribute("actualUser", email);

        req.getSession(true).setAttribute("edit", "false");

        disp = req.getRequestDispatcher("SelectTopic.jsp");

        disp.forward(req, response);

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (FileUploadException e) {

        e.printStackTrace();

    }

}

From source file:com.sifiso.yazisa.util.PhotoUtil.java

public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil)
        throws FileUploadException {
    logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n");
    ResponseDTO resp = new ResponseDTO();
    InputStream stream = null;/*  ww w.  jav  a  2  s.com*/
    File rootDir;
    try {
        rootDir = YazisaProperties.getImageDir();
        logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath());
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Properties file problem", ex);
        resp.setMessage("Server file unavailable. Please try later");
        resp.setStatusCode(114);

        return resp;
    }

    PhotoUploadDTO dto = null;
    Gson gson = new Gson();
    File schoolDir = null, classDir = null, parentDir = null, teacherDir = null, studentDir = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            stream = item.openStream();
            if (item.isFormField()) {
                if (name.equalsIgnoreCase("JSON")) {
                    String json = Streams.asString(stream);
                    if (json != null) {
                        logger.log(Level.INFO, "picture with associated json: {0}", json);
                        dto = gson.fromJson(json, PhotoUploadDTO.class);
                        if (dto != null) {
                            if (dto.getSchoolID() > 0) {
                                schoolDir = createSchoolDirectory(rootDir, schoolDir, dto.getSchoolID());
                            }

                            if (dto.getClassID() > 0) {
                                classDir = createClassDirectory(schoolDir, classDir, dto.getClassID());
                            }
                            if (dto.getParentID() > 0) {
                                parentDir = createParentDirectory(schoolDir, parentDir);
                            }
                            if (dto.getTeacherID() > 0) {
                                teacherDir = createTeacherDirectory(schoolDir, teacherDir);
                            }
                            if (dto.getStudentID() > 0) {
                                studentDir = createStudentDirectory(rootDir, studentDir);
                            }
                        }
                    } else {
                        logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL..");
                    }
                }
            } else {
                File imageFile = null;
                if (dto == null) {
                    continue;
                }
                DateTime dt = new DateTime();
                String fileName = "";
                if (dto.isIsFullPicture()) {
                    fileName = "f" + dt.getMillis() + ".jpg";
                } else {
                    fileName = "t" + dt.getMillis() + ".jpg";
                }
                if (dto.getSchoolID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getSchoolID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getSchoolID() + ".jpg";
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getTeacherID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getTeacherID() + ".jpg";
                        } else {
                            fileName = "t" + dto.getTeacherID() + ".jpg";
                        }
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getClassID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getClassID() + "-" + new Date().getYear() + ".jpg";
                        } else {
                            fileName = "t" + dto.getClassID() + "-" + new Date().getYear() + ".jpg";
                        }
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getParentID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getParentID() + ".jpg";
                        } else {
                            fileName = "t" + dto.getParentID() + ".jpg";
                        }
                    }
                }

                if (dto.getStudentID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getStudentID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getStudentID() + ".jpg";
                    }
                }

                //
                switch (dto.getPictureType()) {
                case PhotoUploadDTO.SCHOOL_IMAGE:
                    imageFile = new File(schoolDir, fileName);
                    break;
                case PhotoUploadDTO.CLASS_IMAGE:
                    imageFile = new File(classDir, fileName);
                    break;
                case PhotoUploadDTO.PARENT_IMAGE:
                    imageFile = new File(parentDir, fileName);
                    break;
                case PhotoUploadDTO.STUDENT_IMAGE:
                    imageFile = new File(studentDir, fileName);
                    break;
                }

                writeFile(stream, imageFile);
                resp.setStatusCode(0);
                resp.setMessage("Photo downloaded from mobile app ");
                //add database
                System.out.println("filepath: " + imageFile.getAbsolutePath());
                //create uri
                /*int index = imageFile.getAbsolutePath().indexOf("monitor_images");
                 if (index > -1) {
                 String uri = imageFile.getAbsolutePath().substring(index);
                 System.out.println("uri: " + uri);
                 dto.setUri(uri);
                 }
                 dto.setDateUploaded(new Date());
                 if (dto.isIsFullPicture()) {
                 dto.setThumbFlag(null);
                 } else {
                 dto.setThumbFlag(1);
                 }
                 dataUtil.addPhotoUpload(dto);*/

            }
        }

    } catch (FileUploadException | IOException | JsonSyntaxException ex) {
        logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex);
        throw new FileUploadException();
    }

    return resp;
}

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

@Post
public Representation addBitstream(InputRepresentation rep) {
    Context c = null;/*  www .  ja va  2  s  .  c om*/
    Bundle bundle = null;
    Bitstream bitstream = null;
    try {
        c = getAuthenticatedContext();
        bundle = Bundle.find(c, this.bundleId);
        if (bundle == null) {
            return errorNotFound(c, "Could not find the bundle.");
        }

        Item[] items = bundle.getItems();

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

        String description = null;
        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("description")) {
                    description = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (bitstream != null) {
                    return error(c, "Only one file can added in one request.", Status.CLIENT_ERROR_BAD_REQUEST);
                }
                String name = fileItemStream.getName();
                bitstream = bundle.createBitstream(fileItemStream.openStream());
                bitstream.setName(name);
                bitstream.setSource(name);
                BitstreamFormat bf = FormatIdentifier.guessFormat(c, bitstream);
                bitstream.setFormat(bf);
            }
        }

        if (bitstream == null) {
            return error(c, "Request does not contain file(?)", Status.CLIENT_ERROR_BAD_REQUEST);
        }
        if (description != null) {
            bitstream.setDescription(description);
        }
        bitstream.update();
        items[0].update(); // This updates at least the
                           // sequence ID of the bitstream.

        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Bitstream created.", baseUrl() + BitstreamResource.relativeUrl(bitstream.getID()));
}

From source file:com.github.thorqin.webapi.FileManager.java

public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize)
        throws ServletException, IOException, FileUploadException {
    List<FileInfo> uploadList = new LinkedList<>();
    request.setCharacterEncoding("utf-8");
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding("UTF-8");

    if (!ServletFileUpload.isMultipartContent(request)) {
        return uploadList;
    }/*from  w ww .j  a  v  a  2 s  .com*/
    upload.setSizeMax(maxSize);
    FileItemIterator iter;
    iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        try (InputStream stream = item.openStream()) {
            if (!item.isFormField()) {
                FileInfo info = new FileInfo();
                info.setFileName(item.getName());
                if (getFileMIME(info.getExtName()) == null) {
                    logger.log(Level.WARNING, "Upload file's MIME type isn't permitted.");
                    continue;
                }
                info = store(stream, info.fileName);
                uploadList.add(info);
            }
        }
    }
    return uploadList;
}

From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java

public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ServletFileUpload upload = null;/*from www  .j a  va2s .c  om*/
    WebTopSession.UploadedFile uploadedFile = null;
    HashMap<String, String> multipartParams = new HashMap<>();

    try {
        String service = ServletUtils.getStringParameter(request, "service", true);
        String cntx = ServletUtils.getStringParameter(request, "context", true);
        String tag = ServletUtils.getStringParameter(request, "tag", null);
        if (!ServletFileUpload.isMultipartContent(request))
            throw new Exception("No upload request");

        IServiceUploadStreamListener istream = getUploadStreamListener(cntx);
        if (istream != null) {
            try {
                MapItem data = new MapItem(); // Empty response data

                // Defines the upload object
                upload = new ServletFileUpload();
                FileItemIterator it = upload.getItemIterator(request);
                while (it.hasNext()) {
                    FileItemStream fis = it.next();
                    if (fis.isFormField()) {
                        InputStream is = null;
                        try {
                            is = fis.openStream();
                            String key = fis.getFieldName();
                            String value = IOUtils.toString(is, "UTF-8");
                            multipartParams.put(key, value);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        // Creates uploaded object
                        uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(),
                                tag, fis.getName(), -1, findMediaType(fis));

                        // Fill response data
                        data.add("virtual", uploadedFile.isVirtual());
                        data.add("editable", isFileEditableInDocEditor(fis.getName()));

                        // Handle listener, its implementation can stop
                        // file upload throwing a UploadException.
                        InputStream is = null;
                        try {
                            getEnv().getSession().addUploadedFile(uploadedFile);
                            is = fis.openStream();
                            istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data);
                        } finally {
                            IOUtils.closeQuietly(is);
                            getEnv().getSession().removeUploadedFile(uploadedFile, false);
                        }
                    }
                }
                new JsonResult(data).printTo(out);

            } catch (UploadException ex1) {
                new JsonResult(false, ex1.getMessage()).printTo(out);
            } catch (Exception ex1) {
                throw ex1;
            }

        } else {
            try {
                MapItem data = new MapItem(); // Empty response data
                IServiceUploadListener iupload = getUploadListener(cntx);

                // Defines the upload object
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //TODO: valutare come imporre i limiti
                //factory.setSizeThreshold(yourMaxMemorySize);
                //factory.setRepository(yourTempDirectory);
                upload = new ServletFileUpload(factory);
                List<FileItem> files = upload.parseRequest(request);

                // Plupload component (client-side) will upload multiple file 
                // each in its own request. So we can skip loop on files.
                Iterator it = files.iterator();
                while (it.hasNext()) {
                    FileItem fi = (FileItem) it.next();
                    if (fi.isFormField()) {
                        InputStream is = null;
                        try {
                            is = fi.getInputStream();
                            String key = fi.getFieldName();
                            String value = IOUtils.toString(is, "UTF-8");
                            multipartParams.put(key, value);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        // Writes content into a temp file
                        File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX);
                        fi.write(file);

                        // Creates uploaded object
                        uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag,
                                fi.getName(), fi.getSize(), findMediaType(fi));
                        getEnv().getSession().addUploadedFile(uploadedFile);

                        // Fill response data
                        data.add("virtual", uploadedFile.isVirtual());
                        data.add("uploadId", uploadedFile.getUploadId());
                        data.add("editable", isFileEditableInDocEditor(fi.getName()));

                        // Handle listener (if present), its implementation can stop
                        // file upload throwing a UploadException.
                        if (iupload != null) {
                            try {
                                iupload.onUpload(cntx, request, multipartParams, uploadedFile, data);
                            } catch (UploadException ex2) {
                                getEnv().getSession().removeUploadedFile(uploadedFile, true);
                                throw ex2;
                            }
                        }
                    }
                }
                new JsonResult(data).printTo(out);

            } catch (UploadException ex1) {
                new JsonResult(ex1).printTo(out);
            }
        }

    } catch (Exception ex) {
        WebTopApp.logger.error("Error uploading", ex);
        new JsonResult(ex).printTo(out);
    }
}

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

private void flushRequest(FileItemIterator iterator, InputStream itemStream) {
    try {// ww w.ja va2s . co  m
        // close any streams left open due to error.
        if (itemStream != null) {
            itemStream.close();
        }

        // iterate through the remaining fields an flush the fields that contain the file data.
        while (null != iterator && iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (!item.isFormField()) {
                item.openStream().close();
            }
        }
    } catch (IOException | FileUploadException ex) {
        logger.warn("Unexpected exception flushing upload request.", ex);
    }
}