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.ikon.servlet.WorkflowRegisterServlet.java

/**
 * Handle GET and POST/*w w  w  .  j  a va  2  s.  co m*/
 */
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("service({}, {}", request, response);
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    try {
        String user = PrincipalUtils.getUser();

        if (Config.ADMIN_USER.equals(user)) {
            String msg = handleRequest(request);
            log.info("Status: {}", msg);
            out.print(msg);
            out.flush();
        } else {
            log.warn("Workflow should be registered by {}", Config.ADMIN_USER);
        }
    } catch (FileUploadException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "FileUploadException: " + e.getMessage());
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IOException: " + e.getMessage());
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:controladoresAdministrador.ControladorCargarInicial.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww .  j a  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, FileUploadException {
    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());
    }
    String nombre = "";
    FileItem item = null;
    for (int i = 0; i < items.size(); i++) {

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

        if (!item.isFormField()) {
            nombre = item.getName();
            archivo = new File(this.getServletContext().getRealPath("/archivos/") + "/" + item.getName());
            try {
                item.write(archivo);
            } catch (Exception ex) {
                out.print(ex.getMessage());
            }
        }
    }
    CargaInicial carga = new CargaInicial();
    String ubicacion = archivo.toString();
    int cargado = carga.cargar(ubicacion);
    if (cargado == 1) {
        response.sendRedirect(
                "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> No se encontro el archivo!</strong> Por favor intentelo de nuevo.&tipoAlert=warning");
    } else {
        response.sendRedirect(
                "pages/indexadmin.jsp?msg=<strong>Carga inicial exitosa! <i class='glyphicon glyphicon-ok'></i></strong>&tipoAlert=success");
    }
}

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

/***
 * Simplest way of handling files that are uploaded from form. Just put them
 * as name-value pair into service data. This is useful ONLY if the files
 * are reasonably small.//from  w  w w.j a  v  a2 s. c o  m
 * 
 * @param req
 * @param data
 *            data in which
 */
public void simpleExtract(HttpServletRequest req, ServiceData data) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        /**
         * ServerFileUpload still deals with raw types. we have to have
         * workaround that
         */
        List<?> list = upload.parseRequest(req);
        if (list != null) {
            for (Object item : list) {
                if (item instanceof FileItem) {
                    FileItem fileItem = (FileItem) item;
                    data.addValue(fileItem.getFieldName(), fileItem.getString());
                } else {
                    Spit.out("Servlet Upload retruned an item that is not a FileItem. Ignorinig that");
                }
            }
        }
    } catch (FileUploadException e) {
        Spit.out(e);
        data.addError("Error while parsing form data. " + e.getMessage());
    }
}

From source file:com.anhth12.lambda.app.serving.AbstractLambdaResource.java

protected final List<FileItem> parseMultipart(HttpServletRequest request) throws LambdaServingException {
    synchronized (sharedFileItemFactory) {
        if (sharedFileItemFactory.get() != null) {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1 << 16,
                    (File) servletContext.getAttribute("javax.servlet.context.tempdir"));
            fileItemFactory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(servletContext));
            sharedFileItemFactory.set(fileItemFactory);
        }/*from   w  w  w  .  ja v a 2 s .c  o  m*/
    }

    List<FileItem> fileItems;

    try {
        fileItems = new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request);
    } catch (FileUploadException ex) {
        throw new LambdaServingException(Response.Status.BAD_REQUEST, ex.getMessage());
    }

    check(!fileItems.isEmpty(), "No parts");
    return fileItems;
}

From source file:com.cloudera.oryx.app.serving.AbstractOryxResource.java

private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException {
    if (sharedFileItemFactory.get() == null) {
        // Not a big deal if two threads actually set this up
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1 << 16,
                (File) servletContext.getAttribute("javax.servlet.context.tempdir"));
        fileItemFactory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(servletContext));
        sharedFileItemFactory.compareAndSet(null, fileItemFactory);
    }//from   w ww  .  j a v  a 2 s  . co  m

    try {
        return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request).stream()
                .map(FileItemPart::new).collect(Collectors.toList());
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:Index.UploadFileServlet.java

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

    String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\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);

        for (FileItem item : partes) {
            File file = new File(ubicacionArchivo,
                    request.getSession().getAttribute("userName").toString() + ".jpg");
            item.write(file);
            System.out.println("name: " + item.getName());
        }
        request.setAttribute("error", null);
        request.setAttribute("result", "Se ha registrado correctamente");
        request.setAttribute("funcionalidad", "Imagen");
        request.getSession().removeAttribute("userName");

        request.getRequestDispatcher("/Login.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:Index.RegisterRestaurantImagesServlet.java

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

        String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\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);

            List<String> listImage = (List<String>) request.getSession().getAttribute("listImagen");
            if (listImage == null) {
                listImage = new ArrayList<String>();
            }

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

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

        }
    }
}

From source file:fll.web.developer.ReplaceChallengeDescriptor.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }/* ww  w. j  ava  2 s. co m*/

    final StringBuilder message = new StringBuilder();

    Connection connection = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final Document curDoc = ApplicationAttributes.getChallengeDocument(application);

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        // create a new empty database from an XML descriptor
        final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldoc");

        final Document newDoc = ChallengeParser
                .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

        final String compareMessage = ChallengeParser.compareStructure(curDoc, newDoc);
        if (null == compareMessage) {
            GenerateDB.insertOrUpdateChallengeDocument(newDoc, connection);
            application.setAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT, newDoc);
            message.append("<p><i>Successfully replaced challenge descriptor</i></p>");
        } else {
            message.append("<p class='error'>");
            message.append(compareMessage);
            message.append("</p>");
        }
    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOGGER.error(fue, fue);
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error talking to the database: " + sqle.getMessage() + "</p>");
        LOGGER.error(sqle, sqle);
        throw new RuntimeException("Error talking to the database", sqle);
    } finally {
        SQLFunctions.close(connection);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("index.jsp"));

}

From source file:com.aspectran.web.support.multipart.inmemory.MemoryMultipartFileParameter.java

/**
 * Save an uploaded file as a given destination file.
 *
 * @param destFile the destination file/*  w ww  .j  av  a  2 s . com*/
 * @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");
    }

    destFile = determineDestinationFile(destFile, overwrite);

    try {
        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:fll.web.UploadSpreadsheet.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    final StringBuilder message = new StringBuilder();
    String nextPage;//  w w  w  .  j a  va2s . co  m
    try {
        UploadProcessor.processUpload(request);
        final String uploadRedirect = (String) request.getAttribute("uploadRedirect");
        if (null == uploadRedirect) {
            throw new RuntimeException(
                    "Missing parameter 'uploadRedirect' params: " + request.getParameterMap());
        }
        session.setAttribute("uploadRedirect", uploadRedirect);

        final FileItem fileItem = (FileItem) request.getAttribute("file");
        final String extension = Utilities.determineExtension(fileItem.getName());
        final File file = File.createTempFile("fll", extension);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Wrote data to: " + file.getAbsolutePath());
        }
        fileItem.write(file);
        session.setAttribute(SPREADSHEET_FILE_KEY, file.getAbsolutePath());

        if (ExcelCellReader.isExcelFile(file)) {
            final List<String> sheetNames = ExcelCellReader.getAllSheetNames(file);
            if (sheetNames.size() > 1) {
                session.setAttribute("sheetNames", sheetNames);
                nextPage = "promptForSheetName.jsp";
            } else {
                session.setAttribute(SHEET_NAME_KEY, sheetNames.get(0));
                nextPage = uploadRedirect;
            }
        } else {
            nextPage = uploadRedirect;
        }

    } catch (final FileUploadException e) {
        message.append("<p class='error'>Error processing team data upload: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error processing team data upload", e);
    } catch (final Exception e) {
        message.append("<p class='error'>Error saving team data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving team data into the database", e);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL(nextPage));
}