Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:controller.ProductProcess.java

public String processImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.print("error");
        return "";
    }//from   www .j a  v  a2  s.c  o m
    String pathh = "";
    DiskFileItemFactory factory = new DiskFileItemFactory(MEMORY_THRESHOLD,
            new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            for (FileItem formItem : formItems) {
                if (!formItem.isFormField()) {
                    String a = formItem.getName();
                    String fileName = new File(a).getName();
                    pathh = fileName;
                    String filePath = uploadPath + File.separator + fileName;

                    File storeFile = new File(filePath);

                    formItem.write(storeFile);
                } else {
                    String nameAttribute = formItem.getFieldName();
                    String valueAttribute = formItem.getString("UTF-8");
                    request.setAttribute(nameAttribute, valueAttribute);
                }
            }

        }

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

    return pathh;
}

From source file:com.mylop.servlet.ImageServlet.java

public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String account = (String) session.getAttribute("userid");
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {//from w ww .  jav  a  2  s  . c  o m
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String[] ext = contentType.split("/");

                    String fileName = UPLOAD_DIRECTORY + File.separator + account + "_Avatar";
                    File file = new File(fileName);

                    item.write(file);
                    String avatarUrl = "http://mylop.tk:8080/Avatar/" + account + "_Avatar";
                    ProfileModel pm = new ProfileModel();
                    Map<String, String> update = new HashMap<String, String>();
                    update.put("avatar", avatarUrl);
                    pm.updateProfile(account, update);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);

}

From source file:com.ccsna.safetynet.AdminNewsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  ww .j  a  v  a2s  .  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 {
    response.setContentType("text/html;charset=UTF-8");
    try {
        PrintWriter out = response.getWriter();
        String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "",
                endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null;
        Date sDate = null, eDate = null;
        Time eTime = null, sTime = null;
        String fullPath = null;
        int action = 0, newsId = 0;
        boolean dataValid = true;
        News news = null;
        Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession());
        if (loggedInMember != null) {
            String home = "";
            String alertPage = "";
            if (loggedInMember.getRole().equals(Menu.MEMBER)) {
                home = "/pages/member.jsp";
                alertPage = "/pages/memberAlert.jsp";

            } else {
                home = "/pages/agencyAdmin.jsp";
                alertPage = "/pages/editAlert.jsp";

            }
            log.info("home page is : " + home);
            log.info("alert page is : " + alertPage);

            String createdBy = String.valueOf(loggedInMember.getMemberId());
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            log.info("isMultipart :" + isMultipart);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String appPath = request.getServletContext().getRealPath("");

                //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot";
                //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            //log.info("item is form field");
                            String fileName = item.getName();
                            //log.info("the name of the item is :" + fileName);
                            String contentType = item.getContentType();
                            //log.info("the content type is :" + contentType);
                            if (item.getContentType().equalsIgnoreCase(JPEG)
                                    || item.getContentType().equalsIgnoreCase(JPG)
                                    || item.getContentType().equalsIgnoreCase(PDF)) {
                                String root = appPath;
                                log.info("pdf content recognised");
                                log.info("root path is :" + appPath);
                                //String smallLoc = "/uploads/small";
                                String largeLoc = "/uploads/large";
                                log.info("largeLoc:" + largeLoc);
                                //File pathSmall = new File(root + smallLoc);
                                File pathLarge = new File(root + largeLoc);
                                //log.info("small image path :" + pathSmall);
                                log.info("large image path :" + pathLarge);
                                if (!pathLarge.exists()) {
                                    // boolean status = pathSmall.mkdirs();
                                    pathLarge.mkdirs();
                                }
                                if (item.getContentType().equalsIgnoreCase(PDF)) {
                                    log.info("loading pdf file");
                                    fileType = Menu.PDF;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + PDF_EXTENSION;

                                    //File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge);

                                } else {
                                    fileType = Menu.IMAGE;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + JPEG_EXTENSION;

                                    log.info("filename is : " + fileName);
                                    // File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall);
                                    Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge);
                                }
                                //smallUrl = smallLoc + "/" + fileName + "";
                                largeUrl = largeLoc + "/" + fileName + "";
                                log.info("largeUrl image url is :" + largeUrl);
                                fullPath = request.getContextPath() + "/" + largeUrl;

                            }
                        } else {
                            if (item.getFieldName().equalsIgnoreCase("newsTitle")) {
                                title = item.getString();
                                log.info("title is :" + title);
                            }
                            if (item.getFieldName().equalsIgnoreCase("type")) {
                                newsType = item.getString();
                                log.info("newsType is :" + newsType);
                            }
                            if (item.getFieldName().equalsIgnoreCase("content")) {
                                content = item.getString();
                                log.info("content is :" + content);
                            }
                            if (item.getFieldName().equalsIgnoreCase("start_Date")) {
                                startDate = item.getString();
                                if (startDate != null && !startDate.isEmpty()) {
                                    sDate = Menu
                                            .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd"));
                                }
                                log.info("startDate is :" + startDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Date")) {
                                endDate = item.getString();
                                if (endDate != null && !endDate.isEmpty()) {
                                    eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd"));
                                }
                                log.info("endDate is :" + endDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("action")) {
                                action = Integer.parseInt(item.getString());
                                log.info("the action is :" + action);
                            }
                            if (item.getFieldName().equalsIgnoreCase("newsId")) {
                                newsId = Integer.parseInt(item.getString());
                                log.info("the newsid is :" + newsId);
                            }
                            if (item.getFieldName().equalsIgnoreCase("status")) {
                                st = item.getString();
                                log.info("the status is :" + st);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Time")) {
                                endTime = item.getString();
                                if (endTime != null && !endTime.isEmpty()) {
                                    eTime = Menu.convertStringToSqlTime(endTime);
                                }
                                log.info("eTime is :" + eTime);

                            }

                            if (item.getFieldName().equalsIgnoreCase("start_Time")) {
                                startTime = item.getString();
                                if (startTime != null && !startTime.isEmpty()) {
                                    sTime = Menu.convertStringToSqlTime(startTime);
                                }
                                log.info("sTime is :" + sTime);

                            }
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
            }
            switch (Validation.Actions.values()[action]) {
            case CREATE:
                log.info("creating new serlvet ................");
                news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy,
                        Menu.ACTIVE, largeUrl, fileType, fullPath);
                if (news != null) {
                    log.info("news successfully created...");
                    message += "News item has been successfully added";
                    Validation.setAttributes(request, Validation.SUCCESS, message);
                    response.sendRedirect(request.getContextPath() + home);
                } else {
                    log.info("news creating failed...");
                    message += "Unable to add news item";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + home);
                }
                break;
            case UPDATE:
                log.info("updating news ...");
                if (title != null && !title.isEmpty()) {
                    news = new NewsModel().findByParameter("title", title);
                }

                if (news != null && (news.getNewsId() == newsId)) {
                    log.info("news is :" + news.getNewsId());
                    dataValid = true;
                } else {
                    dataValid = false;
                }
                if (news == null) {
                    dataValid = true;
                }

                log.info("dataValid is :" + dataValid);

                if (dataValid) {
                    boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate,
                            eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime);
                    if (newsUpdated) {
                        message += "News/Alert has been successfully updated";
                        Validation.setAttributes(request, Validation.SUCCESS, message);
                        response.sendRedirect(request.getContextPath() + home);

                    } else {
                        message += "Unable to update news item";
                        Validation.setAttributes(request, Validation.ERROR, message);
                        response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId);
                    }
                } else {
                    message += "News with same title already exist, Enter a different title";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId);
                }
                break;
            }
        } else {
            message += "Session expired, Kindly login with username and password";
            Validation.setAttributes(request, Validation.ERROR, message);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    } catch (Exception e) {

    }

}

From source file:com.founder.fix.fixflow.FlowCenter.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from   w  w  w  .  ja v a 2s.  c o  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID));

    if (StringUtil.isEmpty(userId)) {
        String context = request.getContextPath();
        response.sendRedirect(context + "/");
        return;
    }
    CurrentThread.init();
    ServletOutputStream out = null;
    String action = StringUtil.getString(request.getParameter("action"));
    if (StringUtil.isEmpty(action)) {
        action = StringUtil.getString(request.getAttribute("action"));
    }
    if (StringUtil.isEmpty(action)) {
        action = "getMyTask";
    }
    RequestDispatcher rd = null;
    try {
        Map<String, Object> filter = new HashMap<String, Object>();

        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload Uploader = new ServletFileUpload(new DiskFileItemFactory());
            // Uploader.setSizeMax("); // 
            Uploader.setHeaderEncoding("utf-8");
            List<FileItem> fileItems = Uploader.parseRequest(request);
            for (FileItem item : fileItems) {
                filter.put(item.getFieldName(), item);
                if (item.getFieldName().equals("action"))
                    action = item.getString();
            }
        } else {
            Enumeration enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                Object tmp = enu.nextElement();
                Object obj = request.getParameter(StringUtil.getString(tmp));

                // if (request.getAttribute("ISGET") != null)
                obj = new String(obj.toString().getBytes("ISO8859-1"), "utf-8");

                filter.put(StringUtil.getString(tmp), obj);
            }
        }

        Enumeration attenums = request.getAttributeNames();
        while (attenums.hasMoreElements()) {
            String paramName = (String) attenums.nextElement();

            Object paramValue = request.getAttribute(paramName);

            // ?map
            filter.put(paramName, paramValue);

        }

        filter.put("userId", userId);
        request.setAttribute("nowAction", action);
        if (action.equals("getMyProcess")) {
            rd = request.getRequestDispatcher("/fixflow/center/startTask.jsp");
            List<Map<String, String>> result = getFlowCenter().queryStartProcess(userId);

            Map<String, List<Map<String, String>>> newResult = new HashMap<String, List<Map<String, String>>>();
            for (Map<String, String> tmp : result) {
                String category = tmp.get("category");
                if (StringUtil.isEmpty(category))
                    category = "";

                List<Map<String, String>> tlist = newResult.get(category);
                if (tlist == null) {
                    tlist = new ArrayList<Map<String, String>>();
                }
                tlist.add(tmp);
                newResult.put(category, tlist);
            }
            request.setAttribute("result", newResult);
            //??sqlserverbug????
            request.setAttribute("userId", userId); // userId add Rex
            try {
                List<Map<String, String>> lastestProcess = getFlowCenter().queryLastestProcess(userId);
                request.setAttribute("lastest", lastestProcess);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (action.equals("getMyTask")) {
            rd = request.getRequestDispatcher("/fixflow/center/todoTask.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().queryMyTaskNotEnd(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getProcessImage")) {
            response.getOutputStream();
        } else if (action.equals("getAllProcess")) {
            rd = request.getRequestDispatcher("/fixflow/center/queryprocess.jsp");
            Map<String, Object> pageResult = getFlowCenter().queryTaskInitiator(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getPlaceOnFile")) {
            rd = request.getRequestDispatcher("/fixflow/center/placeOnFile.jsp");
            Map<String, Object> pageResult = getFlowCenter().queryPlaceOnFile(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("getTaskDetailInfo")) {
            rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp");
            Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getTaskDetailInfoSVG")) {
            rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp");
            Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfoSVG(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getFlowGraph")) {
            InputStream is = getFlowCenter().getFlowGraph(filter);
            out = response.getOutputStream();
            response.setContentType("application/octet-stream;charset=UTF-8");
            byte[] buff = new byte[2048];
            int size = 0;
            while (is != null && (size = is.read(buff)) != -1) {
                out.write(buff, 0, size);
            }
        } else if (action.equals("getUserInfo")) {
            rd = request.getRequestDispatcher("/fixflow/common/userInfo.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("getUserIcon")) {
            rd = request.getRequestDispatcher("/fixflow/common/userOperation.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("updateUserIcon")) {
            rd = request.getRequestDispatcher("/FlowCenter?action=getUserInfo");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            getFlowCenter().saveUserIcon(filter);

        } else if (action.equals("selectUserList")) { //
            String isMulti = request.getParameter("isMulti");
            rd = request.getRequestDispatcher("/fixflow/common/selectUserList.jsp?isMulti=" + isMulti);
            Map<String, Object> pageResult = getFlowCenter().getAllUsers(filter);
            filter.putAll(pageResult);

            request.setAttribute("result", filter);
            request.setAttribute("isMulti", isMulti);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("selectNodeList")) { //
            rd = request.getRequestDispatcher("/fixflow/common/selectNodeList.jsp");
            Map<String, Object> pageResult = getFlowCenter().getRollbackNode(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("selectStepList")) { //
            rd = request.getRequestDispatcher("/fixflow/common/selectStepList.jsp");
            Map<String, Object> pageResult = getFlowCenter().getRollbackTask(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("viewDelegation")) { //
            rd = request.getRequestDispatcher("/fixflow/common/setDelegation.jsp");
            Map<String, Object> pageResult = new HashMap<String, Object>();
            pageResult = this.getFlowIdentityService().getUserDelegationInfo(userId);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if (action.equals("saveDelegation")) { //

            String agentInfoJson = StringUtil.getString(request.getParameter("insertAndUpdate"));
            if (StringUtil.isNotEmpty(agentInfoJson)) {
                Map<String, Object> delegationInfo = JSONUtil.parseJSON2Map(agentInfoJson);
                this.getFlowIdentityService().saveUserDelegationInfo(delegationInfo);
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<script>alert('??');window.close();</script>");
        }
    } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute("errorMsg", e.getMessage());
        try {
            CurrentThread.rollBack();
        } catch (SQLException e1) {
            e1.printStackTrace();
            request.setAttribute("errorMsg", e.getMessage());
        }
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        try {
            CurrentThread.clear();
        } catch (SQLException e) {
            request.setAttribute("errorMsg", e.getMessage());
            e.printStackTrace();
        }
    }
    if (rd != null) {
        rd.forward(request, response);
    }
}

From source file:edu.lternet.pasta.portal.MetadataPreviewerServlet.java

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * /*  ww  w . j  av a  2 s  .c o  m*/
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();
    String uid = (String) httpSession.getAttribute("uid");
    String forward = "./metadataViewer.jsp";

    if (uid == null || uid.isEmpty())
        uid = "public";

    String html = null;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {

            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();

                if (!(item.isFormField())) {

                    String eml = processUploadedFile(item);

                    EmlUtility emlUtility = new EmlUtility(eml);
                    html = emlUtility.xmlToHtmlSaxon(cwd + xslpath, null);
                }

            }

        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    request.setAttribute("metadataHtml", html);
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:com.mylop.servlet.TimelineServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w w w.j  a v  a2 s  . c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String userid = (String) session.getAttribute("userid");
    String status = "aaa";
    String urlTimelineImage = "";
    String title = "";
    String subtitle = "";
    String content = "";
    Date date = new Date(Calendar.getInstance().getTimeInMillis());
    TimelineModel tm = new TimelineModel();
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {

                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String fileName = UPLOAD_DIRECTORY + File.separator + userid + "_"
                            + (tm.getLastIndex() + 1);
                    File file = new File(fileName);
                    item.write(file);
                    urlTimelineImage = "http://mylop.tk:8080/Timeline/" + file.getName();
                } else {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("title")) {
                        title = item.getString();
                    }
                    if (fieldName.equals("subtitle")) {
                        subtitle = item.getString();
                    }
                    if (fieldName.equals("content")) {
                        content = item.getString();
                    }
                    if (fieldName.equals("date")) {
                        Long dateLong = Long.parseLong(item.getString());
                        date = new Date(dateLong);
                    }

                }
            }

            tm.addTimeline(userid, title, subtitle, date, content, urlTimelineImage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);
}

From source file:com.rubinefocus.admin.servlet.UploadProductImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  ww.  ja  v  a 2 s .  c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File f = new File(this.getServletContext().getRealPath("admin/assets/images/products"));
    String savePath = f.getPath();
    savePath = savePath.replace("%20", " ");
    savePath = savePath.replace("build", "");
    String fileName = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if its multipart content
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    fileName = new File(item.getName()).getName();
                    File file = new File(savePath + "/" + fileName);

                    if (file.exists()) {
                        String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
                        String ext = FilenameUtils.getExtension(fileName);
                        fileName = fileNameWithOutExt
                                + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()) + "." + ext;
                        fileName = fileName.replace(" ", "");
                        fileName = fileName.replace("-", "");
                        fileName = fileName.replace(":", "");
                        item.write(new File(savePath + File.separator + fileName));

                    } else {
                        item.write(new File(savePath + File.separator + fileName));

                    }
                    Gson gson = new Gson();
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");

                    response.getWriter().write(gson.toJson(fileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:it.lufraproini.cms.servlet.Upload.java

private Map prendiInfo(HttpServletRequest request) throws FileUploadException {
    Map info = new HashMap();
    Map files = new HashMap();

    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        items = upload.parseRequest(request);
        ///*w  w  w.  j  a v  a2 s. c o  m*/
        for (FileItem item : items) {
            String name = item.getFieldName();
            //le form che prevedono l'upload di un file devono avere il campo del file chiamato in questo modo
            if (name.startsWith("file_to_upload")) {
                files.put(name, item);
            } else {
                info.put(name, item.getString());
            }
        }
        info.put("files", files);
        return info;
    }
    return null;
}

From source file:edu.ucla.loni.pipeline.server.Upload.Uploaders.FileUploadServlet.java

/**
 * Handles Request to Upload File, Builds a Response
 * //from   ww  w.  ja  v a  2  s .  c o m
 * @param req
 * @param respBuilder
 */
private void handleFileUpload(HttpServletRequest req, ResponseBuilder respBuilder) {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        try {
            // Parse the request
            FileItemIterator iter = upload.getItemIterator(req);

            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                handleUploadedFile(item, respBuilder);
            }
        } catch (FileUploadException e) {
            respBuilder.appendRespMessage("The file was not uploaded successfully.");
        } catch (IOException e) {
            respBuilder.appendRespMessage("The file was not uploaded successfully.");
        }
    } else {
        respBuilder.appendRespMessage("Your form of request is not supported by this upload servlet.");
    }
}

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 w  w w  .j a  va  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;
}