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, String pEncoding) throws IOException 

Source Link

Document

This convenience method allows to read a org.apache.commons.fileupload.FileItemStream 's content into a string, using the given character encoding.

Usage

From source file:jetbrick.web.mvc.multipart.CommonsFileUpload.java

@Override
public MultipartRequest transform(HttpServletRequest request) throws IOException {
    String contextType = request.getHeader("Content-Type");
    if (contextType == null || !contextType.startsWith("multipart/form-data")) {
        return null;
    }/* ww  w.  j  a  v a  2s.  c om*/

    String encoding = request.getCharacterEncoding();

    MultipartRequest req = new MultipartRequest(request);
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(encoding);

    try {
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            String fieldName = item.getFieldName();
            InputStream stream = item.openStream();
            try {
                if (item.isFormField()) {
                    req.setParameter(fieldName, Streams.asString(stream, encoding));
                } else {
                    String originalFilename = item.getName();
                    if (originalFilename == null || originalFilename.length() == 0) {
                        continue;
                    }
                    File diskFile = UploadUtils.getUniqueTemporaryFile(originalFilename);
                    OutputStream fos = new FileOutputStream(diskFile);

                    try {
                        IoUtils.copy(stream, fos);
                    } finally {
                        IoUtils.closeQuietly(fos);
                    }

                    FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
                    req.addFile(filePart);
                }
            } finally {
                IoUtils.closeQuietly(stream);
            }
        }
    } catch (FileUploadException e) {
        throw new IllegalStateException(e);
    }

    return req;
}

From source file:is.hax.spring.web.multipart.StreamingMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Parse the request
    try {// w  ww  . java 2s.  c o m
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }

            } else {

                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);

                if (multipartFiles.put(name, file) != null) {
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}

From source file:ee.jaaaar.dreamestate.core.StreamingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();

    // Parse the request
    try {/*w ww.  j  a va  2s . co m*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.add(name, file);
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}

From source file:com.google.phonenumbers.PhoneNumberParserServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String phoneNumber = null;/*w  w  w .  j av  a  2 s .  c  om*/
    String defaultCountry = null;
    String languageCode = "en"; // Default languageCode to English if nothing is entered.
    String regionCode = "";
    String fileContents = null;
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("phoneNumber")) {
                    phoneNumber = Streams.asString(in, "UTF-8");
                } else if (fieldName.equals("defaultCountry")) {
                    defaultCountry = Streams.asString(in).toUpperCase();
                } else if (fieldName.equals("languageCode")) {
                    String languageEntered = Streams.asString(in).toLowerCase();
                    if (languageEntered.length() > 0) {
                        languageCode = languageEntered;
                    }
                } else if (fieldName.equals("regionCode")) {
                    regionCode = Streams.asString(in).toUpperCase();
                }
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

    StringBuilder output;
    if (fileContents.length() == 0) {
        output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println("<html><head>");
        resp.getWriter()
                .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />");
        resp.getWriter().println("</head>");
        resp.getWriter().println("<body>");
        resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>");
        resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>");
        resp.getWriter().println("Language entered: " + languageCode
                + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>"));
    } else {
        output = getOutputForFile(defaultCountry, fileContents);
        resp.setContentType("text/html");
    }
    resp.getWriter().println(output);
    resp.getWriter().println("</body></html>");
}

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * Creates a new {@link DynamicInputImpl}
 * @param request from which to read the request parameters
 */// w w w.  ja va2  s  . co  m
public DynamicInputImpl(HttpServletRequest request) {
    @SuppressWarnings("unchecked")
    Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap());
    this.inputParams = reqParams;
    if (ServletFileUpload.isMultipartContent(request)) {
        this.fileUploads = Maps.newHashMap();
        Multimap<String, String> inputParamsWithList = ArrayListMultimap.create();

        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name()));
                } else {
                    final String filename = item.getName();
                    final byte[] bytes = ByteStreams.toByteArray(stream);
                    fileUploads.put(fieldName, new UploadedFile() {
                        @Override
                        public String getFilename() {
                            return filename;
                        }

                        @Override
                        public byte[] getBytes() {
                            return bytes;
                        }

                        @Override
                        public int getSize() {
                            return bytes.length;
                        }
                    });
                }
            }
            for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) {
                inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0]));
            }
        } catch (IOException | FileUploadException e) {
            throw new IllegalArgumentException("Failed to parse multipart", e);
        }
    } else {
        this.fileUploads = Collections.emptyMap();
    }
}

From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

@Override
public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from w  w w.j  av a2 s  . c  om*/
        // We always return xhtml in utf-8
        response.setContentType("application/xhtml+xml");
        response.setCharacterEncoding("utf-8");

        // Default filename just in case none is found in form
        String filename = defaultFilename;

        // Commons file upload
        ServletFileUpload upload = new ServletFileUpload();

        // Go through upload items
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Parse form fields
                String fieldname = item.getFieldName();

                if ("chartFilename".equals(fieldname)) {
                    // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default
                    // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
                    //   "The parts are sent to the processing agent in the same order the
                    //    corresponding controls appear in the document stream."
                    filename = Streams.asString(stream, "utf-8");
                } else if ("chartDataXML".equals(fieldname)) {
                    log.info("Doing form bounce");
                    String filenameAscii = formSafeAscii(filename);
                    String fileNameUtf = formSafeUtfName(filename);
                    String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''"
                            + fileNameUtf;
                    response.setHeader("Content-Disposition", cdh);
                    ServletOutputStream out = response.getOutputStream();
                    Streams.copy(stream, out, false);
                    out.flush();
                    // No more processing needed (prevent BOTH form AND upload from happening)
                    return;
                }
            } else {
                // Handle upload
                log.info("Doing file bounce");
                ServletOutputStream out = response.getOutputStream();
                Streams.copy(stream, out, false);
                out.flush();
                // No more processing needed (prevent BOTH form AND upload from happening)
                return;
            }
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {/*from w w w  .  j  ava2  s  .c o m*/
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }/*from   w w  w .  j  ava  2  s .co  m*/
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

From source file:cn.webwheel.ActionSetter.java

@SuppressWarnings("unchecked")
public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException {
    SetterConfig cfg = ai.getSetterConfig();
    List<SetterInfo> setters;
    if (action != null) {
        Class cls = action.getClass();
        setters = setterMap.get(cls);/*from   ww w . ja v  a  2  s . c o  m*/
        if (setters == null) {
            synchronized (this) {
                setters = setterMap.get(cls);
                if (setters == null) {
                    Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap);
                    map.put(cls, setters = parseSetters(cls));
                    setterMap = map;
                }
            }
        }
    } else {
        setters = Collections.emptyList();
    }

    List<SetterInfo> args = argMap.get(ai.actionMethod);
    if (args == null) {
        synchronized (this) {
            args = argMap.get(ai.actionMethod);
            if (args == null) {
                Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap);
                map.put(ai.actionMethod, args = parseArgs(ai.actionMethod));
                argMap = map;
            }
        }
    }

    if (setters.isEmpty() && args.isEmpty())
        return new Object[0];

    Map<String, Object> params;
    try {
        if (cfg.getCharset() != null) {
            request.setCharacterEncoding(cfg.getCharset());
        }
    } catch (UnsupportedEncodingException e) {
        //
    }

    if (ServletFileUpload.isMultipartContent(request)) {
        params = new HashMap<String, Object>(request.getParameterMap());
        request.setAttribute(WRPName, params);
        ServletFileUpload fileUpload = new ServletFileUpload();
        if (cfg.getCharset() != null) {
            fileUpload.setHeaderEncoding(cfg.getCharset());
        }
        if (cfg.getFileUploadSizeMax() != 0) {
            fileUpload.setSizeMax(cfg.getFileUploadSizeMax());
        }
        if (cfg.getFileUploadFileSizeMax() != 0) {
            fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax());
        }
        boolean throwe = false;
        try {
            FileItemIterator it = fileUpload.getItemIterator(request);
            while (it.hasNext()) {
                FileItemStream fis = it.next();
                if (fis.isFormField()) {
                    String s = Streams.asString(fis.openStream(), cfg.getCharset());
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new String[] { s });
                    } else if (o instanceof String[]) {
                        String[] ss = (String[]) o;
                        String[] nss = new String[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = s;
                        params.put(fis.getFieldName(), nss);
                    }
                } else if (!fis.getName().isEmpty()) {
                    File tempFile;
                    try {
                        tempFile = File.createTempFile("wfu", null);
                    } catch (IOException e) {
                        throwe = true;
                        throw e;
                    }
                    FileExImpl fileEx = new FileExImpl(tempFile);
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new FileEx[] { fileEx });
                    } else if (o instanceof FileEx[]) {
                        FileEx[] ss = (FileEx[]) o;
                        FileEx[] nss = new FileEx[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = fileEx;
                        params.put(fis.getFieldName(), nss);
                    }
                    Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true);
                    fileEx.fileName = fis.getName();
                    fileEx.contentType = fis.getContentType();
                }
            }
        } catch (FileUploadException e) {
            if (action instanceof FileUploadExceptionAware) {
                ((FileUploadExceptionAware) action).setFileUploadException(e);
            }
        } catch (IOException e) {
            if (throwe) {
                throw e;
            }
        }
    } else {
        params = request.getParameterMap();
    }

    if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField
            || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) {
        for (SetterInfo si : setters) {
            si.setter.set(action, si.member, params, si.paramName);
        }
    }

    Object[] as = new Object[args.size()];
    for (int i = 0; i < as.length; i++) {
        SetterInfo si = args.get(i);
        as[i] = si.setter.set(action, null, params, si.paramName);
    }
    return as;
}

From source file:com.cognifide.aet.executor.SuiteServlet.java

private Map<String, String> getRequestData(HttpServletRequest request) {
    Map<String, String> requestData = new HashMap<>();

    ServletFileUpload upload = new ServletFileUpload();
    try {/*from  w  w  w. ja  va2  s  .  c  o m*/
        FileItemIterator itemIterator = upload.getItemIterator(request);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            InputStream itemStream = item.openStream();
            String value = Streams.asString(itemStream, CharEncoding.UTF_8);
            requestData.put(item.getFieldName(), value);
        }
    } catch (FileUploadException | IOException e) {
        LOGGER.error("Failed to process request", e);
    }

    return requestData;
}