Example usage for javax.servlet.http Cookie getName

List of usage examples for javax.servlet.http Cookie getName

Introduction

In this page you can find the example usage for javax.servlet.http Cookie getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:ed.net.CookieJar.java

/**
 * Checks if the cookie has expired/*from  w w  w . j a v  a2s.c  om*/
 * @param cookie the cookie to check
 * @return true, if the cookie has an expiration date that has been reached
 */
private boolean isExpired(Cookie cookie) {
    if (cookie.getMaxAge() < 0)
        return false;

    if (cookie.getMaxAge() == 0)
        return true;

    Date createDate = _creationDates.get(cookie.getName());
    Date expirationDate = new Date(createDate.getTime() + (cookie.getMaxAge() * 1000));

    return expirationDate.getTime() <= System.currentTimeMillis();
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }//from   ww  w .  j a  v a 2 s .  c o  m
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {
            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Dump out things from HttpServletRequest object
 * //from ww  w.  j  ava2s.  c  o  m
 * @param req
 * @return
 */
public static String dumpRequest(HttpServletRequest req) {
    if (req == null)
        return null;
    char column = ':', rtn = '\n', space = ' ';
    StringBuilder builder = new StringBuilder(req.getMethod());
    builder.append(space).append(req.getRequestURL().toString()).append(space).append(req.getProtocol())
            .append(rtn);
    Enumeration<String> headers = req.getHeaderNames();
    builder.append("HEADERS:\n");
    String header;
    for (; headers.hasMoreElements();) {
        header = headers.nextElement();
        builder.append(header).append(column).append(req.getHeader(header)).append(rtn);
    }
    builder.append("COOKIES:\n");
    Cookie cookie;
    Cookie[] cookies = req.getCookies();
    if (!ValidationUtils.isEmpty(cookies)) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            builder.append(cookie.getName()).append(column).append(GsonUtils.format(cookie)).append(rtn);
        }
    }
    builder.append("BODY:\n");
    Map<String, String[]> params = req.getParameterMap();
    for (String name : params.keySet()) {
        builder.append(name).append(ShenStrings.DELIMITER_DOT);
        builder.append(name.matches(PASS_PATTERN) ? params.get(SECRET_STRING) : params.get(name));
    }
    return builder.toString();

}

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

protected void redirectToApp(HttpServletRequest request, HttpServletResponse response, String contextName,
        String[] uriParts, String action) throws IOException {
    StringBuilder redirectAddress = new StringBuilder();
    for (int i = 0; i < uriParts.length; i++) {
        redirectAddress.append(uriParts[i]);
        if (uriParts[i].equals(contextName)) {
            break;
        }/*from   w  ww  . j a v  a 2s.  com*/
        if (i < uriParts.length - 1) {
            redirectAddress.append("/");
        }
    }

    // redirect to ROOT context
    if (redirectAddress.length() == 0) {
        redirectAddress.append("/");
    }

    HttpSession httpSession = request.getSession();
    if (action != null) {
        httpSession.setAttribute(AppUI.LAST_REQUEST_ACTION_ATTR, action);
    }
    if (request.getParameterNames().hasMoreElements()) {
        Map<String, String> params = new HashMap<>();
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            if (!FROM_HTML_REDIRECT_PARAM.equals(name)) {
                params.put(name, request.getParameter(name));
            }
        }
        httpSession.setAttribute(AppUI.LAST_REQUEST_PARAMS_ATTR, params);
    }

    statisticsCounter.incWebRequestsCount();
    String httpSessionId = httpSession.getId();
    log.debug("Redirect to application {}", httpSessionId);

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("JSESSIONID".equals(cookie.getName()) && !httpSessionId.equals(cookie.getValue())) {
                cookie.setValue(httpSessionId);
                break;
            }
        }
    }
    response.sendRedirect(redirectAddress.toString());
}

From source file:de.uhh.l2g.plugins.guest.OpenAccessVideos.java

public void viewOpenAccessVideo(ActionRequest request, ActionResponse response) {
    String objectType = ParamUtil.getString(request, "objectType");
    String password = request.getParameter("password");
    boolean objectExists = true;

    Long objectId = new Long(0);
    boolean secLink = false;
    String oid = request.getParameter("objectId");

    try {/*from www  .ja v a  2 s .  c  o  m*/
        objectId = new Long(oid);
    } catch (NumberFormatException e) {
        if (objectType.equals("v")) { //for video objects
            try {
                objectId = VideoLocalServiceUtil.getBySecureUrl(oid).getVideoId();
                secLink = true;
            } catch (NoSuchVideoException e1) {
            } catch (SystemException e1) {
            }
        }
        if (objectType.equals("l")) { //for lecture series objects
            objectId = LectureseriesLocalServiceUtil.getByUSID(oid).getLectureseriesId();
            secLink = true;
        }
    }

    Long timeStart = new Long(0);
    Long timeEnd = new Long(0);

    try {
        timeStart = new Long(ParamUtil.getString(request, "timeStart"));
        timeEnd = new Long(ParamUtil.getString(request, "timeEnd"));
    } catch (Exception e) {
    }

    Video video = new VideoImpl();
    //lecture series object
    Lectureseries lectureseries = new LectureseriesImpl();

    //Lecture series
    if (objectType.equals("l")) {
        try {
            lectureseries = LectureseriesLocalServiceUtil.getLectureseries(objectId);
            if (!secLink) {
                video = VideoLocalServiceUtil.getFullVideo(lectureseries.getLatestOpenAccessVideoId());
            } else {
                Long videoId = VideoLocalServiceUtil.getLatestClosedAccessVideoId(objectId);
                video = VideoLocalServiceUtil.getFullVideo(videoId);
            }
        } catch (Exception e) {
            objectExists = false;
            response.setRenderParameter("jspPage", "/guest/noVideosFound.jsp");
        }
    } else if (objectType.equals("v")) {
        video = VideoLocalServiceUtil.getFullVideo(objectId);
        if (video.getVideoId() == 0)
            objectExists = false;
        try {
            lectureseries = LectureseriesLocalServiceUtil.getLectureseries(video.getLectureseriesId());
        } catch (Exception e) {
        }
    }
    if (objectExists) {
        List<Video> relatedVideos = new ArrayList<Video>();
        //related videos by lectureseries id
        try {
            int os = 0;
            if (video.getOpenAccess() == 1)
                os = 1;
            relatedVideos = VideoLocalServiceUtil
                    .getByLectureseriesAndOpenaccess(lectureseries.getLectureseriesId(), os);
        } catch (SystemException e) {
        }

        //chapters and segments
        List<Segment> segments = new ArrayList<Segment>();
        try {
            segments = SegmentLocalServiceUtil.getSegmentsByVideoId(objectId);
        } catch (PortalException e) {
        } catch (SystemException e) {
        }

        //lectureseries for video
        List<Video_Lectureseries> vl = new ArrayList<Video_Lectureseries>();
        try {
            vl = Video_LectureseriesLocalServiceUtil.getByVideo(video.getVideoId());
        } catch (SystemException e) {
        }

        //institutions for video
        List<Video_Institution> vi = new ArrayList<Video_Institution>();
        vi = Video_InstitutionLocalServiceUtil.getByVideo(video.getVideoId());

        //metadata for video
        Metadata m = new MetadataImpl();
        try {
            m = MetadataLocalServiceUtil.getMetadata(video.getMetadataId());
        } catch (PortalException e) {
        } catch (SystemException e) {
        }

        //license for video

        License l = new LicenseImpl();
        try {
            l = LicenseLocalServiceUtil.getByVideoId(video.getVideoId());
        } catch (NoSuchLicenseException e) {
        } catch (SystemException e) {
        }

        //update video hits
        Long hits = video.getHits();
        hits = hits + 1;
        video.setHits(hits);
        try {
            VideoLocalServiceUtil.updateVideo(video);
        } catch (SystemException e) {
        }

        //check password access
        if (secLink == false) {
            if (video.getOpenAccess() == 1)
                video.setAccessPermitted(1);
            else
                video.setAccessPermitted(2);
        } else {
            //access denied by default
            video.setAccessPermitted(0);

            //1. authentication by lecture series password
            try {
                if (password.equals(lectureseries.getPassword()))
                    video.setAccessPermitted(1);
                else
                    video.setAccessPermitted(0);
            } catch (Exception e) {
            }

            //2. authentication by cookie
            Cookie[] c = request.getCookies();
            try {
                for (int i = 0; i < c.length; i++) {
                    Cookie coo = c[i];
                    String cooVal = "";
                    if (coo.getName().equals("L2G_LSID"))
                        cooVal = c[i].getValue();
                    //has been already logged in
                    if (cooVal.equals(video.getLectureseriesId() + "")) {
                        video.setAccessPermitted(1);
                    }
                }
            } catch (java.lang.NullPointerException e) {
                System.out.print(e);
            }

            //3. authentication by video password
            if (!video.getPassword().isEmpty()) {
                try {
                    if (password.equals(video.getPassword())) {
                        video.setAccessPermitted(1);
                    } else {
                        video.setAccessPermitted(0);
                    }
                } catch (Exception e) {
                    video.setAccessPermitted(0);
                }
            }
        }

        request.setAttribute("videoLicense", l);
        request.setAttribute("videoMetadata", m);
        request.setAttribute("videoInstitutions", vi);
        request.setAttribute("videoLectureseries", vl);
        request.setAttribute("video", video);
        request.setAttribute("relatedVideos", relatedVideos);
        request.setAttribute("segments", segments);
        request.setAttribute("lectureseries", lectureseries);
        request.setAttribute("timeStart", timeStart);
        request.setAttribute("timeEnd", timeEnd);
        request.setAttribute("objectType", objectType);
        request.setAttribute("objectId", oid);

        if (video.getVideoId() == 0)
            response.setRenderParameter("jspPage", "/guest/noVideosFound.jsp");
        else
            response.setRenderParameter("jspPage", "/guest/videoDetails.jsp");
    }
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

/** 
  * Recupera la informacin almacenada en una cookie
  * @param nombre: nombre de la cookie/*from   ww w .j  av a2s .com*/
  * @param cookies: cookies
  */
Cookie getCookie(String name, Cookie[] cookies) {
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals(name))
                return cookie;
        }
    }

    return new Cookie(name, "");
}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP// w w  w . ja v a2 s  .  c  o m
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @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 {
    try {
        String raceFleetKeyStr = request.getParameter("RaceFleetKey");
        if (raceFleetKeyStr == null) {
            throw new ServletException("no RaceFleetKey");
        }
        Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr);
        Entity raceFleetEntity = datastore.get(raceFleetKey);
        Key raceSeriesKey = raceFleetKey.getParent();
        Entity raceseriesEntity = datastore.get(raceSeriesKey);
        RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity);
        RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity);
        RaceEntry raceEntry = new RaceEntry(raceFleet);
        raceEntry.populate(request.getParameterMap());

        String fn = request.getParameter(RaceEntry.FIRSTNAME);
        String ln = request.getParameter(RaceEntry.LASTNAME);
        raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln);

        String sa = request.getParameter(RaceEntry.STREETADDRESS);
        String zc = request.getParameter(RaceEntry.ZIPCODE);
        String ct = request.getParameter(RaceEntry.CITY);
        String cn = request.getParameter(RaceEntry.COUNTRY);
        if (cn == null || cn.isEmpty()) {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct);
        } else {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn);
        }

        Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate);
        Number fee = 0.0;
        if (closingDay != null) {
            Day now = new Day();
            if (closingDay.before(now)) {
                fee = (Number) raceFleet.get(RaceFleet.Fee2);
            } else {
                fee = (Number) raceFleet.get(RaceFleet.Fee);
            }
        }
        Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT);
        String clubname = repositoryBundle.getString("Clubname");
        if (clubDiscount != null && clubDiscount
                && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) {
            fee = new Double(0);
        }
        raceEntry.set(RaceEntry.FEE, fee);
        raceEntry.set(RaceEntry.TIMESTAMP, new Date());

        entities.put(raceEntry);

        String payingInstructions = "";
        String payingInstructionsHtml = "";
        BankingBarcode bb = races.getBarcode(raceEntry);
        if (bb != null) {
            Day dueDay = new Day(bb.getDueDate());
            String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8");
            String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8");
            payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode
                    bb.getAccount().getIBAN(), // 2 = account
                    bb.getReference().toFormattedRFString(), // 3 = ref
                    dueDay, // 4 = due date
                    String.format("%.2f", bb.getTotal()), // 5 = total
                    bic // 6 = bic
            );
            payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"),
                    "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode
                    "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account
                    "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref
                    "<span id='due'>" + dueDay + "</span>", // 4 = due date
                    "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total
                    "<span id='bic'>" + bic + "</span>" // 6 = bic
            );
        }
        URL base = new URL(request.getRequestURL().toString());
        URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString());
        String name = (String) raceEntry.get(RaceEntry.HELMNAME);
        String email = (String) raceEntry.get(RaceEntry.HELMEMAIL);
        String confirmation = msg(Messages.RACEENTRYCONFIRMATION);
        String plainMessage = "";
        String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation)
                + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src="
                + barcodeUrl.toString() + "/>" + "</body></html>";
        if (email != null) {
            InternetAddress recipient = new InternetAddress(email, name);
            String senderStr = msg(Messages.RACEENTRYFROMADDRESS);
            InternetAddress sender;
            try {
                sender = new InternetAddress(senderStr);
                plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields();

                String subject = msg(Messages.RACEENTRYSUBJECT);
                mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient);
            } catch (Exception ex) {
                log(senderStr, ex);
            }
        }
        Cookie cookie = null;
        Cookie[] cookies = null;
        if (useCookies) {
            cookies = request.getCookies();
        }
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if (COOKIENAME.equals(ck.getName())) {
                    cookie = ck;
                }
            }
        }
        JSONObject json = null;
        if (useCookies && cookie != null) {
            Base64 decoder = new Base64();
            String str = new String(decoder.decode(cookie.getValue()));
            json = new JSONObject(str);
        } else {
            json = new JSONObject();
        }
        for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            String property = entry.getKey();
            String[] values = entry.getValue();
            if (values.length == 1) {
                json.put(property, values[0]);
            }
        }
        Base64 encoder = new Base64();
        String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8"));
        if (useCookies) {
            if (cookie == null) {
                cookie = new Cookie(COOKIENAME, base64);
                cookie.setPath("/");
                cookie.setMaxAge(400 * 24 * 60 * 60);
            } else {
                cookie.setValue(base64);
            }
            response.addCookie(cookie);
        }
        sendError(response, HttpServletResponse.SC_OK,
                "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>");
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eJSON\">Internal error.</div>");
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eEntityNotFound\">Internal error.</div>");
    } catch (NumberFormatException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>");
    }
}

From source file:com.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java

public XWikiUser checkAuth(XWikiContext context) throws XWikiException {
    Cookie cookie;//from   w w  w.ja  va2  s.c  o m

    LOG.debug("checkAuth");

    LOG.debug("Action: " + context.getAction());
    if (context.getAction().startsWith("logout")) {
        cookie = getCookie("XWIKINTLMAUTHINFO", context);
        if (cookie != null) {
            cookie.setMaxAge(0);
            context.getResponse().addCookie(cookie);
        }

        return null;
    }

    Principal principal = null;

    Cookie[] cookies = context.getRequest().getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            LOG.debug("CookieList: " + c.getName() + " => " + c.getValue());
        }
    }

    cookie = getCookie("XWIKINTLMAUTHINFO", context);
    if (cookie != null) {
        LOG.debug("Found Cookie");
        String uname = decryptText(cookie.getValue(), context);
        if (uname != null) {
            principal = new SimplePrincipal(uname);
        }
    }

    String msg = context.getRequest().getHeader("Authorization");
    if (msg != null) {
        LOG.debug("Found NTLM Auth Cookie, this could be an IE6 bug (#831167)");
        if (msg.startsWith("NTLM ")) {
            LOG.debug("Removing principal because of NTLM header");
            principal = null;
        }
    }

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(null, null, context);
        if (principal == null) {
            LOG.debug("Can't get principal");
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie("XWIKINTLMAUTHINFO", encuname);
        usernameCookie.setMaxAge(-1);
        usernameCookie.setPath("/");
        context.getResponse().addCookie(usernameCookie);

        user = new XWikiUser(principal.getName());
    } else {
        user = new XWikiUser(principal.getName().startsWith(context.getDatabase())
                ? principal.getName().substring(context.getDatabase().length() + 1)
                : principal.getName());
    }

    LOG.debug("XWikiUser=" + user);

    return user;
}

From source file:fr.paris.lutece.plugins.mylutece.modules.oauth.authentication.OAuthAuthentication.java

/**
 * Finds a cookie by its name/*ww  w.ja v a 2s. co m*/
 * @param request the request
 * @param strKey the cookie name
 * @return the cookie found, <code>null</code> otherwise.
 */
private Cookie findCookie(HttpServletRequest request, String strKey) {
    if (StringUtils.isBlank(strKey)) {
        return null;
    }

    for (Cookie cookie : request.getCookies()) {
        if (strKey.equals(cookie.getName())) {
            return cookie;
        }
    }

    return null;
}

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 .  jav a  2s .c  o m
    String fileName = "";
    int f = 0;
    String action = "";
    String first = request.getParameter("first");
    String user = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                user = cookie.getValue();
        }
    }
    String title = request.getParameter("title");
    String header = request.getParameter("header");
    String text_field = request.getParameter("text_field");

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (!rs.next()) {

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

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

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

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

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

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

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

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

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

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

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