Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:mercury.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {//  ww w.j a  v a  2s.c  om
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    if (StringUtils.isBlank(targetUrl)) {
                        targetUrl = request.getRequestURL().toString();
                        targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/'));
                    }
                    targetUrl += "/DigitalMediaController";
                    PostMethod filePost = new PostMethod(targetUrl);
                    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
                    UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(),
                            item.getInputStream());
                    Part[] parts = new Part[1];
                    parts[0] = new FilePart(item.getName(), src, item.getContentType(), null);
                    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                    HttpClient client = new HttpClient();
                    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                    int status = client.executeMethod(filePost);
                    if (status == HttpStatus.SC_OK) {
                        String data = filePost.getResponseBodyAsString();
                        JSONObject json = new JSONObject(data);
                        if (json.has("id")) {
                            JSONObject responseJson = new JSONObject();
                            responseJson.put("success", true);
                            responseJson.put("id", json.getString("id"));
                            responseJson.put("uri", targetUrl + "?id=" + json.getString("id"));
                            response.getWriter().write(responseJson.toString());
                        }
                    }
                    filePost.releaseConnection();
                    return;
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }
    response.getWriter().write("{success: false}");
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

private File uploadFile(HttpServletRequest request) throws Exception {
    // ,??ServletFileUpload
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    dfif.setSizeThreshold(4096);// ?,4K.
    String tempfilepath = FileFactory.getInstance().lookupPathConfigByFlag("UP", true).getLocalPath();
    dfif.setRepository(new File(tempfilepath));// 

    // //from  ww w . j  a va 2s  . co m
    ServletFileUpload sfu = new ServletFileUpload(dfif);
    sfu.setHeaderEncoding("utf-8");
    // 
    //sfu.setSizeMax(MAX_SIZE_5M);

    // PrintWriter out = response.getWriter();
    // request  
    List fileList = null;
    try {
        fileList = sfu.parseRequest(request);
    } catch (FileUploadException e) {// ?
        logger.error("FileUploadException", e);
        if (e instanceof SizeLimitExceededException) {
            throw new Exception("?:" + MAX_SIZE_5M / 1024 + "K");
        }
    }
    // 
    if (fileList == null || fileList.size() == 0) {
        throw new Exception("");
    }
    // 
    Iterator fileItr = fileList.iterator();
    // ?
    while (fileItr.hasNext()) {
        FileItem fileItem = null;
        String path = null;
        long size = 0;
        // ?
        fileItem = (FileItem) fileItr.next();
        // ?form?(<input type="text" />)

        if (fileItem == null || fileItem.isFormField()) {
            continue;
        }
        // 
        path = fileItem.getName();

        logger.debug("path:" + path);

        // ?
        size = fileItem.getSize();
        if ("".equals(path) || size == 0) {
            throw new Exception("");
        }

        // ??
        String t_name = path.substring(path.lastIndexOf("\\") + 1);
        // ??(????)
        String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);

        logger.debug("the file ext name:" + t_ext);

        // ???
        int allowFlag = 0;
        int allowedExtCount = allowedExt.length;
        for (; allowFlag < allowedExtCount; allowFlag++) {
            if (allowedExt[allowFlag].equals(t_ext.toLowerCase()))
                break;
        }
        if (allowFlag == allowedExtCount) {
            String error = ":";
            for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                error += "*." + allowedExt[allowFlag] + "  ";
            throw new Exception(error);
        }

        // ?
        String u_name = FileFactory.getInstance().getNextFileName("UP", t_ext, true);
        File temp = new File(u_name);

        int[] imgSize = getimgSize(fileItem);
        if ((imgSize[0] > 0 && imgSize[0] < 300) || (imgSize[1] > 0 && imgSize[1] < 300)) {
            throw new Exception("300x300");
        }

        logger.debug("to write file:" + temp);

        // ?
        fileItem.write(temp);

        temp = resizePic(temp);
        return temp;

    }

    throw new Exception("");

}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {/*from  w w w  . ja  v a  2  s . co  m*/
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java

/**
 * Starts a HTTP server to given port.//from   ww  w  .  j a  v a  2  s .  c  o  m
 *
 * @param params: the parameters of the connection, including HTTP port and host
 * @param manager: the manager which will deal with connections
 * @param serv: the set of services to be listening on this connection
 * @throws AServException when something goes wrong (e.g., socket already in use)
 */
public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv)
        throws AServException {
    this.manager = manager;
    services = serv;
    tcpPort = Integer.parseInt(params.getProperty("http"));
    tcpHost = params.getProperty("host");

    // ********************************************************************
    // JE: Jetty implementation
    server = new Server(tcpPort);

    // The handler deals with the request
    // most of its work is to deal with large content sent in specific ways 
    Handler handler = new AbstractHandler() {
        public void handle(String String, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String method = request.getMethod();
            String uri = request.getPathInfo();
            Properties params = new Properties();
            try {
                decodeParams(request.getQueryString(), params);
            } catch (Exception ex) {
                logger.debug("IGNORED EXCEPTION: {}", ex);
            }
            ;
            // I do not decode them here because it is useless
            // See below how it is done.
            Properties header = new Properties();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                header.setProperty(headerName, request.getHeader(headerName));
            }

            // Get the content if any
            // This is supposed to be only an uploaded file
            // Note that this could be made more uniform 
            // with the text/xml part stored in a file as well.
            String mimetype = request.getContentType();
            // Multi part: the content provided by an upload HTML form
            if (mimetype != null && mimetype.startsWith("multipart/form-data")) {
                try {
                    //if ( !ServletFileUpload.isMultipartContent( request ) ) {
                    //   logger.debug( "Does not detect multipart" );
                    //}
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    File tempDir = new File(System.getProperty("java.io.tmpdir"));
                    factory.setRepository(tempDir);
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(request);
                    for (FileItem fi : items) {
                        if (fi.isFormField()) {
                            logger.trace("  >> {} = {}", fi.getFieldName(), fi.getString());
                            params.setProperty(fi.getFieldName(), fi.getString());
                        } else {
                            logger.trace("  >> {} : {}", fi.getName(), fi.getSize());
                            logger.trace("  Stored at {}", fi.getName(), fi.getSize());
                            try {
                                // FilenameUtils.getName() needed for Internet Explorer problem
                                File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName()));
                                fi.write(uploadedFile);
                                params.setProperty("filename", uploadedFile.toString());
                                params.setProperty("todiscard", "true");
                            } catch (Exception ex) {
                                logger.warn("Cannot load file", ex);
                            }
                            // Another solution is to run this in 
                            /*
                              InputStream uploadedStream = item.getInputStream();
                              ...
                              uploadedStream.close();
                            */
                        }
                    }
                    ;
                } catch (FileUploadException fuex) {
                    logger.trace("Upload Error", fuex);
                }
            } else if (mimetype != null && mimetype.startsWith("text/xml")) {
                // Most likely Web service request (REST through POST)
                int length = request.getContentLength();
                if (length > 0) {
                    char[] mess = new char[length + 1];
                    try {
                        new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0,
                                length);
                    } catch (Exception e) {
                        logger.debug("IGNORED Exception", e);
                    }
                    params.setProperty("content", new String(mess));
                }
                // File attached to SOAP messages
            } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) {
                File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf");
                // check if file already exists - and overwrite if necessary.
                if (alignFile.exists())
                    alignFile.delete();
                FileOutputStream fos = new FileOutputStream(alignFile);
                InputStream is = request.getInputStream();

                try {
                    byte[] buffer = new byte[4096];
                    int bytes = 0;
                    while (true) {
                        bytes = is.read(buffer);
                        if (bytes < 0)
                            break;
                        fos.write(buffer, 0, bytes);
                    }
                } catch (Exception e) {
                } finally {
                    fos.flush();
                    fos.close();
                }
                is.close();
                params.setProperty("content", "");
                params.setProperty("filename", alignFile.getAbsolutePath());
            }

            // Get the answer (HTTP)
            HTTPResponse r = serve(uri, method, header, params);

            // Return it
            response.setContentType(r.getContentType());
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(r.getData());
            ((Request) request).setHandled(true);
        }
    };
    server.setHandler(handler);

    // Common part
    try {
        server.start();
    } catch (Exception e) {
        throw new AServException("Cannot launch HTTP Server", e);
    }
    //server.join();

    // ********************************************************************
    //if ( params.getProperty( "wsdl" ) != null ){
    //    wsmanager = new WSAServProfile();
    //    if ( wsmanager != null ) wsmanager.init( params, manager );
    //}
    //if ( params.getProperty( "http" ) != null ){
    //    htmanager = new HTMLAServProfile();
    //    if ( htmanager != null ) htmanager.init( params, manager );
    //}
    myId = "LocalHTMLInterface";
    serverId = manager.serverURL();
    logger.info("Launched on {}/html/", serverId);
    localId = 0;
}

From source file:Atualizar.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;//  www  .j av a2 s  .co  m
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    resp.getWriter()
                            .println("No  campo file" + this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());
                    req.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file

                    resp.getWriter().println("Campo file");
                    resp.getWriter().println("Name:" + item.getFieldName());
                    resp.getWriter().println("nome arquivo :" + item.getName());
                    resp.getWriter().println("Size:" + item.getSize());
                    resp.getWriter().println("ContentType:" + item.getContentType());
                    resp.getWriter().println(
                            "C:\\uploads" + File.separator + new Date().getTime() + "_" + item.getName());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = this.getServletContext().getRealPath("\\img\\user.jpg");
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                    }

                    resp.getWriter().println("Caminho: " + caminho);
                    req.setAttribute("caminho", caminho);
                    File uploadedFile = new File(
                            "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho);
                    item.write(uploadedFile);
                    req.setAttribute("caminho", caminho);
                    //                                                req.getRequestDispatcher("cadastrouser").forward(req, resp);
                }
            }
        } catch (Exception e) {
            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }

}

From source file:eionet.gdem.utils.MultipartFileUpload.java

/**
 * Stores uploaded file in the filesystem with the original filename. If the file with the same name exisits, appends next
 * available number at the end of the filename.
 *
 * @param fieldName//from   w w  w .  ja  v a2  s . c om
 *            - file item field name
 * @param folderName
 *            - target folder
 *
 * @return File name
 * @throws GDEMException
 *             Thrown in case of missing data or error during file writing.
 */
public String saveFile(String fieldName, String folderName) throws GDEMException {

    folderName = (folderName == null) ? _folderName : folderName;
    if (folderName == null)
        throw new GDEMException("Folder name is empty!");

    FileItem fileItem = getFileItem(fieldName);
    if (fileItem == null)
        throw new GDEMException("No files found!");

    String fileName = getFileItemName(fileItem.getName());
    if (fileName == null)
        throw new GDEMException("File name is empty!");

    factory.setRepository(new File(folderName));

    if (fileItem.getSize() == 0)
        return null; // There is nothing to save, file size is 0

    File file = getUniqueFile(folderName, fileName);
    fileName = file.getName();

    if (fileItem.getSize() > 0) {
        try {
            fileItem.write(file);
        } catch (Exception e) {
            throw new GDEMException(e.toString());
        }
    }
    return fileName;
}

From source file:gov.nih.nci.evs.browser.servlet.UploadServlet.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 *
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *///from ww w.ja va2 s .co m

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // Determine request by attributes
    String action = (String) request.getParameter("action");
    String type = (String) request.getParameter("type");

    System.out.println("(*) UploadServlet ...action " + action);
    if (action == null) {
        action = "upload_data";
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    //fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                //String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

            } else {
                //Handle Uploaded files.
                System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());

                String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

                request.getSession().setAttribute("action", action);

                if (action.compareTo("upload_data") == 0) {
                    request.getSession().setAttribute("codes", s);
                } else {
                    Mapping mapping = new Mapping().toMapping(s);

                    System.out.println("Mapping " + mapping.getMappingName() + " uploaded.");
                    System.out.println("Mapping version: " + mapping.getMappingVersion());

                    MappingObject obj = mapping.toMappingObject();
                    HashMap mappings = (HashMap) request.getSession().getAttribute("mappings");
                    if (mappings == null) {
                        mappings = new HashMap();
                    }
                    mappings.put(obj.getKey(), obj);
                    request.getSession().setAttribute("mappings", mappings);
                }
            }
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

    //long ms = System.currentTimeMillis();

    if (action.compareTo("upload_data") == 0) {
        if (type.compareTo("codingscheme") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/codingscheme_data.jsf"));
        } else if (type.compareTo("ncimeta") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/ncimeta_data.jsf"));
        } else if (type.compareTo("valueset") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/valueset_data.jsf"));
        }
    } else {
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/pages/home.jsf"));
    }

}

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 av a2s .  c om*/
    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:eu.wisebed.wiseui.server.rpc.ImageUploadServiceImpl.java

/**
 * Override executeAction to save the received files in a custom place
 * and delete these items from session/*from   w ww  .  j  a  v  a 2s .c  o  m*/
 */
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    String response = "";
    int cont = 0;

    for (FileItem item : sessionFiles) {
        if (false == item.isFormField()) {
            cont++;
            try {
                // Save a temporary file in the default system temp directory
                File uploadedFile = File.createTempFile("upload-", ".bin");

                // write item to a file
                item.write(uploadedFile);

                // open and read content from file stream
                FileInputStream in = new FileInputStream(uploadedFile);
                byte fileContent[] = new byte[(int) uploadedFile.length()];
                in.read(fileContent);

                // store content in persistance
                BinaryImage image = new BinaryImage();
                image.setFileName(item.getName());
                image.setFileSize(item.getSize());
                image.setContent(fileContent);
                image.setContentType(item.getContentType());
                LOGGER.info("Storing image: [Filename-> " + item.getName() + " ]");
                persistenceService.storeBinaryImage(image);

                // Compose an xml message with the full file information
                // which can be parsed in client side
                response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n";
                response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n";
                response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n";
                response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "-type>\n";

            } catch (Exception e) {
                throw new UploadActionException(e);
            }
        }
    }

    // Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // set the count of files
    response += "<file-count>" + cont + "</file-count>\n";

    // Send information of the received files to the client
    return "<response>\n" + response + "</response>\n";
}

From source file:com.silverpeas.form.displayers.FileFieldDisplayer.java

private String processUploadedFile(List<FileItem> items, String parameterName, PagesContext pagesContext,
        FileHandler fileHandler) throws Exception {
    String attachmentId = null;/*from   w  w  w .j  a  v a2 s .  c om*/
    FileItem item = FileUploadUtil.getFile(items, parameterName);
    if (!item.isFormField()) {
        String componentId = pagesContext.getComponentId();
        String userId = pagesContext.getUserId();
        String objectId = pagesContext.getObjectId();
        if (StringUtil.isDefined(item.getName())) {
            String fileName = FileUtil.getFilename(item.getName());
            SilverTrace.info("form", "AbstractForm.processUploadedFile", "root.MSG_GEN_PARAM_VALUE",
                    "fullFileName on Unix = " + fileName);
            long size = item.getSize();
            if (size > 0L) {
                SimpleDocument document = createSimpleDocument(objectId, componentId, item, fileName, userId,
                        pagesContext.isVersioningUsed());
                return document.getId();
            }
        }
    }
    return attachmentId;
}