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:mml.handler.post.MMLPostHTMLHandler.java

void parseRequest(HttpServletRequest request) throws FileUploadException, Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(encoding);
        List<FileItem> items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString(encoding);
                    if (fieldName.equals(Params.DOCID))
                        this.docid = contents;
                    else if (fieldName.equals(Params.DIALECT)) {
                        JSONObject jv = (JSONObject) JSONValue.parse(contents);
                        if (jv.get("language") != null)
                            this.langCode = (String) jv.get("language");
                        this.dialect = jv;
                    } else if (fieldName.equals(Params.HTML)) {
                        html = contents;
                    } else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }/*from w w w  .j  a  v a2 s  .  c  om*/
            }
            // we're not uploading files
        }
        if (encoding == null)
            encoding = "UTF-8";
        if (author == null)
            author = "Anon";
        if (style == null)
            style = "TEI/default";
        if (format == null)
            format = "MVD/TEXT";
        if (section == null)
            section = "";
        if (version1 == null)
            version1 = "/Base/first";
        if (description == null)
            description = "Version " + version1;
        if (docid == null)
            throw new Exception("missing docid");
        if (html == null)
            throw new Exception("Missing html");
        if (dialect == null)
            throw new Exception("Missing dialect");
    }
}

From source file:com.jdon.jivejdon.presentation.servlet.upload.ExtendedMultiPartRequestHandler.java

/**
 * Adds a regular text parameter to the set of text parameters for this
 * request and also to the list of all parameters. Handles the case of
 * multiple values for the same parameter by using an array for the
 * parameter value.//w  ww .  j a va  2s.c  o  m
 * 
 * @param request
 *            The request in which the parameter was specified.
 * @param item
 *            The file item for the parameter to add.
 */
protected void addTextParameter(HttpServletRequest request, FileItem item) {
    String name = item.getFieldName();
    String value = null;
    boolean haveValue = false;
    String encoding = request.getCharacterEncoding();

    if (encoding != null) {
        try {
            value = item.getString(encoding);
            haveValue = true;
        } catch (Exception e) {
            // Handled below, since haveValue is false.
        }
    }
    if (!haveValue) {
        try {
            value = item.getString("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            value = item.getString();
        }
        haveValue = true;
    }

    if (request instanceof MultipartRequestWrapper) {
        MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
        wrapper.setParameter(name, value);
    }

    String[] oldArray = (String[]) elementsText.get(name);
    String[] newArray;

    if (oldArray != null) {
        newArray = new String[oldArray.length + 1];
        System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
        newArray[oldArray.length] = value;
    } else {
        newArray = new String[] { value };
    }

    elementsText.put(name, newArray);
    elementsAll.put(name, newArray);
}

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

/**
 * Parses a <code>multipart/form-data</code>-encoded request parameter and
 * stores it in the parameter map./*www .j  a v  a 2 s .  com*/
 *
 * @param item       the uploaded file item.
 * @param encoding   the parameter encoding.
 * @param parameters the parameters map.
 * @throws UnsupportedEncodingException if an error occurred during
 *                                      parameter value decoding.
 */
protected void parseMultiPartParameter(FileItem item, String encoding, Map[] parameters)
        throws UnsupportedEncodingException {
    String name = item.getFieldName();
    if (name.startsWith(getDataPrefix()) || name.startsWith(CompositeControlValue.prefix)) {
        if (item.isFormField()) {
            parameters[1] = parseControlParameter(name, item.getString(encoding), parameters[1]);
        } else {
            parameters[0] = parseUploadParameter(name, item, parameters[0]);
        }
    } else if (name.startsWith(getSelectorPrefix())) {
        parameters[2] = parseRepeatParameter(name, item.getString(encoding), parameters[2]);
    } else if (name.startsWith(getTriggerPrefix())) {
        parameters[3] = parseTriggerParameter(name, item.getString(encoding), parameters[3]);
    }
}

From source file:controller.insertProduct.java

private void insertProduct(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    String productType = null;/*ww w.  ja  v  a 2  s . c  o m*/
    String resolution = null;
    String hdmi = null;
    String usb = null;
    String model = null;
    String size = null;
    String warranty = null;

    String productName = null;
    int price = 0;
    String description = null;
    Integer quantity = null;
    String produceID = null;
    String image = null;

    String uploadDirectory = "/Product/Images";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    File uploadDir;
    File storeFile;
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadDirectory + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    image = produceID + "/" + fileName;
                    System.out.println(storeFile.getPath());
                } else {
                    switch (item.getFieldName()) {
                    case "productName":
                        productName = item.getString("UTF-8");
                        break;
                    case "produceID": {
                        produceID = item.getString("UTF-8");
                        uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        uploadDirectory = uploadPath + uploadDirectory + "/" + produceID;
                        break;
                    }
                    case "price":
                        price = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "quantity":
                        quantity = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "productType":
                        productType = item.getString("UTF-8");
                        break;
                    case "resolution":
                        resolution = item.getString("UTF-8");
                        break;
                    case "hdmi":
                        hdmi = item.getString("UTF-8");
                        break;
                    case "usb":
                        usb = item.getString("UTF-8");
                        break;
                    case "Model":
                        model = item.getString("UTF-8");
                        break;
                    case "size":
                        size = item.getString("UTF-8");
                        break;
                    case "warranty":
                        warranty = item.getString("UTF-8");
                        break;
                    case "description": {
                        description = item.getString("UTF-8");
                        System.out.println(description);
                        break;
                    }
                    }
                }
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }

    @SuppressWarnings("null")
    ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty);
    Products product = new Products(productName, price, description, quantity, image, prinfo, produceID);

    if (ProductsDAO.insertProduct(product)) {
        out.print(
                "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    } else {
        out.print(
                "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    }
}

From source file:bijian.util.upload.MyMultiPartRequest.java

private void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException {
    LOG.debug("Item is a normal form field");
    List<String> values;
    if (params.get(item.getFieldName()) != null) {
        values = params.get(item.getFieldName());
    } else {/*w  ww  .  j a va2  s . c  o  m*/
        values = new ArrayList<String>();
    }

    // note: see http://jira.opensymphony.com/browse/WW-633
    // basically, in some cases the charset may be null, so
    // we're just going to try to "other" method (no idea if this
    // will work)
    if (charset != null) {
        values.add(item.getString(charset));
    } else {
        values.add(item.getString());
    }
    params.put(item.getFieldName(), values);
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*from w ww  .  j a v a  2s. co m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String type = "";
            String qs = "";
            byte[] data = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    executeMetadata(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DatabaseQueryServlet.GlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*  w  w w. java  2  s .c o m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            boolean showSql = false;
            String vtable = "";
            String type = "";
            String qs = "";
            byte[] data = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("showSql")) {
                        showSql = true;
                    } else if (item.getFieldName().equals("vtables")) {
                        vtable = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, showSql, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    sc.setAttribute("vtable", vtable);
                    executeMetadata(session, qs, false, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("showSql", showSql);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        } else {
            // Edit table cell value
            String action = request.getParameter("action");
            String vtable = request.getParameter("vtable");
            String column = request.getParameter("column");
            String value = request.getParameter("value");
            String id = request.getParameter("id");

            if (action.equals("edit")) {
                int idx = column.indexOf('(');

                if (idx > 0) {
                    column = column.substring(idx + 1, idx + 6);
                }

                String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value
                        + "' where dmv.table='" + vtable + "' and dmv.id=" + id;
                log.info("HQL: {}", hql);
                session = HibernateUtil.getSessionFactory().openSession();
                int rows = session.createQuery(hql).executeUpdate();
                log.info("Rows affected: {}", rows);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.redoute.datamap.servlet.picture.AddPicture.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String page = "";
    String application = "";
    String pictureName = "";
    String screenshot = "";
    FileItem item = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/*  w  ww .  java  2  s.  c  o m*/

            String fileName = null;
            List items = upload.parseRequest(request);
            List items2 = items;
            Iterator iterator = items.iterator();
            Iterator iterator2 = items2.iterator();
            File uploadedFile = null;
            String idNC = "";

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();

                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equals("Page")) {
                        page = item.getString("UTF-8");
                        System.out.println(page);
                    }
                    if (name.equals("Application")) {
                        application = item.getString("UTF-8");
                        System.out.println(application);
                    }
                    if (name.equals("PictureName")) {
                        pictureName = item.getString("UTF-8");
                        System.out.println(pictureName);
                    }
                    if (name.equals("Screenshot")) {
                        screenshot = item.getString().split("<img src=\"")[1].split("\">")[0];
                        System.out.println(screenshot);
                        System.out.println(screenshot.length());
                    }
                }
            }

            ApplicationContext appContext = WebApplicationContextUtils
                    .getWebApplicationContext(this.getServletContext());
            IPictureService pictService = appContext.getBean(IPictureService.class);
            IFactoryPicture factoryPicture = appContext.getBean(IFactoryPicture.class);

            Picture pict = factoryPicture.create(0, application, page, pictureName, screenshot);
            pictService.createPicture(pict);

            response.sendRedirect("Datamap.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:com.hrhih.dispatcher.HrhihJakartaMultiPartRequest.java

private void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Item is a normal form field");
    }//  w  ww.j a  v  a  2  s  .  c o  m
    List<String> values;
    if (params.get(item.getFieldName()) != null) {
        values = params.get(item.getFieldName());
    } else {
        values = new ArrayList<String>();
    }

    // note: see http://jira.opensymphony.com/browse/WW-633
    // basically, in some cases the charset may be null, so
    // we're just going to try to "other" method (no idea if this
    // will work)
    if (charset != null) {
        values.add(item.getString(charset));
    } else {
        values.add(item.getString());
    }
    params.put(item.getFieldName(), values);
    item.delete();
}

From source file:com.krawler.spring.documents.documentDAOImpl.java

public void parseRequest(List fileItems, HashMap<String, String> arrParam, ArrayList<FileItem> fi,
        boolean fileUpload) throws ServiceException {

    FileItem fi1 = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();/*from w ww  .  j a va2s.  c o m*/
        if (fi1.isFormField()) {
            try {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        } else {
            if (fi1.getSize() != 0) {
                fi.add(fi1);
                fileUpload = true;
            }
        }
    }
}