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.adito.security.DefaultLogonController.java

public int hasClientLoggedOn(HttpServletRequest request, HttpServletResponse response)
        throws SecurityErrorException {
    // Get the logon cookie
    String logonCookie = null;//from   w  w w  .  j av a2 s .  c o m
    if (request.getCookies() != null) {
        for (int i = 0; i < request.getCookies().length; i++) {
            Cookie cookie = request.getCookies()[i];
            if (cookie.getName().equals(Constants.LOGON_TICKET)
                    || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) {
                logonCookie = cookie.getValue();
            }
        }
    }
    // If there is a logon ticket in the requests attributes then reassign
    // as we've just been issued a new ticket.
    if (request.getAttribute(Constants.LOGON_TICKET) != null)
        logonCookie = (String) request.getAttribute(Constants.LOGON_TICKET);
    // First check the users session for a logonticket
    String sessionLogonTicket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET);
    if (sessionLogonTicket != null) {
        // Make sure we are still receiving the logon ticket
        /**
         * LDP - Users are having too many issues with this change. If we
         * still have a ticket in the session then the HTTP session must
         * still be alive and the the cookie has simply expired before the
         * HTTP session (or the browser has elected not to send it). We
         * should allow this to continue and refresh the cookie here.
         */
        /*
         * if(logonCookie == null &&
         * request.getAttribute(Constants.LOGON_TICKET) == null) {
         * 
         * 
         * log.warn("Lost logon ticket. It is likely that logon cookie has
         * expired. "); return INVALID_TICKET; } else
         */
        if (logonCookie == null) {

            SessionInfo session = getSessionInfo(sessionLogonTicket);
            if (session == null)
                return NOT_LOGGED_ON;
            addCookies(new ServletRequestAdapter(request), new ServletResponseAdapter(response),
                    sessionLogonTicket, session);
        }
        // Still check that the cookie is what we expect it to be
        if (logonCookie != null && !sessionLogonTicket.equals(logonCookie)) {
            log.warn("Expected a different logon ticket.");
            return NOT_LOGGED_ON;
        }

        if (checkRemoteAddress(sessionLogonTicket, request.getRemoteAddr())) {
            return LOGGED_ON;
        }
    } else {
        if (logonCookie != null && logons.containsKey(logonCookie)) {
            if (checkRemoteAddress(logonCookie, request.getRemoteAddr())) {
                refreshLogonTicket(request, response, logonCookie);
                return LOGGED_ON;
            }
        }
    }
    return NOT_LOGGED_ON;
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpFields.java

/** Format a set cookie value
 * @param cookie The cookie.//from  ww  w.  j a v a  2  s  .co m
 */
public void addSetCookie(Cookie cookie) {
    String name = cookie.getName();
    String value = cookie.getValue();
    int version = cookie.getVersion();

    // Check arguments
    if (name == null || name.length() == 0)
        throw new IllegalArgumentException("Bad cookie name");

    // Format value and params
    StringBuffer buf = new StringBuffer(128);
    String name_value_params = null;
    synchronized (buf) {
        buf.append(name);
        buf.append('=');
        if (value != null && value.length() > 0) {
            if (version == 0)
                URI.encodeString(buf, value, "\";, '");
            else
                buf.append(QuotedStringTokenizer.quote(value, "\";, '"));
        }

        if (version > 0) {
            buf.append(";Version=");
            buf.append(version);
            String comment = cookie.getComment();
            if (comment != null && comment.length() > 0) {
                buf.append(";Comment=");
                QuotedStringTokenizer.quote(buf, comment);
            }
        }
        String path = cookie.getPath();
        if (path != null && path.length() > 0) {
            buf.append(";Path=");
            buf.append(path);
        }
        String domain = cookie.getDomain();
        if (domain != null && domain.length() > 0) {
            buf.append(";Domain=");
            buf.append(domain.toLowerCase());// lowercase for IE
        }
        long maxAge = cookie.getMaxAge();
        if (maxAge >= 0) {
            if (version == 0) {
                buf.append(";Expires=");
                if (maxAge == 0)
                    buf.append(__01Jan1970);
                else
                    formatDate(buf, System.currentTimeMillis() + 1000L * maxAge, true);
            } else {
                buf.append(";Max-Age=");
                buf.append(cookie.getMaxAge());
            }
        } else if (version > 0) {
            buf.append(";Discard");
        }
        if (cookie.getSecure()) {
            buf.append(";Secure");
        }
        if (cookie instanceof HttpOnlyCookie)
            buf.append(";HttpOnly");

        name_value_params = buf.toString();
    }
    put(__Expires, __01Jan1970);
    add(__SetCookie, name_value_params);
}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Removes the cookie with the given name from the request
 * @param name the name of a cookie/*from  w w w .  j a v  a2 s .co m*/
 */
public void removeCookie(String name) {
    if (name == null || "".equals(name)) {
        throw new IllegalArgumentException("name cannot be null");
    }
    for (Iterator<Cookie> iterator = cookies.iterator(); iterator.hasNext();) {
        Cookie c = iterator.next();
        if (name.equals(c.getName())) {
            iterator.remove();
        }
    }
}

From source file:com.kodemore.servlet.ScServletData.java

private Cookie _getCookie(String name) {
    for (Cookie e : _getCookies())
        if (e.getName().equals(name))
            return e;
    return null;/*from   w w w .j  a  v  a 2s  .co  m*/
}

From source file:com.kodemore.servlet.ScServletData.java

private KmList<Cookie> _getCookies() {
    KmMap<String, Cookie> m = new KmMap<>();

    Cookie[] cookies = _getRequest().getCookies();
    if (cookies != null)
        for (Cookie e : cookies)
            m.put(e.getName(), e);

    for (Cookie e : _setCookies.getValues())
        m.put(e.getName(), e);/*from w w  w. j  a v a 2 s.  com*/

    KmList<Cookie> v = new KmList<>();
    for (Cookie e : m.getValues())
        if (Kmu.isNotEqual(e.getValue(), REMOVED_COOKIE_VALUE))
            v.add(e);

    return v;
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) {
        String domain = commonsCookie.getDomain();

        if (Validator.isNotNull(domain)) {
            cookie.setDomain(domain);//from   w  ww  .  ja  v a2 s .  com
        }
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}

From source file:de.micromata.genome.gwiki.page.GWikiContext.java

/**
 * Gets the cookie.//w  w  w  . j  a v  a 2s  .  c o  m
 *
 * @param key the key
 * @param defaultValue the default value
 * @return the cookie
 */
@SuppressWarnings("deprecation")
public String getCookie(String key, String defaultValue) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return defaultValue;
    }
    for (Cookie co : cookies) {
        if (StringUtils.equals(key, co.getName()) == true) {
            String sv = co.getValue();
            sv = URLDecoder.decode(sv);
            return sv;
        }
    }

    return defaultValue;
}

From source file:com.kodemore.servlet.ScServletData.java

/**
 * The cookie should be a new instance that contains the correct
 * values for name, domain, and path./*from w  w  w.  j ava 2 s. c  o  m*/
 */
public void _setCookie(Cookie c) {
    // Note: the http response is updated in flushResult()
    _setCookies.put(c.getName(), c);
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    String format;//from   ww  w. ja  va2 s .c o  m
    String language;
    String redirect_url;

    this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo());
    this.logger.debug("QueryString = " + httpServletRequest.getQueryString());

    String service = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    String[] params = path.substring(1, path.length()).split("/");

    if (params.length == 1) {
        service = params[0];
    }

    format = "html";
    language = "";

    // Hole 'Accept' und 'Authorization' aus dem Header;
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = (String) headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Accept")) {

            this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

            if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                format = "html";
            } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                format = "xml";
            } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                format = "json";
            }
        }
        if (headerNameKey.equals("Accept-Language")) {
            language = httpServletRequest.getHeader(headerNameKey);
            this.logger.debug("Accept-Language: " + language);
        }
        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.debug("Service: " + service);

    if (httpServletRequest.getParameter("format") != null
            && !httpServletRequest.getParameter("format").equals("")) {

        format = httpServletRequest.getParameter("format");
    }

    this.logger.info("format = " + format);

    if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) {

        this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format, language, "");
    } else {

        // redirect_url
        redirect_url = "";

        if (httpServletRequest.getParameter("redirect_url") != null
                && !httpServletRequest.getParameter("redirect_url").equals("")) {

            if (httpServletRequest.getParameter("redirect_url").contains("redirect_url=")) {
                String tmp[] = httpServletRequest.getParameter("redirect_url").split("redirect_url=");

                redirect_url = tmp[0] + "redirect_url=" + URLEncoder.encode(tmp[1], "UTF-8");
            } else {
                redirect_url = httpServletRequest.getParameter("redirect_url");
            }
        }

        this.logger.info("redirect_url = " + redirect_url);

        // language
        if (language.startsWith("de")) {
            language = "de";
        } else if (language.startsWith("en")) {
            language = "en";
        } else if (httpServletRequest.getParameter("l") != null) {
            language = httpServletRequest.getParameter("l");
        } else {
            language = "de";
        }

        this.logger.info("language = " + language);

        if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null) {

            authorization = httpServletRequest.getParameter("access_token");
        }

        if (authorization.equals("")) {

            // if exists PaiaService-Cookie: read content
            Cookie[] cookies = httpServletRequest.getCookies();

            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("PaiaService")) {

                        String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                        this.logger.info(value);
                        LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                        authorization = loginResponse.getAccess_token();

                        break;
                    }
                }
            }
        }

        this.logger.debug("Access_token: " + authorization);

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = httpServletRequest.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
            /*report an error*/ }

        String requestBody = jb.toString();

        this.logger.info(requestBody);

        httpServletResponse.setHeader("Access-Control-Allow-Origin",
                this.config.getProperty("Access-Control-Allow-Origin"));
        httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control"));

        // 2. Schritt: Service
        if (service.equals("login") || service.equals("logout") || service.equals("change")
                || service.equals("renew")) {

            this.provideService(httpServletRequest, httpServletResponse, service, authorization, requestBody,
                    format, language, redirect_url);
        } else {

            this.logger.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service
                    + "' not allowed!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
            requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }
    }
}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Adds a new cookie to the request/*ww w  .jav a  2s  . c  o m*/
 * @param cookie a cookie to add, will displace existing cookies with the same name
 */
public void addCookie(Cookie cookie) {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie cannot be null");
    }
    for (Iterator<Cookie> iterator = cookies.iterator(); iterator.hasNext();) {
        Cookie c = iterator.next();
        if (cookie.getName().equals(c.getName())) {
            iterator.remove();
        }
    }
    cookies.add(cookie);
}