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

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

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.runwaysdk.web.SecureFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }//from   w ww  . j a va 2 s. c  o  m

    String fileId = req.getParameter("sessionId").toString().trim();
    FileItemFactory factory = new ProgressMonitorFileItemFactory(req, fileId);
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request

        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                String fileName = fullName.substring(0, extensionInd);
                String extension = fullName.substring(extensionInd + 1);
                InputStream stream = item.openStream();

                BusinessDTO fileDTO = clientRequest.newSecureFile(fileName, extension, stream);

                // return the vault id to the dhtmlxVault callback
                req.getSession().setAttribute("FileUpload.Progress." + fileId, fileDTO.getId());
            }
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    } catch (RuntimeException e) {
        req.getSession().setAttribute("FileUpload.Progress." + fileId, "fail: " + e.getLocalizedMessage());
    }
}

From source file:com.runwaysdk.web.WebFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    // capture the session id
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }/*from www  . j  a  v a 2 s. com*/

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);

        String fileName = null;
        String extension = null;
        InputStream stream = null;
        String uploadPath = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream input = item.openStream();
            if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) {
                uploadPath = Streams.asString(input);
            } else if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                fileName = fullName.substring(0, extensionInd);
                extension = fullName.substring(extensionInd + 1);
                stream = input;
            }
        }

        if (stream != null) {
            clientRequest.newFile(uploadPath, fileName, extension, stream);
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    }
}

From source file:ar.com.easytech.faces.filters.MultipartRequest.java

@SuppressWarnings("unchecked")
public MultipartRequest(HttpServletRequest request, String path) throws Exception {
    super(request);
    DiskFileItemFactory factory = new DiskFileItemFactory();

    if (path != null)
        factory.setRepository(new File(path));

    ServletFileUpload upload = new ServletFileUpload(factory);
    parameterMap.put("path", path);

    try {// w ww . j a va2  s. com
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : items) {

            String str = item.getString();
            if (item.isFormField())
                parameterMap.put(item.getFieldName(), str);
            else {
                if (item.getName() != null) {
                    parameterMap.put("fileName", item.getName());
                }
                request.setAttribute(item.getFieldName(), item);
            }
        }

    } catch (FileUploadException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw new Exception(ex.getLocalizedMessage());
    }
}

From source file:Game_DataS.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w .ja  v  a  2  s .  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,
        ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
    String datetime = null, field = null, visitors = null, hteamname = null, fteamname = null;
    Integer Ivisitors = null;

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = null;
    try {
        out = response.getWriter();
        //First do the Proccesing of data . Data received from URL-POST method..

        // // Check that we have a file upload request
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);

        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Parse the request to get file items.
        List<FileItem> fields = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator<FileItem> it = fields.iterator();
        //loop

        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();

            //Form Field
            if (isFormField) {
                String tmp = fileItem.getFieldName();

                if (tmp.equals("datetime")) {
                    datetime = fileItem.getString();
                } else if (tmp.equals("field")) {
                    field = fileItem.getString();
                } else if (tmp.equals("visitors")) {
                    visitors = fileItem.getString();
                    //cast to Integer
                    Ivisitors = Integer.parseInt(visitors);
                } else if (tmp.equals("hteamname")) {
                    hteamname = fileItem.getString();
                } else if (tmp.equals("fteamname")) {
                    fteamname = fileItem.getString();
                }
            } //extracted all STATIC INFO, now go to txt;s
            else {
                //Call Method that parses txt and do the inserts
                TXT_FILES_PROCESS(fileItem.getString(), fileItem.getFieldName(), out, hteamname, fteamname,
                        datetime, field, Ivisitors);
            }
        }

        //-------------------------------------
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>EuroLeague Page</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div><h1>Successfull Registry in DataBase !!</h1>");
        out.println("<br></br>");
        out.println("<br>");
        out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">");
        out.println("Home Page for further action  --->  <input type=\"submit\" value=\"Home Page!\">");
        out.println("</form>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException FUE) {
        System.out.println("debugg " + FUE.getLocalizedMessage());
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title> EuroLeague Page</title>");
        out.println("</head>");
        out.println("<body style = \"background-color: #720;\">");
        out.println(
                "<div><h1> Sorry...Something went wrong with the TXT uploading.Please go to home page and try again uploading a valid txt !!</h1>");
        out.println("<br> </br>");
        out.println("<br>");
        out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">");
        out.println("Press here -> <input  type = \"submit\" value = \"Home Page!\">");
        out.println("</form>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
    } catch (IOException IOE) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title> EuroLeague Page</title>");
        out.println("</head>");
        out.println("<body style = \"background-color: #720;\">");
        out.println(
                "<div><h1> Sorry...Something went wrong.Maybe a network error.Please go to home page !!</h1>");
        out.println("<br> </br>");
        out.println("<br>");
        out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">");
        out.println("Press here -> <input  type = \"submit\" value = \"Home Page!\">");
        out.println("</form>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java

/**
 * UPDATE request with a request body containing the statements to be
 * removed and added as a multi-part mime request.
 *//*from w w  w. ja va  2 s  .  c om*/
private void doUpdateWithBody(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {

    final DiskFileItemFactory factory = new DiskFileItemFactory();

    final ServletFileUpload upload = new ServletFileUpload(factory);

    FileItem add = null, remove = null;

    try {

        final List<FileItem> items = upload.parseRequest(req);

        for (FileItem item : items) {

            if (item.getFieldName().equals("add")) {

                if (!validateItem(resp, add = item)) {
                    return;
                }

            } else if (item.getFieldName().equals("remove")) {

                if (!validateItem(resp, remove = item)) {
                    return;
                }

            }

        }

    } catch (FileUploadException ex) {

        throw new IOException(ex);

    }

    final String baseURI = req.getRequestURL().toString();

    final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false);

    /*
     * Allow the caller to specify the default context for insert.
     */
    final Resource[] defaultContextInsert;
    {
        final String[] s = req.getParameterValues("context-uri-insert");
        if (s != null && s.length > 0) {
            try {
                defaultContextInsert = toURIs(s);
            } catch (IllegalArgumentException ex) {
                buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage());
                return;
            }
        } else {
            defaultContextInsert = null;
        }
    }

    /*
     * Allow the caller to specify the default context for delete.
     */
    final Resource[] defaultContextDelete;
    {
        final String[] s = req.getParameterValues("context-uri-delete");
        if (s != null && s.length > 0) {
            try {
                defaultContextDelete = toURIs(s);
            } catch (IllegalArgumentException ex) {
                buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage());
                return;
            }
        } else {
            defaultContextDelete = null;
        }
    }

    final String namespace = getNamespace(req);

    try {

        submitApiTask(new UpdateWithBodyTask(req, resp, namespace, ITx.UNISOLATED, //
                baseURI, //
                suppressTruthMaintenance, //
                remove, //
                defaultContextDelete, //
                add, //
                defaultContextInsert//
        )).get();

    } catch (Throwable t) {

        launderThrowable(t, resp,
                "UPDATE-WITH-BODY: baseURI=" + baseURI + (add == null ? null
                        : ", add=" + add
                                + (defaultContextInsert == null ? ""
                                        : ",context-uri-insert=" + Arrays.toString(defaultContextInsert)))
                        + (remove == null ? null
                                : ", remove=" + remove + (defaultContextDelete == null ? ""
                                        : ",context-uri-delete=" + Arrays.toString(defaultContextDelete))));

    }

}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(NedServerResponses.ERROR_MULTIPART_CONTENT);
        resp.flushBuffer();//from w  w w.j  a v a  2 s  .  com
        return; // send response
    }

    FileItemFactory factory = new DiskFileItemFactory();
    List<?> items = null;
    Iterator<?> iter = null;
    FileItem item = null;
    String name = null;
    String libraryId = null;
    String contentId = null;
    String file = null;
    String contentType = null;
    File uploadedFile = null;

    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    }

    // now the downloading begins
    if (items == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(NedServerResponses.ERROR_BAD_REQUEST);
        resp.flushBuffer();
        return;
    }

    // first get only parameters
    iter = items.iterator();
    while (iter.hasNext()) {
        item = (FileItem) iter.next();

        if (item.getFieldName().equals("libId")) {
            libraryId = item.getString();
        } else if (item.getFieldName().equals("contentId")) {
            contentId = item.getString();
        } else if (item.getFieldName().equals("languageName")) {
            processUploadNewLanguage(items, resp);
            return;
        }
    }
    iter = items.iterator();
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (!item.isFormField()) {
            name = item.getName();
            int slashindex = name.lastIndexOf('\\');
            if (slashindex > -1) {
                file = name.substring(slashindex + 1, name.length());
            } else {
                file = name.substring(name.lastIndexOf('/') + 1, name.length());
            }

            contentType = getMediaType(name);
            if (contentType == null || contentType.isEmpty()) {
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                resp.getWriter().print(NedServerResponses.ERROR_WRONG_FILE_TYPE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }

            // FILE PATH CONSISTS OF
            // ROOT - TOMCAT_PATH\webapps\ROOT
            // BASEROOT - PASSED FROM CLIENT - librartId(signifies the catalogue instance)
            // nokiaecd\videos
            // FILENAME - GET FROM CHOSEN FILE

            String directory = createDirectory(libraryId);

            File fDir = new File(directory);
            fDir.getAbsolutePath();
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            file = createFilePath(directory, file);
            String uf = directory + file;
            uploadedFile = new File(uf);

            // //////////////////////////////////////////////
            InputStream uploadedStream = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(uploadedFile);
            byte[] myarray = new byte[1024];
            int i = 0;
            while ((i = uploadedStream.read(myarray)) != -1) {
                fos.write(myarray, 0, i);
            }
            fos.flush();
            fos.close();
            uploadedStream.close();

            // update database
            try {
                getPosgresConnection().updateContentData(file, contentType, contentId);
            } catch (Exception ex) {
                // TODO delete file
                Logger.getLogger(NedFileUploadServlet.class.getSimpleName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().print(NedServerResponses.ERROR_DATABASE_UPDATE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }
        }
    }

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().print(contentType);
    resp.flushBuffer();
    disconnectPostgres();
}