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.google.identitytoolkit.GitkitClient.java

private String lookupCookie(HttpServletRequest request, String cookieName) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }//www .jav a 2s  .co m
    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:com.google.acre.script.AcreRequest.java

@SuppressWarnings("unchecked")
public AcreRequest(AcreHttpServletRequest request) throws IOException {

    _request = request;//from   w w  w.j  a  va 2  s.  c  om

    request_start_time = new Date();
    headers = new HashMap<String, Object>();
    cookies = new HashMap<String, AcreCookie>();
    version = Configuration.Values.ACRE_VERSION.getValue();
    server = OneTrueServlet.getServer();

    if (server.indexOf("jetty") > -1) {
        server_type = "acre_server";
    } else if (server.indexOf("app engine") > -1) {
        if (server.indexOf("development") > -1) {
            server_type = "appengine_development";
        } else {
            server_type = "appengine";
        }
    } else {
        server_type = server;
    }

    trusted = Configuration.Values.ACRE_TRUSTED_MODE.getBoolean();
    skip_routes = false;
    _metaweb_tid = (String) request.getAttribute("X-Metaweb-TID");

    String urlstr = request.getRequestURL().toString();

    server_name = request.getHeader("X-Forwarded-Host");
    if (server_name == null)
        server_name = request.getHeader("Host");

    String quotas_str = request.getHeader(HostEnv.ACRE_QUOTAS_HEADER);

    long max_deadline = System.currentTimeMillis() + Configuration.Values.ACRE_REQUEST_MAX_TIME.getInteger();
    if (quotas_str == null) {
        _deadline = max_deadline;
        _has_quotas = false;
    } else {
        Map<String, String> quotas = parseQuotas(quotas_str);
        _has_quotas = true;
        try {
            long deadline = Long.parseLong(quotas.get("td"));
            _deadline = Math.min(max_deadline, deadline);
        } catch (NumberFormatException e) {
            _deadline = max_deadline;
        }
        _reentries = quotas.containsKey("r") ? Integer.parseInt(quotas.get("r")) : 0;
    }

    Matcher m = hostValidator.matcher(server_name);
    if (!m.matches()) {
        throw new IOException("Host name '" + server_name + "' contains invalid characters");
    }

    request_method = request.getMethod();

    server_protocol = request.getHeader("X-Forwarded-Proto");
    if (server_protocol == null)
        server_protocol = request.getScheme();

    request_server_name = request.getHeader("X-Untransformed-Host");

    query_string = request.getQueryString();

    StringBuilder b = new StringBuilder();
    b.append(server_protocol);
    b.append("://");
    b.append(request_server_name);
    request_app_url = b.toString();
    request_base_url = request_app_url + "/";
    // XXX - shouldn't we be adding request_server_port here?

    // XXX - shouldn't this be request.getPathInfo() instead?
    b.append((new URL(urlstr)).getPath());
    if (query_string != null) {
        b.append('?');
        b.append(query_string);
    }
    request_url = b.toString();

    if (query_string == null) {
        query_string = "";
    }

    Server sinfo = splitHostAndPort(server_name);
    Server osinfo = splitHostAndPort(request_server_name);

    server_name = sinfo.name;
    server_port = sinfo.port;
    request_server_name = osinfo.name;
    request_server_port = osinfo.port;

    path_info = request.getPathInfo();
    request_path_info = request.getRequestPathInfo();

    String content_type = null;
    for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
        String hname = e.nextElement().toLowerCase();
        Enumeration<String> hvalue = request.getHeaders(hname);

        Object new_entry = null;
        for (; hvalue.hasMoreElements();) {
            String hval = hvalue.nextElement();
            if (hvalue.hasMoreElements() && new_entry == null) {
                new_entry = new ArrayList<String>();
                ((ArrayList<String>) new_entry).add(hval);
            } else {
                if (new_entry == null) {
                    new_entry = hval;
                } else {
                    ((ArrayList<String>) new_entry).add(hval);
                }
            }
        }
        if (hname.equalsIgnoreCase("content-type")) {
            if (new_entry instanceof ArrayList) {
                content_type = (String) ((ArrayList<?>) new_entry).get(0);
            } else {
                content_type = (String) new_entry;
            }
        }
        headers.put(hname, new_entry);

    }

    if (request_method.equals("POST") || request_method.equals("PUT")) {
        // NOTE(SM): we can't use request.getReader() because
        // if a previous servlet in the chain called getParameter 
        // during a POST, jetty calls getInputStream to obtain
        // the parameter and then a call to the reader will throw
        InputStream is = request.getInputStream();

        if (content_type != null
                && (content_type.startsWith("image/") || content_type.startsWith("application/octet-stream")
                        || content_type.startsWith("multipart/form-data"))) {
            byte[] data = IOUtils.toByteArray(is);

            request_body = new JSBinary();
            ((JSBinary) request_body).set_data(data);
            is.close();
        } else {
            String encoding = request.getCharacterEncoding();
            if (encoding == null)
                encoding = "ISO_8859_1";
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, encoding));
            StringBuilder buf = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buf.append(line);
                buf.append("\n");
            }
            String body = buf.toString();
            reader.close();

            // this following code is because of this bug in local AppEngine
            //  http://code.google.com/p/googleappengine/issues/detail?id=5396
            // which fails to provide a readable getInputStream() on a regular 
            // urlencoded POST, so we re-encode it ourselves. It's a waste
            // but it should only occur during develoment.
            if (body.length() == 0) {
                Map<String, String[]> params = request.getParameterMap();
                Set<Entry<String, String[]>> entries = params.entrySet();
                Iterator<Entry<String, String[]>> iterator = entries.iterator();
                while (iterator.hasNext()) {
                    Entry<String, String[]> e = iterator.next();
                    buf.append(URLEncoder.encode(e.getKey(), encoding));
                    buf.append('=');
                    buf.append(URLEncoder.encode(e.getValue()[0], encoding));
                    if (iterator.hasNext()) {
                        buf.append('&');
                    }
                }
                body = buf.toString();
            }

            request_body = body;
        }
    }

    // XXX fix this when figuring out cookies
    Cookie[] cks = request.getCookies();
    if (cks != null) {
        for (Cookie c : cks) {
            if (c.getName().equals(""))
                continue;
            cookies.put(c.getName(), new AcreCookie(c));
        }
    }

    String user_agent = _request.getHeader("user-agent");
    String log_header = _request.getHeader("x-acre-enable-log");
    if (user_agent != null && user_agent.indexOf("FirePHP") > 0) {
        _logtype = _LOG_FirePHP;
    }
    if (log_header != null) {
        if (!(log_header.toLowerCase().startsWith("firephp"))) {
            _logtype = _logtype | _LOG_JSONBODY;
        } else {
            _logtype = _LOG_FirePHP;
        }
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private String retrieveAuthTokenString(Cookie[] cookies) {

    /* no cookies */
    if (cookies == null)
        return null;
    for (Cookie c : cookies) {
        if (c.getName().equals(ConfigurationListener.getTokenName())) {
            /* found correct cookie */
            return c.getValue();
        }//  w  ww  . j  a va 2s . co m
    }
    return null;
}

From source file:com.google.identitytoolkit.GitkitClient.java

/**
 * Verifies Gitkit token in http request.
 *
 * @param request http request/* w  ww  .  j  a  v a2  s.  c  o  m*/
 * @return Gitkit user if valid token is found in the request.
 * @throws GitkitClientException if there is token but signature is invalid
 */
public GitkitUser validateTokenInRequest(HttpServletRequest request) throws GitkitClientException {
    Cookie[] cookies = request.getCookies();
    if (cookieName == null || cookies == null) {
        return null;
    }

    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return validateToken(cookie.getValue());
        }
    }
    return null;
}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthGitFilter.java

private String generateRandomGerritPassword(String username, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse, FilterChain chain) throws IOException, ServletException {
    log.warn("User " + username + " has not a Gerrit HTTP password: "
            + "generating a random one in order to be able to use Git over HTTP");
    Cookie gerritCookie = getGerritLoginCookie(username, httpRequest, httpResponse, chain);
    String xGerritAuthValue = xGerritAuth.getAuthValue(gerritCookie);

    HttpPut putRequest = new HttpPut(
            getRequestUrlWithAlternatePath(httpRequest, "/accounts/self/password.http"));
    putRequest.setHeader("Cookie", gerritCookie.getName() + "=" + gerritCookie.getValue());
    putRequest.setHeader(XGerritAuth.X_GERRIT_AUTH, xGerritAuthValue);

    putRequest.setEntity(new StringEntity("{\"generate\":true}", ContentType.APPLICATION_JSON));
    HttpResponse putResponse = httpClientProvider.get().execute(putRequest);
    if (putResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ServletException("Cannot generate HTTP password for authenticating user " + username);
    }//from  w  w  w . j  a v a2  s.  co  m

    return accountCache.getByUsername(username).getPassword(username);
}

From source file:com.hangum.tadpole.login.core.dialog.LoginDialog.java

/**
 * initialize cookie data/* w  w w.  j av  a2  s.c  o  m*/
 */
private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        int intCount = 0;
        for (Cookie cookie : cookies) {
            if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
                textEMail.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
                btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
                Locale locale = Locale.forLanguageTag(cookie.getValue());
                comboLanguage.setText(locale.getDisplayLanguage(locale));
                changeUILocale(comboLanguage.getText());
                intCount++;
            }

            if (intCount == 3)
                return;
        }
    }

    // ? ? .
    comboLanguage.select(0);
    changeUILocale(comboLanguage.getText());
}

From source file:com.xwiki.authentication.trustedldap.TrustedLDAPAuthServiceImpl.java

public XWikiUser checkAuthSSO(String username, String password, XWikiContext context) throws XWikiException {
    Cookie cookie;/* www  . j  a v  a 2  s  .  com*/

    LOG.debug("checkAuth");

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

        return null;
    }

    Principal principal = null;

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

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

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(username, password, context);
        if (principal == null) {
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie("XWIKISSOAUTHINFO", 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:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java

private void cookies(MockHttpServletRequest result) {
    String cookieHeaderValue = header("Cookie");
    Cookie[] parentCookies = result.getCookies();
    List<Cookie> cookies = new ArrayList<Cookie>();
    if (cookieHeaderValue != null) {
        StringTokenizer tokens = new StringTokenizer(cookieHeaderValue, "=;");
        while (tokens.hasMoreTokens()) {
            String cookieName = tokens.nextToken().trim();
            if (!tokens.hasMoreTokens()) {
                throw new IllegalArgumentException("Expected value for cookie name " + cookieName
                        + ". Full cookie was " + cookieHeaderValue);
            }/*from www.j  a  v  a2 s  . com*/
            String cookieValue = tokens.nextToken().trim();
            processCookie(result, cookies, new Cookie(cookieName, cookieValue));
        }
    }

    Set<com.gargoylesoftware.htmlunit.util.Cookie> managedCookies = cookieManager
            .getCookies(webRequest.getUrl());
    for (com.gargoylesoftware.htmlunit.util.Cookie cookie : managedCookies) {
        processCookie(result, cookies, new Cookie(cookie.getName(), cookie.getValue()));
    }
    if (parentCookies != null) {
        for (Cookie cookie : parentCookies) {
            cookies.add(cookie);
        }
    }
    if (!cookies.isEmpty()) {
        result.setCookies(cookies.toArray(new Cookie[0]));
    }
}

From source file:com.hangum.tadpole.application.start.dialog.login.LoginDialog.java

/**
 * initialize cookie data// w  ww .jav  a 2  s .c  o  m
 */
private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        int intCount = 0;
        for (Cookie cookie : cookies) {
            if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
                textEMail.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_PWD.equals(cookie.getName())) {
                textPasswd.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
                btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
                comboLanguage.setText(cookie.getValue());
                changeUILocale(comboLanguage.getText());
                intCount++;
            }

            if (intCount == 4)
                break;
        }
    }
}

From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

/**
 * Retrieves the client name from cookieString. If the cookie does not
 * correspond to a valid client, the function returns null.
 * @param cookies HTTP Request cookies.//from   w  w w.ja  v a2s  .  c  om
 * @return Client Username if cookieString has a HS2 Generated cookie that is currently valid.
 * Else, returns null.
 */
private String getClientNameFromCookie(Cookie[] cookies) {
    // Current Cookie Name, Current Cookie Value
    String currName, currValue;

    // Following is the main loop which iterates through all the cookies send by the client.
    // The HS2 generated cookies are of the format hive.server2.auth=<value>
    // A cookie which is identified as a hiveserver2 generated cookie is validated
    // by calling signer.verifyAndExtract(). If the validation passes, send the
    // username for which the cookie is validated to the caller. If no client side
    // cookie passes the validation, return null to the caller.
    for (Cookie currCookie : cookies) {
        // Get the cookie name
        currName = currCookie.getName();
        if (!currName.equals(AUTH_COOKIE)) {
            // Not a HS2 generated cookie, continue.
            continue;
        }
        // If we reached here, we have match for HS2 generated cookie
        currValue = currCookie.getValue();
        // Validate the value.
        currValue = signer.verifyAndExtract(currValue);
        // Retrieve the user name, do the final validation step.
        if (currValue != null) {
            String userName = HttpAuthUtils.getUserNameFromCookieToken(currValue);

            if (userName == null) {
                LOG.warn("Invalid cookie token " + currValue);
                continue;
            }
            //We have found a valid cookie in the client request.
            if (LOG.isDebugEnabled()) {
                LOG.debug("Validated the cookie for user " + userName);
            }
            return userName;
        }
    }
    // No valid HS2 generated cookies found, return null
    return null;
}