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

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

Introduction

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

Prototype

public FileUploadException(String msg) 

Source Link

Document

Constructs a new FileUploadException with specified detail message.

Usage

From source file:gr.forth.ics.isl.x3mlEditor.upload.MultipartUploadParser.java

/**
 *
 * @param request/*from  www. j av  a 2s . c  o  m*/
 * @param repository
 * @param context
 * @throws Exception
 */
public MultipartUploadParser(HttpServletRequest request, File repository, ServletContext context)
        throws Exception {
    if (!repository.exists() && !repository.mkdirs()) {
        throw new IOException("Unable to mkdirs to " + repository.getAbsolutePath());
    }

    fileItemsFactory = setupFileItemFactory(repository, context);

    ServletFileUpload upload = new ServletFileUpload(fileItemsFactory);
    List<FileItem> formFileItems = upload.parseRequest(request);

    parseFormFields(formFileItems);

    if (files.isEmpty()) {
        writeDebugInfo(request);
        throw new FileUploadException("No files were found when processing the request.");
    } else {

    }
}

From source file:com.exilant.exility.core.XLSHandler.java

/**
 * This method returns FileItem handler out of file field in HTTP request
 * /* w  w w.j a  v a  2  s.  co m*/
 * @param req
 * @return FileItem
 * @throws IOException
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
public static FileItem getFileItem(HttpServletRequest req) throws IOException, FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    /*
     * we can increase the in memory size to hold the file data but its
     * inefficient so ignoring to factory.setSizeThreshold(20*1024);
     */
    ServletFileUpload sFileUpload = new ServletFileUpload(factory);
    List<FileItem> items = sFileUpload.parseRequest(req);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            return item;
        }
    }

    throw new FileUploadException("File field not found");

}

From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java

@RequestMapping(value = "/{wsName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(value = HttpStatus.CREATED) @ResponseBody JSONArr create(@PathVariable String wsName,
        HttpServletRequest request) throws IOException, FileUploadException {

    WorkspaceInfo ws;/*  w w w  .java  2 s .  c om*/
    Resource styles;

    if (wsName == null) {
        ws = null;
        styles = dataDir().getRoot("styles");
    } else {
        ws = findWorkspace(wsName, catalog());
        styles = dataDir().get(ws, "styles");
    }

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    @SuppressWarnings("unchecked")
    List<FileItem> input = (List<FileItem>) upload.parseRequest(request);

    JSONArr created = new JSONArr();
    for (FileItem file : input) {
        String filename = file.getName();

        // trim filename if required
        if (filename.lastIndexOf('/') != -1) {
            filename = filename.substring(filename.lastIndexOf('/'));
        }
        if (filename.lastIndexOf('\\') != -1) {
            filename = filename.substring(filename.lastIndexOf('\\'));
        }
        String ext = fileExt(filename);
        if (!ICON_FORMATS.containsKey(ext)) {
            String msg = "Icon " + filename + " format " + ext + " unsupported - try:" + ICON_FORMATS.keySet();
            LOG.warning(msg);
            throw new FileUploadException(msg);
        }
        try {
            InputStream data = file.getInputStream();
            Resources.copy(data, styles, filename);

            icon(created.addObject(), ws, styles.get(filename), request);
        } catch (Exception e) {
            throw new FileUploadException("Unable to write " + filename, e);
        }
    }

    return created;
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;/*from  ww w. j a  v a2s .  co  m*/
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:filter.MultipartRequestFilter.java

/**
 * Process multipart request item as file field. The name and FileItem object of each file field
 * will be added as attribute of the given HttpServletRequest. If a FileUploadException has
 * occurred when the file size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 */// w  ww  .  jav a2s .  co  m
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        addAttributeValue(request, fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        addAttributeValue(request, fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        addAttributeValue(request, fileField.getFieldName(), fileField);
    }
}

From source file:com.sun.portal.portletcontainer.driver.admin.UploadServlet.java

private String processFileItem(FileItem fi) throws FileUploadException {

    // On some browsers fi.getName() will return the full path to the file
    // the client select this can cause problems
    // so the following is a workaround.
    try {// w  w w .j av a 2s .c o  m
        String fileName = fi.getName();
        if (fileName == null || fileName.trim().length() == 0) {
            return null;
        }
        fileName = FilenameUtils.getName(fileName);

        File fNew = File.createTempFile("opc", ".tmp");
        fNew.deleteOnExit();
        fi.write(fNew);

        File finalFileName = new File(fNew.getParent() + File.separator + fileName);
        if (fNew.renameTo(finalFileName)) {
            return finalFileName.getAbsolutePath();
        } else {
            // unable to rename, copy the contents of the file instead
            PortletWarUpdaterUtil.copyFile(fNew, finalFileName, true, false);
            return finalFileName.getAbsolutePath();
        }

    } catch (Exception e) {
        throw new FileUploadException(e.getMessage());
    }
}

From source file:com.app.framework.web.MultipartFilter.java

/**
 * Process multipart request item as file field. The name and FileItem
 * object of each file field will be added as attribute of the given
 * HttpServletRequest. If a FileUploadException has occurred when the file
 * size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 *
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 *///from   w  w w.  j av a  2 s .c o  m
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        request.setAttribute(fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        request.setAttribute(fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        request.setAttribute(fileField.getFieldName(), fileField);
    }
}

From source file:com.example.webapp.filter.MultipartFilter.java

/**
 * Process multipart request item as file field. The name and FileItem
 * object of each file field will be added as attribute of the given
 * HttpServletRequest. If a FileUploadException has occurred when the file
 * size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 * //  ww  w .ja  va2 s .  c om
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 */
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        request.setAttribute(fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        request.setAttribute(fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk
        // space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        request.setAttribute(fileField.getFieldName(), fileField);
    }
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.form.upload.DiskFileItem2.java

/**
 * A convenience method to write an uploaded item to disk. The client code
 * is not concerned with whether or not the item is stored in memory, or on
 * disk in a temporary location. They just want to write the uploaded item
 * to a file.//from   www  .j  a va2s . c o  m
 * <p>
 * This implementation first attempts to rename the uploaded item to the
 * specified destination file, if the item was originally written to disk.
 * Otherwise, the data will be copied to the specified file.
 * <p>
 * This method is only guaranteed to work <em>once</em>, the first time it
 * is invoked for a particular item. This is because, in the event that the
 * method renames a temporary file, that file will no longer be available
 * to copy or rename again at a later time.
 *
 * @param file The <code>File</code> into which the uploaded item should
 *             be stored.
 *
 * @throws Exception if an error occurs.
 */
public void write(File file) throws Exception {
    // PAG: we just can't write files
    throw new FileUploadException("Cannot write uploaded file to disk!");
}

From source file:com.masscustsoft.service.inner.DiskTempItem.java

/**
 * A convenience method to write an uploaded item to disk. The client code
 * is not concerned with whether or not the item is stored in memory, or on
 * disk in a temporary location. They just want to write the uploaded item
 * to a file./*from www  .j a v  a  2 s  . c  om*/
 * <p>
 * This implementation first attempts to rename the uploaded item to the
 * specified destination file, if the item was originally written to disk.
 * Otherwise, the data will be copied to the specified file.
 * <p>
 * This method is only guaranteed to work <em>once</em>, the first time it
 * is invoked for a particular item. This is because, in the event that the
 * method renames a temporary file, that file will no longer be available
 * to copy or rename again at a later time.
 *
 * @param file The <code>File</code> into which the uploaded item should
 *             be stored.
 *
 * @throws Exception if an error occurs.
 */
public void write(File file) throws Exception {
    if (isInMemory()) {
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            fout.write(get());
        } finally {
            if (fout != null) {
                fout.close();
            }
        }
    } else {
        TempItem outputFile = getStoreLocation();
        if (outputFile != null) {
            // Save the length of the file
            size = outputFile.length();
            /*
             * The uploaded file is being stored on disk
             * in a temporary location so move it to the
             * desired file.
             */
            {
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(outputFile.getInputStream());
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(in, out);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                }
            }
        } else {
            /*
             * For whatever reason we cannot write the
             * file to disk.
             */
            throw new FileUploadException("Cannot write uploaded file to disk!");
        }
    }
}