Java Code Examples for org.eclipse.jetty.http.HttpCookie

Following code examples demonstrate how to use org.eclipse.jetty.http.HttpCookie from jetty. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.eclipse.jetty.http.HttpCookie and various code implementation of this class.

  public NewCookie cookieFor(String value, ZonedDateTime expiration) {
    long maxAge = Duration.between(ZonedDateTime.now(clock), expiration).getSeconds();

    HttpCookie cookie = new HttpCookie(config.getName(), value, config.getDomain(),
        config.getPath(), maxAge, config.isHttpOnly(), config.isSecure());

    Response response = newResponse();
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().get(HttpHeader.SET_COOKIE));
  } 


  public NewCookie getExpiredSessionCookie() {
    HttpCookie cookie = new HttpCookie(config.getName(), "expired", config.getDomain(), config.getPath(),
        0, config.isHttpOnly(), config.isSecure());

    Response response = newResponse();
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
  } 

    @Ignore("failing because an http cookie with null value is coming over as \"null\"")
    public void testSessionCookie() throws Exception
    {
        String contextPath = "";
        String servletMapping = "/server";
        int scavengePeriod = 3;
        AbstractTestServer server = createServer(0, 1, scavengePeriod);
        ServletContextHandler context = server.addContext(contextPath);
        context.addServlet(TestServlet.class, servletMapping);
        server.start();
        int port=server.getPort();
        try
        {
            HttpClient client = new HttpClient();
            client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
            client.start();
            try
            {
                ContentExchange exchange = new ContentExchange(true);
                exchange.setMethod(HttpMethods.GET);
                client.send(exchange);
                exchange.waitForDone();
                assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
                String sessionCookie = exchange.getResponseFields().getStringField("Set-Cookie");
                assertTrue(sessionCookie != null);


                exchange = new ContentExchange(true);
                exchange.setMethod(HttpMethods.GET);
                exchange.getRequestFields().add("Cookie", sessionCookie);
                client.send(exchange);
                exchange.waitForDone();
                assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
                
                exchange = new ContentExchange(true);
                exchange.setMethod(HttpMethods.GET);
                HttpDestination dest = client.getDestination(new Address("localhost",port),false);
                
                dest.addCookie(new HttpCookie("Cookie",null));
                
                client.send(exchange);
                exchange.waitForDone();
                assertEquals(HttpServletResponse.SC_OK,exchange.getResponseStatus());
            }
            finally
            {
                client.stop();
            }
        }
        finally
        {
            server.stop();
        }

    } 

    @Test
    public void testSecureSessionCookie () throws Exception
    {
        MockSessionIdManager idMgr = new MockSessionIdManager();
        idMgr.setWorkerName("node1");
        MockSessionManager mgr = new MockSessionManager();
        mgr.setSessionIdManager(idMgr);

        SessionCookieConfig sessionCookieConfig = mgr.getSessionCookieConfig();
        sessionCookieConfig.setSecure(true);

        HttpCookie cookie = mgr.getSessionCookie(session, "/foo", true);
        assertTrue(cookie.isSecure());
        cookie = mgr.getSessionCookie(session, "/foo", false);
        assertTrue(cookie.isSecure());

        sessionCookieConfig.setSecure(false);
        cookie = mgr.getSessionCookie(session, "/foo", true);
        assertTrue(cookie.isSecure());

        cookie = mgr.getSessionCookie(session, "/foo", false);
        assertFalse(cookie.isSecure());

        mgr.setSecureRequestOnly(false);
        cookie = mgr.getSessionCookie(session, "/foo", false);
        assertFalse(cookie.isSecure());

        cookie = mgr.getSessionCookie(session, "/foo", true);
        assertFalse(cookie.isSecure());


    } 

    }

    protected void doSend(HttpExchange ex) throws IOException
    {
        if (_cookies != null)
        {
            StringBuilder buf = null;
            for (HttpCookie cookie : _cookies)
            {
                if (buf == null)
                    buf = new StringBuilder();
                else
                    buf.append("; ");
                buf.append("=");
            }
            if (buf != null)
                ex.addRequestHeader(HttpHeaders.COOKIE, buf.toString());
        }

        if (_authorizations != null)
        {
            Authentication auth = (Authentication)_authorizations.match(ex.getURI());
            if (auth != null)
                (auth).setCredentials(ex);
        }

        HttpConnection connection = getIdleConnection();
        if (connection != null)
        {
            send(connection, ex);
        }
        else
        {
            synchronized (this)
            {
                _queue.add(ex);
                if (_connections.size() + _pendingConnections < _maxConnections)
                {
                    startNewConnection();
                }
            }
        }
    } 

    }

    public void addCookie(HttpCookie cookie)
    {
        synchronized (this)
        {
            if (_cookies == null)
                _cookies = new ArrayList<HttpCookie>();
            _cookies.add(cookie);
        }

    } 

  public NewCookie generate(String session) {
    checkArgument(!session.isEmpty());
    String cookieValue = SHA512.hashString(session, UTF_8).toString();

    HttpCookie cookie = new HttpCookie(config.getName(), cookieValue, config.getDomain(),
        config.getPath(), -1, config.isHttpOnly(), config.isSecure());
    Response response = newResponse();
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
  } 

    public HttpCookie access(HttpSession httpSession, boolean secure) {
        HttpCookie cookie = null;

        InfinispanHttpSession session = (InfinispanHttpSession) httpSession;
        long now = System.currentTimeMillis();

        session.access(now);
        long cookieCreatedAt = session.getCookieCreatedAt();

        if (cookieConfig.maxAge > 0 && now >= cookieCreatedAt) {
            session.setCookieCreatedAt(now);
            String contextPath = (context == null) ? "/" : context.getContextPath();
            cookie = getSessionCookie(session, contextPath, secure);
        }

        return cookie;
    } 

    public HttpCookie getSessionCookie(HttpSession session, String contextPath, boolean requestIsSecure) {
        String path = (cookieConfig.path == null) ? contextPath : cookieConfig.path;

        HttpCookie cookie = new HttpCookie(
            cookieConfig.name,
            session.getId(),
            cookieConfig.domain,
            (path == null || path.isEmpty()) ? "/" : path,
            cookieConfig.maxAge,
            cookieConfig.httpOnly,
            requestIsSecure && cookieConfig.secure);

        return cookie;
    } 

    }

    public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        setRequestedId(baseRequest,request);

        SessionManager old_session_manager=null;
        HttpSession old_session=null;
        TerracottaSessionManager sessionManager = (TerracottaSessionManager)getSessionManager();
        Request currentRequest = (request instanceof Request) ? (Request)request : HttpConnection.getCurrentConnection().getRequest();
        try
        {
            old_session_manager = baseRequest.getSessionManager();
            old_session = baseRequest.getSession(false);
           
            if (old_session_manager != sessionManager)
            {
                baseRequest.setSessionManager(sessionManager);
                baseRequest.setSession(null);
            }
            if (sessionManager != null) 
                sessionManager.enter(currentRequest);
            
            HttpSession session=null;
            if (sessionManager!=null)
            {
                session=baseRequest.getSession(false);
                if (session!=null)
                {
                    if(session!=old_session)
                    {
                        HttpCookie cookie = sessionManager.access(session,request.isSecure());
                            baseRequest.getResponse().addCookie(cookie);
                    }
                }
                else
                {
                    session=baseRequest.recoverNewSession(sessionManager);
                    if (session!=null)
                        baseRequest.setSession(session);
                }
            }

            if(Log.isDebugEnabled())
            {
                Log.debug("sessionManager="+sessionManager);
                Log.debug("session="+session);
            }

            if (false)
                nextScope(target,baseRequest,request,response);
            else if (_nextScope!=null)
                _nextScope.doScope(target,baseRequest,request, response);
            else if (_outerScope!=null)
                _outerScope.doHandle(target,baseRequest,request, response);
            else 
                doHandle(target,baseRequest,request, response);

        }
        finally
        {
            HttpSession session=request.getSession(false);
            if (sessionManager != null)
            {
                HttpSession currentSession = currentRequest.getSession(false);
                if (currentSession != null) 
                    sessionManager.complete(currentSession);

                sessionManager.exit(currentRequest);
            }
            
            if (old_session_manager != sessionManager)
            {
                if (session!=null)
                    sessionManager.complete(session);
                baseRequest.setSessionManager(old_session_manager);
                baseRequest.setSession(old_session);
            }
        }
    } 

    }

    public void applyResponse(org.eclipse.jetty.server.Response servletResponse, Response response)
    {
        for (Map.Entry<String, ArrayList<String>> entry : response.getHeaders().entrySet()) {
            String name = entry.getKey();
            ArrayList<String> headers = entry.getValue();
            for (String values : headers) {
                servletResponse.addHeader(name, values);
            }
        }

        for (HttpCookie cookie : response.getCookies()) {
            servletResponse.addCookie(cookie);
        }

        if (response instanceof RedirectResponse) {
            RedirectResponse redirectResponse = (RedirectResponse) response;

            try {
                servletResponse.sendRedirect(redirectResponse.getStatus().getRequestStatus(), redirectResponse.getTargetUrl());
            } catch (IOException e) {
                e.printStackTrace();
                Response error = new Response("Internal Error", Status.INTERNAL_ERROR, "text/plain");

                applyResponse(servletResponse, error);
            }

            return;
        }

        servletResponse.setContentType(response.getMimeType());
        servletResponse.setStatus(response.getStatus().getRequestStatus());

        try {
            servletResponse.getWriter().print(response.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 

    @Override
    public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        SessionManager old_session_manager = null;
        HttpSession old_session = null;
        HttpSession access = null;
        try
        {
            old_session_manager = baseRequest.getSessionManager();
            old_session = baseRequest.getSession(false);

            if (old_session_manager != _sessionManager)
            {
                baseRequest.setSessionManager(_sessionManager);
                baseRequest.setSession(null);
                checkRequestedSessionId(baseRequest,request);
            }

            HttpSession session = null;
            if (_sessionManager != null)
            {
                session = baseRequest.getSession(false);
                if (session != null)
                {
                    if (session != old_session)
                    {
                        access = session;
                        HttpCookie cookie = _sessionManager.access(session,request.isSecure());
                            baseRequest.getResponse().addCookie(cookie);
                    }
                }
                else
                {
                    session = baseRequest.recoverNewSession(_sessionManager);
                    if (session != null)
                        baseRequest.setSession(session);
                }
            }

            if (LOG.isDebugEnabled())
            {
                LOG.debug("sessionManager=" + _sessionManager);
                LOG.debug("session=" + session);
            }

            if (_nextScope != null)
                _nextScope.doScope(target,baseRequest,request,response);
            else if (_outerScope != null)
                _outerScope.doHandle(target,baseRequest,request,response);
            else
                doHandle(target,baseRequest,request,response);

        }
        finally
        {
            if (access != null)
                _sessionManager.complete(access);

            HttpSession session = baseRequest.getSession(false);
            if (session != null && old_session == null && session != access)
                _sessionManager.complete(session);

            if (old_session_manager != null && old_session_manager != _sessionManager)
            {
                baseRequest.setSessionManager(old_session_manager);
                baseRequest.setSession(old_session);
            }
        }
    } 

    
    public HttpCookie getSessionCookie(HttpSession session, String contextPath, boolean requestIsSecure)
    {
        if (isUsingCookies())
        {
            String sessionPath = (_cookieConfig.getPath()==null) ? contextPath : _cookieConfig.getPath();
            sessionPath = (sessionPath==null||sessionPath.length()==0) ? "/" : sessionPath;
            String id = getNodeId(session);
            HttpCookie cookie = null;
            if (_sessionComment == null)
            {
                cookie = new HttpCookie(
                                        _cookieConfig.getName(),
                                        id,
                                        _cookieConfig.getDomain(),
                                        sessionPath,
                                        _cookieConfig.getMaxAge(),
                                        _cookieConfig.isHttpOnly(),
                                        _cookieConfig.isSecure() || (isSecureRequestOnly() && requestIsSecure));
            }
            else
            {
                cookie = new HttpCookie(
                                        _cookieConfig.getName(),
                                        id,
                                        _cookieConfig.getDomain(),
                                        sessionPath,
                                        _cookieConfig.getMaxAge(),
                                        _cookieConfig.isHttpOnly(),
                                        _cookieConfig.isSecure() || (isSecureRequestOnly() && requestIsSecure),
                                        _sessionComment,
                                        1);
            }

            return cookie;
        }
        return null;
    } 

    
    public HttpCookie access(HttpSession session,boolean secure)
    {
        long now=System.currentTimeMillis();

        AbstractSession s = ((SessionIf)session).getSession();

       if (s.access(now))
       {
            if (isUsingCookies() &&
                (s.isIdChanged() ||
                (getSessionCookieConfig().getMaxAge()>0 && getRefreshCookieAge()>0 && ((now-s.getCookieSetTime())/1000>getRefreshCookieAge()))
                )
               )
            {
                HttpCookie cookie=getSessionCookie(session,_context==null?"/":(_context.getContextPath()),secure);
                s.cookieSet();
                s.setIdChanged(false);
                return cookie;
            }
        }
        return null;
    }