Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:m.c.m.proxyma.resource.ProxymaResponseDataBeanTest.java

/**
 * Test of clone method, of class ProxymaResponseDataBean.
 */// www.java  2s .c o m
public void testClone() throws CloneNotSupportedException {
    System.out.println("clone");

    ProxymaResponseDataBean instance = new ProxymaResponseDataBean();
    instance.addHeader("nAme1 ", "value1");
    instance.addCookie(new Cookie("name1", "value1"));
    instance.setData(new RamBuffer(1024));
    instance.setStatus(200);

    ProxymaResponseDataBean clone = (ProxymaResponseDataBean) instance.clone();

    assertNotSame(instance, clone);
    assertNotSame(instance.getCookie("name1"), clone.getCookie("name1"));
    assertNotSame(instance.getHeader("name1"), clone.getHeader("name1"));
    assertNotSame(instance.getData(), clone.getData());
    assertEquals(instance.getStatus(), clone.getStatus());
    assertEquals(instance.getCookie("name1").getValue(), clone.getCookie("name1").getValue());
    assertEquals(instance.getHeader("name1").getValue(), clone.getHeader("name1").getValue());
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerOptionalTest.java

@Test
public void testMethod19() {
    ControllerUtil.sendAndReceive(mockMvc, null,
            Collections.singletonList(new Cookie("stringCookie", "aString")), "remoteProviderOptional",
            "method19", "aString", (Object[]) null);
    ControllerUtil.sendAndReceive(mockMvc, null, null, "remoteProviderOptional", "method19", Void.TYPE,
            (Object[]) null);// w ww .  j  ava2s. c  o m
}

From source file:com.persistent.cloudninja.controller.TenantTaskListController.java

private Cookie getTenantLogoCookieInResponse(String tenantId, String cookieName) {
    String logoUrl = "";
    Tenant tenant = hibernateTemplate.get(Tenant.class, tenantId);
    String logoFilename = tenant.getLogoFileName();
    if (null == logoFilename || logoFilename.trim().length() == 0) {
        logoUrl = "";
    } else {//from w  w  w.  ja  v a 2s.  c om

        //create logo URL from config property file
        logoUrl = getLogoUrlFromConfig(logoFilename, tenantId);
    }
    Cookie logoCokie = new Cookie("CLOUDNINJALOGO", logoUrl);
    logoCokie.setMaxAge(-1);
    logoCokie.setPath("/");
    return logoCokie;

}

From source file:com.mentor.questa.vrm.jenkins.QuestaVrmHostAction.java

public void doFlipMode(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {

    // flip!//from   w w w. j  a  v a 2s  . c o  m
    boolean showActions = !getActionCookie(req);

    // set the updated value
    Cookie cookie = new Cookie("HostAction_showActions", String.valueOf(showActions));
    List anc = req.getAncestors();
    Ancestor a = (Ancestor) anc.get(anc.size() - 2);
    cookie.setPath(a.getUrl()); // just for this project
    cookie.setMaxAge(60 * 60 * 24 * 365); // 1 year

    rsp.addCookie(cookie);

    // back to the same page
    rsp.sendRedirect(".");
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendImageDownloadResponse(ImageUtil image, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (image == null)
        return;//from w w  w  .  ja v  a  2s.c o m

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(image.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(image.getLength());

    }

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(image.getBytes());
    os.close();
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testSessionLogin() throws Exception {
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, SESSION_ID);
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(null /* loginString */, sessionCookie);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, false, STATE, NONCE);
}

From source file:com.feilong.servlet.http.CookieUtil.java

/**
 * To cookie./*w  w w.  j  a va  2  s  .c  om*/
 *
 * @param cookieEntity
 *            the cookie entity
 * @return the cookie
 * @since 1.5.3
 */
private static Cookie toCookie(CookieEntity cookieEntity) {
    Cookie cookie = new Cookie(cookieEntity.getName(), cookieEntity.getValue());
    PropertyUtil.copyProperties(cookie, cookieEntity, "maxAge", "secure", "version", "httpOnly");

    PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "comment", cookieEntity.getComment());//???cookie.
    //NullPointerException at javax.servlet.http.Cookie.setDomain(Cookie.java:213) ~[servlet-api-6.0.37.jar:na]
    PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "domain", cookieEntity.getDomain());// cookie.
    PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "path", cookieEntity.getPath());//cookiecookie.
    return cookie;
}

From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java

/**
 *
 * @param userId/* w  w  w  . j av a  2 s  . c o m*/
 * @param cookiePath
 * @param expiry
 * @return
 */
private Cookie createSessionAuthenticationCookie(String userId, String cookiePath, int expiry) {
    try {
        long expiriesAt = new Date().getTime();

        if (expiry > 0) {
            expiriesAt += (expiry * 1000); // seconds to millseconds
        }

        final String timestamp = String.valueOf(expiriesAt);
        String cookieData = createCookieData(userId, timestamp);

        Cookie cookie = new Cookie(cookieName, cookieData);
        cookie.setPath(cookiePath);
        cookie.setMaxAge(expiry); // in seconds

        return cookie;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.yahoo.yos.YahooFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String yap_appid = getParam(request, "yap_appid");
    SESSION_TYPE sessionType;//  w w w  . ja va  2s . co m
    if ("POST".equals(request.getMethod()) && yap_appid != null && yap_appid.length() > 0) {
        sessionType = SESSION_TYPE.YAHOO_YAP_SESSION_TYPE;
    } else if (cookieExists(request.getCookies(), "yosdk_at")) {
        sessionType = SESSION_TYPE.YAHOO_OAUTH_AT_SESSION_TYPE;
    } else if (cookieExists(request.getCookies(), "yosdk_rt")) {
        sessionType = SESSION_TYPE.YAHOO_OAUTH_RT_SESSION_TYPE;
    } else {
        sessionType = null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("sessionType: {}", sessionType);
    }

    OAuthAccessor accessor = new OAuthAccessor(consumer);

    if (sessionType == null) {
        if (redirect) {
            if (logger.isDebugEnabled()) {
                logger.debug("redirecting user to yahoo acquire access token");
            }
            redirectForAuthorization(accessor, request, response);
            return;
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("inserting YahooSession suitable for 2-legged oauth calls into request attribute");
            }
            String appId = oauthConfig.getProperty("yos.appid");
            request.setAttribute("yahooSession", new YahooSession(client, consumer, null, appId));
        }
    } else if (sessionType == SESSION_TYPE.YAHOO_YAP_SESSION_TYPE) {
        if (logger.isDebugEnabled()) {
            logger.debug("inserting YahooSession suitable for 2-legged oauth calls into request attribute");
        }
        if (consumer.consumerKey == null
                || !consumer.consumerKey.equals(getParam(request, "yap_consumer_key"))) {
            logger.error("Consumer key from YAP does not match config.");
            clearSession(request, response);
            if (redirect) {
                redirectForAuthorization(accessor, request, response);
                return;
            }
        }
        try {
            OAuthSignatureMethod method = OAuthSignatureMethod.newMethod("HMAC-SHA1", accessor);
            OAuthMessage msg = OAuthServlet.getMessage(request, null);
            method.validate(msg);
        } catch (OAuthProblemException ex) {
            logger.error("Signature from YAP failed.", ex);
            clearSession(request, response);
            if (redirect) {
                redirectForAuthorization(accessor, request, response);
                return;
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        AccessToken at = new AccessToken();
        at.setKey(getParam(request, "yap_viewer_access_token"));
        at.setSecret(getParam(request, "yap_viewer_access_token_secret"));
        at.setGuid(getParam(request, "yap_viewer_guid"));
        at.setOwner(getParam(request, "yap_owner_guid"));
        at.setTokenExpires(-1);
        String appId = getParam(request, "yap_appid");
        YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
        request.setAttribute("yahooSession", yahooSession);
    } else if (sessionType == SESSION_TYPE.YAHOO_OAUTH_AT_SESSION_TYPE) {
        long now = System.currentTimeMillis() / 1000;
        try {
            AccessToken accessToken = new AccessToken(cookie(request.getCookies(), "yosdk_at"));
            if (consumer.consumerKey == null || !consumer.consumerKey.equals(accessToken.getConsumer())) {
                logger.error(
                        "Consumer key for token does not match the defined Consumer Key.  The Consumer Key has probably changed since the user last authorized the application.");
                clearSession(request, response);
                if (redirect) {
                    redirectForAuthorization(accessor, request, response);
                    return;
                }
            }
            if (accessToken.getTokenExpires() >= 0 && logger.isDebugEnabled()) {
                logger.debug("AT Expires in: {}", (accessToken.getTokenExpires() - now));
            }
            if (accessToken.getTokenExpires() >= 0 && (accessToken.getTokenExpires() - now) < 30) {
                try {
                    accessTokenExpired(accessor, request, response, accessToken, filterChain);
                } catch (OAuthException ex) {
                    if (ex instanceof OAuthProblemException) {
                        OAuthProblemException oape = (OAuthProblemException) ex;
                        String s = oape.getProblem() + oape.getParameters();
                        throw new ServletException(s, ex);
                    }
                    throw new ServletException(ex);
                } catch (URISyntaxException ex) {
                    throw new ServletException(ex);
                }
                return;
            } else {
                String appId = oauthConfig.getProperty("yos.appid");
                YahooSession yahooSession = new YahooSession(client, consumer, accessToken, appId);
                request.setAttribute("yahooSession", yahooSession);
            }
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    } else if (sessionType == SESSION_TYPE.YAHOO_OAUTH_RT_SESSION_TYPE) {
        try {
            RequestToken rt = new RequestToken(cookie(request.getCookies(), "yosdk_rt"));
            accessor.tokenSecret = rt.getSecret();

            String verifier = getParam(request, "oauth_verifier");
            if (logger.isDebugEnabled()) {
                logger.debug("got oauth_verifier {}", verifier);
            }

            try {
                if (logger.isDebugEnabled()) {
                    logger.error("request token found, fetching access token for user");
                }
                AccessToken at = fetchAccessToken(accessor, rt, verifier);
                Cookie yosdk_at = at.getCookie();
                Cookie yosdk_rt = new Cookie("yosdk_rt", "");
                yosdk_at.setMaxAge(30 * 24 * 60 * 60);
                yosdk_rt.setMaxAge(0);
                response.addCookie(yosdk_at);
                response.addCookie(yosdk_rt);
                String appId = oauthConfig.getProperty("yos.appid");
                YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
                request.setAttribute("yahooSession", yahooSession);
            } catch (URISyntaxException ex) {
                throw new ServletException(ex);
            } catch (OAuthException ex) {
                clearSession(request, response);
                if (redirect) {
                    redirectForAuthorization(accessor, request, response);
                    return;
                } else {
                    throw new ServletException(ex);
                }
            }
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:memedb.httpd.MemeDBHandler.java

private void addCredentialedCookie(HttpServletResponse response, Credentials cred) {
    Cookie cookie = new Cookie(COOKIE_ID, cred.getToken());
    cookie.setMaxAge(24 * 60 * 60); // max time is one day... afterwhich, it needs to reauth.
    response.addCookie(cookie);/*from  w w  w  .j a va2 s. c o m*/
}