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:com.esri.gpt.control.publication.UploadMetadataController.java

/**
 * Extracts the XML string associated with an uploaded multipath file item.
 * @return the XML string (null if none)
 * @throws UnsupportedEncodingException (should never be thrown)
 *///from   ww  w.  ja va 2  s.c om
private String extractItemXml(FileItem item) throws UnsupportedEncodingException {
    String xml = null;
    if (item != null) {
        xml = Val.chkStr(Val.removeBOM(item.getString("UTF-8")));
    }
    return xml;
}

From source file:com.wabacus.WabacusFacade.java

public static void uploadFile(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;//from   w  ww.  ja va  2 s .c o m
    try {
        out = response.getWriter();
    } catch (IOException e1) {
        throw new WabacusRuntimeException("response?PrintWriter", e1);
    }
    out.println(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + Config.encode + "\">");
    importWebresources(out);
    if (Config.getInstance().getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog")) {
        out.print("<script type=\"text/javascript\"  src=\"" + Config.webroot
                + "webresources/component/artDialog/artDialog.js\"></script>");
        out.print("<script type=\"text/javascript\"  src=\"" + Config.webroot
                + "webresources/component/artDialog/plugins/iframeTools.js\"></script>");
    }
    /**if(true)
    {
    out.print("<table style=\"margin:0px;\"><tr><td style='font-size:13px;'><font color='#ff0000'>");
    out.print("???WabacusDemo????\n\rWabacusDemo.war?samples/");
    out.print("</font></td></tr></table>");
    return;
    }*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    String repositoryPath = FilePathAssistant.getInstance().standardFilePath(Config.webroot_abspath
            + File.separator + "wxtmpfiles" + File.separator + "upload" + File.separator);
    FilePathAssistant.getInstance().checkAndCreateDirIfNotExist(repositoryPath);
    factory.setRepository(new File(repositoryPath));
    ServletFileUpload fileUploadObj = new ServletFileUpload();
    fileUploadObj.setFileItemFactory(factory);
    fileUploadObj.setHeaderEncoding(Config.encode);
    List lstFieldItems = null;
    String errorinfo = null;
    try {
        lstFieldItems = fileUploadObj.parseRequest(request);
        if (lstFieldItems == null || lstFieldItems.size() == 0) {
            errorinfo = "??";
        }
    } catch (FileUploadException e) {
        log.error("?", e);
        errorinfo = "?";
    }
    Map<String, String> mFormFieldValues = new HashMap<String, String>();
    Iterator itFieldItems = lstFieldItems.iterator();
    FileItem item;
    while (itFieldItems.hasNext()) {//??mFormFieldValues??
        item = (FileItem) itFieldItems.next();
        if (item.isFormField()) {
            try {
                mFormFieldValues.put(item.getFieldName(), item.getString(Config.encode));
                request.setAttribute(item.getFieldName(), item.getString(Config.encode));
            } catch (UnsupportedEncodingException e) {
                log.warn("??????" + Config.encode
                        + "?", e);
            }
        }
    }
    String fileuploadtype = mFormFieldValues.get("FILEUPLOADTYPE");
    AbsFileUpload fileUpload = getFileUploadObj(request, fileuploadtype);
    boolean isPromtAuto = true;
    if (fileUpload == null) {
        errorinfo = "";
    } else if (errorinfo == null || errorinfo.trim().equals("")) {
        fileUpload.setMFormFieldValues(mFormFieldValues);
        errorinfo = fileUpload.doFileUpload(lstFieldItems, out);
        if (fileUpload.getInterceptorObj() != null) {
            isPromtAuto = fileUpload.getInterceptorObj().beforeDisplayFileUploadPrompt(request, lstFieldItems,
                    fileUpload.getMFormFieldValues(), errorinfo, out);
        }
    }
    out.println("<script language='javascript'>");
    out.println("  try{hideLoadingMessage();}catch(e){}");
    out.println("</script>");
    if (isPromtAuto) {
        if (errorinfo == null || errorinfo.trim().equals("")) {
            out.println("<script language='javascript'>");
            fileUpload.promptSuccess(out, Config.getInstance()
                    .getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog"));
            out.println("</script>");
        } else {
            out.println("<table style=\"margin:0px;\"><tr><td style='font-size:13px;'><font color='#ff0000'>"
                    + errorinfo + "</font></td></tr></table>");
        }
    }
    if (errorinfo != null && !errorinfo.trim().equals("")) {
        if (fileUpload != null) {
            request.setAttribute("WX_FILE_UPLOAD_FIELDVALUES", fileUpload.getMFormFieldValues());
        }
        showUploadFilePage(request, out);
    } else if (!isPromtAuto) {//???????????
        out.println("<script language='javascript'>");
        if (Config.getInstance().getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog")) {
            out.println("art.dialog.close();");
        } else {
            out.println("parent.closePopupWin();");
        }
        out.println("</script>");
    }
}

From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java

public <T> void processUploadedFile(FileItem item, T pojo) {
    try {//from ww w .  j av a  2s .c o  m
        String name = item.getFieldName();
        if (name == null || Magic.EmtpyString.equals(name)) {
            return;
        }
        Class<?> cls = getPropertyClass(pojo.getClass(), name);
        if (cls == null) {
            return;
        }
        if (cls.equals(String.class)) {
            String value = item.getString(encoding);
            IParamConvert paramConvert = classParamConvertRegistry.get(cls.getName());
            Object oldValue = getPropertyValue(pojo, pojo.getClass(), name);
            Object convertedValue = ConvertUtil.addUrlEncodedStringIfArray(oldValue, value, encoding, cls,
                    paramConvert == null ? primitiveConvert : paramConvert);
            if (convertedValue != null) {
                BeanUtils.setProperty(pojo, name, convertedValue);
            }
        } else if (cls.equals(InputStream.class)) {
            Object convertedValue = item.getInputStream();
            if (convertedValue != null) {
                BeanUtils.setProperty(pojo, name, convertedValue);
            }
        } else if (cls.equals(FileItem.class)) {
            BeanUtils.setProperty(pojo, name, item);
        } else {
            logger.warn("Not support field[{}] type:{}.", name, cls);
        }
    } catch (IllegalAccessException e) {
        logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo",
                pojo.getClass());
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        logger.error("set pojo property error!", e);
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error("can't convert stream to " + encoding, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("getInputStream from item error!", e);
        throw new RuntimeException(e);
    }
}

From source file:Logic.UploadLogic.java

public void pictureUpload(HttpServletRequest request, UserDataBeans loginAccount, String contextPath) {
    for (int i = 0; i < 6; i++) {
    }/*from  w w  w .  j av a 2 s.  c om*/
    PictureDataBeans picture = null;

    //?
    System.out.println("" + request.getRequestURI());
    String path = "/Users/gest/NetBeansProjects/WorkSpacesProto/web/common/image/";
    File newDirectry = new File(path + loginAccount.getUserName());

    //?????
    if (!newDirectry.exists() || newDirectry == null) {
        newDirectry.mkdir();
        System.out.println("?");
    }

    //??
    String dPath = newDirectry.getPath();

    //???
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);

    try {
        //????????
        List<FileItem> list = sfu.parseRequest(request);
        Iterator iterator = list.iterator();

        String pictureName = "";
        String extension = "";
        String comment = "????";
        int categoryID = 1;

        FileItem pictureData = null;

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

            //??
            if (!item.isFormField()) {
                pictureData = item;
                String itemName = item.getName();
                extension = itemName.substring(itemName.lastIndexOf("."));

                //()??   
            } else {
                System.out.println(item.getString("UTF-8"));
                switch (item.getFieldName()) {

                case "pictureName":
                    //?????
                    pictureName = item.getString("UTF-8");
                    //?????, [+]??
                    if (pictureName.isEmpty()) {
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        String strDate = sdf.format(date);
                        pictureName = "" + strDate;
                    }
                    break;

                case "category":
                    categoryID = Integer.parseInt(item.getString("UTF-8"));
                    break;

                case "comment":
                    comment = item.getString("UTF-8");
                    break;
                }
            }
        }

        pictureData.write(new File(dPath + "/" + pictureName + extension));
        //??, DB??
        String pPath = contextPath + "/common/image/" + loginAccount.getUserName() + "/" + pictureName
                + extension;
        picture = new PictureDataBeans((pictureName + extension), pPath, comment, categoryID,
                loginAccount.getUserName());
        picture.setPictureID(picture.hashCode());

        //DB??
        PictureDataDTO dto = new PictureDataDTO();
        picture.PDB2DTOMapping(dto, loginAccount.getUserID());
        PictureDataDAO.getInstance().setPictureData(dto);

    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.recipes.controller.Recipes.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww . ja  v  a 2  s.c  om
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    DAO dao = new DAO();
    HttpSession session = request.getSession(true);
    if (request.getParameter("add") != null) {
        response.sendRedirect("addRecipe.jsp");
    } else if (request.getParameter("insert") != null) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fields = upload.parseRequest(request);

            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                // fayl yoxdur mesaj
                return;
            }

            String title = "";//String deyiwenleri gotururuy
            String article = "";
            String category = "";
            String prepareRules = "";
            String image = "";
            List<String> composition = new ArrayList<>();
            String cook_time = "";
            String total_time = "";
            String prep_time = "";

            while (it.hasNext()) { // eger file varsa
                FileItem fileItem = it.next(); // iteratorun next metodu cagrilir
                boolean isFormField = fileItem.isFormField(); // isformField-input yoxlanilirki 
                if (isFormField) { // eger isFormFIelddise
                    switch (fileItem.getFieldName()) {
                    case "title":
                        title = fileItem.getString("UTF-8").trim();
                        break;
                    case "category":
                        category = fileItem.getString("UTF-8").trim();
                        break;
                    case "article":
                        article = fileItem.getString("UTF-8").trim();
                        break;
                    case "prepareRules":
                        prepareRules = fileItem.getString("UTF-8").trim();
                        break;
                    case "image":
                        image = fileItem.getString("UTF-8").trim();
                        break;
                    case "tags":
                        composition.add(fileItem.getString("UTF-8").trim());
                        break;
                    case "prep_time":
                        prep_time = fileItem.getString("UTF-8").trim();
                        break;
                    case "cook_time":
                        cook_time = fileItem.getString("UTF-8").trim();
                        break;
                    case "total_time":
                        total_time = fileItem.getString("UTF-8").trim();
                        break;
                    }
                } else {
                    if (fileItem.getFieldName().equals("image")) {
                        if (!fileItem.getString("UTF-8").trim().equals("")) {
                            image = fileItem.getName();
                            image = dao.generateCode() + image;
                            String relativeWebPath = "photos";
                            String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
                            File file = new File(absoluteDiskPath + "/", image);
                            fileItem.write(file);
                        }
                    }
                }
            }

            Recipe recipe = new Recipe();
            recipe.setArticle(article);
            recipe.setCategory(category);
            String comps = "";
            for (String c : composition)
                comps += c + ",";
            if (comps.contains(","))
                comps = comps.substring(0, comps.length() - 1);
            recipe.setComposition(comps);
            if (image.isEmpty()) {
                image = "defaultrecipe.jpg";
            }
            recipe.setImage(image);
            recipe.setLike_count(0);
            recipe.setPrepared_rules(prepareRules);
            recipe.setTitle(title);
            recipe.setUser_id(Integer.parseInt(session.getAttribute("user_id").toString()));
            recipe.setVisible(1);
            recipe.setPrep_time(prep_time);
            recipe.setCook_time(cook_time);
            recipe.setTotal_time(total_time);
            dao.insertRecipe(recipe);
            response.sendRedirect("addRecipe.jsp?success=");
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

    } else if (request.getParameter("id") != null) {
        response.sendRedirect("recipeDetails.jsp?id=" + request.getParameter("id"));
    }

    else {
        response.sendRedirect("index.jsp");
    }

}

From source file:com.recipes.controller.AdminP.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww w  .j ava2 s. co 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 {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession(true);
    DAO dao = new DAO();
    if (request.getParameter("createUser") != null) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fields = upload.parseRequest(request);

            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                // fayl yoxdur mesaj
                return;
            }

            String firstname = "";//String deyiwenleri gotururuy
            String lastname = "";
            String email = "";
            String password = "";
            String image = "";
            String address = "";
            String gender = "";
            String admin = "";

            while (it.hasNext()) { // eger file varsa
                FileItem fileItem = it.next(); // iteratorun next metodu cagrilir
                boolean isFormField = fileItem.isFormField(); // isformField-input yoxlanilirki 
                if (isFormField) { // eger isFormFIelddise
                    switch (fileItem.getFieldName()) {
                    case "name":
                        firstname = fileItem.getString("UTF-8").trim();
                        break;
                    case "surname":
                        lastname = fileItem.getString("UTF-8").trim();
                        break;
                    case "address":
                        address = fileItem.getString("UTF-8").trim();
                        break;
                    case "email":
                        email = fileItem.getString("UTF-8").trim();
                        break;
                    case "password":
                        password = fileItem.getString("UTF-8").trim();
                        break;
                    case "gender":
                        gender = fileItem.getString("UTF-8").trim();
                        break;
                    case "admin":
                        admin = fileItem.getString("UTF-8").trim();
                        break;
                    }
                } else {
                    if (fileItem.getFieldName().equals("image")) {
                        if (!fileItem.getString("UTF-8").trim().equals("")) {
                            image = fileItem.getName();
                            image = dao.generateCode() + image;
                            String relativeWebPath = "photos";
                            String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
                            File file = new File(absoluteDiskPath + "/", image);
                            fileItem.write(file);
                        }
                    }
                }
            }

            User up = new User();
            up.setAddress(address);
            up.setEmail(email);
            up.setFirstname(firstname);
            up.setLastname(lastname);
            up.setGender(gender);
            up.setPassword(password);
            up.setImage("photos/" + image);
            if (admin.equals("on"))
                up.setAdmin(1);
            else
                up.setAdmin(0);

            dao.insertUser(up);

            response.sendRedirect("admin/users.jsp");
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

    } else if (request.getParameter("delete") != null) {
        dao.deleteUser(request.getParameter("id"));
        response.sendRedirect("admin/users.jsp");
    } else if (request.getParameter("approveRecipe") != null) {
        String id = request.getParameter("approveRecipe");
        dao.approveRecipe(id);
        response.sendRedirect("admin/recipes.jsp");
    } else if (request.getParameter("deleteRecipe") != null) {
        String id = request.getParameter("deleteRecipe");
        dao.deleteRecipe(id);
        response.sendRedirect("admin/recipes.jsp");
    } else if (request.getParameter("deleteDictionary") != null) {
        dao.deleteDictionary(request.getParameter("deleteDictionary"));
        response.sendRedirect("admin/dictionary.jsp");
    } else if (request.getParameter("createWord") != null) {
        Dictionary dic = new Dictionary();
        dic.setWord(request.getParameter("word"));
        dic.setAbout(request.getParameter("about"));
        dao.insertDictionary(dic);
        response.sendRedirect("admin/dictionary.jsp");
    } else if (request.getParameter("createTips") != null) {
        Tips tips = new Tips();
        tips.setFrom(request.getParameter("from"));
        tips.setTips(request.getParameter("tips"));
        dao.insertTips(tips);
        response.sendRedirect("admin/tips.jsp");
    } else if (request.getParameter("deleteTips") != null) {
        dao.deleteTips(request.getParameter("deleteTips"));
        response.sendRedirect("admin/tips.jsp");
    } else {
        response.sendRedirect("admin/users.jsp");
    }

}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Returns the value of a multipart/form-data fields posted on this request
 * This method can also read fields posted on WebTML forms.
 * However the WebTML input data type is not enforced on the returned value.
 * @param name Name of the field/* ww w.j  ava  2s .c om*/
 * @param encoding The encoding used to decode the field value
 * @return The field value
 * @throws WGException
 */
public String getFormField(String name, String encoding) throws WGException {
    try {
        FileItem fi = fetchFormData(_wga.getRequest()).get(name);
        if (fi != null) {
            return fi.getString(encoding);
        }
        return null;
    } catch (UnavailableResourceException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        throw new WGAServerException("Unsupported encoding: " + encoding);
    }
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;/*from w  w w .ja  va2s  .c  o m*/
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void addTextParameter(HttpServletRequest request, FileItem item) {
    final String name = item.getFieldName();
    final String encoding = request.getCharacterEncoding();
    String value = null;/*w w  w  .ja v a2  s .c  om*/
    boolean haveValue = false;
    if (encoding != null) {
        try {
            value = item.getString(encoding);
            haveValue = true;
        } catch (Exception e) {
        }
    }
    if (!haveValue) {
        try {
            value = item.getString("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            value = item.getString();
        }
        haveValue = true;
    }
    if (request instanceof MultipartRequestWrapper) {
        final MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
        wrapper.setParameter(name, value);
    }
    final String[] oldArray = elementsText.get(name);
    final 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:com.globalsight.everest.webapp.pagehandler.administration.config.xmldtd.FileUploader.java

private File saveTmpFile(List<FileItem> fileItems) throws Exception {

    File file = File.createTempFile("GSDTDUpload", null);

    // Set overall request size constraint
    long uploadTotalSize = 0;
    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            uploadTotalSize += item.getSize();
        }// www. j  a v  a 2s. c  o m
    }

    for (ProcessStatus status : listeners) {
        status.setTotalSize(uploadTotalSize);
    }

    log.debug("File size: " + uploadTotalSize);

    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            item.write(file);
            setName(getFileName(item.getName()));
        } else {
            fields.put(item.getFieldName(), item.getString("utf-8"));
        }
    }

    for (ProcessStatus status : listeners) {
        status.finished();
    }

    return file;
}