Example usage for org.apache.commons.fileupload.util Streams asString

List of usage examples for org.apache.commons.fileupload.util Streams asString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.util Streams asString.

Prototype

public static String asString(InputStream pStream) throws IOException 

Source Link

Document

This convenience method allows to read a org.apache.commons.fileupload.FileItemStream 's content into a string.

Usage

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

private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException {
    Task task = null;/* www.java2 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:com.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java

private void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer,
        Consumer<BinaryFile> fileConsumer) throws IOException {

    if (fileItem.isFormField()) {
        InputStream stream = fileItem.getInputStream();

        valueConsumer.accept(Streams.asString(stream));
    } else {/* ww w.  j a va2  s  .c  o m*/
        BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(),
                fileItem.getContentType());

        fileConsumer.accept(binaryFile);
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request__/*w  w w  .ja  v  a2  s. c o  m*/
 * @param response__
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__)
        throws ServletException, IOException {
    response__.setContentType("text/html;charset=UTF-8");
    Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"),
            request__.getLocale());
    PrintWriter out = response__.getWriter();

    final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI");

    try {
        fileUpload: {
            if (!isFileUploadPermitted()) {
                errorTemporarilyDisabled(out);
                break fileUpload;
            }
            processSignOn: {
                final HttpSession session = request__.getSession(false);

                if (session == null) {
                    errorNoLogin(out);
                    break fileUpload;
                } else if (session.getAttribute(ServletLogin.HumanUser) == null) {
                    errorNoLogin(out);
                    break processSignOn;
                }

                processRequestType: {
                    @SuppressWarnings("unchecked")
                    final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session
                            .getAttribute(ServletLogin.HumanUser)).getBoundInstance();
                    try {
                        /*Check that we have a file upload request*/
                        final boolean isMultipart = ServletFileUpload.isMultipartContent(request__);
                        if (!isMultipart) {
                            LoggerFactory.getLogger(ServletFileUploads.class.getName()).error(
                                    logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001"));
                            errorNonMultipart(out);

                            break processRequestType;
                        }

                        processRequest: {

                            // Create a new file upload handler
                            final ServletFileUpload upload = new ServletFileUpload();
                            // Parse the request
                            FileItemIterator iter = upload.getItemIterator(request__);
                            boolean persisted = false;

                            loop: {
                                Long locationId = null;
                                String photoDescription = null;
                                String photoName = null;
                                Boolean isPublic = null;
                                Boolean isPrivate = null;
                                boolean fileSaved = false;

                                while (iter.hasNext()) {
                                    FileItemStream item = iter.next();
                                    String name = item.getFieldName();
                                    String absoluteFileSystemFileName = FilePath;

                                    InputStream stream = item.openStream();
                                    @_fix(issue = "Handle no extension files")
                                    String usersFileName = null;
                                    String randomFileName = null;

                                    if (item.isFormField()) {
                                        final String value = Streams.asString(stream);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0002"),
                                                name);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0003"),
                                                value);
                                        if (name.equals("locationId")) {
                                            locationId = Long.parseLong(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0004")));
                                        }

                                        if (name.equals("photoDescription")) {
                                            photoDescription = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0005")));
                                        }

                                        if (name.equals("photoName")) {
                                            photoName = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0006")));
                                        }

                                        if (name.equals("isPublic")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPublic = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0008")));

                                        }
                                        if (name.equals("isPrivate")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPrivate = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName.");

                                        }

                                    }
                                    if ((!item.isFormField())) {
                                        Loggers.DEBUG.debug((logMsgs.getString(
                                                "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name));
                                        Loggers.DEBUG.debug((logMsgs
                                                .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010")
                                                + item.getName()));
                                        // Process the input stream
                                        if (!(item.getName().lastIndexOf(".") > 0)) {
                                            errorFileType(out, item.getName());
                                            break processRequest;
                                        }

                                        usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName()
                                                : item.getName()
                                                        .substring(item.getName().lastIndexOf("\\") + 1));

                                        final String userUploadedFileName = item.getName();

                                        String fileExtension = "error";

                                        if (userUploadedFileName.toLowerCase().endsWith(".jpg")) {
                                            fileExtension = ".jpg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) {
                                            fileExtension = ".jpeg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".png")) {
                                            fileExtension = ".png";
                                        } else {
                                            errorFileType(out, gUI.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0019"));
                                            break processRequest;
                                        }

                                        randomFileName = getRandomFileName(locationId);

                                        randomFileName += fileExtension;

                                        final File uploadedFile = new File(
                                                absoluteFileSystemFileName += randomFileName);
                                        final FileOutputStream fos = new FileOutputStream(uploadedFile);
                                        while (true) {
                                            final int dataByte = stream.read();
                                            if (dataByte != -1) {
                                                fos.write(dataByte);
                                            } else {
                                                break;
                                            }

                                        }
                                        fos.close();
                                        stream.close();
                                        fileSaved = true;
                                    }

                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011")
                                                    + locationId);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012")
                                                    + fileSaved);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013")
                                                    + photoDescription);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014")
                                                    + photoName);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015")
                                                    + isPublic);

                                    if (fileSaved && (photoDescription != null)) {
                                        persistData: {
                                            handlePublicPrivateness: {
                                                if ((isPublic != null) && isPublic && (locationId != null)) {
                                                    Return<PublicPhoto> r = DB
                                                            .getHumanCRUDPublicPhotoLocal(true)
                                                            .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    locationId, absoluteFileSystemFileName,
                                                                    photoName, photoDescription,
                                                                    new String(CDN + randomFileName), 4);
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, logMsgs.getString(
                                                                "ai.ilikeplaces.servlets.ServletFileUploads.0016"));
                                                    } else {
                                                        errorBusy(out);
                                                    }

                                                } else if ((isPrivate != null) && isPrivate) {
                                                    Return<PrivatePhoto> r = DB
                                                            .getHumanCRUDPrivatePhotoLocal(true)
                                                            .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    absoluteFileSystemFileName, photoName,
                                                                    photoDescription,
                                                                    new String(CDN + randomFileName));
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, "private");
                                                    } else {
                                                        errorBusy(out);
                                                    }
                                                } else {
                                                    throw UNSUPPORTED_OPERATION_EXCEPTION;
                                                }
                                            }
                                        }
                                        /*We got what we need from the loop. Lets break it*/

                                        break loop;
                                    }

                                }

                            }
                            if (!persisted) {
                                errorMissingParameters(out);
                                break processRequest;
                            }

                        }

                    } catch (FileUploadException ex) {
                        Loggers.EXCEPTION.error(null, ex);
                        errorBusy(out);
                    }
                }

            }

        }
    } catch (final Throwable t_) {
        Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_);
    }

}

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 {// w ww . java 2s.c o m
            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:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody/*w w  w . java2 s . c o  m*/
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * Extract data from request object (form, data and session)
 * /*from w  ww.ja v a 2 s .  c  o m*/
 * @param req
 * @param formIsSubmitted
 * @param hasSerializedDc
 * @param outData
 * @return all input fields into a service data
 * @throws ExilityException
 */
@SuppressWarnings("resource")
public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc,
        ServiceData outData) throws ExilityException {

    ServiceData inData = new ServiceData();
    if (formIsSubmitted == false) {
        /**
         * most common call from client that uses serverAgent to send an
         * ajax request with serialized dc as data
         */
        this.extractSerializedData(req, hasSerializedDc, inData);
    } else {
        /**
         * form is submitted. this is NOT from serverAgent.js. This call
         * would be from other .jsp files
         */
        if (hasSerializedDc == false) {
            /**
             * client has submitted a form with form fields in that.
             * Traditional form submit
             **/
            this.extractParametersAndFiles(req, inData);
        } else {
            /**
             * Logic got evolved over a period of time. several calling jsps
             * actually inspect the stream for file, and in the process they
             * would have extracted form fields into session. So, we extract
             * form fields, as well as dip into session
             */
            HttpSession session = req.getSession();
            if (ServletFileUpload.isMultipartContent(req) == false) {
                /**
                 * Bit convoluted. the .jsp has already extracted files and
                 * form fields into session. field.
                 */
                String txt = session.getAttribute("dc").toString();
                this.extractSerializedDc(txt, inData);
                this.extractFilesToDc(req, inData);
            } else {
                /**
                 * jsp has not touched input stream, and it wants us to do
                 * everything.
                 */
                try {
                    ServletFileUpload fileUploader = new ServletFileUpload();
                    fileUploader.setHeaderEncoding("UTF-8");
                    FileItemIterator iterator = fileUploader.getItemIterator(req);
                    while (iterator.hasNext()) {
                        FileItemStream stream = iterator.next();
                        String fieldName = stream.getFieldName();
                        InputStream inStream = null;
                        inStream = stream.openStream();
                        try {
                            if (stream.isFormField()) {
                                String fieldValue = Streams.asString(inStream);
                                /**
                                 * dc is a special name that contains
                                 * serialized DC
                                 */
                                if (fieldName.equals("dc")) {
                                    this.extractSerializedDc(fieldValue, inData);
                                } else {
                                    inData.addValue(fieldName, fieldValue);
                                }
                            } else {
                                /**
                                 * it is a file. we assume that the files
                                 * are small, and hence we carry the content
                                 * in memory with a specific naming
                                 * convention
                                 */
                                String fileContents = IOUtils.toString(inStream);
                                inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents);
                            }
                        } catch (Exception e) {
                            Spit.out("error whiel extracting data from request stream " + e.getMessage());
                        }
                        IOUtils.closeQuietly(inStream);
                    }
                } catch (Exception e) {
                    // nothing to do here
                }
                /**
                 * read session variables
                 */
                @SuppressWarnings("rawtypes")
                Enumeration e = session.getAttributeNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (name.equals("dc")) {
                        this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData);
                    }
                    String value = req.getSession().getAttribute(name).toString();
                    inData.addValue(name, value);
                    System.out.println("name is: " + name + " value is: " + value);
                }
            }
        }
    }
    this.getStandardFields(req, inData);
    return inData;
}

From source file:com.bristle.javalib.net.http.MultiPartFormDataParamMap.java

/**************************************************************************
* Parse the specified HTTP request, initializing the map, and calling 
* the specified callback (if not null) for each file (if any) in the 
* streamed HTTP request. /*w ww .j  a  va  2  s  . co m*/
*
*@param request              The HTTP request
*@param callback             The callback class
*@throws FileUploadException When the request is badly formed.
*@throws IOException         When an I/O error occurs reading the request.
*@throws Throwable           When thrown by the callback.
**************************************************************************/
public void parseRequestStream(HttpServletRequest request, FileItemStreamCallBack callback)
        throws FileUploadException, IOException, Throwable {
    if (ServletFileUpload.isMultipartContent(request)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String strParamName = fileItemStream.getFieldName();
                InputStream streamIn = fileItemStream.openStream();
                String strParamValue = Streams.asString(streamIn);
                put(strParamName, strParamValue);
                // Note: Can't do the following usefully.  The Parameter 
                //       Map of the HTTP Request is effectively readonly.
                //       This does not report an error, but is a no-op.
                // request.getParameterMap().put(strParamName, strParamValue);
            } else {
                if (callback != null) {
                    callback.fullyProcessAFileItemStream(fileItemStream);
                }
            }
        }
    } else {
        putAll(request.getParameterMap());
    }
}

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/*ww  w. jav  a2  s  . c  o  m*/
            processStream(name, item.getContentType(), stream);
    }
}

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  ava  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);
        }/*w w w .j  av  a 2  s  . c om*/
        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);
}