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:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

/**
 * @param request/* w w w.  j  a  v a2 s  .  com*/
 * @param response
 * @param callbackUrl
 * @throws IOException
 * @throws Oops
 */
private void authorizeRequestToken(HttpServletRequest request, HttpServletResponse response, String username)
        throws Oops {

    String token = null, callbackUrl = null;

    Cookie[] cookies = request.getCookies();

    String shareId = null;

    if (null != request.getParameter("oauth_token")) {
        token = request.getParameter("oauth_token");
        callbackUrl = request.getParameter("oauth_callback");
    } else if (cookies != null) {
        OauthCookie parsedCookie = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(OauthCookie.COOKIE_NAME)) {
                // Remove the temporary 3rd party app cookie
                Cookie removeCookie = new Cookie(OauthCookie.COOKIE_NAME, "");
                removeCookie.setMaxAge(0);
                response.addCookie(removeCookie);
                try {
                    parsedCookie = OauthCookie.create(cookie);
                    shareId = parsedCookie.getShareId();
                    if (isBlank(parsedCookie.getRequestToken()))
                        throw new Oops(
                                "No request token present in oauth cookie (\"" + cookie.getValue() + "\").");
                    logger.debug("Parsed oauth cookie \"" + cookie.getValue() + "\" as \""
                            + parsedCookie.toString() + "\".");
                } catch (IOException e) {
                    logger.debug("Error parsing cookie. Just removing it.");
                }
            }
        }

        if (null != parsedCookie) {
            token = parsedCookie.getRequestToken();
            callbackUrl = parsedCookie.getCallbackUrl();
        }
    }

    if (null == token)
        throw new Oops("No request token found in request.");

    try {
        Token reqToken = MySQLOAuthProvider2.getRequestToken(token);
        if (null == reqToken)
            throw new PermissionDeniedException("401 Unauthorized");
        if (null != reqToken.getAttributes().getFirst("root_container")) { // pre-shared container accessor
            if (shareId != null) {//already created the share - user bound sharing
                List<String> groupUserLogins = MySQLOAuthProvider2.getShareUsers(shareId);
                if (!groupUserLogins.contains(username)) { // the username of the one authorized != user that share was created for
                    throw new PermissionDeniedException("401 Unauthorized");
                }
            } // else share is open for everyone
        }

        MySQLOAuthProvider2.markAsAuthorized(reqToken, username);

        if (null != callbackUrl && !callbackUrl.isEmpty()) {
            if (callbackUrl.indexOf('?') <= 0)
                callbackUrl += "?" + "oauth_token=" + reqToken.getToken();
            else
                callbackUrl += "&" + "oauth_token=" + reqToken.getToken();
            logger.debug("Redirecting user to " + callbackUrl);
            response.sendRedirect(callbackUrl);
        } else {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println("You have successfully authorized "
                    + ".\nPlease close this browser window and click continue" + " in the client.");
            out.close();
        }
    } catch (IOException e) {
        logger.error("Error performing the token authorization " + e.getMessage());
        e.printStackTrace();
        throw new Oops(e.getMessage());
    }
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.AbstractSessionManager.java

public Cookie getSessionCookie(HttpSession session, boolean requestIsSecure) {
    if (_handler.isUsingCookies()) {
        Cookie cookie = _handler.getSessionManager().getHttpOnly()
                ? new HttpOnlyCookie(SessionManager.__SessionCookie, session.getId())
                : new Cookie(SessionManager.__SessionCookie, session.getId());
        String domain = _handler.getServletContext().getInitParameter(SessionManager.__SessionDomain);
        String maxAge = _handler.getServletContext().getInitParameter(SessionManager.__MaxAge);
        String path = _handler.getServletContext().getInitParameter(SessionManager.__SessionPath);
        if (path == null)
            path = getCrossContextSessionIDs() ? "/" : _handler.getHttpContext().getContextPath();
        if (path == null || path.length() == 0)
            path = "/";

        if (domain != null)
            cookie.setDomain(domain);/*from   w  w  w. j  a  v a  2s.  c  o  m*/
        if (maxAge != null)
            cookie.setMaxAge(Integer.parseInt(maxAge));
        else
            cookie.setMaxAge(-1);

        cookie.setSecure(requestIsSecure && getSecureCookies());
        cookie.setPath(path);

        return cookie;
    }
    return null;
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * /*from  w w w  . j av  a  2 s  .  co m*/
 *
 * @param shoppingCartId
 *            id
 * @param marketingId
 *            ??id
 * @param marketingActivityId
 *            id
 * @return int
 */
@Override
public int changeShoppingCartMarket(Long shoppingCartId, Long marketingId, Long marketingActivityId,
        HttpServletRequest request, HttpServletResponse response) {
    Long marketingIdNew = marketingId;
    Long marketingActivityIdNew = marketingActivityId;
    Long customerId = (Long) request.getSession().getAttribute(CUSTOMERID);

    // ?
    if (customerId != null) {
        ShoppingCart sc = new ShoppingCart();

        sc.setShoppingCartId(shoppingCartId);
        // ??id0???
        if (marketingIdNew != null && marketingIdNew == 0) {
            marketingIdNew = null;
        }
        sc.setMarketingId(marketingIdNew);
        // id0?
        if (marketingActivityIdNew != null && marketingActivityIdNew == 0) {
            marketingActivityIdNew = null;
        }
        sc.setMarketingActivityId(marketingActivityIdNew);
        return shoppingCartMapper.changeShoppingCartMarket(sc);
    } else {
        Cookie[] cookies = request.getCookies();

        StringBuilder newMid = new StringBuilder();

        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie != null && NPSTORE_MID.equals(cookie.getName()) && cookie.getValue() != null
                        && !"".equals(cookie.getValue())) {
                    String[] mIds = cookie.getValue().split("-");
                    // ?cookie
                    for (int j = 0; j < mIds.length; j++) {
                        String[] mid = mIds[j].split("e");
                        // ??
                        if (mid[0] != null) {
                            if (mid[0].equals(shoppingCartId.toString())) {
                                newMid.append(shoppingCartId);
                                newMid.append("e");
                                newMid.append(marketingIdNew);
                                newMid.append("e");
                                newMid.append(marketingActivityIdNew);
                                newMid.append("e");
                                newMid.append("1");
                                newMid.append("-");
                            } else {
                                newMid.append(mIds[j]);
                                newMid.append("-");
                            }
                        }
                    }
                }
            }
            Cookie cookie = new Cookie(NPSTORE_MID, newMid.toString());
            cookie.setMaxAge(15 * 24 * 3600);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return 0;
    }

}

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

@Test
public void testMethod18() {
    ControllerUtil.sendAndReceive(mockMvc, null,
            Collections.singletonList(new Cookie("nameOfTheCookie", "cookieValue")), "remoteProviderOptional",
            "method18", "cookieValue", (Object[]) null);
    ControllerUtil.sendAndReceive(mockMvc, null, null, "remoteProviderOptional", "method18", "default",
            (Object[]) null);/*w  w w  . ja  va2  s  .co  m*/
}

From source file:com.o2o.util.WebUtils.java

public static void clearCookie(HttpServletRequest request, HttpServletResponse response, String path,
        String domain) {//from ww w .j a  v  a2s  .c  o  m
    Assert.notNull(request);
    Assert.notNull(response);
    try {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie_old : cookies) {
            String name = URLEncoder.encode(cookie_old.getName(), "UTF-8");
            Cookie cookie = new Cookie(name, null);
            cookie.setMaxAge(0);
            if (StringUtils.isNotEmpty(path)) {
                cookie.setPath(path);
            }
            if (StringUtils.isNotEmpty(domain)) {
                cookie.setDomain(domain);
            }
            response.addCookie(cookie);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

From source file:com.expressui.core.MainApplication.java

/**
 * Adds a cookie to the HTTP response./*from   www  . j a  va 2  s  .  c  om*/
 *
 * @param name   name of the cookie
 * @param value  value
 * @param maxAge max age
 * @see Cookie#Cookie(String, String)
 * @see Cookie#setMaxAge(int)
 */
public void addCookie(String name, String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    cookie.setPath("/");
    getResponse().addCookie(cookie);
}

From source file:de.eod.jliki.users.utils.UserDBHelper.java

/**
 * Logs out the user.<br/>//w w  w.  java  2 s.c o m
 * @param userLogin the login object
 */
public static void logoutUser(final LoginBean userLogin) {
    final SessionFactory sf = DBSetup.getDbManager().getSessionFactory();
    final Session session = sf.openSession();
    final Transaction trx = session.beginTransaction();
    final Query query = session.createQuery("select user from User as user where user.name = :username");
    query.setString("username", userLogin.getUserName());

    final Iterator<?> it = query.iterate();
    if (query.iterate().hasNext()) {
        final User dbUser = (User) it.next();
        dbUser.setCookieid("");
        session.update(dbUser);
    }

    trx.commit();
    session.close();

    userLogin.setLoggedIn(false);
    userLogin.setPassword(null);
    userLogin.setRememberMe(false);
    userLogin.setUserName(null);
    userLogin.clearPermissions();

    if (userLogin.isRememberMe()) {
        final HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        final Cookie cookie = new Cookie("login", "");
        cookie.setMaxAge(0);
        httpServletResponse.addCookie(cookie);
    }

    userLogin.setRememberMe(false);
}

From source file:com.appeligo.search.actions.BaseAction.java

public TimeZone getTimeZone() {
    User user = getUser();/*from  ww  w .  j  a v a  2s  .c o m*/
    if (user != null) {
        getServletRequest().getSession().setAttribute(TIMEZONE_ID, user.getTimeZone());
        return user.getTimeZone();
    } else {
        TimeZone zone = (TimeZone) getServletRequest().getSession().getAttribute(TIMEZONE_ID);
        if (zone == null) {
            String timeZoneId = null;
            Cookie[] cookies = getServletRequest().getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(TIMEZONE_ID)) {
                        cookie.setMaxAge(Integer.MAX_VALUE);
                        timeZoneId = cookie.getValue();
                        break;
                    }
                }
            }
            if (timeZoneId == null) {
                timeZoneId = DEFAULT_TIMEZONE_ID;
                Cookie cookie = new Cookie(TIMEZONE_ID, timeZoneId);
                cookie.setMaxAge(Integer.MAX_VALUE);
                response.addCookie(cookie);
            }
            zone = TimeZone.getTimeZone(timeZoneId);
            getServletRequest().getSession().setAttribute(TIMEZONE_ID, zone);
            return zone;
        } else {
            return zone;
        }
    }
}

From source file:org.sakaiproject.nakamura.auth.rest.RestAuthenticationHandlerTest.java

private void setUpSsoCredentials() throws Exception {
    Cookie[] cookies = new Cookie[2];
    cookies[0] = new Cookie("some-other-cookie", "nothing-great");
    cookies[1] = new Cookie(RestAuthenticationHandler.DEFAULT_ARTIFACT_NAME, ARTIFACT);
    when(request.getCookies()).thenReturn(cookies);

    setupValidateHandler();/*from   w  ww. jav  a  2  s.c  om*/

    when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost"));
    when(request.getQueryString()).thenReturn("resource=/dev/index.html");
}