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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

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

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

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

From source file:egovframework.asadal.asapro.com.cmm.web.AsaproEgovMultipartResolver.java

/**
 * multipart?  parsing? .//from   w  w w  . j  av  a  2 s.  c  o  m
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

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

        if (fileItem.isFormField()) {

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

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (!AsaproEgovWebUtil.checkAllowUploadFileExt(file.getOriginalFilename()))
                    throw new MultipartException(" ? ? .");

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

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

private String extractParameter(String name, List<?> files) {
    for (Iterator<?> i = files.iterator(); i.hasNext();) {
        FileItem file = (FileItem) i.next();
        if (file.isFormField() && file.getFieldName().equals(name)) {
            return "".equals(file.getString()) ? null : file.getString();
        }/*from  w  ww  .ja  va 2s .c  o m*/
    }
    return null;
}

From source file:egovframework.oe1.cms.com.web.EgovOe1MultipartResolver.java

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

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

        if (fileItem.isFormField()) {

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

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

        }
    }

    return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles,
            (Map<String, String[]>) multipartParameters);
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

private FileItem extractFile(String name, List<?> files) {
    for (Iterator<?> i = files.iterator(); i.hasNext();) {
        FileItem file = (FileItem) i.next();
        if (!file.isFormField() && file.getFieldName().equals(name)) {
            return file;
        }/* w  w  w.jav  a 2 s .c  om*/
    }
    return null;
}

From source file:lcn.module.oltp.web.common.base.MultipartResolver.java

/**
 * multipart?  parsing? ./*from  w w w .ja va  2 s .c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    //   Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    //   Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

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

        if (fileItem.isFormField()) {

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

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

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

        }
    }
    return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles,
            (Map<String, String[]>) multipartParameters, multipartParameters);

    //   return new MultipartParsingResult(multipartFiles, multipartParameters);
}

From source file:com.example.web.Update_profile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        String fileName = "";
        int f = 0;
        String user = null;//from w w  w  .j a v a2s. co m
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    user = cookie.getValue();
                }
            }
        }
        String email = request.getParameter("email");
        String First_name = request.getParameter("First_name");
        String Last_name = request.getParameter("Last_name");
        String Phone_number_1 = request.getParameter("Phone_number_1");
        String Address = request.getParameter("Address");
        String message = "";
        int valid = 1;
        String query;
        ResultSet rs;
        Connection conn;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "tworld";
        String driver = "com.mysql.jdbc.Driver";
        isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
            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.setSizeMax(maxFileSize);

            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();

                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();
                        fileName = fi.getName();
                        String contentType = fi.getContentType();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        String[] spliting = fileName.split("\\.");
                        // Write the file
                        System.out.println(sizeInBytes + " " + maxFileSize);
                        System.out.println(spliting[spliting.length - 1]);
                        if (!fileName.equals("")) {
                            if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                    || spliting[spliting.length - 1].equals("png")
                                    || spliting[spliting.length - 1].equals("jpeg"))) {

                                if (fileName.lastIndexOf("\\") >= 0) {
                                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                                } else {
                                    file = new File(
                                            filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                                }
                                fi.write(file);
                                System.out.println("Uploaded Filename: " + fileName + "<br>");
                            } else {
                                valid = 0;
                                message = "not a valid image";
                            }
                        }
                    }
                    BufferedReader br = null;
                    StringBuilder sb = new StringBuilder();

                    String line;
                    try {
                        br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                    if (f == 0) {
                        email = sb.toString();
                    } else if (f == 1) {
                        First_name = sb.toString();
                    } else if (f == 2) {
                        Last_name = sb.toString();
                    } else if (f == 3) {
                        Phone_number_1 = sb.toString();
                    } else if (f == 4) {
                        Address = sb.toString();
                    }
                    f++;

                }
            } catch (Exception ex) {
                System.out.println("hi");
                System.out.println(ex);

            }
        }
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (!email.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?");
                pst.setString(1, email);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!First_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?");
                pst.setString(1, First_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Last_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?");
                pst.setString(1, Last_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Phone_number_1.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?");
                pst.setString(1, Phone_number_1);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Address.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?");
                pst.setString(1, Address);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!fileName.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?");
                pst.setString(1, fileName);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            System.out.println("hi mom");
        }

        request.setAttribute("s_page", "4");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CurrentThread.init();//from ww  w .ja v  a  2 s .  c o  m
    String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID));
    if (StringUtil.isEmpty(userId)) {
        String context = request.getContextPath();
        response.sendRedirect(context + "/");
        return;
    }
    ServletOutputStream out = null;
    String action = StringUtil.getString(request.getParameter("action"));
    if (StringUtil.isEmpty(action)) {
        action = StringUtil.getString(request.getAttribute("action"));
    }
    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();
                if (item.getFieldName().equals("deploymentId")) {
                    filter.put("deploymentId", 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 ("processDefinitionList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/processDefinitionList.jsp");
            Map<String, Object> result = getProcessDefinitionService().getProcessDefitionList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("processManageList")) {
            rd = request.getRequestDispatcher("/fixflow/manager/processInstanceList.jsp");
            Map<String, Object> result = getFlowManager().getProcessInstances(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("suspendProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().suspendProcessInstance(filter);
        } else if (action.equals("continueProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().continueProcessInstance(filter);

        } else if (action.equals("terminatProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().terminatProcessInstance(filter);
        } else if (action.equals("deleteProcessInstance")) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().deleteProcessInstance(filter);
        } else if (action.equals("toProcessVariable")) {
            rd = request.getRequestDispatcher("/fixflow/manager/processVariableList.jsp");
            Map<String, Object> result = getFlowManager().getProcessVariables(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if (action.equals("saveProcessVariables")) {
            String tmp = (String) filter.get("insertAndUpdate");
            if (StringUtil.isNotEmpty(tmp)) {
                Map<String, Object> tMap = JSONUtil.parseJSON2Map(tmp);
                filter.put("insertAndUpdate", tMap);
            }
            getFlowManager().saveProcessVariables(filter);
            rd = request.getRequestDispatcher("/FlowManager?action=toProcessVariable");
        } else if (action.equals("processTokenList")) {
            Map<String, Object> result = getFlowManager().getProcessTokens(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            rd = request.getRequestDispatcher("/fixflow/manager/processTokenList.jsp");
        } else if (action.equals("taskInstanceList")) {
            rd = request.getRequestDispatcher("/fixflow/manager/taskInstanceList.jsp");
            filter.put("path", request.getSession().getServletContext().getRealPath("/"));
            Map<String, Object> pageResult = getTaskManager().getTaskList(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if (action.equals("doTaskSuspend")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().suspendTask(filter);
        } else if (action.equals("doTaskResume")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().resumeTask(filter);
        } else if (action.equals("doTaskTransfer")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().transferTask(filter);
        } else if (action.equals("doTaskRollBackNode")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().rollBackNode(filter);
        } else if (action.equals("doTaskRollBackTask")) {
            rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList");
            getTaskManager().rollBackStep(filter);
        } else if (action.equals("flowLibrary")) {
            rd = request.getRequestDispatcher("/fixflow-explorer/flowLibrary.jsp");
        }
        //???deploymentId
        if ("deploy".equals(action)) {
            rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList");
            response.setContentType("text/html;charset=utf-8");
            getProcessDefinitionService().deployByZip(filter);
        } else if ("deleteDeploy".equals(action)) {
            rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList");
            getProcessDefinitionService().deleteDeploy(filter);
        } else if ("download".equals(action)) {
            String processDefinitionId = StringUtil.getString(filter.get("processDefinitionId"));
            response.reset();
            request.setCharacterEncoding("gbk");
            response.setContentType("applcation/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + processDefinitionId + ".zip");
            response.setHeader("Cache-Control",
                    "must-revalidate, post-check=0, pre-check=0,private, max-age=0");
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");

            ZipOutputStream outZip = new ZipOutputStream(response.getOutputStream());
            List<Map<String, Object>> fileList = getProcessDefinitionService().getResources(filter);
            for (Map<String, Object> file : fileList) {
                ZipEntry entry = new ZipEntry(file.get("FILENAME").toString());
                entry.setSize(((byte[]) file.get("BYTES")).length);
                outZip.putNextEntry(entry);
                outZip.write((byte[]) file.get("BYTES"));
                outZip.closeEntry();
            }
            outZip.close();
            outZip.flush();
            outZip.close();
        } else if ("getUserList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/userList.jsp");
            request.setAttribute("nowAction", "UserGroup");
            Map<String, Object> result = getUserGroupService().getAllUsers(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);

            List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter);
            request.setAttribute("groupList", groupList);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if ("getGroupList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/groupList.jsp");
            request.setAttribute("nowAction", "UserGroup");
            Map<String, Object> result = getUserGroupService().getAllGroup(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
            List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter);
            request.setAttribute("groupList", groupList);
            request.setAttribute("pageInfo", filter.get("pageInfo"));
        } else if ("getUserInfo".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/userInfo.jsp");
            Map<String, Object> pageResult = getUserGroupService().getUserInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if ("getGroupInfo".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/groupInfo.jsp");
            Map<String, Object> pageResult = getUserGroupService().getGroupInfo(filter);
            filter.putAll(pageResult);
            request.setAttribute("result", filter);
        } else if ("getJobList".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp");
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("viewJobInfo".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp");
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobTrigger(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("suspendJob".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp");
            request.setAttribute("nowAction", "jobManager");
            getJobService().suspendJob(filter);
            Map<String, Object> result = getJobService().getJobList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("continueJob".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp");
            getJobService().continueJob(filter);
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobList(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("suspendTrigger".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp");
            getJobService().suspendTrigger(filter);
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobTrigger(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("continueTrigger".equals(action)) {
            rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp");
            getJobService().continueTrigger(filter);
            request.setAttribute("nowAction", "jobManager");
            Map<String, Object> result = getJobService().getJobTrigger(filter);
            filter.putAll(result);
            request.setAttribute("result", filter);
        } else if ("setHis".equals(action)) {
            rd = request.getRequestDispatcher("/FlowManager?action=processManageList");
            getFlowManager().setHistory(filter);
        } else if ("updateCache".equals(action)) {
            ProcessEngineManagement.getDefaultProcessEngine().cleanCache(true, true);
            response.getWriter().write("update success!");
        }
    } 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) {
            e.printStackTrace();
            request.setAttribute("errorMsg", e.getMessage());
        }
    }
    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 {/*from  w  w w . ja v a 2 s .c  o  m*/
        // 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:easyJ.http.upload.CommonsMultipartRequestHandler.java

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

    try {
        value = item.getString(request.getCharacterEncoding());
    } catch (Exception e) {
        value = item.getString();
    }

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

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

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

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