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

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

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:com.bibisco.filters.FileFilter.java

/**
 * Handling of requests in multipart-encoded format.
 * // w ww.  ja  v a2  s.  c  o  m
 * <p>Decodes MIME payload and extracts each field and file.
 * 
 * @param pRequest
 * @throws FileUploadException: see Jakarta commons FileUpload library
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void handleIt(ServletRequest pRequest) throws FileUploadException, IOException {
    DiskFileItemFactory lDiskFileItemFactory = new DiskFileItemFactory();
    lDiskFileItemFactory.setSizeThreshold(mIntDiskThreshold);
    lDiskFileItemFactory.setRepository(new File(mStrTmpDir));
    ServletFileUpload lServletFileUpload = new ServletFileUpload(lDiskFileItemFactory);
    lServletFileUpload.setSizeMax(mIntRejectThreshold);

    List<FileItem> lListFileItem = lServletFileUpload.parseRequest((HttpServletRequest) pRequest);
    for (FileItem lFileItem : lListFileItem)
        if (!lFileItem.isFormField()) { // file detected
            mLog.info("elaborating file ", lFileItem.getName());
            processUploadedFile(lFileItem, pRequest);
        } else // regular form field
            processRegularFormField(lFileItem, pRequest);
}

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.ja v  a2  s.  c om*/

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

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java

/**
 * Create an upload handler that will throw an exception if the file is too
 * large.//from   www  .j  a  v a 2s  . c o  m
 */
private ServletFileUpload createUploadHandler(int maxFileSize, File tempDir) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
    factory.setRepository(tempDir);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileSize);

    return upload;
}

From source file:com.estampate.corteI.servlet.guardarEstampa.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  w w  . jav  a  2 s.c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String rutaImg = "NN";
    /*
     SUBIR LA IMAGEN AL SERVIDOR
     */
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(dirUploadFiles, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            subioImagen = true;
                            rutaImg = "estampas/" + nombre;
                            //                response.sendRedirect("uploadsave.jsp");
                        } else {
                            subioImagen = false;
                        }
                    }
                } else {
                    campos.add(item.getString());
                }
            }
        } catch (FileUploadException e) {
            subioImagen = false;
        } catch (Exception e) {
            subioImagen = false;
        }
    }
    /*
     FIN DE SUBIR IMAGEN
     */
    String nombreImg = campos.get(1);
    EstampaCamiseta estampa = new EstampaCamiseta();
    //estampa.setIdEstampaCamiseta(null);
    //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA
    datosGeneralesDAO artista = new datosGeneralesDAO();
    Artista artEstampa = artista.getArtista(Integer.parseInt(campos.get(0)));
    estampa.setArtista(artEstampa);
    //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA
    datosGeneralesDAO rating = new datosGeneralesDAO();
    RatingEstampa ratingEstampa = rating.getRating(1);
    estampa.setRatingEstampa(ratingEstampa);
    //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA
    datosGeneralesDAO tamano = new datosGeneralesDAO();
    TamanoEstampa tamEstampa = tamano.getTamano(Integer.parseInt(campos.get(4)));
    estampa.setTamanoEstampa(tamEstampa);
    //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA
    datosGeneralesDAO tema = new datosGeneralesDAO();
    TemaEstampa temaEstampa = tema.getTema(Integer.parseInt(campos.get(2)));
    estampa.setTemaEstampa(temaEstampa);
    //ASIGNO EL NOMBRE DE LA ESTAMPA
    estampa.setDescripcion(nombreImg);
    //ASIGNO LA RUTA DE LA IMAGEN QUE CREO
    estampa.setImagenes(rutaImg);
    //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA
    estampa.setUbicacion(campos.get(5));
    //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO
    estampa.setPrecio(campos.get(3));
    //ASIGNO EL ID DEL LUGAR 
    estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5)));
    guardarRegistroDAO guardarEstampa = new guardarRegistroDAO();
    guardarEstampa.guardaEstampa(estampa);
    processRequest(request, response);
}

From source file:controller.ControlPembayaran.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
    String timeStamp2 = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());

    Pembayaran p = new Pembayaran();
    DatabaseManager db = new DatabaseManager();

    //Menyimpan file ke dalam sistem
    File file;//from  w  w w .j av  a  2s .  c  o  m
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "c:/Apache/";

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

        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()) {
                    if (fi.getName().contains(".csv")) {
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + "DataPembayaran_" + timeStamp + ".csv");
                        fi.write(file);
                    } else {
                        throw new Exception("Format File Salah");
                    }
                }
            }
        } catch (Exception ex) {
            returnError(request, response, ex);
        }
    } else {
        Exception e = new Exception("no file uploaded");
        returnError(request, response, e);
    }
    //Membaca file dari dalam sistem
    String csvFile = filePath + "DataPembayaran_" + timeStamp + ".csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));
        int counter = 1;
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] dataSet = line.split(cvsSplitBy);
            p.setID(timeStamp2 + "_" + counter);
            p.setWaktuPembayaran(dataSet[0]);
            p.setNoRekening(dataSet[1]);
            p.setJumlahPembayaran(Double.parseDouble(dataSet[2]));
            p.setNis(dataSet[3].substring(0, 5));
            p.setBulanTagihan(Integer.parseInt(dataSet[3].substring(6)));
            //Membandingkan nis, jumlah, bulan pembayaran ke tagihan
            Tagihan[] t = Tagihan.getListTagihan(p.getNis());
            for (int i = 0; i < t.length; i++) {
                if (t[i].getNis().equals(p.getNis()) && t[i].getJumlah_pembayaran() == p.getJumlahPembayaran()
                        && t[i].getBulan_tagihan() == p.getBulanTagihan())// bandingkan jumlah pembayaran
                {
                    //Masukan data pembayaran ke database
                    Pembayaran.simpanPembayaran(p);
                    //update status pembayaran tagihan
                    t[i].verifikasiSukses(p.getNis(), p.getBulanTagihan());//update status bayar tagihan menjadi sudah bayar
                }
            }
            counter++;
        }
        this.tampil(request, response, "Data Terverifikasi");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //        }
}

From source file:com.lp.webapp.cc.CCOrderResponseServlet.java

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

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setSizeMax(maxUploadSize);

    if (!ServletFileUpload.isMultipartContent(req)) {
        myLogger.info("Received request without form/multipart data. Aborting.");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//from w  w  w  . j av a2s.  co  m
    }

    FileItem file = null;

    try {
        List<FileItem> files = upload.parseRequest(req);
        if (files.size() != 1) {
            response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
            return;
        }

        file = files.get(0);
        processOrder(req, response, file);
    } catch (FileUploadException e) {
        myLogger.error("Upload exception: ", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        myLogger.error("Processing file exception: ", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        saveXmlFile(file);
    }
}

From source file:Emporium.Servlet.ServPreVendaImportarNFe.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww. j a va 2 s .  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 {

    HttpSession sessao = request.getSession();
    String nomeBD = (String) sessao.getAttribute("nomeBD");

    boolean isMultiPart = FileUpload.isMultipartContent(request);

    String departamento = "", servico = "", tipo = "";
    int idCliente = 0, vd = 0, ar = 0, rm = 0, tipoEntrega = 0;

    if (nomeBD != null) {
        if (isMultiPart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(1024 * 1024 * 2);

                List items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                ArrayList<FileItem> listaArq = new ArrayList<FileItem>();

                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tipo")) {
                            tipo = item.getString();
                        }
                        if (item.getFieldName().equals("departamento")) {
                            departamento = item.getString();
                        }
                        if (item.getFieldName().equals("servico")) {
                            servico = item.getString();
                        }
                        if (item.getFieldName().equals("idCliente")) {
                            idCliente = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("vd")) {
                            vd = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("ar")) {
                            ar = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("rm")) {
                            rm = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("tipoEntrega")) {
                            tipoEntrega = Integer.parseInt(item.getString());
                        }
                    }

                    if (!item.isFormField()) {
                        if (item.getName().length() > 0) {
                            listaArq.add(item);
                        }
                    }
                }

                if (listaArq.isEmpty()) {
                    response.sendRedirect(
                            "Cliente/Servicos/imp_postagem.jsp?msg=Escolha um arquivo para importacao !");
                } else if (listaArq.size() > 200) {
                    response.sendRedirect(
                            "Cliente/Servicos/imp_postagem.jsp?msg=Importacao maxima de 200 arquivos de cada vez!");
                } else {
                    ContrPreVendaImporta.excluirNaoConfirmados(idCliente, nomeBD);
                    String condicao = ContrPreVendaImporta.importaPedidoNFe(listaArq, idCliente, departamento,
                            servico, vd, ar, rm, tipoEntrega, nomeBD);
                    if (condicao.startsWith("ERRO")) {
                        response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=" + condicao);
                    } else {
                        response.sendRedirect("Cliente/Servicos/imp_confirma.jsp?msg=" + condicao);
                    }
                }

            } catch (FileUploadException ex) {
                response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=Falha na importacao!\n" + ex);
            } catch (Exception ex) {
                response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=Falha na importacao!\n" + ex);
            }

        } else {
            response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=is not a multipart form");
        }
    } else {
        response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=Sua sessao expirou!");
    }

}

From source file:com.antinymail.ventadecasas.servlet.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;/*  w w  w . ja  v a2 s.com*/
    }
    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("c:\\temp"));

    //factory.setRepository(new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); 

    factory.setRepository(
            new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images"));

    //factory.setRepository(new File("//petylde.esy.es//uploads//casapueblo"));
    //factory.setRepository(new Uri());

    // 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 = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {

                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));

                    //file = new File( fileName);

                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));

                    //file = new File( fileName);
                }
                fi.write(file);
                //fi.write( fileNa ) ;  

                out.println("Uploaded Filename: " + fileName + "<br>");
                out.println("La ruta inicial era: " + filePath + "<br>");

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.google.dotorg.translation_workflow.servlet.UploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, MalformedURLException {
    String rawProjectId = request.getParameter("projectId");
    try {/*  w w  w  .  j  a va  2s . co m*/
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(1048576);
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        Cloud cloud = Cloud.open();

        int projectId = Integer.parseInt(rawProjectId);
        Project project = cloud.getProjectById(projectId);
        TextValidator nameValidator = TextValidator.BRIEF_STRING;
        String invalidRows = "";
        int validRows = 0;

        try {
            FileItemIterator iterator = upload.getItemIterator(request);
            int articlesLength = 0;
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    String fileContents = null;
                    if (!contentType.equalsIgnoreCase("text/csv")) {
                        logger.warning("Invalid filetype upload " + contentType);
                        response.sendRedirect(
                                "/project_overview?project=" + rawProjectId + "&msg=invalid_type");
                    }
                    try {
                        fileContents = IOUtils.toString(in);
                        PersistenceManager pm = cloud.getPersistenceManager();
                        Transaction tx = pm.currentTransaction();
                        tx.begin();
                        String[] lines = fileContents.split("\n");
                        List<Translation> newTranslations = new ArrayList<Translation>();
                        articlesLength = lines.length;
                        validRows = articlesLength;
                        int lineNo = 0;
                        for (String line : lines) {
                            lineNo++;
                            line = line.replaceAll("\",", "\";");
                            line = line.replaceAll("\"", "");
                            String[] fields = line.split(";");
                            String articleName = fields[0].replace("_", " ");
                            articleName = nameValidator.filter(URLDecoder.decode(articleName));
                            try {
                                URL url = new URL(fields[1]);
                                String category = "";
                                String difficulty = "";
                                if (fields.length > 2) {
                                    category = nameValidator.filter(fields[2]);
                                }
                                if (fields.length > 3) {
                                    difficulty = nameValidator.filter(fields[3]);
                                }
                                Translation translation = project.createTranslation(articleName, url.toString(),
                                        category, difficulty);
                                newTranslations.add(translation);
                            } catch (MalformedURLException e) {
                                validRows--;
                                invalidRows = invalidRows + "," + lineNo;
                                logger.warning("Invalid URL : " + fields[1]);

                            }
                        }
                        pm.makePersistentAll(newTranslations);
                        tx.commit();
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
            cloud.close();
            logger.info(validRows + " of " + articlesLength + " articles uploaded from csv to the project "
                    + project.getId() + " by User :" + user.getUserId());
            if (invalidRows.length() > 0) {
                response.sendRedirect(
                        "/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1));
            } else {
                response.sendRedirect("/project_overview?project=" + rawProjectId);
            }
            /*response.sendRedirect("/project_overview?project=" + rawProjectId +
                "&_invalid=" + invalidRows.substring(1));*/
        } catch (SizeLimitExceededException e) {

            logger.warning("Exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
            response.sendRedirect("/project_overview?project=" + rawProjectId + "&msg=size_exceeded");
        }
    } catch (Exception ex) {
        logger.info("String " + ex.toString());
        throw new ServletException(ex);

    }
}

From source file:com.themodernway.server.core.servlet.ContentUploadServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {/*  w  w w.j  av a 2  s.  co  m*/
        final IFolderItem fold = getRoot();

        if (null == fold) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find storage root.");
            }
            sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        if (false == fold.isWritable()) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't write storage root.");
            }
            sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        final String path = getPathNormalized(toTrimOrElse(request.getPathInfo(), FileUtils.SINGLE_SLASH));

        if (null == path) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find path info.");
            }
            sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        final ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory());

        upload.setSizeMax(getFileSizeLimit());

        final List<FileItem> items = upload.parseRequest(request);

        for (final FileItem item : items) {
            if (false == item.isFormField()) {
                if (item.getSize() > fold.getFileSizeLimit()) {
                    item.delete();

                    if (logger().isErrorEnabled()) {
                        logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "File size exceeds limit.");
                    }
                    sendErrorCode(request, response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

                    return;
                }
                final IFileItem file = fold.file(FileUtils.concat(path, item.getName()));

                if (null != file) {
                    try (InputStream read = item.getInputStream()) {
                        fold.create(file.getPath(), read);
                    } catch (final IOException e) {
                        item.delete();

                        final IServletExceptionHandler handler = getServletExceptionHandler();

                        if ((null == handler) || (false == handler.handle(request, response,
                                getServletResponseErrorCodeManagerOrDefault(), e))) {
                            if (logger().isErrorEnabled()) {
                                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't write file.", e);
                            }
                            sendErrorCode(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        }
                        return;
                    }
                } else {
                    item.delete();

                    if (logger().isErrorEnabled()) {
                        logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find file.");
                    }
                    sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

                    return;
                }
            }
            item.delete();
        }
    } catch (IOException | FileUploadException e) {
        final IServletExceptionHandler handler = getServletExceptionHandler();

        if ((null == handler) || (false == handler.handle(request, response,
                getServletResponseErrorCodeManagerOrDefault(), e))) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "captured overall exception for security.", e);
            }
            sendErrorCode(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}