Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository.

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:com.aes.controller.EmpireController.java

@RequestMapping(value = "addpresentation", method = RequestMethod.POST)
public String doAction5(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute Chapter chapter, @ModelAttribute UserDetails loggedUser, BindingResult result,
        Map<String, Object> map) throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    Presentation tempPresentation = new Presentation();
    String chapterId = "";
    String description = "";
    try {// www .  j  a  va2  s.c o m
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = context.getRealPath("") + File.separator + "uploads" + File.separator
                            + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    tempPresentation.setFilePath(filePath);
                    tempPresentation.setFileSize(item.getSize());
                    tempPresentation.setFileType(item.getContentType());
                    tempPresentation.setFileName(fileName);
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("chapterId")) {
                        chapterId = value;
                    } else {
                        description = value;
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    tempPresentation.setRecordStatus(true);
    tempPresentation.setDescription(description);
    int id = Integer.parseInt(chapterId);
    tempPresentation.setChapter(this.service.getChapterById(id));
    service.addPresentation(tempPresentation);
    map.put("tempPresentation", new Presentation());
    map.put("chapterId", chapterId);
    map.put("presentations", service.getAllPresentationsByChapterId(Integer.parseInt(chapterId)));
    return "../../admin/add_presentation";
}

From source file:edu.harvard.hul.ois.fits.service.servlets.FitsServlet.java

/**
 * Handles the file upload for FITS processing via streaming of the file using the
 * <code>POST</code> method.
 * Example: curl -X POST -F datafile=@<path/to/file> <host>:[<port>]/fits/examine
 * Note: "fits" in the above URL needs to be adjusted to the final name of the WAR file.
 *
 * @param request servlet request/*from w w w .ja va2s  .  c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                "Missing multipart POST form data.", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold((maxInMemoryFileSizeMb * (int) MB_MULTIPLIER));
    String tempDir = System.getProperty("java.io.tmpdir");
    logger.debug("Creating temp directory for storing uploaded files: " + tempDir);
    factory.setRepository(new File(tempDir));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(maxFileUploadSizeMb * MB_MULTIPLIER);
    upload.setSizeMax(maxRequestSizeMb * MB_MULTIPLIER);

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();
        Map<String, String[]> paramMap = request.getParameterMap();

        boolean includeStdMetadata = true;
        String[] vals = paramMap.get(Constants.INCLUDE_STANDARD_OUTPUT_PARAM);
        if (vals != null && vals.length > 0) {
            if (FALSE.equalsIgnoreCase(vals[0])) {
                includeStdMetadata = false;
                logger.debug("flag includeStdMetadata set to : " + includeStdMetadata);
            }
        }

        // file-specific directory path to store uploaded file
        // ensures unique sub-directory to handle rare case of duplicate file name
        String subDir = String.valueOf((new Date()).getTime());
        String uploadPath = uploadBaseDir + File.separator + subDir;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        // iterates over form's fields -- should only be one for uploaded file
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (!item.isFormField() && item.getFieldName().equals(FITS_FORM_FIELD_DATAFILE)) {

                String fileName = item.getName();
                if (StringUtils.isEmpty(fileName)) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            "Missing File Data.", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // ensure a unique local fine name
                String fileNameAndPath = uploadPath + File.separator + item.getName();
                File storeFile = new File(fileNameAndPath);
                item.write(storeFile); // saves the file on disk

                if (!storeFile.exists()) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Uploaded file does not exist.", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // Send it to the FITS processor...
                try {

                    sendFitsExamineResponse(storeFile.getAbsolutePath(), includeStdMetadata, request, response);

                } catch (Exception e) {
                    logger.error("Unexpected exception: " + e.getMessage(), e);
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            e.getMessage(), request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                } finally {
                    // delete the uploaded file
                    if (storeFile.delete()) {
                        logger.debug(storeFile.getName() + " is deleted!");
                    } else {
                        logger.warn(storeFile.getName() + " could not be deleted!");
                    }
                    if (uploadDir.delete()) {
                        logger.debug(uploadDir.getName() + " is deleted!");
                    } else {
                        logger.warn(uploadDir.getName() + " could not be deleted!");
                    }
                }
            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        "The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), "Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (Exception ex) {
        logger.error("Unexpected exception: " + ex.getMessage(), ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage(), request.getRequestURL().toString(), "Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

From source file:com.glaf.mail.web.rest.MailTaskResource.java

@POST
@Path("/uploadMails")
@ResponseBody//  w w  w. ja va 2s  . c  o  m
public void uploadMails(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    logger.debug(params);
    String taskId = request.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = request.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        // 
        factory.setRepository(new File(SystemProperties.getConfigRootPath() + "/temp/"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // ?
        // 
        // upload.setSizeMax(4194304);
        upload.setHeaderEncoding("UTF-8");
        List<?> fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
            Iterator<?> i = fileItems.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                logger.debug(fi.getName());
                if (fi.getName().endsWith(".txt")) {
                    byte[] bytes = fi.get();
                    String rowIds = new String(bytes);
                    List<String> addresses = StringTools.split(rowIds);
                    if (addresses.size() <= 100000) {
                        mailDataFacede.saveMails(taskId, addresses);
                        taskId = mailTask.getId();

                        if (mailTask.getLocked() == 0) {
                            QuartzUtils.stop(taskId);
                            QuartzUtils.restart(taskId);
                        } else {
                            QuartzUtils.stop(taskId);
                        }

                    } else {
                        throw new RuntimeException("mail addresses too many");
                    }
                    break;
                }
            }
        } catch (FileUploadException ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
}

From source file:com.servlet.tools.FileUploadHelper.java

public boolean Initialize() {
    boolean result;
    String tempRealPath;/*w ww .  j  ava2s .c  om*/
    File repository;
    int sizeThreshold;
    DiskFileItemFactory diskFileItemFactory;
    ServletFileUpload fileUpload;
    try {
        tempRealPath = SystemInfo.ProjectRealPath + File.separator + tempFilePath;
        if (!FileHelper.CheckAndCreateDirectory(tempRealPath)) {
            //                log
            return false;
        }
        this.relativePath = MappingRelativePath();
        System.out.println(tempRealPath);
        repository = new File(tempRealPath);
        sizeThreshold = 1024 * 6;
        diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setRepository(repository);
        diskFileItemFactory.setSizeThreshold(sizeThreshold);
        fileUpload = new ServletFileUpload(diskFileItemFactory);
        fileUpload.setSizeMax(limitedSize);
        fileUpload.setHeaderEncoding("UTF-8");
        result = true;
    } catch (Exception ex) {
        fileUpload = null;
        result = false;
        //log
    }
    if (result) {
        this.servletFileUpload = fileUpload;
    }
    return result;
}

From source file:au.org.ala.layers.web.ShapesService.java

@RequestMapping(value = "/shape/upload/shp", method = RequestMethod.POST)
@ResponseBody//from w  w  w  .java2s  .c  o m
public Map<Object, Object> uploadShapeFile(HttpServletRequest req, HttpServletResponse resp,
        @RequestParam(value = "user_id", required = false) String userId,
        @RequestParam(value = "api_key", required = false) String apiKey) throws Exception {
    // Use linked hash map to maintain key ordering
    Map<Object, Object> retMap = new LinkedHashMap<Object, Object>();

    File tmpZipFile = File.createTempFile("shpUpload", ".zip");

    if (!ServletFileUpload.isMultipartContent(req)) {
        String jsonRequestBody = IOUtils.toString(req.getReader());

        JSONRequestBodyParser reqBodyParser = new JSONRequestBodyParser();
        reqBodyParser.addParameter("user_id", String.class, false);
        reqBodyParser.addParameter("shp_file_url", String.class, false);
        reqBodyParser.addParameter("api_key", String.class, false);

        if (reqBodyParser.parseJSON(jsonRequestBody)) {

            String shpFileUrl = (String) reqBodyParser.getParsedValue("shp_file_url");
            userId = (String) reqBodyParser.getParsedValue("user_id");
            apiKey = (String) reqBodyParser.getParsedValue("api_key");

            if (!checkAPIKey(apiKey, userId)) {
                retMap.put("error", "Invalid user ID or API key");
                return retMap;
            }

            // Use shape file url from json body
            InputStream is = null;
            OutputStream os = null;
            try {
                is = new URL(shpFileUrl).openStream();
                os = new FileOutputStream(tmpZipFile);
                IOUtils.copy(is, os);
                retMap.putAll(handleZippedShapeFile(tmpZipFile));
                os.flush();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }

        } else {
            retMap.put("error", StringUtils.join(reqBodyParser.getErrorMessages(), ","));
        }

    } else {
        if (false && !checkAPIKey(apiKey, userId)) {
            retMap.put("error", "Invalid user ID or API key");
            return retMap;
        }

        // Create a factory for disk-based file items. File size limit is
        // 50MB
        // Configure a repository (to ensure a secure temp location is used)
        File repository = new File(System.getProperty("java.io.tmpdir"));
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 50, repository);

        factory.setRepository(repository);

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(req);

        if (items.size() == 1) {
            FileItem fileItem = items.get(0);
            IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(tmpZipFile));
            retMap.putAll(handleZippedShapeFile(tmpZipFile));
        } else {
            retMap.put("error",
                    "Multiple files sent in request. A single zipped shape file should be supplied.");
        }
    }

    return retMap;
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link PostMethod}
 * @throws javax.servlet.ServletException If something fails when uploading the content to the server
 *///from   w  ww . ja v a  2s .c  o  m
@SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" })
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:it.infn.ct.mpi_portlet.java

public void getInputForm(ActionRequest request) {
    if (PortletFileUpload.isMultipartContent(request))
        try {//w  w w.  j  a  va  2 s . c o m
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    inputFileName = item.getString();
                    processInputFile(item);
                    break;
                case inputFile:
                    inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    jobIdentifier = item.getString();
                    break;
                case cpunumber:
                    cpunumber = item.getString();
                    break;
                default:
                    _log.info("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring);
        } catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        inputFileName = (String) request.getParameter("file_inputFile");
        inputFileText = (String) request.getParameter("inputFile");
        jobIdentifier = (String) request.getParameter("JobIdentifier");
        cpunumber = (String) request.getParameter("cpunumber");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "inputFileName: '" + inputFileName + "'" + LS
            + "inputFileText: '" + inputFileText + "'" + LS + "jobIdentifier: '" + jobIdentifier + "'" + LS
            + "cpunumber: '" + cpunumber + "'");
}

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;//ww  w. j a v a  2 s.co 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.ibm.btt.sample.SampleFileHandler.java

/**
 * Just handle one file upload in this handler, developer can extend to support 
 * multi-files upload /* w  w w.jav a  2 s  .com*/
 */
@Override
public int saveFile(HttpServletRequest request) {
    int code = SAVE_FAILED;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //config the memory cache, if above the cache, the file data will be 
        // saved on cache folder 
        factory.setSizeThreshold(memCacheSize);
        // set up cache folder, when uploading, the tmp file 
        // will be saved in cache folder with a internal managed name. 
        factory.setRepository(new File(cachePath));

        ServletFileUpload upload = new ServletFileUpload(factory);
        // max size of a file 
        upload.setSizeMax(maxSize);

        try {
            if (isExpired()) {
                return REQ_TIMEOUT;
            }
            List<FileItem> fileItems = upload.parseRequest(request);
            // save file from request 
            code = uploadFilesFromReq(request, fileItems);
        } catch (SizeLimitExceededException e) {
            code = FILE_SIZE_EXCEED;
        } catch (FileUploadException e) {
            if (LOG.doDebug()) {
                LOG.debug("SampleFileHandler:saveFile() -- upload file stream was been cancelled", e);
            }
        }
    }
    return code;
}

From source file:it.infn.ct.chipster.Chipster.java

public String[] uploadChipsterSettings(ActionRequest actionRequest, ActionResponse actionResponse,
        String username) {//from   ww w. j a v  a 2s. c  o m
    String[] CHIPSTER_Parameters = new String[4];
    boolean status;

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

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

        // Set factory constrains
        File CHIPSTER_Repository = new File("/tmp");
        if (!CHIPSTER_Repository.exists())
            status = CHIPSTER_Repository.mkdirs();
        factory.setRepository(CHIPSTER_Repository);

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

        try {
            // Parse the request
            List items = upload.parseRequest(actionRequest);
            // Processing items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();

                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                //String timeStamp = dateFormat.format(Calendar.getInstance().getTime());

                // Processing a regular form field
                if (item.isFormField()) {
                    //if (fieldName.equals("chipster_login"))                                
                    //        CHIPSTER_Parameters[0]=item.getString();

                    if (fieldName.equals("chipster_password1"))
                        CHIPSTER_Parameters[1] = item.getString();

                }

                if (fieldName.equals("EnableNotification"))
                    CHIPSTER_Parameters[2] = item.getString();

                if (fieldName.equals("chipster_alias"))
                    CHIPSTER_Parameters[3] = item.getString();

            } // end while
        } catch (FileUploadException ex) {
            Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return CHIPSTER_Parameters;
}