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:ea.ejb.AbstractFacade.java

/**
 * Provide the ability to cache multi-part items in a variable to save
 * re-parsing//from w w  w.  j  a  v  a  2s  . c om
 */
public static List<FileItem> getMultipartItems(HttpServletRequest request) {
    List<FileItem> multipartItems = new LinkedList<FileItem>();
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            multipartItems = upload.parseRequest(request);
        } catch (FileUploadException fuex) {
            System.out.println("Error parsing multi-part form data: " + fuex.getMessage());
        }
    }
    return multipartItems;
}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);// ww w  .j  a  va 2s.  c  o  m

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:dk.clarin.tools.userhandle.java

@SuppressWarnings("unchecked")
public static List<FileItem> getParmList(HttpServletRequest request) throws ServletException {
    List<FileItem> items = null;
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    if (is_multipart_formData) {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*/*from w ww.  j  a  v  a2  s .co m*/
        *Set the size threshold, above which content will be stored on disk.
        */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
        * Set the temporary directory to store the uploaded files of size above threshold.
        */
        File tmpDir = new File(ToolsProperties.tempdir);
        if (!tmpDir.isDirectory()) {
            throw new ServletException("Trying to set \"" + ToolsProperties.tempdir
                    + "\" as temporary directory, but this is not a valid directory.");
        }
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            items = (List<FileItem>) uploadHandler.parseRequest(request);
        } catch (FileUploadException ex) {
            logger.error("Error encountered while parsing the request: " + ex.getMessage());
        }
    }
    return items;
}

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

/**
 * @param req//ww  w .j  a  v a  2 s  .c o  m
 * @param container
 * @return whether we are able to parse it
 */
@SuppressWarnings("unchecked")
public static boolean parseMultiPartData(HttpServletRequest req, ServiceData container) {
    /**
     * I didnt check here for multipart request ?. caller should check.
     */
    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 = null;

    try {
        items = sFileUpload.parseRequest(req);
    } catch (FileUploadException e) {
        container.addMessage("fileUploadFailed", e.getMessage());
        Spit.out(e);
        return false;
    }

    /*
     * If user is asked for multiple file upload with filesPathGridName then
     * create a grid with below columns and send to the client/DC
     */
    String filesPathGridName = req.getHeader("filesPathGridName");
    OutputColumn[] columns = { new OutputColumn("fileName", DataValueType.TEXT, "fileName"),
            new OutputColumn("fileSize", DataValueType.INTEGRAL, "fileSize"),
            new OutputColumn("filePath", DataValueType.TEXT, "filePath") };
    Value[] columnValues = null;

    FileItem f = null;
    String allowMultiple = req.getHeader("allowMultiple");

    List<Value[]> rows = new ArrayList<Value[]>();

    String fileNameWithPath = "";
    String rootPath = getResourcePath();

    String fileName = null;

    int fileCount = 0;

    for (FileItem item : items) {
        if (item.isFormField()) {
            String name = item.getFieldName();
            container.addValue(name, item.getString());
        } else {
            f = item;
            if (allowMultiple != null) {
                fileCount++;
                fileName = item.getName();
                fileNameWithPath = rootPath + getUniqueName(fileName);

                String path = XLSHandler.write(item, fileNameWithPath, container);
                if (path == null) {
                    return false;
                }

                if (filesPathGridName != null && filesPathGridName.length() > 0) {
                    columnValues = new Value[3];
                    columnValues[0] = Value.newValue(fileName);
                    columnValues[1] = Value.newValue(f.getSize());
                    columnValues[2] = Value.newValue(fileNameWithPath);
                    rows.add(columnValues);
                    fileNameWithPath = "";
                    continue;
                }

                container.addValue("file" + fileCount + "_ExilityPath", fileNameWithPath);
                fileNameWithPath = "";
            }

        }
    }

    if (f != null && allowMultiple == null) {
        fileNameWithPath = rootPath + getUniqueName(f.getName());
        String path = XLSHandler.write(f, fileNameWithPath, container);
        if (path == null) {
            return false;
        }
        container.addValue(container.getValue("fileFieldName"), path);
        return true;
    }

    /**
     * If user asked for multiple file upload and has supplied gridName for
     * holding the file path then create a grid
     */

    if (rows.size() > 0) {
        Grid aGrid = new Grid(filesPathGridName);
        aGrid.setValues(columns, rows, null);

        container.addGrid(filesPathGridName, aGrid.getRawData());
    }
    return true;
}

From source file:io.lightlink.servlet.MultipartServlet.java

protected Map<String, Object> getParams(HttpServletRequest req) throws IOException {

    MultipartParameters multipart = new MultipartParameters(req);

    Map<String, Object> inputParams = null;
    try {/*ww  w. ja  v a  2  s  .  c  o  m*/
        inputParams = multipart.getInitialParams();
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage(), e);
    }
    inputParams.put("mutipart", multipart);

    return inputParams;
}

From source file:com.pamarin.servlet.uploadfile.UploadFileServet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.log(Level.INFO, "uploaded");

    try {/*from  ww w.  ja  v  a  2s .c om*/
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }

        LOG.log(Level.INFO, "is multipart");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        //
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);

        List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> iterator = fileItems.iterator();

        LOG.log(Level.INFO, "file size --> {0}", fileItems.size());
        while (iterator.hasNext()) {
            FileItem item = iterator.next();
            //if (!item.isFormField()) {
            LOG.log(Level.INFO, "content type --> {0}", item.getContentType());
            LOG.log(Level.INFO, "name --> {0}", item.getName());
            LOG.log(Level.INFO, "field name --> {0}", item.getFieldName());
            LOG.log(Level.INFO, "string --> {0}", item.getString());

            item.write(new File("c:\\temp", UUID.randomUUID().toString() + ".png"));
            //}
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.WARNING, ex.getMessage());
    } catch (Exception ex) {
        LOG.log(Level.WARNING, ex.getMessage());
    }
}

From source file:com.oskopek.r3s.web.servlet.UploadResultsServlet.java

/**
 * @param request  the HttpServletRequest
 * @param response the HttpServletResponse
 * @throws IOException//from   ww  w  .  ja va  2  s  .  co  m
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Path batchDir = Files.createTempDirectory("results");

    ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
    List<FileItem> items;
    try {
        items = servletFileUpload.parseRequest(request);
    } catch (FileUploadException e) {
        response.sendError(500, e.getMessage());
        e.printStackTrace();
        return;
    }

    //TODO result upload

    /*
    for (FileItem item : items) {
    if (item.isFormField()) {
        // ignore regular form fields
    } else {
        // process files
            
        String fileName = FilenameUtils.getName(item.getName());
        InputStream fileContent = item.getInputStream();
            
        storageBean.storeToDirectory(fileContent, fileName, batchDir);
    }
    }
            
    Path infoProps = Paths.get(batchDir.toString(), DirectoryLoader.infoFileName);
    if (!Files.exists(infoProps)) { // if the info file wasn't uploaded, generate a random demo one
    Properties demo = Main.createDemoProperties();
    Path props = Paths.get(batchDir.toString(), DirectoryLoader.infoFileName);
    demo.store(Files.newOutputStream(props), "Demo properties");
    }
    */
}

From source file:com.carolinarollergirls.scoreboard.jetty.LoadXmlScoreBoard.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.doPost(request, response);

    try {/*  w  w w.  ja va2  s  .c  om*/
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        ServletFileUpload sfU = new ServletFileUpload();
        FileItemIterator items = sfU.getItemIterator(request);
        while (items.hasNext()) {
            FileItemStream item = items.next();
            if (!item.isFormField()) {
                InputStream stream = item.openStream();
                Document doc = editor.toDocument(stream);
                stream.close();
                handleDocument(request, response, doc);
                return;
            }
        }

        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded");
    } catch (FileUploadException fuE) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage());
    } catch (JDOMException jE) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage());
    }
}

From source file:controlador.Carga.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www  .  ja  va  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");
    PrintWriter out = response.getWriter();

    DiskFileItemFactory ff = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(ff);

    List items = null;
    File archivo = null;
    try {
        items = sfu.parseRequest(request);
    } catch (FileUploadException ex) {
        out.print(ex.getMessage());
    }
    for (int i = 0; i < items.size(); i++) {

        FileItem item = (FileItem) items.get(i);

        if (!item.isFormField()) {

            //                archivo = new File(this.getServletContext().getRealPath("/datos/") +"/" + item.getName());
            archivo = new File(
                    "/var/lib/openshift/55672e834382ec6dbc00010d/jbossews/webapps/" + item.getName());
            try {
                item.write(archivo);
            } catch (Exception ex) {
                out.print(ex.getMessage());
            }
        }

    }
    out.print("Se subio el archivo" + this.getServletContext().getRealPath("/datos/"));

    CargaInicial cargar;
    try {
        cargar = new CargaInicial();
        String ubicacion = archivo.toString();
        cargar.cargar(ubicacion);
    } catch (MiExcepcion ex) {
        out.print("Ha ocurrido un error de conexin a base de datos.");
    }

}

From source file:edu.vt.vbi.patric.portlets.CircosGenomeViewerPortlet.java

public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {

    Map<String, Object> parameters = new LinkedHashMap<>();
    int fileCount = 0;

    try {/*from w  ww.  ja v a  2 s  .  c om*/
        List<FileItem> items = new PortletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                parameters.put(item.getFieldName(), item.getString());
            } else {
                if (item.getFieldName().matches("file_(\\d+)$")) {
                    parameters.put("file_" + fileCount, item);
                    fileCount++;
                }
            }
        }
    } catch (FileUploadException e) {
        LOGGER.error(e.getMessage(), e);
    }

    LOGGER.debug(parameters.toString());

    // Generate Circo Image
    CircosData circosData = new CircosData(request);
    Circos circosConf = circosGenerator.createCircosImage(circosData, parameters);

    if (circosConf != null) {
        String baseUrl = "https://" + request.getServerName();
        String redirectUrl = baseUrl
                + "/portal/portal/patric/CircosGenomeViewer/CircosGenomeViewerWindow?action=b&cacheability=PAGE&imageId="
                + circosConf.getUuid() + "&trackList=" + StringUtils.join(circosConf.getTrackList(), ",");

        LOGGER.trace("redirect: {}", redirectUrl);
        response.sendRedirect(redirectUrl);
    }
}