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:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java

@Test
public void mergeCookie() throws Exception {
    String cookieName = "PARENT";
    String cookieValue = "VALUE";
    MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
            .defaultRequest(get("/").cookie(new Cookie(cookieName, cookieValue))).build();

    Cookie[] cookies = mockMvc.perform(requestBuilder).andReturn().getRequest().getCookies();
    assertThat(cookies, notNullValue());
    assertThat(cookies.length, equalTo(1));
    Cookie cookie = cookies[0];//from w  ww.  j  a v  a2  s. c o  m
    assertThat(cookie.getName(), equalTo(cookieName));
    assertThat(cookie.getValue(), equalTo(cookieValue));
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java

@Test
public void buildRequestCookiesMulti() {
    webRequest.setAdditionalHeader("Cookie", "name=value; name2=value2");

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    Cookie[] cookies = actualRequest.getCookies();
    assertThat(cookies.length, equalTo(2));
    Cookie cookie = cookies[0];//from   w  ww.j a v  a  2s. c  o m
    assertThat(cookie.getName(), equalTo("name"));
    assertThat(cookie.getValue(), equalTo("value"));
    cookie = cookies[1];
    assertThat(cookie.getName(), equalTo("name2"));
    assertThat(cookie.getValue(), equalTo("value2"));
}

From source file:org.apache.solr.client.solrj.impl.BasicHttpSolrClientTest.java

/**
 * Set cookies via interceptor//from w ww  .ja v  a 2 s . co  m
 * Change the request via an interceptor
 * Ensure cookies are actually set and that request is actually changed
 */
@Test
public void testInterceptors() {
    DebugServlet.clear();
    HttpClientUtil.addRequestInterceptor(changeRequestInterceptor);
    HttpClientUtil.addRequestInterceptor(cookieSettingRequestInterceptor);

    final String clientUrl = jetty.getBaseUrl().toString() + "/debug/foo";
    try (HttpSolrClient server = getHttpSolrClient(clientUrl)) {

        SolrQuery q = new SolrQuery("foo");
        q.setParam("a", "\u1234");
        try {
            server.query(q, random().nextBoolean() ? METHOD.POST : METHOD.GET);
        } catch (Throwable t) {
        }

        // Assert cookies from UseContextCallback 
        assertNotNull(DebugServlet.cookies);
        boolean foundCookie = false;
        for (javax.servlet.http.Cookie cookie : DebugServlet.cookies) {
            if (cookieName.equals(cookie.getName()) && cookieValue.equals(cookie.getValue())) {
                foundCookie = true;
                break;
            }
        }
        assertTrue(foundCookie);

        // Assert request changes by ChangeRequestCallback
        assertEquals("\u1234", DebugServlet.parameters.get("a")[0]);
        assertEquals("\u4321", DebugServlet.parameters.get("b")[0]);

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        HttpClientUtil.removeRequestInterceptor(changeRequestInterceptor);
        HttpClientUtil.removeRequestInterceptor(cookieSettingRequestInterceptor);
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected boolean prepareForwardingCookies(HttpRequestBase method, HttpServletRequest request,
        DefaultHttpClient httpClient) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    Cookie[] cookies = request.getCookies();
    BasicCookieStore cs = new BasicCookieStore();
    httpClient.setCookieStore(cs);/*from   w w w . j av a  2  s  .c  o  m*/
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookiename = cookie.getName();
                if (StringUtil.isNotEmpty(cookiename)) {
                    String cookieval = cookie.getValue();
                    if (cookiename.startsWith(PASSTHRUID)) {
                        cookiename = cookiename.substring(PASSTHRUID.length());
                        if (isCookieAllowed(cookiename)) {
                            String[] parts = decodeCookieNameAndPath(cookiename);
                            if (parts != null && parts.length == 3) {
                                cookiename = parts[0];
                                String path = parts[1];
                                String domain = parts[2];

                                // Got stored domain now see if it matches destination
                                BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                                methodcookie.setDomain(domain);
                                methodcookie.setPath(path);
                                cs.addCookie(methodcookie);
                                if (getDebugHook() != null) {
                                    getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                            methodcookie.toString());
                                }
                            }
                        }
                    } else if (isCookieAllowed(cookiename)) {
                        BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                        String domain = cookie.getDomain();
                        if (domain == null) {
                            try {
                                domain = method.getURI().getHost();
                                domain = domain.substring(domain.indexOf('.'));
                            } catch (Exception e) {
                                domain = "";
                            }
                        }
                        methodcookie.setDomain(domain);
                        String path = cookie.getPath();
                        if (path == null) {
                            path = "/";
                        }
                        methodcookie.setPath(path);
                        cs.addCookie(methodcookie);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                    methodcookie.toString());
                        }
                    }
                }
            }
        }
    }
    ProxyProfiler.profileTimedRequest(timedObject, "perpareForwardingCookie");
    return true;
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * Sets the LDAP authentication cookie/*from ww  w  .  ja  v a 2s. c o m*/
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie(SSO_COOKIE_NAME, "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:com.britesnow.snow.web.RequestContext.java

public Map<String, String> getCookieMap() {
    if (cookieMap == null) {
        cookieMap = new HashMap<String, String>();
        Cookie[] cookies = getReq().getCookies();

        if (cookies != null) {
            for (Cookie c : cookies) {
                String value = c.getValue();
                try {
                    value = URLDecoder.decode(value, "UTF-8");
                } catch (Exception e) {
                    // YES, ignore for now. If failed, the raw value will be in the cookie.
                }/*from   w  ww . jav a  2s .c  om*/
                cookieMap.put(c.getName(), value);
            }
        }
    }
    return cookieMap;
}

From source file:org.orbeon.oxf.util.Connection.java

private void saveHttpState(ExternalContext externalContext, IndentedLogger indentedLogger) {
    if (cookieStore != null) {
        switch (stateScope) {
        case REQUEST:
            externalContext.getRequest().getAttributesMap().put(HTTP_COOKIE_STORE_ATTRIBUTE, cookieStore);
            break;
        case SESSION:
            final ExternalContext.Session session = externalContext.getSession(false);
            if (session != null)
                session.getAttributesMap().put(HTTP_COOKIE_STORE_ATTRIBUTE, cookieStore);
            break;
        case APPLICATION:
            externalContext.getWebAppContext().getAttributesMap().put(HTTP_COOKIE_STORE_ATTRIBUTE, cookieStore);
            break;
        }//from  ww  w . j a v a2  s .com

        if (indentedLogger.isDebugEnabled()) {
            // Log information about state
            if (cookieStore != null) {
                final StringBuilder sb = new StringBuilder();
                for (org.apache.http.cookie.Cookie cookie : cookieStore.getCookies()) {
                    if (sb.length() > 0)
                        sb.append(" | ");
                    sb.append(cookie.getName());
                }
                indentedLogger.logDebug(LOG_TYPE, "saved HTTP state", "scope",
                        stateScope.toString().toLowerCase(), (sb.length() > 0) ? "cookie names" : null,
                        sb.toString());
            }
        }
    }
}

From source file:com.netspective.sparx.form.DialogContext.java

public String getClientPersistentValue(DialogField field) {
    if (cookieValues == null) {
        cookieValues = new HashMap();
        final Cookie[] cookies = getHttpRequest().getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                final Cookie cookie = cookies[i];
                final String cookieName = getDialog().getCookieName();
                if (cookie.getName().equals(cookieName)) {
                    try {
                        UrlQueryStringParser parser = new UrlQueryStringParser(
                                new ByteArrayInputStream(cookie.getValue().getBytes()));
                        cookieValues = parser.parseArgs();
                    } catch (IOException e) {
                        getDialog().getLog().error(e);
                    }/* w  w  w  .  j a  v  a2  s .co m*/
                }
            }
        }
    }

    if (cookieValues != null)
        return (String) cookieValues.get(field.getQualifiedName());
    else
        return null;
}

From source file:memedb.httpd.MemeDBHandler.java

protected Credentials getCredentials(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Credentials cred = null;/*ww w .j av  a  2 s .  com*/

    if (request.getRequestURI().equals("/_auth")) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.debug("login attempt for {}", username);
        if (!allowAnonymous && "anonymous".equals(username)) {
            sendNoAuthError(response, "Bad username / password combination");
            return null;
        }
        if (username != null) {
            if (password == null) {
                password = "";
            }
            if (allowAnonymous && allowAnonymousAsSa && "anonymous".equals(username)) {
                return new SACredentials("anonymous", "", timeout);
            }
            cred = memeDB.getAuthentication().authenticate(username, password);
            if (cred != null) {
                if (request.getParameter("setcookie") == null
                        || request.getParameter("setcookie").toLowerCase().equals("false")) {
                    Cookie cookie = new Cookie(COOKIE_ID, cred.getToken());
                    cookie.setMaxAge(timeout);
                    response.addCookie(cookie);
                }
                return cred;
            } else {
                log.warn("Bad login attempt for {}", username);
                sendNoAuthError(response, "Bad username / password combination");
                return null;
            }
        }
    }

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_ID)) {
                cred = memeDB.getAuthentication().getCredentialsFromToken(cookie.getValue());
                if (cred != null) {
                    log.debug("Got credentials from cookie token: {}", cookie.getValue());
                    return cred;
                }
            }
        }
    }

    String param = request.getParameter("token");
    if (param != null && !param.equals("")) {
        cred = memeDB.getAuthentication().getCredentialsFromToken(param);
        if (cred != null) {
            log.debug("Authenticated as {} => {} via Req param", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String headerparam = request.getHeader("MemeDB-Token");
    if (headerparam != null && !headerparam.equals("")) {
        log.info("Attempting authentication with token {}", headerparam);
        cred = memeDB.getAuthentication().getCredentialsFromToken(headerparam);
        if (cred != null) {
            log.info("Got credentials!");
            log.debug("Authenticated as {} => {} via HTTP-Header", cred.getUsername(), cred.getToken());
            addCredentialedCookie(response, cred);
            return cred;
        }
    }

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        String[] authSplit = authHeader.split(" ");
        if (authSplit.length == 2) {
            String userpass = new String(Base64.decodeBase64(authSplit[1].getBytes()));
            if (userpass != null) {
                String[] ar = userpass.split(":");
                if (ar.length > 0) {
                    String u = ar[0];
                    String p = "";
                    if (ar.length > 1) {
                        p = ar[1];
                    }
                    if (!allowAnonymous && "anonymous".equals(u)) {
                    } else {
                        cred = memeDB.getAuthentication().authenticate(u, p);

                        if (cred != null) {
                            log.debug("Authenticated as {} => {} via HTTP-AUTH", cred.getUsername(),
                                    cred.getToken());
                            addCredentialedCookie(response, cred);
                        }
                        return cred;
                    }
                }
            }
        }
        response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
        sendNoAuthError(response, "You need a username and password");
        return null;
    }

    if (allowAnonymous) {
        if (allowAnonymousAsSa)
            return new SACredentials("anonymous", "", timeout);
        return new AnonCredentials("", timeout);
    }

    log.warn("Error authenticating");
    response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\"");
    sendNoAuthError(response, "You need a username and password");
    return null;
}