Example usage for org.apache.commons.fileupload FileUploadException getMessage

List of usage examples for org.apache.commons.fileupload FileUploadException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www.  j a v a  2s.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("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    HttpSession sesion = request.getSession(true);
    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 tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));

                        sesion.setAttribute("sArNombre", String.valueOf(nombre));
                        sesion.setAttribute("sArTipo", String.valueOf(tipo));
                        sesion.setAttribute("sArExtension", String.valueOf(extension));

                        File archivo = new File(dirUploadFiles, "nombreRequest" + extension);
                        item.write(archivo);
                        if (archivo.exists()) {
                            response.sendRedirect("uploadsave.jsp");
                        } else {
                            sesion.setAttribute("sArError", "Ocurrio un error al subir el archiv o");
                            response.sendRedirect("uploaderror.jsp");
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            sesion.setAttribute("sArError", String.valueOf(e.getMessage()));
            response.sendRedirect("uploaderror.jsp");
        } catch (Exception e) {
            sesion.setAttribute("sArError", String.valueOf(e.getMessage()));
            response.sendRedirect("uploaderror.jsp");
        }
    }
    out.close();

}

From source file:com.corejsf.UploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    //System.out.println("**** doFilter #1");
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;//from  ww w .j a  v  a  2s  .c  o  m
    }

    //System.out.println("**** doFilter #2");
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
        chain.doFilter(request, response);
        return;
    }

    //System.out.println("**** doFilter #3");
    DiskFileUpload upload = new DiskFileUpload();
    if (repositoryPath != null)
        upload.setRepositoryPath(repositoryPath);

    try {
        List list = upload.parseRequest(httpRequest);
        final Map map = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);
            //System.out.println("form filed="+item.getFieldName()+" : "+str);
            if (item.isFormField()) {
                String str = item.getString("UTF-8");
                map.put(item.getFieldName(), new String[] { str });
            } else {
                httpRequest.setAttribute(item.getFieldName(), item);
            }
        }

        chain.doFilter(new HttpServletRequestWrapper(httpRequest) {
            public Map getParameterMap() {
                return map;
            }

            // busywork follows ... should have been part of the wrapper
            public String[] getParameterValues(String name) {
                Map map = getParameterMap();
                return (String[]) map.get(name);
            }

            public String getParameter(String name) {
                String[] params = getParameterValues(name);
                if (params == null)
                    return null;
                return params[0];
            }

            public Enumeration getParameterNames() {
                Map map = getParameterMap();
                return Collections.enumeration(map.keySet());
            }
        }, response);
    } catch (FileUploadException ex) {
        log.error(ex.getMessage());
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}

From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java

@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("service({}, {})", request, response);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    InputStream is = null;/*from   w  w  w .  j a v a  2 s .  c o m*/
    String id = "";

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        // Parse the request and get all parameters and the uploaded file
        List<FileItem> items;

        try {
            items = upload.parseRequest(request);
            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    // if (item.getFieldName().equals("format")) { format =
                    // item.getString("UTF-8"); }
                    if (item.getFieldName().equals("id")) {
                        id = item.getString("UTF-8");
                    }
                    // if (item.getFieldName().equals("filename")) {
                    // filename = item.getString("UTF-8"); }
                } else {
                    is = item.getInputStream();
                }
            }

            // Retrieve token
            ZohoToken zot = ZohoTokenDAO.findByPk(id);

            // Save document
            if (Config.REPOSITORY_NATIVE) {
                String sysToken = DbSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new DbDocumentModule().checkout(sysToken, path, zot.getUser());
                new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            } else {
                String sysToken = JcrSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new JcrDocumentModule().checkout(sysToken, path, zot.getUser());
                new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            }
        } catch (FileUploadException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.error(e.getMessage(), e);
        } catch (FileSizeExceededException e) {
            log.error(e.getMessage(), e);
        } catch (UserQuotaExceededException e) {
            log.error(e.getMessage(), e);
        } catch (VirusDetectedException e) {
            log.error(e.getMessage(), e);
        } catch (VersionException e) {
            log.error(e.getMessage(), e);
        } catch (LockException e) {
            log.error(e.getMessage(), e);
        } catch (AccessDeniedException e) {
            log.error(e.getMessage(), e);
        } catch (ExtensionException e) {
            log.error(e.getMessage(), e);
        } catch (AutomationException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:Index.RegisterClienteImagesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w.j  a  v 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");
    try (PrintWriter out = response.getWriter()) {

        String ubicacionArchivo = "~\\NetBeansProjects\\QuickOrderWeb\\web\\images";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        factory.setRepository(new File(ubicacionArchivo));

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> partes = upload.parseRequest(request);
            webservice.Cliente client = new webservice.Cliente();

            for (FileItem item : partes) {
                client = (webservice.Cliente) request.getSession().getAttribute("registroUsuario");
                File file = new File(ubicacionArchivo, client.getNickname() + ".jpg");
                item.write(file);
                System.out.println("name: " + item.getName());
                client.setImagen(client.getNickname() + ".jpg");
            }

            QuickOrderWebService webService = new QuickOrderWebService();
            ControllerInterface port = webService.getQuickOrderWebServicePort();
            port.registrarCliente(client);

            request.setAttribute("error", null);
            request.setAttribute("agregado", "OK");
            request.removeAttribute("registroUsuario");
            request.getSession().removeAttribute("userName");

            request.getRequestDispatcher("/AltaCliente.jsp").forward(request, response);
        } catch (FileUploadException ex) {
            System.out.println("Error al subir el archivo: " + ex.getMessage());

            request.setAttribute("error", "Error al subir la imagen");
            request.setAttribute("funcionalidad", "Imagen");

            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        } catch (Exception ex) {
            System.out.println("Error al subir el archivo: " + ex.getMessage());
            request.setAttribute("error", "Error al subir la imagen");
            request.setAttribute("funcionalidad", "Imagen");

            request.getRequestDispatcher("/Login.jsp").forward(request, response);

        }
    }
}

From source file:com.takin.mvc.mvc.server.CommonsMultipartFile.java

public void transferTo(File dest) throws IOException, IllegalStateException {
    if (!isAvailable()) {
        throw new IllegalStateException("File has already been moved - cannot be transferred again");
    }//  w  w  w  .ja  va  2  s  .co  m

    if (dest.exists() && !dest.delete()) {
        throw new IOException(
                "Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
    }

    try {
        this.fileItem.write(dest);
        if (logger.isDebugEnabled()) {
            String action = "transferred";
            if (!this.fileItem.isInMemory()) {
                action = isAvailable() ? "copied" : "moved";
            }
            logger.debug("Multipart file '" + getName() + "' with original filename [" + getOriginalFilename()
                    + "], stored " + getStorageDescription() + ": " + action + " to [" + dest.getAbsolutePath()
                    + "]");
        }
    } catch (FileUploadException ex) {
        throw new IllegalStateException(ex.getMessage());
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        logger.error("Could not transfer to file", ex);
        throw new IOException("Could not transfer to file: " + ex.getMessage());
    }
}

From source file:de.betterform.agent.web.servlet.UploadServlet.java

private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String payload = "";
    try {//from  w  w w .j av a 2  s. co m
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List /* FileItem */ items = upload.parseRequest(request);

        Iterator iter = items.iterator();
        FileItem uploadItem = null;
        String collectionPath = "";
        String collectionName = "";
        String relativeUploadPath = "";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String fieldName = item.getFieldName();
            if (item.isFormField() && "bfUploadPath".equals(fieldName)) {
                relativeUploadPath = this.getFieldValue(item);
            } else if (item.isFormField() && "bfCollectionPath".equals(fieldName)) {
                collectionPath = this.getFieldValue(item);
            } else if (item.isFormField() && "bfCollectionName".equals(fieldName)) {
                collectionName = this.getFieldValue(item);
            } else if (item.getName() != null) {
                // FileItem of the uploaded file
                uploadItem = item;
            }
        }

        if (uploadItem != null && !"".equals(relativeUploadPath)) {
            this.uploadFile(request, uploadItem, relativeUploadPath);
        } else if (!"".equals(collectionName) && !"".equals(collectionPath)) {
            this.createColection(request, collectionName, collectionPath);
        } else {
            LOGGER.warn("error uploading file to '" + relativeUploadPath + "'");
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
        payload = e.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        payload = e.getMessage();
    }
    response.getOutputStream().println("<html><body><textarea>" + payload + "</textarea></body></html>");
}

From source file:com.vaporwarecorp.mirror.component.configuration.WebServer.java

@Override
public Response serve(IHTTPSession session) {
    final String uri = session.getUri().substring(1);
    if (Method.GET.equals(session.getMethod()) && "proxy".equals(uri)) {
        return get(session.getParms().get("url"));
    } else if (NanoFileUpload.isMultipartContent(session)) {
        try {//from w  ww.  j  av  a 2  s.  c o  m
            List<FileItem> files = mUploader.parseRequest(session);
            if (files != null && files.size() > 0) {
                return newFixedLengthResponse(saveFileItemToDisk(files.get(0)));
            }
        } catch (FileUploadException e) {
            Timber.e(e, e.getMessage());
            return getInternalErrorResponse(e.getMessage());
        }
    } else if (Method.POST.equals(session.getMethod())) {
        for (Configuration configuration : mConfigurations) {
            if (configuration.getClass().getName().startsWith(uri)) {
                return updateConfiguration(session, configuration);
            }
        }
        return newFixedLengthResponse(null);
    } else if (uri.endsWith(".ico")) {
        return getNotFoundResponse();
    } else if (uri.endsWith(".js")) {
        String template = read("configuration/" + uri);
        if (uri.endsWith(JAVASCRIPT_APP)) {
            final List<String> modules = new LinkedList<>();
            for (Configuration configuration : mConfigurations) {
                final String jsonString = read(configuration.getJsonConfiguration());
                modules.add(new StringBuilder(jsonString)
                        .insert(jsonString.lastIndexOf('}'), MODEL_PLACEHOLDER + configuration.getJsonValues())
                        .toString());
            }
            template = template.replace(MODULES_PLACEHOLDER, TextUtils.join(",", modules));
        }
        return newFixedLengthResponse(OK, "application/javascript", template);
    } else if (uri.endsWith(".css")) {
        return newFixedLengthResponse(OK, "text/css", read("configuration/" + uri));
    }
    return newFixedLengthResponse(read("configuration/index.html"));
}

From source file:com.aspectran.web.support.multipart.commons.CommonsMultipartFileParameter.java

/**
 * Save an uploaded file as a given destination file.
 *
 * @param destFile the destination file//from   www  .  java2 s  .  c  om
 * @param overwrite whether to overwrite if it already exists
 * @return a saved file
 * @throws IOException if an I/O error has occurred
 */
@Override
public File saveAs(File destFile, boolean overwrite) throws IOException {
    if (destFile == null) {
        throw new IllegalArgumentException("destFile can not be null");
    }

    validateFile();

    try {
        destFile = determineDestinationFile(destFile, overwrite);
        fileItem.write(destFile);
    } catch (FileUploadException e) {
        throw new IllegalStateException(e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not save as file " + destFile, e);
    }

    setSavedFile(destFile);
    return destFile;
}

From source file:com.liteoc.bean.rule.FileUploadHelper.java

@SuppressWarnings("unchecked")
private List<File> getFiles(HttpServletRequest request, ServletContext context,
        String dirToSaveUploadedFileIn) {
    List<File> files = new ArrayList<File>();

    // FileCleaningTracker fileCleaningTracker =
    // FileCleanerCleanup.getFileCleaningTracker(context);

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

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(getFileProperties().getFileSizeMax());
    try {// www . j  av a  2s  .  c  o m
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items

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

            if (item.isFormField()) {
                request.setAttribute(item.getFieldName(), item.getString());
                // DO NOTHING , THIS SHOULD NOT BE Handled here
            } else {
                getFileProperties().isValidExtension(item.getName());
                files.add(processUploadedFile(item, dirToSaveUploadedFileIn));

            }
        }
        return files;
    } catch (FileSizeLimitExceededException slee) {
        throw new OpenClinicaSystemException("exceeds_permitted_file_size",
                new Object[] { String.valueOf(getFileProperties().getFileSizeMaxInMb()) }, slee.getMessage());
    } catch (FileUploadException fue) {
        throw new OpenClinicaSystemException("file_upload_error_occured", new Object[] { fue.getMessage() },
                fue.getMessage());
    }
}

From source file:com.aspectran.web.activity.request.multipart.MultipartFileParameter.java

/**
 * Save the uploaded file to the given destination file.
 *
 * @param destFile the destination file//  w  w  w .  j  a  v  a  2  s. c  o  m
 * @param overwrite whether to overwrite if the file already exists
 * @return a saved file
 * @throws IOException if an I/O error has occurred
 */
@Override
public File saveAs(File destFile, boolean overwrite) throws IOException {
    if (destFile == null) {
        throw new IllegalArgumentException("'destFile' must not be null.");
    }

    if (!isAvailable()) {
        throw new IllegalStateException("File has been moved - cannot be read again.");
    }

    if (!overwrite) {
        File newFile = FilenameUtils.seekUniqueFile(destFile);
        if (destFile != newFile) {
            destFile = newFile;
        }
    } else {
        if (destFile.exists() && !destFile.delete()) {
            throw new IOException("Destination file [" + destFile.getAbsolutePath()
                    + "] already exists and could not be deleted.");
        }
    }

    try {
        fileItem.write(destFile);
    } catch (FileUploadException e) {
        throw new IllegalStateException(e.getMessage());
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException("Could not save file. Cause: " + e);
    }

    savedFile = destFile;

    return destFile;
}