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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from   w  w w  . j ava  2 s .  c  om
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}

From source file:it.biblio.servlets.Inserimento_pub.java

/**
 * metodo per gestire l'upload di file e inserimento pubblicazione con prima
 * ristampa/*from   ww w .  j  av a 2  s. c o  m*/
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    HttpSession s = SecurityLayer.checkSession(request);
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
                pub.put("utente", s.getAttribute("userid"));
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("autore", item.getString());

            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());

            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        Database.insertRecord("keyword", keyword);
        ResultSet ss = Database.selectRecord("keyword", "tag1='" + keyword.get("tag1") + "' && " + "tag2='"
                + keyword.get("tag2") + "' && tag3='" + keyword.get("tag3") + "'");
        if (!isNull(ss)) {
            int indicek = 0;
            while (ss.next()) {
                indicek = ss.getInt("id");
            }
            pub.put("keyword", indicek);
            Database.insertRecord("pubblicazioni", pub);
            ResultSet rs = Database.selectRecord("pubblicazioni", "titolo='" + pub.get("titolo") + "'");
            while (rs.next()) {
                ristampe.put("pubblicazioni", rs.getInt("id"));
            }
            return Database.insertRecord("ristampe", ristampe);
        } else {
            return false;
        }

    }
    return false;
}

From source file:ch.zhaw.init.walj.projectmanagement.admin.properties.LogoUpload.java

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

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    boolean small = request.getParameter("size").equals("small");

    String message = "";

    if (!isMultipart) {
        message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div></div>" + "</div></div>";
    }//w  w  w .  jav  a 2s  .c o m

    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(this.getServletContext().getRealPath("/") + "img/"));

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

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");

        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();

            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName;
                if (small) {
                    fileName = "logo_small.png";
                } else {
                    fileName = "logo.png";
                }
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                filePath = this.getServletContext().getRealPath("/") + "img/" + fileName;
                // Write the file
                file = new File(filePath);
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }

        }

        out.println("</body>");
        out.println("</html>");

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

}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww  w . jav a  2s .c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession(true);
    DAO dao = new DAO();
    if (request.getParameter("createUser") != null) {

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

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

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

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

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

            dao.insertUser(up);

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

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

}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {//from w ww. j  ava2s.  c  om
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java

protected void workingdoPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    out.println();// ww w  .  j  a  va2 s.co  m

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     * Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above
     * threshold.
     */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List<FileItem> items = uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                // Handle Uploaded files.
                out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, "LogisticNetwork.mxe");
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

}

From source file:controllers.FrameworkController.java

private void adicionarOuEditarFramework() throws IOException {
    String nome, genero, paginaOficial, id, descricao, caminhoLogo;
    int idLinguagem = -1;
    genero = nome = paginaOficial = descricao = id = caminhoLogo = "";

    File file;//from  w  w w. ja  v  a  2s . c  om
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = getServletContext();
    String filePath = context.getInitParameter("file-upload");

    String contentType = request.getContentType();

    if ((contentType.contains("multipart/form-data"))) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    if (fileName.lastIndexOf("\\") >= 0) {
                        //String name = fileName.substring(fileName.lastIndexOf("\\"), fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    } else {
                        //String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    }
                    caminhoLogo = file.getName();
                    fi.write(file);
                } else {
                    String campo = fi.getFieldName();
                    String valor = fi.getString("UTF-8");

                    switch (campo) {
                    case "nome":
                        nome = valor;
                        break;
                    case "genero":
                        genero = valor;
                        break;
                    case "pagina_oficial":
                        paginaOficial = valor;
                        break;
                    case "descricao":
                        descricao = valor;
                        break;
                    case "linguagem":
                        idLinguagem = Integer.parseInt(valor);
                        break;
                    case "id":
                        id = valor;
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    boolean atualizando = !id.isEmpty();

    if (atualizando) {
        Framework framework = dao.select(Integer.parseInt(id));

        framework.setDescricao(descricao);
        framework.setGenero(genero);
        framework.setIdLinguagem(idLinguagem);
        framework.setNome(nome);
        framework.setPaginaOficial(paginaOficial);

        if (!caminhoLogo.isEmpty()) {
            File imagemAntiga = new File(filePath + framework.getCaminhoLogo());
            imagemAntiga.delete();

            framework.setCaminhoLogo(caminhoLogo);
        }

        dao.update(framework);

    } else {
        Framework framework = new Framework(nome, descricao, genero, paginaOficial, idLinguagem, caminhoLogo);

        dao.insert(framework);
    }

    response.sendRedirect("frameworks.jsp");
    //response.getWriter().print("<script>window.location.href='frameworks.jsp';</script>");
}

From source file:controller.Upload.java

/**
 * Servlet implementation class UploadServlet
 *//*from w w w. ja va2  s.c om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

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

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);
    String fileName = "", newname = "";
    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                //                    fileName = (String)session.getId() + new File(item.getName()).getName();
                //                    String filePath = uploadFolder + File.separator + fileName;
                fileName = new File(item.getName()).getName();
                newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf("."));
                String filePath = uploadFolder + File.separator + newname;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
            }
        }
        userDao ud = new userDao();
        ud.changeuserpic((int) session.getAttribute("userID"), newname);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {//from w w  w .j a  va2s.  com
            ArrayList<Long> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(new Long(cid));
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(user.getId(), product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            logger.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            logger.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            logger.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.manning.cmis.theblend.servlets.AddVersionServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session)
        throws ServletException, IOException, TheBlendException {

    // check for multipart content
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        // show add version page
        dispatch("addversion.jsp", "Add new version. The Blend.", request, response);
    }// w  ww .j ava 2s  .  co m

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String docId = null;
    boolean major = true;
    ObjectId newId = null;

    // process the request
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(50 * 1024 * 1024);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();

                if (PARAM_DOC_ID.equalsIgnoreCase(name)) {
                    docId = item.getString();
                } else if (PARAM_MAJOR.equalsIgnoreCase(name)) {
                    major = Boolean.parseBoolean(item.getString());
                }
            } else {
                properties.put(PropertyIds.NAME, item.getName());

                uploadedFile = File.createTempFile("blend", "tmp");
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {
        throw new TheBlendException("Upload failed: " + e, e);
    }

    if (uploadedFile == null) {
        throw new TheBlendException("No content!", null);
    }

    try {
        // find the document
        Document doc = CMISHelper.getDocumet(session, docId, CMISHelper.LIGHT_OPERATION_CONTEXT, "document");

        // check out document and get Private Working Copy
        Document pwc = null;
        try {
            // check out
            ObjectId pwcId = doc.checkOut();

            // the PWC must be a document object
            pwc = (Document) session.getObject(pwcId, CMISHelper.LIGHT_OPERATION_CONTEXT);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Checkout failed!", cbe);
        }

        // prepare the content stream
        ContentStream contentStream = null;
        try {
            contentStream = prepareContentStream(session, uploadedFile, doc.getType().getId(), properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // create new version
        try {
            newId = pwc.checkIn(major, properties, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create new version: " + cbe.getMessage(), cbe);
        } finally {
            try {
                contentStream.getStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    } finally {
        // delete temp file
        uploadedFile.delete();
    }

    // show the newly created document
    redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response);
}