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:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Adds a cookie to the response.//  w ww  .  ja v  a2s.  c om
 * 
 * @param response The servlet response.
 * @param cookie The cookie to be sent.
 */
private void addCookie(HttpServletResponse response, Cookie cookie) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Adding cookie: " + cookie.getDomain() + cookie.getPath() + " " + cookie.getName() + "="
                + cookie.getValue());
    }
    // We don't use the container's response.addCookie, since the HttpOnly cookie flag was introduced only recently
    // in the servlet specification, and we're still using the older 2.4 specification as a minimal requirement for
    // compatibility with as many containers as possible. Instead, we write the cookie manually as a HTTP header.
    StringBuilder cookieValue = new StringBuilder(150);
    cookieValue.append(cookie.getName() + "=");
    if (StringUtils.isNotEmpty(cookie.getValue())) {
        cookieValue.append("\"" + cookie.getValue() + "\"");
    }
    cookieValue.append("; Version=1");
    if (cookie.getMaxAge() >= 0) {
        cookieValue.append("; Max-Age=" + cookie.getMaxAge());
        // IE is such a pain, it doesn't understand the modern, safer Max-Age
        cookieValue.append("; Expires=");
        if (cookie.getMaxAge() == 0) {
            cookieValue.append(COOKIE_EXPIRE_NOW);
        } else {
            cookieValue.append(COOKIE_EXPIRE_FORMAT
                    .format(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L)));
        }
    }
    if (StringUtils.isNotEmpty(cookie.getDomain())) {
        // IE needs toLowerCase for the domain name
        cookieValue.append("; Domain=" + cookie.getDomain().toLowerCase());
    }
    if (StringUtils.isNotEmpty(cookie.getPath())) {
        cookieValue.append("; Path=" + cookie.getPath());
    }
    // Protect cookies from being used from JavaScript, see http://www.owasp.org/index.php/HttpOnly
    cookieValue.append("; HttpOnly");

    // Session cookies should be discarded.
    // FIXME Safari 5 can't handle properly "Discard", as it really discards all the response header data after the
    // first "Discard" encountered, so it will only see the first such cookie. Disabled for the moment until Safari
    // gets fixed, or a better idea comes to mind.
    // Since we don't set a Max-Age, the rfc2109 behavior will kick in, and recognize this as a session cookie.
    // if (cookie.getMaxAge() < 0) {
    // cookieValue.append("; Discard");
    // }
    response.addHeader("Set-Cookie", cookieValue.toString());
}

From source file:com.portfolio.data.attachment.FileServlet.java

String[] processCookie(Cookie[] cookies) {
    String login = null;/* w  w w. j  a va2s.c o  m*/
    String[] ret = { login };
    if (cookies == null)
        return ret;

    for (int i = 0; i < cookies.length; ++i) {
        Cookie cookie = cookies[i];
        String name = cookie.getName();
        if ("user".equals(name) || "useridentifier".equals(name))
            login = cookie.getValue();
    }

    ret[0] = login;
    return ret;
}

From source file:org.apache.jsp.sources_jsp.java

public static String getBrowserInfiniteCookie(HttpServletRequest request) {
       Cookie[] cookieJar = request.getCookies();
       if (cookieJar != null) {
           for (Cookie cookie : cookieJar) {
               if (cookie.getName().equals("infinitecookie")) {
                   return cookie.getValue() + ";";
               }//  w w  w  .  j  av a 2  s  .  com
           }
       }
       return null;
   }

From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java

/**
 * ????// w  w  w .ja v  a2 s.c om
 * @param request
 */
private void dealCoremailUserName(HttpServletRequest request) {
    Cookie[] cs = request.getCookies();
    if (cs != null) {
        for (Cookie c : cs) {
            if ("passport.remember.user".equals(c.getName())) {
                if (StringUtils.isNotEmpty(c.getValue())) {
                    request.setAttribute("userName", c.getValue());
                }
            }
        }
    }
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession locateSession(UrlHolder holder, HttpServletRequest request, ServletContext ctx,
        String cookieName, HttpServletResponse resp) throws Exception {
    Cookie sessionCookie = null;/*  www . java 2s.  co m*/

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equalsIgnoreCase(cookieName)) {
                sessionCookie = cookie;
                break;
            }
        }
    }

    ConfigManager cfg = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG);

    ApplicationType app;

    if (holder != null) {
        app = holder.getApp();
    } else {
        app = null;

        String appName = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("autoIdmAppName")) {
                    appName = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                    break;
                }
            }
        }

        if (appName == null) {
            // TODO create open session
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName()
                            .equals(cfg.getCfg().getApplications().getOpenSessionCookieName())) {
                        String sessionID = cookies[i].getValue();
                        TremoloHttpSession tsession = this.sessions.get(sessionID);
                        // TODO add timeouts
                        if (tsession == null) {
                            return this.createOpenSession(request, resp, ctx);
                        } else {
                            return tsession;
                        }

                    }
                }
            }

            return createOpenSession(request, resp, ctx);
        } else {
            app = cfg.getApp(appName);

            if (app == null) {
                throw new Exception("No application named '" + appName + "' found");
            }

        }
    }

    SecretKey encKey = cfg.getSecretKey(app.getCookieConfig().getKeyAlias());

    // TremoloHttpSession tsession = (TremoloHttpSession)
    // request.getSession().getAttribute(app.getCookieConfig().getSessionCookieName());

    if (sessionCookie == null) {
        // if (tsession != null) tsession.invalidate();
        return createSession(app, request, resp, ctx, encKey);
    } else {

        HttpSession session = null;

        try {

            try {

                TremoloHttpSession tsession = findSessionFromCookie(sessionCookie, encKey, this);

                if (tsession == null) {
                    return createSession(app, request, resp, ctx, encKey);
                }

                String fromSessionID = (String) tsession.getAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID);

                if (app.getCookieConfig().getTimeout() > 0) {
                    DateTime lastAccessed = (DateTime) tsession
                            .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED);
                    DateTime now = new DateTime();
                    if (now.minusSeconds(app.getCookieConfig().getTimeout()).isAfter(lastAccessed)) {
                        tsession.invalidate();
                        return createSession(app, request, resp, ctx, encKey);
                    } else {
                        tsession.setAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED, now);
                        session = tsession;
                    }
                } else {
                    session = tsession;
                }

            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Exception loading session", e);
                }
                return createSession(app, request, resp, ctx, encKey);

            }

            // this.sessions.put(session.getSessionID(), key);
            // }

        } catch (Exception e) {
            logger.error("Error generating session", e);
        }
        if (session == null) {
            // session.invalidate();
            return createSession(app, request, resp, ctx, encKey);
        }

        // session.resetAccess();

        return session;

    }
}

From source file:EditForm.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // change the following parameters to connect to the oracle database
    String photo_id = request.getQueryString();

    PrintWriter out = response.getWriter();

    // Check to makes sure the user is logged in
    String userid = "";
    Cookie login_cookie = null;/* ww w  .j a v a2  s .c  o  m*/
    Cookie cookie = null;
    Cookie[] cookies = null;
    // Get an array of cookies associated with this domain
    cookies = request.getCookies();
    // If any cookies were found, see if any of them contain a valid login.
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            // out.println(cookie.getName()+"<br>");
            // However, we only want one cookie, the one whose name matches
            // the
            // userid that has logged in on this browser.
            if (i != 0 && userid == "") {
                userid = cookie.getName();
            }
        }
    }
    // If no login was detected, redirect the user to the login page.
    if (userid == "") {
        out.println("<a href=login.jsp>Please login to access this site.</a>");
    }
    // Else, we have a valid session.
    else {

        out.println("<html><body><head><title>Edit Image</title></head><body ><P>");
        out.println("<form name=\"EditForm\" method=\"POST\" action=\"EditImage?" + photo_id + "\"><table>");
        out.println("<tr><td> Subject: <td> <input type=text size=20 name=subject>");
        out.println(
                "<tr><td alian = right>  Location: </td><td alian = left> <input type=text size=20 name=place></td></tr>");
        out.println("<tr><td alian = right>  Date: </td><td alian = left> <script type=\"text/javascript\""
                + " src=\"http://www.snaphost.com/jquery/Calendar.aspx?dateFormat=yy-mm-dd\"></script></script> &nbsp;</td></tr>");
        out.println(
                "<tr><td alian = right>  Description: </td><td alian = left> <textarea name=description rows=10 cols=30></textarea></td></tr>");

        out.println("<tr><td alain = right>     Who Can See This Photo:");
        out.println(
                "<td>Everyone <input class=\"everyone\" name = \"permission\" type=\"radio\" id=\"everyone\" value=\"everyone\">");
        out.println(
                "Only Me <input class=\"useronly\" name = \"permission\" type=\"radio\" id=\"useronly\" value=\"useronly\">");
        out.println(
                "Specific Group <input class=\"conditional_form_part_activator\" name = \"permission\" type=\"radio\" id=\"group\" value=\"group\">");

        out.println(
                "<div class=\"conditional_form_part\">Group Name: <input class=\"groupname\" type=text size=20 name=\"groupName\"></td></select> </div></tr></td>");

        out.println(
                "<tr><td alian = center colspan=\"2\"><input type = submit value = \"Update Image\"></td></tr></form></table></body></html>");
    }

}

From source file:com.traffitruck.web.HtmlController.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        chain.doFilter(request, response);
    } else {//from   ww w  .j a  v  a  2  s  . c o m
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(HtmlController.DEVICE_REGISTRATION_COOKIE_NAME)
                    && cookie.getValue() != null) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication != null) {
                    String username = authentication.getName();
                    LoadsUser user = dao.getUser(username);
                    if (user != null && user.getRoles() != null) {
                        boolean isTruckOwner = false;
                        for (Role role : user.getRoles()) {
                            if (Role.TRUCK_OWNER.equals(role)) {
                                isTruckOwner = true;
                            }
                        }
                        if (isTruckOwner) {
                            dao.addDevice(username, cookie.getValue());
                        }
                        setSessionCookie((HttpServletResponse) response, "", DELETE_COOKIE);
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}

From source file:com.openvcx.webcall.ConferenceCreateServlet.java

/**
 * <p>Lookup a client conference number stored in a cookie. If no phone number is provided by the client a random SIP URI phone number is automatically generated.</p>
 * <p>A conference definition template file is used to create the conference definition for the phone number.</p>
 * <p>The auto-assigned phone number is then stored in a cookie and returned to the client.</p>
 * @param out standard output Output writer
 * @param request The HTTP request object
 * @param response The HTTP response object
 */// w ww  .j  a va  2  s. c  o m
private boolean doCreateNumber(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String strOutputNumber = null;

    Cookie[] arrCookies = request.getCookies();
    if (null != arrCookies) {
        for (Cookie cookie : arrCookies) {
            //logger.debug("cookie name: " + cookie.getName() + ", path: " + cookie.getPath() + ", domain: " + cookie.getDomain() + ", maxAge: " + cookie.getMaxAge() + ", value: " + cookie.getValue());
            if (COOKIE_NUMBER_KEY.equals(cookie.getName())) {
                if (null != (strOutputNumber = cookie.getValue()) && strOutputNumber.length() == 0) {
                    strOutputNumber = null;
                }
                logger.debug("Using cookie stored conference output number: '" + strOutputNumber + "'.");
                break;
            }
        }
    }

    strOutputNumber = createConferenceDefinition(strOutputNumber);

    if (null != strOutputNumber) {

        int cookieAgeDays = 7;
        Cookie cookie = new Cookie(COOKIE_NUMBER_KEY, strOutputNumber);
        cookie.setMaxAge(cookieAgeDays * SECONDS_IN_DAY);
        cookie.setPath("/" + getUriDirSegment(request.getRequestURI(), 0) + "/");
        logger.debug("Setting cookie " + COOKIE_NUMBER_KEY + "=" + strOutputNumber);
        response.addCookie(cookie);
        out.println("number=" + strOutputNumber);
    }

    return true;
}

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

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request/*from ww w  . j  av  a2s  .  co  m*/
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}