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();

Source Link

Document

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

Usage

From source file:eg.agrimarket.controller.ProductController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w w  w.j av a2s. com*/
        PrintWriter out = response.getWriter();
        eg.agrimarket.model.pojo.Product product = new eg.agrimarket.model.pojo.Product();
        Product productJPA = new Product();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    product.setImage(image);
                    productJPA.setImage(image);
                }
            } else {
                switch (item.getFieldName()) {
                case "name":
                    product.setName(item.getString());
                    productJPA.setName(item.getString());
                    System.out.println("name" + item.getString());
                    break;
                case "price":
                    product.setPrice(Float.valueOf(item.getString()));
                    productJPA.setPrice(Float.valueOf(item.getString()));
                    break;
                case "quantity":
                    product.setQuantity(Integer.valueOf(item.getString()));
                    productJPA.setQuantity(Integer.valueOf(item.getString()));
                    break;
                case "desc":
                    product.setDesc(item.getString());
                    productJPA.setDesc(item.getString());
                    System.out.println("desc: " + item.getString());
                    break;
                default:
                    Category category = new Category();
                    category.setId(Integer.valueOf(item.getString()));
                    product.setCategoryId(category);
                    productJPA.setCategoryId(category.getId());
                }
            }
        }

        ProductDao daoImp = new ProductDaoImp();
        boolean check = daoImp.addProduct(product);
        if (check) {
            List<Product> products = (List<Product>) request.getServletContext().getAttribute("products");
            if (products != null) {
                products.add(productJPA);
                request.getServletContext().setAttribute("products", products);

            }
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?success=Successfully#header3-41");
        } else {
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?status=Exist!#header3-41");
        }

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

From source file:eu.impact_project.wsclient.SOAPresults.java

/**
 * Loads the user values/files and sends them to the web service. Files are
 * encoded to Base64. Stores the resulting message in the session and the
 * resulting files on the server./*from   ww  w. j  a va2 s . c  o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream outStream = null;
    BufferedInputStream bis = null;
    user = request.getParameter("user");
    pass = request.getParameter("pass");

    try {

        HttpSession session = request.getSession(true);

        String folder = session.getServletContext().getRealPath("/");
        if (!folder.endsWith("/")) {
            folder = folder + "/";
        }

        Properties props = new Properties();
        InputStream stream = new URL("file:" + folder + "config.properties").openStream();

        props.load(stream);
        stream.close();

        boolean loadDefault = Boolean.parseBoolean(props.getProperty("loadDefaultWebService"));
        boolean supportFileUpload = Boolean.parseBoolean(props.getProperty("supportFileUpload"));
        boolean oneResultFile = Boolean.parseBoolean(props.getProperty("oneResultFile"));
        String defaultFilePrefix = props.getProperty("defaultFilePrefix");

        SoapService serviceObject = (SoapService) session.getAttribute("serviceObject");
        SoapOperation operation = null;
        if (supportFileUpload) {

            // stores all the strings and encoded files from the html form
            Map<String, String> htmlFormItems = new HashMap<String, String>();

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                // a normal string field
                if (item.isFormField()) {
                    htmlFormItems.put(item.getFieldName(), item.getString());

                    // uploaded file
                } else {

                    // encode the uploaded file to base64
                    String currentAttachment = new String(Base64.encode(item.get()));

                    htmlFormItems.put(item.getFieldName(), currentAttachment);
                }
            }

            // get the chosen WSDL operation
            String operationName = htmlFormItems.get("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                input.setValue(htmlFormItems.get(input.getName()));
            }

        } else {
            // get the chosen WSDL operation
            String operationName = request.getParameter("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                String[] soapInputValues = request.getParameterValues(input.getName());
                input.clearValues();
                for (String value : soapInputValues) {
                    input.addValue(value);
                }
            }

        }

        List<SoapOutput> outs = operation.execute(user, pass);
        String soapResponse = operation.getResponse();

        String htmlResponse = useXslt(soapResponse, "/SoapToHtml.xsl");

        session.setAttribute("htmlResponse", htmlResponse);
        session.setAttribute("soapResponse", soapResponse);

        // for giving the file names back to the JSP
        List<String> fileNames = new ArrayList<String>();

        // process possible attachments in the response
        List<SoapAttachment> attachments = operation.getReceivedAttachments();
        int i = 0;
        for (SoapAttachment attachment : attachments) {

            // path to the server directory
            String serverPath = getServletContext().getRealPath("/");
            if (!serverPath.endsWith("/")) {
                serverPath = folder + "/";
            }

            // construct the file name for the attachment
            String fileEnding = "";
            String contentType = attachment.getContentType();
            System.out.println("content type: " + contentType);
            if (contentType.equals("image/gif")) {
                fileEnding = ".gif";
            } else if (contentType.equals("image/jpeg")) {
                fileEnding = ".jpg";
            } else if (contentType.equals("image/tiff")) {
                fileEnding = ".tif";
            } else if (contentType.equals("application/vnd.ms-excel")) {
                fileEnding = ".xlsx";
            }

            String fileName = loadDefault ? defaultFilePrefix : "attachedFile";

            String counter = oneResultFile ? "" : i + "";

            String attachedFileName = fileName + counter + fileEnding;

            // store the attachment into the file
            File file = new File(serverPath + attachedFileName);
            outStream = new FileOutputStream(file);

            InputStream inStream = attachment.getInputStream();

            bis = new BufferedInputStream(inStream);

            int bufSize = 1024 * 8;

            byte[] bytes = new byte[bufSize];

            int count = bis.read(bytes);
            while (count != -1 && count <= bufSize) {
                outStream.write(bytes, 0, count);
                count = bis.read(bytes);
            }
            if (count != -1) {
                outStream.write(bytes, 0, count);
            }
            outStream.close();
            bis.close();

            fileNames.add(attachedFileName);
            i++;
        }

        // pass the file names to JSP
        request.setAttribute("fileNames", fileNames);

        request.setAttribute("round3", "round3");
        // get back to JSP
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/interface.jsp");
        rd.forward(request, response);

    } catch (Exception e) {
        logger.error("Exception", e);
        e.printStackTrace();
    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (bis != null) {
            bis.close();
        }
    }

}

From source file:com.sixsq.slipstream.module.ModuleResource.java

protected String getContent(FileItem fi) {
    return fi.getString();
}

From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java

public void fileUpload(CommandArgument commandArgument, HttpServletRequest request,
        HttpServletResponse response) {/*from   w  w  w.j av a  2 s  . c  o  m*/

    InputStream inputStream = null;

    String returnValue = null;

    try {
        ServletFileUpload servletFileUpload = new LiferayFileUpload(
                new LiferayFileItemFactory(UploadServletRequestImpl.getTempDir()), request);

        servletFileUpload
                .setFileSizeMax(PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE));

        LiferayServletRequest liferayServletRequest = new LiferayServletRequest(request);

        List<FileItem> fileItems = servletFileUpload.parseRequest(liferayServletRequest);

        Map<String, Object> fields = new HashMap<String, Object>();

        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                fields.put(fileItem.getFieldName(), fileItem);
            }
        }

        DiskFileItem diskFileItem = (DiskFileItem) fields.get("NewFile");

        String fileName = StringUtil.replace(diskFileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH);
        String[] fileNameArray = StringUtil.split(fileName, '/');
        fileName = fileNameArray[fileNameArray.length - 1];

        String contentType = diskFileItem.getContentType();

        if (Validator.isNull(contentType) || contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) {

            contentType = MimeTypesUtil.getContentType(diskFileItem.getStoreLocation());
        }

        if (diskFileItem.isInMemory()) {
            inputStream = diskFileItem.getInputStream();
        } else {
            inputStream = new ByteArrayFileInputStream(diskFileItem.getStoreLocation(),
                    LiferayFileItem.THRESHOLD_SIZE);
        }

        long size = diskFileItem.getSize();

        returnValue = fileUpload(commandArgument, fileName, inputStream, contentType, size);
    } catch (Exception e) {
        FCKException fcke = null;

        if (e instanceof FCKException) {
            fcke = (FCKException) e;
        } else {
            fcke = new FCKException(e);
        }

        Throwable cause = fcke.getCause();

        returnValue = "203";

        if (cause != null) {
            String causeString = GetterUtil.getString(cause.toString());

            if (causeString.contains("NoSuchFolderException") || causeString.contains("NoSuchGroupException")) {

                returnValue = "204";
            } else if (causeString.contains("ImageNameException")) {
                returnValue = "205";
            } else if (causeString.contains("FileExtensionException")
                    || causeString.contains("FileNameException")) {

                returnValue = "206";
            } else if (causeString.contains("PrincipalException")) {
                returnValue = "207";
            } else if (causeString.contains("ImageSizeException")
                    || causeString.contains("FileSizeException")) {

                returnValue = "208";
            } else if (causeString.contains("SystemException")) {
                returnValue = "209";
            } else {
                throw fcke;
            }
        }

        _writeUploadResponse(returnValue, response);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }

    _writeUploadResponse(returnValue, response);
}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.WorkflowUploadPortlet.java

@Override
protected void doUpload(ActionRequest request, ActionResponse response) {
    PortletContext context = getPortletContext();
    context.log("[FileUploadPortlet] doUpload() called");

    try {//  www  .  j ava2 s  . com
        DiskFileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload pfu = new PortletFileUpload(factory);
        pfu.setSizeMax(uploadMaxSize); // Maximum upload size
        pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

        PortletSession ps = request.getPortletSession();
        if (ps.getAttribute("uploads", ps.APPLICATION_SCOPE) == null)
            ps.setAttribute("uploads", new Hashtable<String, ProgressListener>());

        //get the FileItems
        String fieldName = null;

        List fileItems = pfu.parseRequest(request);
        Iterator iter = fileItems.iterator();
        File serverSideFile = null;
        Hashtable h = new Hashtable(); //fileupload
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // retrieve hidden parameters if item is a form field
            if (item.isFormField()) {
                fieldName = item.getFieldName();
                if ("newGrafName".equals(fieldName))
                    h.put("newGrafName", item.getString());
                if ("newAbstName".equals(fieldName))
                    h.put("newAbstName", item.getString());
                if ("newRealName".equals(fieldName))
                    h.put("newRealName", item.getString());
            } else { // item is not a form field, do file upload
                Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps
                        .getAttribute("uploads");//,ps.APPLICATION_SCOPE
                pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

                String s = item.getName();
                s = FilenameUtils.getName(s);
                ProgressListener pl = pfu.getProgressListener();
                tmp.put(s, pl);
                ps.setAttribute("uploads", tmp);

                String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser();
                File f = new File(tempDir);
                if (!f.exists())
                    f.mkdirs();
                serverSideFile = new File(tempDir, s);
                item.write(serverSideFile);
                item.delete();
                context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir);
            }
        }
        // file upload to storage
        try {
            ServiceType st = InformationBase.getI().getService("wfs", "portal", new Hashtable(), new Vector());
            h.put("senderObj", "ZipFileSender");
            h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url"));
            h.put("wfsID", st.getServiceUrl());
            h.put("userID", request.getRemoteUser());

            Hashtable hsh = new Hashtable();
            //                    st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
            //                    hsh.put("url", "http://localhost:8080/storage");
            st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
            PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject()).newInstance();
            psc.setServiceURL(st.getServiceUrl());
            psc.setServiceID("/receiver");
            if (serverSideFile != null)
                psc.fileUpload(serverSideFile, "fileName", h);
        } catch (Exception ex) {
            response.setRenderParameter("full", "error.upload");
            ex.printStackTrace();
            return;
        }
        ps.removeAttribute("uploads", ps.APPLICATION_SCOPE);

    } catch (FileUploadException fue) {
        response.setRenderParameter("full", "error.upload");

        fue.printStackTrace();
        context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        response.setRenderParameter("full", "error.exception");
        context.log("[FileUploadPortlet] - failed to upload file - " + e.toString());
        return;
    }
    response.setRenderParameter("full", "action.succesfull");
}

From source file:com.insurance.manage.UploadFile.java

private void uploadLicense(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    //       Create a factory for disk-based file items
    String custId = null;//from w  ww  .  j  av  a2s .c o m
    String year = null;
    String license = null;
    CustomerManager cManage = new CustomerManager();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    factory.setRepository(new File("temp"));

    //       Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpSession session = request.getSession();
    //      System.out.println("eCust : "+session.getAttribute("eCust"));
    //      if (session.getAttribute("eCust")!=null) {
    //         Customer cEntity = (Customer)request.getAttribute("eCust");
    //         System.out.println("CustId : "+cEntity.getName());
    //      }

    //       Parse the request
    //      System.out.println("--------- Uploading --------------");
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        //          Process the uploaded items
        Iterator iter = items.iterator();
        File fi = null;
        File file = null;
        Calendar calendar = Calendar.getInstance();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = df.format(calendar.getTime()) + ".jpg";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //                System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType());
                if (item.getFieldName().equals("custId") && !item.getString().equals("")) {
                    custId = item.getString();
                    //                   System.out.println("custId : "+custId);
                }
                if (item.getFieldName().equals("year") && !item.getString().equals("")) {
                    year = item.getString();
                    //                   System.out.println("year : "+year);
                }
                if (item.getFieldName().equals("license") && !item.getString().equals("")) {
                    license = (String) session.getAttribute(item.getString());
                    //                   System.out.println("license : "+license+" : "+session.getAttribute(item.getString()));
                }
            } else {
                //                Handle Uploaded files.
                //                System.out.println("Handle Uploaded files.");
                if (item.getFieldName().equals("vat") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/vat/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "vatpic", year + fileName);
                }
                if (item.getFieldName().equals("car") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/car/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "carpic", year + fileName);
                }
                if (item.getFieldName().equals("act") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/act/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "actpic", year + fileName);
                }
                if (item.getFieldName().equals("chk") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/chk/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "chkpic", year + fileName);
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId);
    request.setAttribute("msg", "!!!Uploading !!!");
    getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response);

}

From source file:Control.HandleAddRestaurant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w  .j a v  a 2  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, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();
        String[] tempS = null;
        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        path = Paths.tempPath;
        Restaurant temp = new Restaurant();
        String name = null;
        String sepName = Tools.CurrentTime();
        if (ServletFileUpload.isMultipartContent(request)) {
            List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Iterator iter = multiparts.iterator();
            int index = 0;
            tempS = new String[multiparts.size() - 1];
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();

                    String FilePath = path + Paths.logoPathStore + sepName + name;
                    item.write(new File(FilePath));
                } else {
                    String test = item.getFieldName();
                    tempS[index++] = item.getString();
                }
            }
            index = 0;
            temp.ID = tempS[index++];
            temp.name = tempS[index++];
            temp.address = tempS[index++];
            temp.city = tempS[index++];
            temp.state = tempS[index++];
            temp.zipcode = tempS[index++];
            temp.email = tempS[index++];
            temp.phone = tempS[index++];
            temp.monHours = tempS[index++];
            temp.sunHours = tempS[index++];
            temp.minPrice = Double.parseDouble(tempS[index++]);
            temp.fee = Double.parseDouble(tempS[index++]);
            temp.type = Integer.parseInt(tempS[index++]);
            temp.logoImage = Paths.logoPath + sepName + name;
        }

        if (Restaurant.checkExisted(temp.ID, temp.name)) {

            response.sendRedirect("./Admin/AddRestaurant.jsp?index=1");
        } else {
            if (Restaurant.addNewRestaurant(temp)) {
                Tools.updateRestaurants(session);
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=2");
            } else {
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=3");
            }
        }

    } catch (Exception e) {
        response.sendRedirect("./Admin/AddRestaurant.jsp?index=0");
    }
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/* w w  w .ja  va 2  s  . c  om*/
 */
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:com.tasktop.c2c.server.internal.wiki.server.WikiServiceController.java

@Section(value = "Attachments")
@Title("Upload Attachment")
@Secured({ Role.Community, Role.User, Role.Admin })
@RequestMapping(value = "{pageId}/attachment", method = RequestMethod.POST)
public void uploadAttachment(@PathVariable(value = "pageId") Integer pageId, HttpServletRequest request,
        HttpServletResponse response) throws IOException, FileUploadException, TextHtmlContentExceptionWrapper {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<Attachment> attachments = new ArrayList<Attachment>();
    Map<String, String> formValues = new HashMap<String, String>();

    PageHandle pageHandle = new PageHandle(pageId);
    try {// w  w  w  .ja  v  a  2 s . c  om
        // find all existing attachments
        List<Attachment> allPageAttachments = service.listAttachments(pageId);
        // map them by name
        Map<String, Attachment> attachmentByName = new HashMap<String, Attachment>();
        for (Attachment attachment : allPageAttachments) {
            attachmentByName.put(attachment.getName(), attachment);
        }

        // inspect the request, getting all posted attachments
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {

            if (item.isFormField()) {
                formValues.put(item.getFieldName(), item.getString());
            } else {
                Attachment attachment = new Attachment();
                attachment.setPage(pageHandle);
                attachment.setContent(item.get());
                attachment.setName(item.getName());
                attachment.setMimeType(item.getContentType());
                attachments.add(attachment);
            }
        }

        // for each new attachment, either create or update
        for (Attachment attachment : attachments) {
            Attachment attach = attachmentByName.get(attachment.getName());
            if (attach != null) {
                attachment.setId(attach.getId());
                service.updateAttachment(attachment);
            } else {
                service.createAttachment(attachment);
            }
        }

        // get content for response
        allPageAttachments = service.listAttachments(pageId);
        Page page = service.retrievePage(pageId);
        page.setContent(null);

        response.setContentType("text/html");
        response.getWriter().write(jsonMapper.writeValueAsString(
                Collections.singletonMap("uploadResult", new UploadResult(page, allPageAttachments))));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}

From source file:application.controllers.admin.EditEmotion.java

private String uploadNewImage(HttpServletRequest request, HttpServletResponse response) {
    String linkImage = emotionSelected.linkImage;
    if (!ServletFileUpload.isMultipartContent(request)) {
        return "";
    }/*from www.  jav  a  2 s.co  m*/
    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    //groupEmotionId chinh la folder chua
    // creates the directory if it does not exist
    String[] arrLink = emotionSelected.linkImage.split("/");
    if (arrLink.length < 3) {
        return "";
    }
    try {
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (item.isFormField()) {
                //form field
                if (item.getFieldName().equals("groupEmotion")) {
                    try {
                        if (emotionSelected.groupEmotionId != Integer.parseInt(item.getString())) {
                            //thay doi group id --> chuyen file sang folder tuong ung va thay doi imagelink
                            //chuyen file sang folder tuong ung theo group da chon

                            String sourcePath = Registry.get("imageHost") + emotionSelected.linkImage;
                            //item.getString --> groupEmotion chon
                            String desPath = Registry.get("imageHost") + "/emotions-image/" + item.getString()
                                    + "/" + arrLink[3];

                            File sourceDir = new File(sourcePath);
                            File desDir = new File(desPath);
                            if (sourceDir.exists()) {
                                FileUtils.copyFile(sourceDir, desDir);
                                sourceDir.delete();

                            }

                            emotionSelected.groupEmotionId = Integer.parseInt(item.getString());
                            linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3];

                        }
                    } catch (NumberFormatException ex) {
                        ex.printStackTrace();
                    }
                }
                if (item.getFieldName().equals("description")) {
                    emotionSelected.description = item.getString();
                }
                if (item.getFieldName().equals("imageURL")) {
                    emotionSelected.linkImage = item.getString();

                }
            } else {

                String fileName = new File(item.getName()).getName();
                //file name bang empty khi ko upload new image
                if ("".equals(fileName)) {
                    continue;
                }
                String filePath = Registry.get("imageHost") + emotionSelected.linkImage;
                File newImage = new File(filePath);
                File oldImage = new File(filePath);
                // xoa image cu bi edit
                if (oldImage.exists()) {
                    oldImage.delete();
                }
                // save image moi vao  folder cua group id va cung ten moi image cu
                item.write(newImage);

                //save lai file cua image moi
                linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3];
            }
        }

    } catch (Exception ex) {
        Logger.getLogger(EditEmotion.class.getName()).log(Level.SEVERE, null, ex);
    }
    return linkImage;

}