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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:controlador.SerCiudadano.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww w . j  a  va2  s  .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //Procesando el archivo .sql con los datos del cnr
    //en esta ruta se guarda temporalmente el archivo .sql
    Bitacora b = new Bitacora();
    String ruta = getServletContext().getRealPath("/") + "pages/procesos/";
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(40960);
        File repositoryPath = new File("/temp");
        diskFileItemFactory.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setSizeMax(81920); // bytes
        upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                //este es el archivo que se envia en el campo file
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(ruta, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            String script = ruta + "" + nombre;
                            //consulta para importar registros
                            if (ConsultasDTO.ejecutar(
                                    "copy padronelectoral from '" + script + "' with (delimiter ',')")) {
                                out.print("Registros importados correctamente");
                            } else {
                                out.print("Hubo un error");
                            }

                        } else {
                            out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>");
                        }
                    }
                } else {
                    //ac recogemos los duis de los magistrados
                    if (item.getFieldName().equals("dui1")) {
                        b.setMagistrado1(item.getString());
                    }
                    if (item.getFieldName().equals("dui2")) {
                        b.setMagistrado2(item.getString());
                    }
                    if (item.getFieldName().equals("dui3")) {
                        b.setMagistrado3(item.getString());
                    }

                }
            }
            //registramos en la base de datos los duis de los magistrados
            //que autorizaron la insercion de datos CNR
            b.setAccion("Registro de datos CNR");
            if (BitacoraDTO.agregarBitacora(b)) {
                out.print("<br>Bitacora agregada");
            } else {
                out.print("<br>Hubo un error al agregar la bitacora");
            }

        } catch (FileUploadException e) {
            out.println("Error Upload: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            out.println("Error otros: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:com.threecrickets.prudence.util.FormWithFiles.java

/**
 * Constructor./* w ww  .  j av  a2 s  .c  om*/
 * 
 * @param webForm
 *        The URL encoded web form
 * @param fileItemFactory
 *        The file item factory
 * @throws ResourceException
 *         In case of an upload handling error
 */
public FormWithFiles(Representation webForm, FileItemFactory fileItemFactory) throws ResourceException {
    if (webForm.getMediaType().includes(MediaType.MULTIPART_FORM_DATA)) {
        RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory);

        try {
            for (FileItem fileItem : fileUpload.parseRepresentation(webForm)) {
                Parameter parameter;
                if (fileItem.isFormField())
                    parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                else {
                    if (fileItem instanceof DiskFileItem) {
                        File file = ((DiskFileItem) fileItem).getStoreLocation();
                        if (file == null)
                            // In memory
                            parameter = new FileParameter(fileItem.getFieldName(), fileItem.get(),
                                    fileItem.getContentType(), fileItem.getSize());
                        else
                            // On disk
                            parameter = new FileParameter(fileItem.getFieldName(), file,
                                    fileItem.getContentType(), fileItem.getSize());
                    } else
                        // Non-file form item
                        parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                }

                add(parameter);
            }
        } catch (FileUploadException x) {
            throw new ResourceException(x);
        }
    } else {
        // Default parsing
        addAll(new Form(webForm));
    }
}

From source file:net.jforum.core.support.vraptor.DefaultLogicLocator.java

@SuppressWarnings({ "deprecation", "unchecked" })
private void handleMultipartRequest(VRaptorServletRequest servletRequest) {
    if (!FileUploadBase.isMultipartContent(servletRequest)) {
        return;/*from   w w w  .  j  a  va  2 s . co m*/
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory(4096 * 16, this.temporaryDirectory);

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

    List<FileItem> fileItems;

    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    try {
        fileItems = upload.parseRequest(servletRequest);
    } catch (FileUploadException e) {
        logger.warn("There was some problem parsing this multipart request, or someone is not sending a "
                + "RFC1867 compatible multipart request.", e);
        return;
    }

    for (FileItem item : fileItems) {
        if (item.isFormField()) {
            servletRequest.addParameterValue(item.getFieldName(), item.getString());
        } else {
            if (!item.getName().trim().equals("")) {
                try {
                    File file = File.createTempFile("vraptor.", ".upload");
                    item.write(file);

                    UploadedFileInformation fileInformation = new BasicUploadedFileInformation(file,
                            item.getName(), item.getContentType());

                    this.registeUploadedFile(servletRequest, item.getFieldName(), fileInformation);
                } catch (Exception e) {
                    logger.error("Nasty uploaded file " + item.getName(), e);
                }
            } else {
                logger.debug("A file field was empy: " + item.getFieldName());
            }
        }
    }
}

From source file:cc.kune.core.server.manager.file.FileUploadManager.java

/**
 * Creates the uploaded file wrapped./*from  ww  w .  j av a2s .  com*/
 * 
 * @param userHash
 *          the user hash
 * @param stateToken
 *          the state token
 * @param fileName
 *          the file name
 * @param fileUploadItem
 *          the file upload item
 * @param typeId
 *          the type id
 * @return the content
 * @throws Exception
 *           the exception
 */
@Authenticated
@Authorizated(accessRolRequired = AccessRol.Editor, actionLevel = ActionLevel.container, mustCheckMembership = false)
@KuneTransactional
Content createUploadedFileWrapped(final String userHash, final StateToken stateToken, final String fileName,
        final FileItem fileUploadItem, final String typeId) throws Exception {
    final String relDir = FileUtils.toDir(stateToken);
    final String absDir = kuneProperties.get(KuneProperties.UPLOAD_LOCATION) + relDir;
    fileManager.mkdir(absDir);

    File file = null;
    try {
        final String filenameUTF8 = new String(fileName.getBytes(), UTF8);
        file = fileManager.createFileWithSequentialName(absDir, filenameUTF8);
        fileUploadItem.write(file);

        final String mimetype = fileUploadItem.getContentType();
        final BasicMimeType basicMimeType = new BasicMimeType(mimetype);
        LOG.info("Mimetype: " + basicMimeType);
        final String extension = FileUtils.getFileNameExtension(file.getName(), false);

        String preview = "";

        if (basicMimeType.isImage()) {
            generateThumbs(absDir, file.getName(), extension, false);
        } else if (basicMimeType.isPdf()) {
            generateThumbs(absDir, file.getName(), "png", true);
        } else if (basicMimeType.isText()) {
            final String textPreview = new String(FileUtils.getBytesFromFile(file));
            preview = "<pre>" + StringW.wordWrap(textPreview) + "</pre>";
        }

        // Persist
        final User user = userSession.getUser();
        final Container container = accessService
                .accessToContainer(ContentUtils.parseId(stateToken.getFolder()), user, AccessRol.Editor);
        final Content content = creationService.createContent(
                FileUtils.getFileNameWithoutExtension(file.getName(), extension), preview, user, container,
                typeId);
        content.setMimeType(basicMimeType);
        content.setFilename(file.getName());
        return content;
    } catch (final Exception e) {
        if (file != null && file.exists()) {
            logFileDel(file.delete());
        }
        throw e;
    }
}

From source file:fr.aliasource.webmail.server.UploadAttachmentsImpl.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestContext ctx = new ServletRequestContext(req);
    String enc = ctx.getCharacterEncoding();
    logger.warn("received encoding is " + enc);
    if (enc == null) {
        enc = "utf-8";
    }/*from   w  w  w  .  j ava 2 s. c  o m*/
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024,
            new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(20 * 1024 * 1024);

    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
        logger.error("upload exception", e1);
        return;
    }

    // Process the uploaded items
    String id = null;
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            id = item.getFieldName();
            String fileName = removePathElementsFromFilename(item.getName());
            logger.warn("FileItem: " + item);
            long size = item.getSize();
            logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@"
                    + account.getDomain() + " size: " + size + ").");
            AttachmentMetadata meta = new AttachmentMetadata();
            meta.setFileName(fileName);
            meta.setSize(size);
            meta.setMime(item.getContentType());
            try {
                account.uploadAttachement(id, meta, item.getInputStream());
            } catch (Exception e) {
                logger.error("Cannot write uploaded file to disk");
            }
        }
    }
}

From source file:com.alibaba.citrus.service.form.impl.validation.UploadedFileValidator.java

/** ? */
public boolean validate(Context context) {
    long minSize = this.minSize.getValue();
    long maxSize = this.maxSize.getValue();

    if (isEmptyArray(contentTypes) && isEmptyArray(extensions) && maxSize <= 0 && minSize < 0) {
        return true;
    }/* w w  w .  jav a  2 s  . c om*/

    FileItem[] fileItems = context.getField().getFileItems();

    // ??fileItems?required-validator??fileItem
    if (isEmptyArray(fileItems)) {
        return true;
    }

    for (FileItem fileItem : fileItems) {
        if (fileItem == null) {
            continue; // item
        }

        // size limit
        if (minSize >= 0 && fileItem.getSize() < minSize) {
            return false;
        }

        if (maxSize >= 0 && fileItem.getSize() > maxSize) {
            return false;
        }

        // content type
        if (!isEmptyArray(contentTypes)) {
            String fileContentType = normalizeContentType(fileItem.getContentType());

            if (fileContentType == null) {
                return false;
            }

            boolean matched = false;

            for (String expectedContentType : contentTypes) {
                if (fileContentType.startsWith(expectedContentType)) {
                    matched = true;
                    break;
                }
            }

            if (!matched) {
                return false;
            }
        }

        // extension
        if (!isEmptyArray(extensions)) {
            // ?? - null
            // ??? - null?
            // ???
            String ext = FileUtil.getExtension(fileItem.getName(), "null", true);

            if (ext == null) {
                return false;
            }

            boolean matched = false;

            for (String expectedExtension : extensions) {
                if (expectedExtension.equals(ext)) {
                    matched = true;
                    break;
                }
            }

            if (!matched) {
                return false;
            }
        }
    }

    return true;
}

From source file:fr.paris.lutece.portal.web.admin.AdminPageJspBean.java

/**
 * Processes the creation of a child page to the page whose identifier is stored in the http request
 *
 * @param request The http request//w w  w  .  j av a  2  s. c o m
 * @return The jsp url result of the process
 */
public String doCreateChildPage(HttpServletRequest request) {
    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

    String strParentPageId = mRequest.getParameter(Parameters.PAGE_ID);
    int nParentPageId = Integer.parseInt(strParentPageId);

    Page page = new Page();
    page.setParentPageId(nParentPageId);

    String strErrorUrl = getPageData(mRequest, page);

    if (strErrorUrl != null) {
        return strErrorUrl;
    }

    // Create the page
    _pageService.createPage(page);

    //set the authorization node
    if (page.getNodeStatus() != 0) {
        Page parentPage = PageHome.getPage(page.getParentPageId());
        page.setIdAuthorizationNode(parentPage.getIdAuthorizationNode());
    } else {
        page.setIdAuthorizationNode(page.getId());
    }

    FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT);

    byte[] bytes = item.get();
    String strMimeType = item.getContentType();

    page.setImageContent(bytes);
    page.setMimeType(strMimeType);

    _pageService.updatePage(page);

    // Displays again the current page with the modifications
    return getUrlPage(page.getId());
}

From source file:ReceiveImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w w  .ja  v  a 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 {

    System.out.println(isMultipart = ServletFileUpload.isMultipartContent(request));

    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("c:\\temp"));

    // 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();
            System.out.println(fi.isFormField());
            if (fi.isFormField()) {
                System.out.println("Got a form field: " + fi.getFieldName() + " " + fi);
            } else {
                // Get the uploaded file parameters
                //System.out.println(fi.getString("Command"));

                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();

                System.out.println(fieldName);
                System.out.println(fileName);
                String courseHour, course, regNo, date, temp = fileName;
                int j = temp.indexOf("sep");

                courseHour = temp.substring(0, j);
                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                course = temp.substring(0, j);

                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                regNo = temp.substring(0, j);

                date = temp.substring(j + 3);
                date = date.replaceAll("s", "-");

                System.out.println("ualal" + courseHour + course + regNo + date);

                System.out.println(contentType);

                long sizeInBytes = fi.getSize();
                // Write the file

                String uploadFolder = getServletContext().getRealPath("") + "Photo\\" + course + "\\" + regNo
                        + "\\";
                //                    String uploadFolder =  "\\SUST_PHOTO_PRESENT\\Photo\\" + course + "\\" + regNo + "\\";

                uploadFolder = uploadFolder.replace("\\build", "");
                Path path = Paths.get(uploadFolder);
                //if directory exists?
                if (!Files.exists(path)) {
                    try {
                        Files.createDirectories(path);
                    } catch (IOException e) {
                        //fail to create directory
                        e.printStackTrace();
                    }
                }
                //uploadFolder+= "\\"+date+".jpg";   
                System.out.println(fileName);
                System.out.println(uploadFolder);

                //               
                file = new File(uploadFolder + date);

                date = date.replaceAll("-", "/");
                date = date.substring(0, 10);

                String total_url = uploadFolder + date.replaceAll("/", "-") + ".jpg";
                System.out.println(total_url);

                String formattedUrl = total_url.replaceAll("\\\\", "/");

                System.out.println(formattedUrl.substring(38));

                System.out.println("-------------->>>>>>>>" + course + "  " + date + regNo + total_url);

                AddUser.updateUrl(courseHour, course, date, regNo, formattedUrl.substring(38));
                fi.write(file);

                //                    System.out.println("-------------->>>>>>>>" +course+"  "+ date+ regNo+total_url);
                //                   try {
                //            SavePhoto.saveIMG("CSE", "2016", "tada","F:\\1.png");
                //        } catch (IOException ex) {
                //            Logger.getLogger(SavePhoto.class.getName()).log(Level.SEVERE, null, ex);
                //        }
                System.out.println(uploadFolder);
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.sun.licenseserver.License.java

/**
 * Construct a license object using the input provided in the 
 * request object,//w  w w  .  j  a v a2s. co m
 * 
 * @param req
 */
public License(HttpServletRequest req) {
    if (FileUpload.isMultipartContent(req)) {
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(2 * 1024 * 1024);
        List items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getSize() > 2 * 1024 * 1024) {
                    continue;
                }
                m_log.fine("Size of uploaded license is [" + item.getSize() + "]");
                try {
                    license = item.getInputStream();
                    licSize = item.getSize();
                    mime = item.getContentType();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

            } else {
                String name = item.getFieldName();
                String value = item.getString();
                m_log.fine("MC ItemName [" + name + "] Value[" + value + "]");
                if (name != null) {
                    if (name.equals("id")) {
                        id = value;
                        continue;
                    }
                    if (name.equals("userId")) {
                        userId = value;
                        continue;
                    }
                    if (name.equals("contentId")) {
                        contentId = value;
                        continue;
                    }
                    if (name.equals("shopId")) {
                        shopId = value;
                        continue;
                    }

                }
            }

        }
    }
}

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;// w ww  .j  a va 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);
    }
}