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:net.daw.control.upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  w w.ja  v a2  s.  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("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String name = "";
        String strMessage = "";
        HashMap<String, String> hash = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(".//..//webapps//images//" + name));
                    } else {
                        hash.put(item.getFieldName(), item.getString());
                    }
                }
                Gson oGson = new Gson();
                Map<String, String> data = new HashMap<>();
                Iterator it = hash.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry e = (Map.Entry) it.next();
                    data.put(e.getKey().toString(), e.getValue().toString());
                }
                data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/images/" + name);
                out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}");
            } catch (Exception ex) {
                strMessage += "File Upload Failed: " + ex;
                out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
            }
        } else {
            strMessage += "Only serve file upload requests";
            out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
        }
    }
}

From source file:com.GTDF.server.FileUploadServlet.java

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

    String rootDirectory = getServletConfig().getInitParameter("TRANSFORM_HOME");
    String workDirectory = getServletConfig().getInitParameter("TRANSFORM_DIR");
    String prefixDirectory = "";
    boolean writeToFile = true;
    String returnOKMessage = "OK";
    String username = "";
    String authResult = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    PrintWriter out = response.getWriter();

    // Create a factory for disk-based file items 
    if (isMultipart) {

        // We are uploading a file (deletes are performed by non multipart requests) 
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler 
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request 
        try {/*w ww  .ja v a2  s. c o  m*/

            List items = upload.parseRequest(request);

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

                    // Hidden field containing username - check authorization
                    if (item.getFieldName().equals("username")) {
                        username = item.getString();
                        String wikiDb = getServletConfig().getInitParameter("WIKIDB");
                        String wikiDbUser = getServletConfig().getInitParameter("WIKIDB_USER");
                        String wikiDbPassword = getServletConfig().getInitParameter("WIKIDB_PASSWORD");
                        String wikiNoAuth = getServletConfig().getInitParameter("NOAUTH"); // v1.5 Check parameter NOAUTH
                        WikiUserImpl wikiUser = new WikiUserImpl();
                        authResult = wikiUser.wikiUserVerifyDb(username, wikiDb, wikiDbUser, wikiDbPassword,
                                wikiNoAuth);
                        if (authResult != "LOGGED") {
                            out.print(authResult);
                            return;
                        } else
                            new File(rootDirectory + workDirectory + '/' + username).mkdirs();
                    }

                    // Hidden field containing file prefix to create subdirectory
                    if (item.getFieldName().equals("prefix")) {
                        prefixDirectory = item.getString();
                        new File(rootDirectory + workDirectory + '/' + username + '/' + prefixDirectory)
                                .mkdirs();
                        prefixDirectory += '/';
                    }
                } else {
                    if (writeToFile) {
                        String fileName = item.getName();
                        if (fileName != null && !fileName.equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                            File uploadedFile = new File(rootDirectory + workDirectory + '/' + username + '/'
                                    + prefixDirectory + fileName);
                            try {
                                item.write(uploadedFile);
                                String hostedOn = getServletConfig().getInitParameter("HOSTED_ON");
                                out.print("Infile at: " + hostedOn + workDirectory + '/' + username + '/'
                                        + prefixDirectory + fileName);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {

        //Process a request to delete a file 
        String[] paramValues = request.getParameterValues("uploadFormElement");
        for (int i = 0; i < paramValues.length; i++) {
            String fileName = FilenameUtils.getName(paramValues[i]);
            File deleteFile = new File(rootDirectory + workDirectory + fileName);
            if (deleteFile.delete()) {
                out.print(returnOKMessage);
            }
        }
    }

}

From source file:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java

@SuppressWarnings("unchecked")
@Override/* w w  w .j  a va 2 s .c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        ServletRequestContext ctx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(ctx) == false) {
            sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "The servlet can only handle multipart requests." + " This is probably a software bug."));
            return;
        }

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> i = items.iterator();
        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, File> files = new HashMap<String, File>();

        while (i.hasNext() == true) {
            FileItem item = i.next();

            if (item.isFormField() == true) {
                String param = item.getFieldName();
                String value = item.getString();
                //                    System.out.println(getClass().getName() + ": param="
                //                            + param + ", value=" + value);
                params.put(param, value);
            } else {
                if (item.getSize() == 0) {
                    continue; // ignore zero-length files
                }

                File tempf = File.createTempFile(request.getRemoteAddr() + "-" + item.getFieldName() + "-", "");
                item.write(tempf);
                files.put(item.getFieldName(), tempf);
                //                    System.out.println("Creating temporary file "
                //                            + tempf.getAbsolutePath());
            }
        }

        // populate, invoke the listener, delete files if needed,
        // send response
        FileUploadAction action = (FileUploadAction) actionClass.newInstance();
        BeanUtils.populate(action, params); // populate the object
        action.setFileList(files);

        FormResponse resp = action.onSubmit(this, request);
        if (resp.isDeleteFiles()) {
            Iterator<Map.Entry<String, File>> j = files.entrySet().iterator();
            while (j.hasNext()) {
                Map.Entry<String, File> entry = j.next();
                File f = entry.getValue();
                f.delete();
            }
        }

        sendResponse(response, resp);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage()));
    }
}

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

@Override
@SuppressWarnings({ "rawtypes" })
protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
        throws ServletException, IOException {

    beforePostStart();/*from  w  w w  . j  a va  2  s. co  m*/

    final DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File("/tmp"));

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
        final List fileItems = upload.parseRequest(req);
        String userHash = null;
        StateToken stateToken = null;
        String typeId = null;
        String fileName = null;
        FileItem file = null;
        for (final Iterator iterator = fileItems.iterator(); iterator.hasNext();) {
            final FileItem item = (FileItem) iterator.next();
            if (item.isFormField()) {
                final String name = item.getFieldName();
                final String value = item.getString();
                LOG.info("name: " + name + " value: " + value);
                if (name.equals(FileConstants.HASH)) {
                    userHash = value;
                }
                if (name.equals(FileConstants.TOKEN)) {
                    stateToken = new StateToken(value);
                }
                if (name.equals(FileConstants.TYPE_ID)) {
                    typeId = value;
                }
            } else {
                fileName = item.getName();
                LOG.info("file: " + fileName + " fieldName: " + item.getFieldName() + " size: " + item.getSize()
                        + " typeId: " + typeId);
                file = item;
            }
        }
        createUploadedFile(userHash, stateToken, fileName, file, typeId);
        onSuccess(response);
    } catch (final FileUploadException e) {
        onFileUploadException(response);
    } catch (final Exception e) {
        onOtherException(response, e);
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.upload.ContactUpload.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */// w  w  w  . j  a v a2 s.  c o  m
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File uploadedFile = null;

    List<String> groupUuids = new LinkedList<>();
    Account account = new Account();

    HttpSession session = request.getSession(false);

    String username = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);

    Element element;
    if ((element = accountsCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }

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

    // Set up where the files will be stored on disk
    File repository = new File(System.getProperty("java.io.tmpdir") + File.separator + username);
    FileUtils.forceMkdir(repository);
    factory.setRepository(repository);

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

    // Parse the request              
    try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        FileItem item;

        while (iter.hasNext()) {
            item = iter.next();

            if (item.isFormField()) {
                // Here we assume only a Group UUID has been submitted as a text field
                groupUuids.add(item.getString());

            } else {
                uploadedFile = processUploadedFile(item);
            }
        } // end 'while (iter.hasNext())'

    } catch (FileUploadException e) {
        logger.error("FileUploadException while getting File Items.");
        logger.error(e);
    }

    // Here we assume that only one file was uploaded
    // First we inspect if it is ok
    String feedback = uploadUtil.inspectContactFile(uploadedFile);
    session.setAttribute(UPLOAD_FEEDBACK, "<p class='error'>" + feedback + "<p>");

    response.sendRedirect("addcontact.jsp");

    // Process the file into the database if it is ok
    if (StringUtils.equals(feedback, UPLOAD_SUCCESS)) {
        uploadUtil.saveContacts(uploadedFile, account, contactDAO, phoneDAO, groupUuids, contactGroupDAO);
    }
}

From source file:edu.lafayette.metadb.web.controlledvocab.CreateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///w w w  .j  a  v  a2 s.c  o m
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            name = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString() + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString();
                } else {

                    @SuppressWarnings("unused")
                    String content = "nothing";
                    /* The file item contains an uploaded file */

                    /* Create new File object
                    File uploadedFile = new File("test.txt");
                    if(!uploadedFile.exists())
                       uploadedFile.createNewFile();
                    // Write the uploaded file to the system
                    fileItem.write(uploadedFile);
                    */
                    name = fileItem.getName();
                    content = fileItem.getContentType();
                    input = fileItem.getInputStream();
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //               status = "Form is not multi-part";
                    //               vocabName = request.getParameter("vocab-name");
                    //               String vocabs = request.getParameter("vocab-terms");
                    MetaDbHelper.note(vocabs);
                    for (String vocab : vocabs.split("\n"))
                        vocabList.add(vocab);
                }
                if (!vocabList.isEmpty()) {
                    if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " created successfully";
                    else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " updated successfully ";
                    else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                }
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:io.milton.servlet.ServletRequest.java

@Override
public void parseRequestParameters(Map<String, String> params, Map<String, io.milton.http.FileItem> files)
        throws RequestParseException {
    try {//from   w w  w  .  j a  v a2 s. c o m
        if (isMultiPart()) {
            log.trace("parseRequestParameters: isMultiPart");
            UploadListener listener = new UploadListener();
            MonitoredDiskFileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);

            parseQueryString(params);

            for (Object o : items) {
                FileItem item = (FileItem) o;
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                } else {
                    // See http://jira.ettrema.com:8080/browse/MIL-118 - ServletRequest#parseRequestParameters overwrites multiple file uploads when using input type="file" multiple="multiple"                        
                    String itemKey = item.getFieldName();
                    if (files.containsKey(itemKey)) {
                        int count = 1;
                        while (files.containsKey(itemKey + count)) {
                            count++;
                        }
                        itemKey = itemKey + count;
                    }
                    files.put(itemKey, new FileItemWrapper(item));
                }
            }
        } else {
            for (Enumeration en = request.getParameterNames(); en.hasMoreElements();) {
                String nm = (String) en.nextElement();
                String[] vals = request.getParameterValues(nm);
                if (vals.length == 1) {
                    params.put(nm, vals[0]);
                } else {
                    StringBuilder sb = new StringBuilder();
                    for (String s : vals) {
                        sb.append(s).append(",");
                    }
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1); // remove last comma
                    }
                    params.put(nm, sb.toString());
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new RequestParseException("FileUploadException", ex);
    } catch (Throwable ex) {
        throw new RequestParseException(ex.getMessage(), ex);
    }
}

From source file:controller.StudentController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addorchange(HttpServletRequest request) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // int mssv = Integer.parseInt(request.getParameter("mssv"));
    // String tensv = request.getParameter("tensv");
    // String ngaysinh = request.getParameter("ngaysinh");
    // String ngaydi = request.getParameter("ngaydi");
    // String que = request.getParameter("que");
    // String lop = request.getParameter("lop");
    // String khoa = request.getParameter("khoa");
    // int sdt = Integer.parseInt(request.getParameter("sdt"));
    // int maphong = Integer.parseInt(request.getParameter("roomnum"));
    // int makhu = Integer.parseInt(request.getParameter("roomregion"));

    int mssv = 0;
    String tensv = null;/* ww w  . j av a 2  s  .  c  om*/
    String ngaysinh = null;
    String ngaydi = null;
    String que = null;
    String lop = null;
    String khoa = null;
    int sdt = 0;
    int maphong = 0;
    int makhu = 0;
    FileItem f = null;
    String fName = null;
    try {
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("mssv")) {
                mssv = Integer.parseInt(item.getString());
            }

            if (item.getFieldName().equals("tensv")) {
                tensv = item.getString();
            }
            if (item.getFieldName().equals("ngaysinh")) {
                ngaysinh = item.getString();
            }
            if (item.getFieldName().equals("ngaydi")) {
                ngaydi = item.getString();
            }
            if (item.getFieldName().equals("que")) {
                que = item.getString();
            }
            if (item.getFieldName().equals("lop")) {
                lop = item.getString();
            }
            if (item.getFieldName().equals("khoa")) {
                khoa = item.getString();
            }
            if (item.getFieldName().equals("sdt")) {
                sdt = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("roomnum")) {
                maphong = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("roomregion")) {
                makhu = Integer.parseInt(item.getString());
            }

            if (!item.isFormField()) {
                f = item;
                fName = new File(item.getName()).getName();

            }
        }

    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    RoomRegion region = new RoomRegion(makhu, "");
    Room room = new Room(maphong, region, 0, 0, null, null);
    if (room.checkRoom()) {
        Student student = new Student(mssv, tensv, ngaysinh, que, lop, khoa, room, sdt, ngaydi, fName);
        request.setAttribute("roomnum", new Room().roomList());
        request.setAttribute("roomregion", new RoomRegion().regionList());
        try {
            if (student.add() >= 3) {
                String path = request.getServletContext().getRealPath("/");
                String UPLOAD_DIRECTORY = path + "/static/uploads";
                File dir = new File(UPLOAD_DIRECTORY);
                dir.mkdirs();
                File file = new File(dir.getAbsolutePath() + System.getProperty("file.separator") + fName);

                f.write(file);
                System.out.println(file.getPath());
                request.setAttribute("message", "Thm thnh cng!");
            } else {
                request.setAttribute("message", "Khng thm c, Sinh vin ny  tn ti!");
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Phng ny hin  y!");
    }
    request.setAttribute("id", "add");
    return SVManager(request);
}

From source file:com.duroty.application.mail.actions.SendAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {/*  w  ww .j  a va  2s. com*/
        boolean isMultipart = FileUpload.isMultipartContent(request);

        Mail mailInstance = getMailInstance(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector attachments = new Vector();

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

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

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("forwardAttachments")) {
                        String[] aux = item.getString().split(":");
                        MailPartObj part = mailInstance.getAttachment(aux[0], aux[1]);
                        attachments.addElement(part);
                    } else {
                        fields.put(item.getFieldName(), item.getString());
                    }
                } else {
                    if (!StringUtils.isBlank(item.getName())) {
                        ByteArrayOutputStream baos = null;

                        try {
                            baos = new ByteArrayOutputStream();

                            IOUtils.copy(item.getInputStream(), baos);

                            MailPartObj part = new MailPartObj();
                            part.setAttachent(baos.toByteArray());
                            part.setContentType(item.getContentType());
                            part.setName(item.getName());
                            part.setSize(item.getSize());

                            attachments.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            String body = "";

            if (fields.get("taBody") != null) {
                body = (String) fields.get("taBody");
            } else if (fields.get("taReplyBody") != null) {
                body = (String) fields.get("taReplyBody");
            }

            Preferences preferencesInstance = getPreferencesInstance(request);

            Send sendInstance = getSendInstance(request);

            String mid = (String) fields.get("mid");

            if (StringUtils.isBlank(mid)) {
                request.setAttribute("action", "compose");
            } else {
                request.setAttribute("action", "reply");
            }

            Boolean isHtml = null;

            if (StringUtils.isBlank((String) fields.get("isHtml"))) {
                isHtml = new Boolean(preferencesInstance.getPreferences().isHtmlMessage());
            } else {
                isHtml = Boolean.valueOf((String) fields.get("isHtml"));
            }

            sendInstance.send(mid, Integer.parseInt((String) fields.get("identity")), (String) fields.get("to"),
                    (String) fields.get("cc"), (String) fields.get("bcc"), (String) fields.get("subject"), body,
                    attachments, isHtml.booleanValue(), Charset.defaultCharset().displayName(),
                    (String) fields.get("priority"));
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
            request.setAttribute("exception", "The form is null");
            request.setAttribute("newLocation", null);
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:com.controller.changeLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww .  j av  a 2  s .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
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("upload")) {
                        uploadType = fi.getString();
                    }

                } else {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID");

                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

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

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    if (uploadType.equals("update")) {
                        String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID);
                        String filePath_to_delete = uploadPath + File.separator + file_name_to_delete;

                        File deletefile = new File(filePath_to_delete);
                        deletefile.delete();
                    }

                    filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fi.write(storeFile);

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");

                    response.sendRedirect(request.getContextPath() + "/settings.jsp");

                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}