Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.example.web.Update_profile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        String fileName = "";
        int f = 0;
        String user = null;/* w w  w.  ja  v a  2 s. co m*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    user = cookie.getValue();
                }
            }
        }
        String email = request.getParameter("email");
        String First_name = request.getParameter("First_name");
        String Last_name = request.getParameter("Last_name");
        String Phone_number_1 = request.getParameter("Phone_number_1");
        String Address = request.getParameter("Address");
        String message = "";
        int valid = 1;
        String query;
        ResultSet rs;
        Connection conn;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "tworld";
        String driver = "com.mysql.jdbc.Driver";
        isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();

                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();
                        fileName = fi.getName();
                        String contentType = fi.getContentType();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        String[] spliting = fileName.split("\\.");
                        // Write the file
                        System.out.println(sizeInBytes + " " + maxFileSize);
                        System.out.println(spliting[spliting.length - 1]);
                        if (!fileName.equals("")) {
                            if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                    || spliting[spliting.length - 1].equals("png")
                                    || spliting[spliting.length - 1].equals("jpeg"))) {

                                if (fileName.lastIndexOf("\\") >= 0) {
                                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                                } else {
                                    file = new File(
                                            filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                                }
                                fi.write(file);
                                System.out.println("Uploaded Filename: " + fileName + "<br>");
                            } else {
                                valid = 0;
                                message = "not a valid image";
                            }
                        }
                    }
                    BufferedReader br = null;
                    StringBuilder sb = new StringBuilder();

                    String line;
                    try {
                        br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                    if (f == 0) {
                        email = sb.toString();
                    } else if (f == 1) {
                        First_name = sb.toString();
                    } else if (f == 2) {
                        Last_name = sb.toString();
                    } else if (f == 3) {
                        Phone_number_1 = sb.toString();
                    } else if (f == 4) {
                        Address = sb.toString();
                    }
                    f++;

                }
            } catch (Exception ex) {
                System.out.println("hi");
                System.out.println(ex);

            }
        }
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (!email.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?");
                pst.setString(1, email);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!First_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?");
                pst.setString(1, First_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Last_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?");
                pst.setString(1, Last_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Phone_number_1.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?");
                pst.setString(1, Phone_number_1);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Address.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?");
                pst.setString(1, Address);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!fileName.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?");
                pst.setString(1, fileName);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            System.out.println("hi mom");
        }

        request.setAttribute("s_page", "4");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:it.geosolutions.servicebox.FileUploadCallback.java

/**
 * Handle a POST request//from   w ww  . j a v a  2  s . co m
 * 
 * @param request
 * @param response
 * 
 * @return CallbackResult
 * 
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response,
        ServiceBoxActionParameters callbackResult) throws IOException {

    // Get items if already initialized
    List<FileItem> items = null;
    if (callbackResult == null) {
        callbackResult = new ServiceBoxActionParameters();
    } else {
        items = callbackResult.getItems();
    }

    String temp = callbackConfiguration.getTempFolder();
    int buffSize = callbackConfiguration.getBuffSize();
    int itemSize = 0;
    long maxSize = 0;
    String itemName = null;
    boolean fileTypeMatch = true;

    File tempDir = new File(temp);

    try {
        if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null
                && tempDir.exists()) {
            // items are not initialized. Read it from the request

            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            /*
             * Set the size threshold, above which content will be stored on
             * disk.
             */
            fileItemFactory.setSizeThreshold(buffSize); // 1 MB

            /*
             * Set the temporary directory to store the uploaded files of
             * size above threshold.
             */
            fileItemFactory.setRepository(tempDir);

            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

            /*
             * Parse the request
             */
            items = uploadHandler.parseRequest(request);

        }

        // Read items
        if (items != null) {

            itemSize = items.size();
            callbackResult.setItems(items);
            if (itemSize <= this.callbackConfiguration.getMaxItems()) {
                // only if item size not exceeded max
                for (FileItem item : items) {
                    itemName = item.getName();
                    if (item.getSize() > maxSize) {
                        maxSize = item.getSize();
                        if (maxSize > this.callbackConfiguration.getMaxSize()) {
                            // max size exceeded
                            break;
                        } else if (this.callbackConfiguration.getFileTypePatterns() != null) {
                            fileTypeMatch = false;
                            int index = 0;
                            while (!fileTypeMatch
                                    && index < this.callbackConfiguration.getFileTypePatterns().size()) {
                                Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++);
                                fileTypeMatch = pattern.matcher(itemName).matches();
                            }
                            if (!fileTypeMatch) {
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            itemSize = 1;
            maxSize = request.getContentLength();
            // TODO: Handle file type
        }

    } catch (Exception ex) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error encountered while parsing the request");

        response.setContentType("text/html");

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("success", false);
        jsonObj.put("errorMessage", ex.getLocalizedMessage());

        Utilities.writeResponse(response, jsonObj.toString(), LOGGER);

    }

    // prepare and send error if exists
    boolean error = false;
    int errorCode = -1;
    String message = null;
    Map<String, Object> errorDetails = null;
    if (itemSize > this.callbackConfiguration.getMaxItems()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxItems());
        errorDetails.put("found", itemSize);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal();
        message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems()
                + "', found: '" + itemSize + "').";
    } else if (maxSize > this.callbackConfiguration.getMaxSize()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxSize());
        errorDetails.put("found", maxSize);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal();
        message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize()
                + "', found: '" + maxSize + "' on item '" + itemName + "').";
    } else if (fileTypeMatch == false) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        String expected = this.callbackConfiguration.getFileTypes();
        errorDetails.put("expected", expected);
        errorDetails.put("found", itemName);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal();
        message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName
                + "').";
    }
    if (error) {
        callbackResult.setSuccess(false);
        Utilities.writeError(response, errorCode, errorDetails, message, LOGGER);
    } else {
        callbackResult.setSuccess(true);
    }

    return callbackResult;
}

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override//from w  w w .ja  v a 2 s .c om
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.Uploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   www. j a va 2 s. c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream dafFileContent = null;
    String dafName = "";
    String dafType = "";

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    dafName = new File(item.getName()).getName();
                    dafFileContent = item.getInputStream();

                } else {

                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName.equals("type")) {
                        dafType = fieldValue;
                    }

                    // String log = "att name: " + fieldname + " - value: " + fieldvalue;
                    // Logger.getLogger(Uploader.class.getName()).log(Level.INFO, log);

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    if (!dafName.equals("")) {

        DafStore dafStore = new DafStore();
        dafStore.insertDAF(dafName, dafType, dafFileContent);
        Logger.getLogger(Uploader.class.getName()).log(Level.INFO, dafName);
    }

    response.sendRedirect("daf.jsp");
}

From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.fine("FeedServlet: doPost(...)");
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    PrintWriter out = null;/*from  w ww  .  ja  v  a2 s. co  m*/
    try {
        out = response.getWriter();
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();

            String datasource = null;
            String feedtype = null;

            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                //Disabled to allow easier update from HTML forms
                //if (item.isFormField()) {
                if (item.getFieldName().equals(FeedParser.XML_DATASOURCE)) {
                    InputStream itemStream = null;
                    try {
                        itemStream = item.openStream();
                        datasource = IOUtils.toString(itemStream);
                    } finally {
                        IOUtils.closeQuietly(itemStream);
                    }
                } else if (item.getFieldName().equals(FeedParser.XML_FEEDTYPE)) {
                    InputStream itemStream = null;
                    try {
                        itemStream = item.openStream();
                        feedtype = IOUtils.toString(itemStream);
                    } finally {
                        IOUtils.closeQuietly(itemStream);
                    }
                } else if (item.getFieldName().equals(FeedParser.XML_DATA)) {
                    try {
                        if (StringUtils.isBlank(datasource)) {
                            throw new IllegalArgumentException("Datasource is blank");
                        }
                        if (StringUtils.isBlank(feedtype)) {
                            throw new IllegalArgumentException("Feedtype is blank");
                        }

                        InputStream contentStream = null;
                        try {
                            contentStream = item.openStream();
                            final Feed feed = new FeedStaxParser().parse(datasource, feedtype, contentStream);

                            Callable<Object> processFeedTask = new Callable<Object>() {
                                @Override
                                public Object call() throws Exception {
                                    FeedProcessor feedProcessor = new FeedProcessor(feed);
                                    feedProcessor.processFeed();
                                    return null;
                                }
                            };
                            threadPoolExecutor.submit(processFeedTask);

                            out.append(GsaFeedConnection.SUCCESS_RESPONSE);
                            return;
                        } catch (Exception e) {
                            LOG.log(Level.SEVERE, "Exception while processing contentStream", e);
                        } finally {
                            IOUtils.closeQuietly(contentStream);
                        }
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
                //}
            }
        }
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, "Exception while uploading", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    out.append(GsaFeedConnection.INTERNAL_ERROR_RESPONSE);
}

From source file:com.example.web.Create_story.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    int count = 1;
    String storyid, storystep;//from ww w.j  a  v  a  2 s.c  o m
    String fileName = "";
    int f = 0;
    String action = "";
    String first = request.getParameter("first");
    String user = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                user = cookie.getValue();
        }
    }
    String title = request.getParameter("title");
    String header = request.getParameter("header");
    String text_field = request.getParameter("text_field");

    String latitude = request.getParameter("lat");
    String longitude = request.getParameter("lng");
    storyid = (request.getParameter("storyid"));
    storystep = (request.getParameter("storystep"));
    String message = "";
    int valid = 1;
    String query;
    ResultSet rs;
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "tworld";
    String driver = "com.mysql.jdbc.Driver";

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    String[] spliting = fileName.split("\\.");
                    // Write the file
                    System.out.println(sizeInBytes + " " + maxFileSize);
                    System.out.println(spliting[spliting.length - 1]);
                    if (!fileName.equals("")) {
                        if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                || spliting[spliting.length - 1].equals("png")
                                || spliting[spliting.length - 1].equals("jpeg"))) {

                            if (fileName.lastIndexOf("\\") >= 0) {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                            } else {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                            }
                            fi.write(file);
                            System.out.println("Uploaded Filename: " + fileName + "<br>");
                        } else {
                            valid = 0;
                            message = "not a valid image";
                        }
                    }
                }
                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {
                    br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                        }
                    }
                }
                if (f == 0)
                    action = sb.toString();
                else if (f == 1)
                    storyid = sb.toString();
                else if (f == 2)
                    storystep = sb.toString();
                else if (f == 3)
                    title = sb.toString();
                else if (f == 4)
                    header = sb.toString();
                else if (f == 5)
                    text_field = sb.toString();
                else if (f == 6)
                    latitude = sb.toString();
                else if (f == 7)
                    longitude = sb.toString();
                else if (f == 8)
                    first = sb.toString();
                f++;

            }
        } catch (Exception ex) {
            System.out.println("hi");
            System.out.println(ex);

        }
    }
    if (latitude == null)
        latitude = "";
    if (latitude.equals("") && first == null) {

        request.setAttribute("message", "please enter a marker");
        request.setAttribute("storyid", storyid);
        request.setAttribute("s_page", "3");
        request.setAttribute("storystep", storystep);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    } else if (valid == 1) {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (first != null) {
                if (first.equals("first_step")) {
                    do {
                        query = "select * from story_database where story_id='" + count + "' ";
                        Statement st = conn.createStatement();
                        rs = st.executeQuery(query);
                        count++;
                    } while (rs.next());

                    int a = count - 1;
                    request.setAttribute("storyid", a);
                    storyid = Integer.toString(a);
                    request.setAttribute("storystep", 2);

                }
            }
            query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='"
                    + storystep + "' ";
            Statement st = conn.createStatement();
            rs = st.executeQuery(query);

            if (!rs.next()) {

                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)");

                pst.setInt(1, Integer.parseInt(storyid));
                pst.setInt(2, Integer.parseInt(storystep));
                pst.setString(3, text_field);
                pst.setString(4, latitude);
                pst.setString(5, longitude);
                pst.setString(6, title);
                pst.setString(7, header);
                pst.setInt(8, Integer.parseInt(storystep));
                pst.setString(9, user);
                if (fileName.equals(""))
                    pst.setString(10, "");
                else
                    pst.setString(10, fileName);
                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            } else {
                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?");

                pst.setString(1, text_field);
                pst.setString(2, latitude);
                pst.setString(3, longitude);
                pst.setString(4, title);
                pst.setString(5, header);

                pst.setInt(6, Integer.parseInt(storystep));
                pst.setString(7, user);
                pst.setInt(8, Integer.parseInt(storyid));
                pst.setInt(9, Integer.parseInt(storystep));

                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            }
            request.setAttribute("storyid", storyid);
            storystep = Integer.toString(Integer.parseInt(storystep) + 1);
            request.setAttribute("storystep", storystep);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {

            //            Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex);  
        }
        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else {
        request.setAttribute("storyid", storyid);
        request.setAttribute("message", message);
        request.setAttribute("storystep", storystep);

        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.ikon.servlet.admin.CheckTextExtractionServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//ww  w  .  ja v  a  2 s . c o m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:br.com.caelum.vraptor.interceptor.multipart.CommonsUploadMultipartInterceptor.java

/**
 * Will intercept the request if apache file upload says that this request is multipart
 *//*from  w w  w . j  a va 2  s . c om*/
public boolean accepts(ResourceMethod method) {
    return ServletFileUpload.isMultipartContent(request);
}

From source file:com.rubinefocus.admin.servlet.UploadAdminImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from www.  j ava 2 s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File f = new File(this.getServletContext().getRealPath("admin/assets/images/adminPic"));
    String savePath = f.getPath();
    savePath = savePath.replace("%20", " ");
    savePath = savePath.replace("build", "");
    String fileName = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if its multipart content
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    fileName = new File(item.getName()).getName();
                    File file = new File(savePath + "/" + fileName);

                    if (file.exists()) {
                        String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
                        String ext = FilenameUtils.getExtension(fileName);
                        fileName = fileNameWithOutExt
                                + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()) + "." + ext;
                        fileName = fileName.replace(" ", "");
                        fileName = fileName.replace("-", "");
                        fileName = fileName.replace(":", "");
                        item.write(new File(savePath + File.separator + fileName));

                    } else {
                        item.write(new File(savePath + File.separator + fileName));

                    }
                    Gson gson = new Gson();
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");

                    response.getWriter().write(gson.toJson(fileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:imageServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* www.j av  a2 s .  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = "";
    String value = "";
    String imageurl = "";
    String path = "";
    try {
        String ImageFile = "";
        String itemName = "";

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                System.out.println("Exception in upload");
                e.getMessage();
            }

            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    name = item.getFieldName();
                    value = item.getString();
                    if (name.equals("ImageFile")) {
                        ImageFile = value;
                    }

                } else {
                    try {

                        itemName = item.getName();
                        File savedFile = new File(
                                this.getServletContext().getRealPath("/") + "images\\" + itemName);
                        File image = new File(request.getParameter("ImageFile"));
                        path = "/images/";
                        name = itemName;
                        item.write(savedFile);
                    } catch (Exception e) {
                        System.out.println("Error" + e.getMessage());
                    }
                }
            }
            try {
                int image = StudyDB.uploadImage("/images/" + itemName);
                imageurl = StudyDB.retrieveImage();

            } catch (Exception el) {
                System.out.println("Inserting error" + el.getMessage());
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    String URL = "/displayImage.jsp";
    String message = "Success";
    request.setAttribute("message", message);
    request.setAttribute("imageurl", imageurl);
    getServletContext().getRequestDispatcher(URL).forward(request, response);

}