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

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

Introduction

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

Prototype

FileItemStream next() throws FileUploadException, IOException;

Source Link

Document

Returns the next available FileItemStream .

Usage

From source file:com.google.livingstories.servlet.DataImportServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    startTime = System.currentTimeMillis();

    message = "";

    if (req.getContentType().contains("multipart/form-data")) {
        try {/*from  ww w.  j  av a 2  s . c  om*/
            ServletFileUpload upload = new ServletFileUpload();
            JSONObject data = null;
            boolean override = false;
            FileItemIterator iter = upload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.getFieldName().equals("override")) {
                    override = true;
                } else if (item.getFieldName().equals("data")) {
                    data = new JSONObject(Streams.asString(item.openStream()));
                }
            }
            checkRunState(override);
            inputData = data;
            setUp();
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        } catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
    }

    try {
        process();
    } catch (Exception ex) {
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        ex.printStackTrace(printWriter);
        message = result.toString();
        runState = RunState.ERROR;
    } finally {
        if (runState != RunState.RUNNING) {
            tearDown();
        }
        Caches.clearAll();
    }

    resp.setContentType("text/html");
    resp.getWriter().append(message + "<br>" + runState.name());
}

From source file:lucee.runtime.type.scope.FormImpl.java

private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
    // get temp directory
    Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory();
    Resource tempFile;//from   ww  w.j  a v a 2s .c  om

    // Create a new file upload handler
    final String encoding = getEncoding();
    FileItemFactory factory = tempDir instanceof File
            ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir)
            : new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding(encoding);
    //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());

    HttpServletRequest req = pc.getHttpServletRequest();
    ServletRequestContext context = new ServletRequestContext(req) {
        public String getCharacterEncoding() {
            return encoding;
        }
    };

    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(context);
        //byte[] value;
        InputStream is;
        ArrayList<URLItem> list = new ArrayList<URLItem>();
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            is = IOUtil.toBufferedInputStream(item.openStream());
            if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) {
                list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false));
            } else {
                tempFile = tempDir.getRealResource(getFileName());
                fileItems.put(item.getFieldName().toLowerCase(),
                        new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName()));
                String value = tempFile.toString();
                IOUtil.copy(is, tempFile, true);

                list.add(new URLItem(item.getFieldName(), value, false));
            }
        }

        raw = list.toArray(new URLItem[list.size()]);
        fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
    } catch (Exception e) {

        //throw new PageRuntimeException(Caster.toPageException(e));
        fillDecodedEL(new URLItem[0], encoding, scriptProteced,
                pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
        initException = e;
    }
}

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

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;/* w  w w. ja va  2  s .  c om*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.create(null, c);

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

        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;
        Bitstream bitstream = null;
        String bitstreamMimeType = 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("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (bitstream != null) {
                    return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // I did not manage to use FormatIdentifier.guessFormat
                // here, so let's do it by ourselves... I would prefer to
                // use the actual file content and not its name, but let's
                // keep the code simple...
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                bitstream = community.setLogo(fileItemStream.openStream());
                // We don't set the format of the logo (bitstream) here,
                // it's done in the code below...
            }
        }

        community.setMetadata("name", name);
        community.setMetadata("short_description", shortDescription);
        community.setMetadata("introductory_text", introductoryText);
        community.setMetadata("copyright_text", copyrightText);
        community.setMetadata("side_bar_text", sideBarText);

        community.update();

        // Set the format (jpeg, png, or gif) of logo:
        Bitstream logo = community.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }

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

    return successCreated("Community created.", baseUrl() + CommunityResource.relativeUrl(community.getID()));
}

From source file:ai.baby.servlets.GenericFileGrabber.java

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }/*from www.j  a v a 2  s. c o  m*/
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

From source file:ai.ilikeplaces.servlets.GenericFileGrabber.java

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }//from  w  w  w.j av  a  2 s  . c  o  m
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    case 2:
        fulf = CDNAlbumPrivateEvent.getAlbumPhotoCDNLocal();
        break;
    case 3:
        fulf = CDNAlbumTribe.getAlbumTribeCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java

private static DSOEditRequest extractDSOEditRequest(FileItemIterator fileItemIterator)
        throws FileUploadException, IOException, UnsupportedEncodingException {
    DSOEditRequest dsoEditRequest = null;
    Gson gson = new Gson();
    FileItemStream headerJSONItemStream = fileItemIterator.next();
    InputStream headerJSONStream = headerJSONItemStream.openStream();
    InputStreamReader isr = null;
    BufferedReader br = null;/*from w  w w.ja  v  a2  s.  c  om*/

    try {
        isr = new InputStreamReader(headerJSONStream, "UTF-8");
        br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        String json = sb.toString();
        log.info("DSOEditRequest:" + json);
        dsoEditRequest = gson.fromJson(json, DSOEditRequest.class);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
    }
    return dsoEditRequest;
}

From source file:fi.iki.elonen.SimpleWebServer.java

private Response getUploadMsgAndExec(IHTTPSession session) throws FileUploadException, IOException {
    uploader = new NanoFileUpload(new DiskFileItemFactory());
    files = new HashMap<String, List<FileItem>>();
    FileItemIterator iter = uploader.getItemIterator(session);
    String fileName = "", newFileName = "";
    try {/*from   w w  w .j  av a 2 s  .c o m*/
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            fileName = item.getName();
            newFileName = rootDirs.get(0) + "/".concat(fileName);
            FileItem fileItem = uploader.getFileItemFactory().createItem(item.getFieldName(),
                    item.getContentType(), item.isFormField(), newFileName);
            files.put(fileItem.getFieldName(), Arrays.asList(new FileItem[] { fileItem }));

            try {
                Streams.copy(item.openStream(), (new FileOutputStream(newFileName)), true);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
            fileItem.setHeaders(item.getHeaders());
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return newFixedLengthResponse(
            "<html><body> \n File: " + fileName + " upload to " + newFileName + "! \n </body></html>\n");
}

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

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;//from  w w w  .  j  av a  2s.  c  o  m
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, "SQLException");
    }

    String msg = null;
    String url = baseUrl();
    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        // Logo
        String bitstreamMimeType = null;
        byte[] logoBytes = null;

        // Community
        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = 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("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (logoBytes != null) {
                    return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // TODO: Refer to comments in....
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                InputStream inputStream = fileItemStream.openStream();
                logoBytes = IOUtils.toByteArray(inputStream);
            }
        }

        msg = "Community created.";
        Community subCommunity = community.createSubcommunity();
        subCommunity.setMetadata("name", name);
        subCommunity.setMetadata("short_description", shortDescription);
        subCommunity.setMetadata("introductory_text", introductoryText);
        subCommunity.setMetadata("copyright_text", copyrightText);
        subCommunity.setMetadata("side_bar_text", sideBarText);
        if (logoBytes != null) {
            ByteArrayInputStream byteStream;
            byteStream = new ByteArrayInputStream(logoBytes);
            subCommunity.setLogo(byteStream);
        }

        subCommunity.update();
        Bitstream logo = subCommunity.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }
        url += CommunityResource.relativeUrl(subCommunity.getID());
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated(msg, url);
}

From source file:com.webpagebytes.cms.controllers.FileController.java

public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {//from w w  w.  j av a2 s . co  m
        ServletFileUpload upload = new ServletFileUpload();
        upload.setHeaderEncoding("UTF-8");
        FileItemIterator iterator = upload.getItemIterator(request);
        WPBFile ownerFile = null;

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) {
                String ownerExtKey = Streams.asString(item.openStream());
                ownerFile = getDirectory(ownerExtKey, adminStorage);
            } else if (!item.isFormField() && item.getFieldName().equals("file")) {
                InputStream stream = item.openStream();
                WPBFile wbFile = null;

                String fileName = getFileNameFromLongName(item.getName());

                if (request.getAttribute("key") != null) {
                    // this is an upload as update for an existing file
                    Long key = Long.valueOf((String) request.getAttribute("key"));
                    wbFile = adminStorage.get(key, WPBFile.class);

                    ownerFile = getDirectory(wbFile.getOwnerExtKey(), adminStorage);

                    //old file need to be deleted from cloud
                    String oldFilePath = wbFile.getBlobKey();
                    if (oldFilePath != null && oldFilePath.length() > 0) {
                        // delete only if the blob key is set
                        WPBFilePath oldCloudFile = new WPBFilePath(PUBLIC_BUCKET, oldFilePath);
                        cloudFileStorage.deleteFile(oldCloudFile);
                    }
                } else {
                    // this is a new upload
                    wbFile = new WPBFile();
                    wbFile.setExternalKey(adminStorage.getUniqueId());
                }

                wbFile.setFileName(fileName);
                wbFile.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
                wbFile.setDirectoryFlag(0);
                addFileToDirectory(ownerFile, wbFile, stream);

            }
        }
        org.json.JSONObject returnJson = new org.json.JSONObject();
        returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null));
        httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null);
    } catch (Exception e) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD);
        httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null),
                errors);
    }
}

From source file:com.google.sampling.experiential.server.EventServlet.java

private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) {
    PrintWriter out = null;//  w  w  w  .  j av a2s .c  o m
    try {
        out = resp.getWriter();
    } catch (IOException e1) {
        log.log(Level.SEVERE, "Cannot get an output PrintWriter!");
    }
    try {
        boolean isDevInstance = isDevInstance(req);
        ServletFileUpload fileUploadTool = new ServletFileUpload();
        fileUploadTool.setSizeMax(50000);
        resp.setContentType("text/html;charset=UTF-8");

        FileItemIterator iterator = fileUploadTool.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = null;
            try {
                in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    String fileContents = null;
                    fileContents = IOUtils.toString(in);
                    out.println("length: " + fileContents.length());
                    out.println(fileContents);
                    saveCSV(fileContents, isDevInstance);
                }
            } catch (ParseException e) {
                log.info("Parse Exception: " + e.getMessage());
                out.println("Could not parse your csv upload: " + e.getMessage());
            } finally {
                in.close();
            }
        }
    } catch (SizeLimitExceededException e) {
        log.info("SizeLimitExceededException: " + e.getMessage());
        out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                + e.getActualSize() + ")");
        return;
    } catch (IOException e) {
        log.severe("IOException: " + e.getMessage());
        out.println("Error in receiving file.");
    } catch (FileUploadException e) {
        log.severe("FileUploadException: " + e.getMessage());
        out.println("Error in receiving file.");
    }
}