Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie.java

private void doWork(HttpServletRequest request, HttpServletResponse response, AuthStep as)
        throws IOException, ServletException {

    as.setExecuted(true);//from w ww . ja v a 2  s  .  co  m

    MyVDConnection myvd = cfgMgr.getMyVD();
    //HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) request).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    if (holder == null) {
        throw new ServletException("Holder is null");
    }

    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());

    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
            .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);

    Attribute attr = authParams.get("cookieName");
    if (attr == null) {
        throw new ServletException("No cookie name specified");
    }

    String cookieName = attr.getValues().get(0);

    boolean useSSLSessionID;
    attr = authParams.get("useSSLSessionID");
    if (attr == null) {
        useSSLSessionID = false;
    } else {
        useSSLSessionID = attr.getValues().get(0).equalsIgnoreCase("true");
    }

    attr = authParams.get("millisToLive");
    if (attr == null) {
        throw new ServletException("No milliseconds to live specified");
    }

    long millisToLive = Long.parseLong(attr.getValues().get(0));

    attr = authParams.get("keyAlias");
    if (attr == null) {
        throw new ServletException("No key name specified");
    }
    String keyAlias = attr.getValues().get(0);

    Cookie authCookie = null;

    if (request.getCookies() == null) {
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equalsIgnoreCase(cookieName)) {
            authCookie = cookie;
            break;
        }
    }

    if (authCookie == null) {
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile();

    SecretKey key = this.cfgMgr.getSecretKey(keyAlias);
    if (key == null) {
        throw new ServletException("Secret key '" + keyAlias + "' does not exist");
    }

    try {
        String cookieVal = authCookie.getValue();
        if (cookieVal.startsWith("\"")) {
            cookieVal = cookieVal.substring(1, cookieVal.length() - 1);
        }
        lastmile.loadLastMielToken(cookieVal, key);
    } catch (Exception e) {
        logger.warn("Could not decrypt cookie", e);
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    if (!lastmile.isValid()) {
        logger.warn("Cookie no longer valid");
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    boolean found = false;
    boolean validip = false;
    boolean validSslSessionId = !useSSLSessionID;
    String dn = null;

    for (Attribute attrib : lastmile.getAttributes()) {
        if (attrib.getName().equalsIgnoreCase("CLIENT_IP")) {
            validip = attrib.getValues().get(0).equals(request.getRemoteAddr());
        } else if (attrib.getName().equalsIgnoreCase("DN")) {
            dn = attrib.getValues().get(0);

        } else if (attrib.getName().equalsIgnoreCase("SSL_SESSION_ID")) {

            Object sessionID = request.getAttribute("javax.servlet.request.ssl_session_id");
            if (sessionID instanceof byte[]) {
                sessionID = new String(Base64.encodeBase64((byte[]) sessionID));
            }

            validSslSessionId = attrib.getValues().get(0).equals(sessionID);

        }
    }

    if (dn != null && validip && validSslSessionId) {
        try {
            LDAPSearchResults res = myvd.search(dn, 0, "(objectClass=*)", new ArrayList<String>());

            if (res.hasMore()) {
                LDAPEntry entry = res.next();

                Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator();
                AuthInfo authInfo = new AuthInfo(entry.getDN(),
                        (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(),
                        act.getLevel());
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);

                while (it.hasNext()) {
                    LDAPAttribute ldapattr = it.next();
                    attr = new Attribute(ldapattr.getName());
                    String[] vals = ldapattr.getStringValueArray();
                    for (int i = 0; i < vals.length; i++) {
                        attr.getValues().add(vals[i]);
                    }
                    authInfo.getAttribs().put(attr.getName(), attr);
                }

                as.setSuccess(true);

            } else {

                as.setSuccess(false);
            }

        } catch (LDAPException e) {
            if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
                logger.error("Could not authenticate user", e);
            }

            as.setSuccess(false);
        }
    } else {
        as.setSuccess(false);
    }

    holder.getConfig().getAuthManager().nextAuth(request, response, session, false);

}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

private RPSession processRequestInfo(HttpServletRequest request, HttpServletResponse response,
        boolean canLogin) {
    RPSession session = new RPSession();
    session.isAdmin = false;//from  w  w  w  . j a va  2  s  . c  o  m
    session.adminRole = false;
    session.isUWLogin = false;
    session.isProxy = false;
    String reloginPath = null;

    log.info("RP new session =============== path=" + request.getPathInfo());

    session.isMobile = false;
    Device currentDevice = DeviceUtils.getCurrentDevice(request);
    if (currentDevice != null)
        session.isMobile = currentDevice.isMobile();
    log.debug("mobile? " + session.isMobile);

    // see if logged in (browser has login cookie; cert user has cert)

    int resetAdmin = 1; // on expired or no cookie, reset the 'admin role cookei'
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(loginCookie)) {
                log.debug("got cookie " + cookies[i].getName());
                String cookieStr = RPCrypt.decode(cookies[i].getValue());
                if (cookieStr == null)
                    continue;
                String[] cookieData = cookieStr.split(";");
                if (cookieData.length == 5) {

                    if (cookieData[3].charAt(0) == '2')
                        session.authn2 = true;

                    log.debug("login time = " + cookieData[4]);
                    long cSec = new Long(cookieData[4]);
                    long nSec = new Date().getTime() / 1000;
                    if (cookieData[1].indexOf("@") < 0)
                        session.isUWLogin = true; // klugey way to know UW people
                    session.timeLeft = (cSec + standardLoginSec) - nSec;
                    if (session.timeLeft > 0) {
                        if ((nSec > (cSec + secureLoginSec)) && session.authn2) {
                            log.debug("secure expired");
                            session.authn2 = false;
                            resetAdmin = 2;
                        }

                        // cookie OK
                        session.remoteUser = cookieData[1];
                        session.xsrfCode = cookieData[2];
                        log.debug("login for " + session.remoteUser);
                        if (session.authn2)
                            log.debug("secure login");
                        if (adminGroup.isMember(session.remoteUser)) {
                            log.debug("is admin");
                            session.isAdmin = true;
                        }

                        if (resetAdmin == 1)
                            resetAdmin = 0;
                    } else {
                        log.debug("cookie expired for " + cookieData[1]);
                        // remember where they logged in last
                        if (session.isUWLogin)
                            reloginPath = browserRootPath + request.getServletPath() + standardLoginPath;
                        else if (cookieData[1].indexOf("gmail.com") > 0)
                            reloginPath = browserRootPath + request.getServletPath() + googleLoginPath;
                        // let others choose
                    }
                }
            } else if (cookies[i].getName().equals(roleCookie) && cookies[i].getValue().equals("a")) {
                log.debug("got role=admin cookie");
                session.adminRole = true;
            }
        }
    }

    if (resetAdmin > 0) {
        log.debug("clearing expired admn request");
        session.adminRole = false;
        Cookie c = new Cookie(roleCookie, "x");
        c.setSecure(true);
        c.setPath("/");
        response.addCookie(c);
    }

    if (session.remoteUser != null) {
        // ok, is a logged in browser
        session.viewType = "browser";
        session.isBrowser = true;
        session.rootPath = browserRootPath;

    } else {
        // maybe is cert client
        // use the CN portion of the DN as the client userid
        X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        if (certs != null) {
            session.viewType = "xml";
            session.isBrowser = false;
            session.rootPath = certRootPath;
            X509Certificate cert = certs[0];
            String dn = cert.getSubjectX500Principal().getName();
            session.remoteUser = dn.replaceAll(".*CN=", "").replaceAll(",.*", "");
            log.info(".. remote user by cert, dn=" + dn + ", cn=" + session.remoteUser);
            session.altNames = new Vector();
            try {
                Collection altNames = cert.getSubjectAlternativeNames();
                if (altNames != null) {
                    for (Iterator i = altNames.iterator(); i.hasNext();) {
                        List item = (List) i.next();
                        Integer type = (Integer) item.get(0);
                        if (type.intValue() == 2) {
                            String altName = (String) item.get(1);
                            log.info(".. adding altname " + altName);
                            session.altNames.add(altName);
                        }
                    }
                } else
                    session.altNames.add(session.remoteUser); // rules say cn meaningful only when altnames not present
            } catch (CertificateParsingException e) {
                log.info(".. altname parse failed: " + e);
            }
        }

    }

    /* send missing remoteUser to login */

    if (session.remoteUser == null) {
        if (canLogin) {
            if (reloginPath != null) {
                log.debug("no user yet:  relogin at " + reloginPath);
                try {
                    response.sendRedirect(reloginPath);
                } catch (IOException e) {
                    log.error("redirect: " + e);
                }
            }
            log.debug("no user yet:  send to choose");
            session.mv = loginChooserMV(session, request, response);
            return session;
        }
        return null;
    }

    // only admins can get admin role
    if (!session.isAdmin)
        session.adminRole = false;
    if (session.adminRole && !session.authn2) { // admin needs 2f
        log.debug("need secure login for admin role");
        sendToLogin(request, response, secureLoginPath);
    }
    session.servletPath = request.getServletPath();
    session.remoteAddr = request.getRemoteAddr();

    // etag headers
    session.ifMatch = getLongHeader(request, "If-Match");
    session.ifNoneMatch = getLongHeader(request, "If-None-Match");
    log.info("tags: match=" + session.ifMatch + ", nonematch=" + session.ifNoneMatch);

    log.info("user: " + session.remoteUser);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max_age=1");
    response.setHeader("X-UA-Compatible", "IE=7");

    log.info("user: " + session.remoteUser);
    if (session.viewType.equals("browser") && session.isMobile)
        session.viewType = "mobile";
    return session;
}

From source file:org.sakaiproject.metaobj.utils.mvc.impl.servlet.FormControllerImpl.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    Map requestMap = HttpServletHelper.getInstance().createRequestMap(request);
    Map session = HttpServletHelper.getInstance().createSessionMap(request);
    Map application = HttpServletHelper.getInstance().createApplicationMap(request);

    ModelAndView returnedMv;//from   w  w  w  .  j  a  v a 2s.c  om

    if (controller instanceof CancelableController
            && ((CancelableController) controller).isCancel(requestMap)) {
        returnedMv = ((CancelableController) controller).processCancel(requestMap, session, application,
                command, errors);
    } else {
        returnedMv = controller.handleRequest(command, requestMap, session, application, errors);
    }

    boolean saveCookies = ServerConfigurationService.getBoolean(PROP_SAVE_COOKIES, false);

    if (errors.hasErrors()) {
        logger.debug("Form submission errors: " + errors.getErrorCount());
        HttpServletHelper.getInstance().reloadApplicationMap(request, application);
        HttpServletHelper.getInstance().reloadSessionMap(request, session);
        HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);
        if (saveCookies) {
            Cookie cookie = new Cookie(FormHelper.FORM_SAVE_ATTEMPT, "yes");
            cookie.setMaxAge(30);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return showForm(request, response, errors);
    }

    if (returnedMv.getViewName() != null) {
        // should get from mappings
        String mappedView = (String) screenMappings.get(returnedMv.getViewName());

        if (mappedView == null) {
            mappedView = returnedMv.getViewName();
        }

        //getControllerFilterManager().processFilters(requestMap, session, application, returnedMv, mappedView);

        returnedMv = new ModelAndView(mappedView, returnedMv.getModel());
    }

    //We have a successful save coming back, so we set/append to a cookie
    String savedForm = (String) session.get(FormHelper.FORM_SAVE_SUCCESS);
    if (savedForm != null && saveCookies) {
        Cookie cookie = null;
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                if (FormHelper.FORM_SAVE_SUCCESS.equals(c.getName())) {
                    String[] forms = c.getValue().split(",");
                    StringBuilder value = new StringBuilder();
                    boolean alreadyIncluded = false;
                    for (String form : forms) {
                        if (form.equals(savedForm)) {
                            alreadyIncluded = true;
                        }
                        value.append(",").append(form);
                    }
                    if (!alreadyIncluded) {
                        value.append(",").append(savedForm);
                    }
                    cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, value.substring(1));
                }
            }
        }
        if (cookie == null) {
            cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, savedForm);
        }
        cookie.setMaxAge(2000000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    HttpServletHelper.getInstance().reloadApplicationMap(request, application);
    HttpServletHelper.getInstance().reloadSessionMap(request, session);
    HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);

    return returnedMv;
}

From source file:com.sg.rest.filters.LoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString());
        throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST);
    }/*from w  w w .j a  v a  2  s  .  c  om*/

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    StringBuilder sb = new StringBuilder();
    //General header
    sb.append(System.lineSeparator());
    sb.append(INCOMING_REQUEST);
    //Request url
    sb.append(System.lineSeparator());
    sb.append(REQUEST_URL);
    sb.append(httpRequest.getRequestURL());
    //Method
    sb.append(System.lineSeparator());
    sb.append(METHOD);
    sb.append(httpRequest.getMethod());
    //Parameters
    if (httpRequest.getParameterNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(PARAMETERS);
        Enumeration enParams = httpRequest.getParameterNames();
        while (enParams.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String paramName = (String) enParams.nextElement();
            sb.append(paramName);
            sb.append(" : ");
            sb.append(httpRequest.getParameter(paramName));
        }
    }
    //Attributes
    if (httpRequest.getAttributeNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(ATTRIBUTES);
        Enumeration enAttribs = httpRequest.getAttributeNames();
        while (enAttribs.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String attribName = (String) enAttribs.nextElement();
            sb.append(attribName);
            sb.append(" : ");
            sb.append(httpRequest.getAttribute(attribName));
        }
    }
    //Headers
    if (httpRequest.getHeaderNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(HEADERS);
        Enumeration enHeaders = httpRequest.getHeaderNames();
        while (enHeaders.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String headerName = (String) enHeaders.nextElement();
            sb.append(headerName);
            sb.append(" : ");
            sb.append(httpRequest.getHeader(headerName));
        }
    }
    //AuthType
    if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(AUTH_TYPE);
        sb.append(httpRequest.getAuthType());
    }
    //Cookies
    if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) {
        sb.append(System.lineSeparator());
        sb.append(COOKIES);
        for (Cookie cookie : httpRequest.getCookies()) {
            sb.append(System.lineSeparator());
            sb.append(cookie.getName());
            sb.append(" : ");
            sb.append(cookie.getValue());
        }
    }
    //RemoteAddr
    if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_ADDR);
        sb.append(httpRequest.getRemoteAddr());
    }
    //RemoteHost
    if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_HOST);
        sb.append(httpRequest.getRemoteHost());
    }
    //User principal
    if (httpRequest.getUserPrincipal() != null) {
        if (httpRequest.getUserPrincipal().getName() != null
                && !httpRequest.getUserPrincipal().getName().isEmpty()) {
            sb.append(System.lineSeparator());
            sb.append(PRINCIPAL);
            sb.append(httpRequest.getUserPrincipal().getName());
        }
    }
    //Body
    ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
            (HttpServletRequest) request);
    String body = IOUtils.toString(wrappedRequest.getReader());
    if (body != null && !body.isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(BODY);
        sb.append(System.lineSeparator());
        sb.append(body);
    }
    wrappedRequest.resetInputStream();

    LOGGER.info(sb.toString());
    chain.doFilter(wrappedRequest, response);
}

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

/**
 * /*from  w  ww .ja v  a2  s. c  o 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:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * /*from w w  w.j  av  a 2 s.c  o  m*/
 *
 * @param shoppingCart
 * @return int
 * @throws UnsupportedEncodingException
 */
@Override
@Transactional
public int addShoppingCart(ShoppingCart shoppingCart, HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    Long custId = (Long) request.getSession().getAttribute(CUSTOMERID);
    if (null != custId) {
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", custId);
        int sum = shoppingCartMapper.selectSumByCustomerId(map);
        if (sum >= 20) {
            return -1;
        }
        shoppingCart.setCustomerId(custId);
        shoppingCart.setDelFlag("0");
        shoppingCart.setShoppingCartTime(new Date());
        int count = shoppingCartMapper.selectCountByReady(shoppingCart);

        if (count == 0) {
            return shoppingCartMapper.addShoppingCart(shoppingCart);
        } else {
            ShoppingCart sc = shoppingCartMapper.selectShopingByParam(shoppingCart);
            // ?
            if (sc.getGoodsNum() == 99) {
                return 0;
            }
            return shoppingCartMapper.updateShoppingCart(shoppingCart);
        }
    } else {
        num = "";
        Cookie[] cookies = request.getCookies();
        String oldCar = "";
        String mId = "";
        Cookie cook;
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (null != cookie && NPSTORE_SHOPCAR.equals(cookie.getName())) {
                    oldCar = URLDecoder.decode(cookie.getValue(), "utf-8");
                    if (oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-") != -1) {
                        num = oldCar.substring(oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-"),
                                oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-") + oldCar
                                        .substring(oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-"),
                                                oldCar.length() - 1)
                                        .indexOf("&"));
                        num = num.substring(num.indexOf("-") + 1, num.length());
                        oldCar = oldCar.replace("," + shoppingCart.getGoodsInfoId() + "-" + num + "&"
                                + shoppingCart.getDistinctId() + "e", "");
                        if (oldCar.indexOf("," + shoppingCart.getGoodsInfoId() + "-" + num + "&"
                                + shoppingCart.getDistinctId()) != -1) {
                            oldCar = oldCar.replace("," + shoppingCart.getGoodsInfoId() + "-" + num + "&"
                                    + shoppingCart.getDistinctId(), "");

                        }
                    }
                }
                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 && "".equals(mIds[0])
                                && !mid[0].equals(shoppingCart.getGoodsInfoId().toString())) {
                            mId = cookie.getValue();
                        }
                    }
                }

            }
        }
        if (!"".equals(num)) {
            num = String.valueOf(Long.parseLong(num) + shoppingCart.getGoodsNum());
        } else {
            num = String.valueOf(shoppingCart.getGoodsNum());
        }
        oldCar += "," + shoppingCart.getGoodsInfoId() + "-" + num + "&" + shoppingCart.getDistinctId() + "e";
        GoodsDetailBean goodsDetailBean = null;
        if (shoppingCart.getFitId() == null) {
            goodsDetailBean = goodsProductService.queryDetailBeanByProductId(shoppingCart.getGoodsInfoId(),
                    Long.parseLong("0"), null);

        }
        cook = new Cookie(NPSTORE_SHOPCAR, URLEncoder.encode(oldCar, "utf-8"));
        cook.setMaxAge(15 * 24 * 3600);
        cook.setPath("/");
        response.addCookie(cook);
        Cookie cookie = new Cookie(NPSTORE_MID, mId);
        cookie.setMaxAge(15 * 24 * 3600);
        cookie.setPath("/");
        response.addCookie(cookie);
        return 1;
    }
}

From source file:com.adito.security.DefaultLogonController.java

private void refreshLogonTicket(HttpServletRequest request, HttpServletResponse response, String logonTicket)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Refreshing logon ticket " + logonTicket);
    User user = getUser(request, logonTicket);
    request.getSession().setAttribute(Constants.USER, user);
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    SessionInfo info = (SessionInfo) logons.get(logonTicket);
    if (info == null) {
        InetAddress address;/*w  w w. j av a2s. co  m*/
        try {
            address = InetAddress.getByName(request.getRemoteAddr());
        } catch (UnknownHostException uhe) {
            throw new SecurityErrorException(SecurityErrorException.ERR_INVALID_TICKET,
                    "Could not refresh logon ticket. " + uhe.getMessage());
        }
        String userAgent = request.getHeader("User-Agent");
        info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, SessionInfo.UI,
                userAgent);
    } else {
        moveSessionTimeoutBlocks(info.getHttpSession(), request.getSession());
        info.setSession(request.getSession());
    }
    request.getSession().setAttribute(Constants.SESSION_INFO, info);

    /**
     * LDP - Allow for the session info to be looked up using the session
     * id.
     */
    try {
        String sessionIdentifier = SystemProperties.get("adito.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    addSession(logonTicket, info, request, response);
    try {
        if (Property.getPropertyBoolean(new SystemConfigKey("security.session.lockSessionOnBrowserClose"))) {
            if (log.isInfoEnabled())
                log.info("New session - will force the user to authenticate again");
            request.getSession().setAttribute(Constants.SESSION_LOCKED, user);
        } else {
            ResourceUtil.setAvailableProfiles(info);
        }
    } catch (Exception e) {
        log.warn("Failed to set session lock.", e);
    }
}

From source file:com.sslexplorer.security.DefaultLogonController.java

private void refreshLogonTicket(HttpServletRequest request, HttpServletResponse response, String logonTicket)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Refreshing logon ticket " + logonTicket);
    User user = getUser(request, logonTicket);
    request.getSession().setAttribute(Constants.USER, user);
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    SessionInfo info = (SessionInfo) logons.get(logonTicket);
    if (info == null) {
        InetAddress address;//from w w  w .j a  va2s.c  o m
        try {
            address = InetAddress.getByName(request.getRemoteAddr());
        } catch (UnknownHostException uhe) {
            throw new SecurityErrorException(SecurityErrorException.ERR_INVALID_TICKET,
                    "Could not refresh logon ticket. " + uhe.getMessage());
        }
        String userAgent = request.getHeader("User-Agent");
        info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, SessionInfo.UI,
                userAgent);
    } else {
        moveSessionTimeoutBlocks(info.getHttpSession(), request.getSession());
        info.setSession(request.getSession());
    }
    request.getSession().setAttribute(Constants.SESSION_INFO, info);

    /**
     * LDP - Allow for the session info to be looked up using the session
     * id.
     */
    try {
        String sessionIdentifier = SystemProperties.get("sslexplorer.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    addSession(logonTicket, info, request, response);
    try {
        if (Property.getPropertyBoolean(new SystemConfigKey("security.session.lockSessionOnBrowserClose"))) {
            if (log.isInfoEnabled())
                log.info("New session - will force the user to authenticate again");
            request.getSession().setAttribute(Constants.SESSION_LOCKED, user);
        } else {
            ResourceUtil.setAvailableProfiles(info);
        }
    } catch (Exception e) {
        log.warn("Failed to set session lock.", e);
    }
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

private void monitoring(Map<HttpParameter, String> parameters, boolean checkResultContent)
        throws IOException, ServletException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes();
    expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(request.getRemoteAddr()).andReturn("here").anyTimes();
    final Random random = new Random();
    if (random.nextBoolean()) {
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("application/gzip"))).anyTimes();
    } else {//from   ww  w  . ja va2 s. co  m
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("text/html"))).anyTimes();
    }
    for (final Map.Entry<HttpParameter, String> entry : parameters.entrySet()) {
        if (HttpParameter.REQUEST == entry.getKey()) {
            expect(request.getHeader(entry.getKey().getName())).andReturn(entry.getValue()).anyTimes();
        } else {
            expect(entry.getKey().getParameterFrom(request)).andReturn(entry.getValue()).anyTimes();
        }
    }
    final Range range = Period.JOUR.getRange();
    final List<JavaInformations> javaInformationsList = Collections
            .singletonList(new JavaInformations(null, false));
    // getAttribute("range") et getAttribute("javaInformationsList") pour PdfController
    expect(request.getAttribute("range")).andReturn(range).anyTimes();
    expect(request.getAttribute("javaInformationsList")).andReturn(javaInformationsList).anyTimes();
    if (parameters.isEmpty() || HttpPart.JNLP.getName().equals(parameters.get(HttpParameter.PART))) {
        // dans au moins un cas on met un cookie
        final Cookie[] cookies = { new Cookie("dummy", "dummy"),
                new Cookie(PERIOD_COOKIE_NAME, Period.SEMAINE.getCode()), };
        expect(request.getCookies()).andReturn(cookies).anyTimes();
    }
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes();
    final StringWriter stringWriter = new StringWriter();
    expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes();
    final FilterChain chain = createNiceMock(FilterChain.class);

    replay(request);
    replay(response);
    replay(chain);
    monitoringFilter.doFilter(request, response, chain);
    verify(request);
    verify(response);
    verify(chain);

    if (checkResultContent) {
        assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0);
    }
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//  w  ww .  j  a  v a  2  s .  c o m
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}