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:mitm.djigzo.web.pages.portal.pdf.PDFAttachments.java

@OnEvent(UploadEvents.UPLOAD_EXCEPTION)
protected Object onUploadException(FileUploadException uploadException) {
    uploadError = true;/*from  w w  w. jav  a2 s .  co m*/
    uploadErrorMessage = uploadException.getMessage();

    return PDFAttachments.class;
}

From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java

/** Performs initializations stuff. */
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize,
        String repositoryPath) {//from w ww.j  a  v a2  s  .c o  m
    if (!ServletFileUpload.isMultipartContent(request)) {
        String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'";

        MultipartRequestWrapper.Log.severe(errorText);

        throw new FacesException(errorText);
    } else {
        this.params = new HashMap<String, String[]>();
        this.fileItems = new HashMap<String, FileItem>();

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

        //factory = new DiskFileItemFactory();
        factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(),
                thresholdSize, new File(repositoryPath));
        //factory.setRepository(new File(repositoryPath));
        //factory.setSizeThreshold(thresholdSize);

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

        String charset = request.getCharacterEncoding();
        if (charset != null) {
            charset = ServletConstants.DefaultCharset;
        }
        upload.setHeaderEncoding(charset);

        List<FileItem> itemList = null;
        try {
            //itemList = (List<FileItem>) upload.parseRequest(request);
            itemList = (List<FileItem>) upload.parseRequest(request);
        } catch (FileUploadException fue) {
            MultipartRequestWrapper.Log.severe(fue.getMessage());
            throw new FacesException(fue);
        } catch (ClassCastException cce) {
            // This shouldn't happen!
            MultipartRequestWrapper.Log.severe(cce.getMessage());
            throw new FacesException(cce);
        }

        MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size());

        for (FileItem item : itemList) {
            String key = item.getFieldName();

            //            {
            //               String value = item.getString();
            //               if (value.length() > 100) {
            //                  value = value.substring(0, 100) + " [...]";
            //               }
            //               MultipartRequestWrapper.Log.fine(
            //                  "Parameter : '" + key + "'='" + value + "' isFormField="
            //                  + item.isFormField() + " contentType='" + item.getContentType() + "'"
            //               );
            //            }
            if (item.isFormField()) {
                Object inStock = this.params.get(key);
                if (inStock == null) {
                    String[] values = null;
                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values = new String[] { item.getString(ServletConstants.DefaultCharset) };
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values = new String[] { item.getString() };
                    }
                    this.params.put(key, values);
                } else if (inStock instanceof String[]) {
                    // two or more parameters
                    String[] oldValues = (String[]) inStock;
                    String[] values = new String[oldValues.length + 1];

                    int i = 0;
                    while (i < oldValues.length) {
                        values[i] = oldValues[i];
                        i++;
                    }

                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values[i] = item.getString(ServletConstants.DefaultCharset);
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values[i] = item.getString();
                    }
                    this.params.put(key, values);
                } else {
                    MultipartRequestWrapper.Log
                            .severe("Program error. Unsupported class: " + inStock.getClass().getName());
                }
            } else {
                //String fieldName = item.getFieldName();
                //String fileName = item.getName();
                //String contentType = item.getContentType();
                //boolean isInMemory = item.isInMemory();
                //long sizeInBytes = item.getSize();
                //...
                this.fileItems.put(key, item);
            }
        }
    }
}

From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java

@OnEvent(UploadEvents.UPLOAD_EXCEPTION)
protected Object onUploadException(FileUploadException uploadException) {
    logger.error("Error uploading file", uploadException);

    importError = true;//  w ww.  j a v a 2 s.c  o  m
    importErrorMessage = uploadException.getMessage();

    return CertificateImportKey.class;
}

From source file:eu.stratuslab.storage.disk.resources.DisksResource.java

private Disk saveAndInflateFiles() {

    int fileSizeLimit = ServiceConfiguration.getInstance().UPLOAD_COMPRESSED_IMAGE_MAX_BYTES;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(FileUtils.getUploadCacheDirectory());
    factory.setSizeThreshold(fileSizeLimit);

    RestletFileUpload upload = new RestletFileUpload(factory);

    List<FileItem> items = null;

    try {// w ww  .  j a  v  a2s.c o  m
        items = upload.parseRequest(getRequest());
    } catch (FileUploadException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    }

    FileItem lastFileItem = null;
    for (FileItem fi : items) {
        if (fi.getName() != null) {
            lastFileItem = fi;
        }
    }

    for (FileItem fi : items) {
        if (fi != lastFileItem) {
            fi.delete();
        }
    }

    if (lastFileItem != null) {
        return inflateAndProcessImage(lastFileItem);
    } else {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "empty file uploaded");
    }
}

From source file:com.bruce.gogo.utils.JakartaMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
 * multipart classes (see class description).
 *
 * @param saveDir        the directory to save off the file
 * @param servletRequest the request containing the multipart
 * @throws java.io.IOException  is thrown if encoding fails.
 *//* w  w w.  ja va2 s  .c  o  m*/
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }

    // Parse the request
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        ProgressListener myProgressListener = new MyProgressListener(servletRequest);
        upload.setProgressListener(myProgressListener);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (LOG.isDebugEnabled())
                LOG.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                LOG.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }

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

                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (FileUploadException e) {
        LOG.error("Unable to parse request", e);
        errors.add(e.getMessage());
    }
}

From source file:com.bradmcevoy.http.ServletRequest.java

@Override
public void parseRequestParameters(Map<String, String> params, Map<String, com.bradmcevoy.http.FileItem> files)
        throws RequestParseException {
    try {//  w  ww  .ja v  a2s  .c om
        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 val = request.getParameter(nm);
                params.put(nm, val);
            }
        }
    } catch (FileUploadException ex) {
        throw new RequestParseException("FileUploadException", ex);
    } catch (Throwable ex) {
        throw new RequestParseException(ex.getMessage(), ex);
    }
}

From source file:mitm.djigzo.web.pages.admin.SSLCertificateManager.java

@OnEvent(UploadEvents.UPLOAD_EXCEPTION)
protected Object onUploadException(FileUploadException uploadException) {
    logger.error("Error uploading file", uploadException);

    uploadError = true;/*w ww.j a v  a 2 s. c o  m*/
    uploadErrorMessage = uploadException.getMessage();

    return SSLCertificateManager.class;
}

From source file:com.googlecode.npackdweb.RepUploadAction.java

@Override
public Page perform(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    List<String> messages = new ArrayList<String>();

    Found f = null;/*  ww w.  java 2  s  .  c o m*/
    String tag = "unknown";
    boolean overwrite = false;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                try {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tag")) {
                            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
                            tag = r.readLine();
                        } else if (item.getFieldName().equals("overwrite")) {
                            overwrite = true;
                        }
                    } else {
                        f = process(stream);
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (FileUploadException e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    } else {
        tag = req.getParameter("tag");
        String rep = req.getParameter("repository");
        overwrite = req.getParameter("overwrite") != null;
        f = process(new ByteArrayInputStream(rep.getBytes("UTF-8")));
    }

    if (f != null) {
        boolean isAdmin = NWUtils.isAdminLoggedIn();

        for (PackageVersion pv : f.pvs) {
            pv.tags.add(tag);
        }

        Objectify ofy = DefaultServlet.getObjectify();
        List<Key<?>> keys = new ArrayList<Key<?>>();
        for (License lic : f.lics) {
            keys.add(lic.createKey());
        }
        for (PackageVersion pv : f.pvs) {
            keys.add(pv.createKey());
        }
        for (Package p : f.ps) {
            keys.add(p.createKey());
        }

        Map<Key<Object>, Object> existing = ofy.get(keys);

        Stats stats = new Stats();
        Iterator<PackageVersion> it = f.pvs.iterator();
        while (it.hasNext()) {
            PackageVersion pv = it.next();
            PackageVersion found = (PackageVersion) existing.get(pv.createKey());
            if (found != null) {
                stats.pvExisting++;
                if (!overwrite)
                    it.remove();
            }
        }

        Iterator<License> itLic = f.lics.iterator();
        while (itLic.hasNext()) {
            License pv = itLic.next();
            License found = (License) existing.get(pv.createKey());
            if (found != null) {
                stats.licExisting++;
                if (!overwrite)
                    itLic.remove();
            }
        }

        Iterator<Package> itP = f.ps.iterator();
        while (itP.hasNext()) {
            Package p = itP.next();
            Package found = (Package) existing.get(p.createKey());
            if (found != null) {
                stats.pExisting++;
                if (!overwrite)
                    itP.remove();
            }
        }

        for (PackageVersion pv : f.pvs) {
            Package p = ofy.find(new Key<Package>(Package.class, pv.package_));
            if (p != null && !p.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + pv.package_);
        }

        for (Package p : f.ps) {
            Package p_ = ofy.find(new Key<Package>(Package.class, p.name));
            if (p_ != null && !p_.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + p.name);
        }

        if (f.lics.size() > 0) {
            if (isAdmin)
                ofy.put(f.lics);
            else
                messages.add("Only an administrator can change licenses");
        }

        ofy.put(f.pvs);

        for (Package p : f.ps) {
            NWUtils.savePackage(ofy, p, true);
        }

        if (overwrite) {
            stats.pOverwritten = stats.pExisting;
            stats.pvOverwritten = stats.pvExisting;
            stats.licOverwritten = stats.licExisting;
            stats.pAppended = f.ps.size() - stats.pOverwritten;
            stats.pvAppended = f.pvs.size() - stats.pvOverwritten;
            stats.licAppended = f.lics.size() - stats.licOverwritten;
        } else {
            stats.pAppended = f.ps.size();
            stats.pvAppended = f.pvs.size();
            stats.licAppended = f.lics.size();
        }
        messages.add(stats.pOverwritten + " packages overwritten, " + stats.pvOverwritten
                + " package versions overwritten, " + stats.licOverwritten + " licenses overwritten, "
                + stats.pAppended + " packages appended, " + stats.pvAppended + " package versions appended, "
                + stats.licAppended + " licenses appended");
    } else {
        messages.add("No data found");
    }

    return new MessagePage(messages);
}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

/**
 * {@inheritDoc}//from w ww  .  ja v a 2  s . c o m
 */
@SuppressWarnings({ "unchecked", "PMD.CyclomaticComplexity" })
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }
    ProgressMonitor monitor = null;
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        monitor = new ProgressMonitor();
        upload.setProgressListener(monitor);
        String uploadKey = getUploadKey(servletRequest);
        servletRequest.getSession().setAttribute(uploadKey, monitor);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(createRequestContext(servletRequest));
        for (FileItem item : items) {
            LOG.debug((new StringBuilder()).append("Found item ").append(item.getFieldName()).toString());
            if (item.isFormField()) {
                handleFormField(servletRequest, item);
            } else {
                handleFileUpload(item);
            }
        }
        handleChunkedUploadHeaders(servletRequest);
    } catch (FileUploadException e) {
        if (monitor != null) {
            monitor.abort();
        }
        LOG.warn("Error processing upload", e);
        errors.add(e.getMessage());
    }
}

From source file:mitm.djigzo.web.pages.certificate.CertificateImport.java

@OnEvent(UploadEvents.UPLOAD_EXCEPTION)
protected Object onUploadException(FileUploadException uploadException) {
    logger.error("Error uploading file", uploadException);

    importError = true;/*from w  ww  . j  ava2s  .  c o m*/
    importErrorMessage = uploadException.getMessage();

    return CertificateImport.class;
}