Example usage for org.apache.commons.fileupload FileItem getString

List of usage examples for org.apache.commons.fileupload FileItem getString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getString.

Prototype

String getString(String encoding) throws UnsupportedEncodingException;

Source Link

Document

Returns the contents of the file item as a String, using the specified encoding.

Usage

From source file:ccc.plugins.multipart.apache.MultipartForm.java

/** {@inheritDoc} */
@Override/*from w ww.j  a  va2  s  .c om*/
public String getString(final String string) {
    try {
        final FileItem item = getFormItem(string);
        return (null == item) ? null : item.getString(_charEncoding);
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("JVM doesn't support encoding: " + _charEncoding, e);
    }
}

From source file:com.bibisco.filters.FileFilter.java

/**
 * Processing classic form fields./*from ww w .j  a  v  a 2s.c om*/
 *<p>They are decoded and transferred to wrapper's map,
 * which will substitute the original request-object later 
 * (@see dpFilter }
 * @param pField
 */
protected void processRegularFormField(FileItem pField, ServletRequest pRequest) {
    String name = pField.getFieldName();
    try {
        String lStrValue = pField.getString(pRequest.getCharacterEncoding());
        mMultipartWrapper.addParameter(name, lStrValue);
    } catch (UnsupportedEncodingException e) {
        mLog.error(e, "Fatal error decoding parameter ", name);
    }
}

From source file:com.trsvax.jacquard.services.EMultipartDecoderImpl.java

protected HttpServletRequest processFileItems(HttpServletRequest request, List<FileItem> fileItems) {
    if (uploadException == null && fileItems.isEmpty()) {
        return request;
    }//from  w  ww.j  a  v  a2 s .  c  o  m

    ParametersServletRequestWrapper wrapper = new ParametersServletRequestWrapper(request);

    // First add parameters from the request
    for (Object e : request.getParameterMap().entrySet()) {
        Map.Entry<String, String[]> ee = (Map.Entry<String, String[]>) e;
        for (String s : ee.getValue())
            wrapper.addParameter(ee.getKey(), s);
    }

    for (FileItem item : fileItems) {
        if (item.isFormField()) {
            String fieldValue;

            try {

                fieldValue = item.getString(requestEncoding);
            } catch (UnsupportedEncodingException ex) {
                throw new RuntimeException(ex);
            }

            wrapper.addParameter(item.getFieldName(), fieldValue);
        } else {
            wrapper.addParameter(item.getFieldName(), item.getName());
            addUploadedFile(item.getFieldName(), new UploadedFileItem(item));
        }
    }

    return wrapper;
}

From source file:com.github.glue.mvc.RequestHandler.java

private void init() {
    try {/*from   w  ww  . ja va  2s  .co m*/
        if (isMultipartContent(request)) {
            FileItemFactory itemFactory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(itemFactory);

            List<FileItem> items = fileUpload.parseRequest(request);
            for (FileItem fileItem : items) {
                if (fileItem.isFormField()) {
                    parameters.put(fileItem.getFieldName(),
                            new String[] { fileItem.getString(definition.getCharset()) });
                } else {
                    parameters.put(fileItem.getFieldName(), fileItem);
                }
            }

        } else {
            Map<String, String[]> paramteters = request.getParameterMap();
            for (Map.Entry<String, String[]> item : paramteters.entrySet()) {
                String[] vars = item.getValue();
                if (vars != null) {
                    for (int i = 0; i < vars.length; i++) {
                        vars[i] = new String(vars[i].getBytes("ISO-8859-1"), definition.getCharset());
                    }
                }
                parameters.put(item.getKey(), vars);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

protected String getValue(FileItem item, ServletRequest request) {
    String encoding = request.getCharacterEncoding();
    if (!isNullOrEmpty(encoding)) {
        try {//from   www.  j av  a2 s  .c  om
            return item.getString(encoding);
        } catch (UnsupportedEncodingException e) {
            logger.warn("Request have an invalid encoding. Ignoring it");
        }
    }
    return item.getString();
}

From source file:br.com.caelum.vraptor.interceptor.multipart.CommonsUploadMultipartInterceptor.java

protected String getValue(FileItem item) {
    String encoding = request.getCharacterEncoding();
    if (!Strings.isNullOrEmpty(encoding)) {
        try {// w  w w . j  a  v a  2s.c  om
            return item.getString(encoding);
        } catch (UnsupportedEncodingException e) {
            logger.warn("Request have an invalid encoding. Ignoring it");
        }
    }
    return item.getString();
}

From source file:hd.controller.AddImageToIdeaBookServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w  . j ava2s  .  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);

                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;

                        File savedFile = new File(RealPath);
                        item.write(savedFile);

                        String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName;
                        //                            savedFile = new File(localPath);
                        //                            item.write(savedFile);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            String ideaBookIdTemp = (String) params.get("txtIdeabookId");
            int ideaBookId = Integer.parseInt(ideaBookIdTemp);
            IdeaBookDAO ideabookDao = new IdeaBookDAO();

            String tilte = (String) params.get("newGalleryName");

            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;

            IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO();
            IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId);

            HDSystem system = new HDSystem();
            system.setNotificationIdeaBook(request);
            response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId);

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:com.esri.gpt.control.publication.ValidateMetadataController.java

/**
 * Verifies the uploaded file.//from  ww w.j a  v a  2s .c  om
 * @param event the associated JSF action event
 * @param context the context associated with the active request
 * @throws Exception if an exception occurs
 */
private void verifyFile(ActionEvent event, RequestContext context) throws Exception {

    // extract the uploaded file information from the request,
    // ensure that a file with valid XML content was supplied
    MessageBroker msgBroker = extractMessageBroker();
    String sFileName = "";
    try {
        FileItem item = extractFileItem();
        if (item != null) {
            sFileName = Val.chkStr(item.getName());
            String sXml = Val.chkStr(item.getString("UTF-8"));

            // remove the UTF-8 byte order mark if present
            byte[] bom = new byte[3];
            bom[0] = (byte) 0xEF;
            bom[1] = (byte) 0xBB;
            bom[2] = (byte) 0xBF;
            String sbom = new String(bom, "UTF-8");
            if (sXml.startsWith(sbom)) {
                sXml = Val.chkStr(sXml.substring(1));
            }

            if (sFileName.length() == 0) {
                msgBroker.addErrorMessage("publication.validateMetadata.err.file.required");
            } else if (sXml.length() == 0) {
                msgBroker.addErrorMessage("publication.validateMetadata.err.file.empty");
            } else {

                //String sOut = "C:/xfer/test19139.xml";
                //com.esri.gpt.framework.xml.XmlIoUtil.writeXmlFile(sXml,new java.io.File(sOut));

                // verifies the file, set the success message
                ValidationRequest request = new ValidationRequest(context, sFileName, sXml);
                request.verify();
                msgBroker.addSuccessMessage("catalog.publication.success.validated");
            }
        }

    } catch (ValidationException e) {
        FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, sFileName, null);
        msgBroker.addMessage(fm);

        String sKey = e.getKey();
        if (sKey.length() > 0) {
            String sMsg = sKey;
            Schema schema = context.getCatalogConfiguration().getConfiguredSchemas().get(sKey);
            if (schema != null) {
                if (schema.getLabel() != null) {
                    String sResKey = schema.getLabel().getResourceKey();
                    if (sResKey.length() > 0) {
                        sMsg = extractMessageBroker().retrieveMessage(sResKey) + " (" + sKey + ")";
                    }
                }
            }
            fm = new FacesMessage(FacesMessage.SEVERITY_WARN, " - " + sMsg, null);
            extractMessageBroker().addMessage(fm);
        }

        e.getValidationErrors().buildMessages(msgBroker, true);

    } catch (Exception e) {
        FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, sFileName, null);
        msgBroker.addMessage(fm);

        // there seems to be no good exception related to a file that is simply
        // not an XML file, a message containing "content is not allowed in prolog"
        // seems to be the best guess at the moment
        String sMsg = e.toString().toLowerCase();
        if (sMsg.indexOf("content is not allowed in prolog") != -1) {
            msgBroker.addErrorMessage("publication.validateMetadata.err.file.prolog");
        } else {
            throw e;
        }
    }
}

From source file:edu.xtec.colex.utils.ParseMultipart.java

/**
 * Creates a new instance of ParseMultipart with a given HttpServletRequest
 * @param requestIn the HttpServletRequest to parse
 *///w  w  w. ja v a2  s .  c o m
public ParseMultipart(HttpServletRequest requestIn) {
    parameters = new Hashtable();

    request = requestIn;

    isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));

    try {
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Configure the factory here, if desired.

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("ISO-8859-1");
            // Configure the uploader here, if desired.

            Iterator fileItems = upload.parseRequest(request).iterator();

            while (fileItems.hasNext()) {
                FileItem fi = (FileItem) fileItems.next();

                if (!fi.isFormField()) {
                    parameters.put(fi.getFieldName(), fi);
                } else {
                    parameters.put(fi.getFieldName(), fi.getString("ISO-8859-1").trim());
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.bbm.common.cmm.web.EgovMultipartResolver.java

/**
 * multipart?  parsing? .//from  w ww  .  j  a  v a  2s.c  o m
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {
    Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
                if (multipartFiles.put(fileItem.getName(), file) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters);
}