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.mhe.mediabanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = Configuration.getSystemValue(Constants.IMAGE_THUMBNAIL_URL_PATH);
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;//from w  w  w  . j  a  v  a2 s.c o m
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");
        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}

From source file:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>/*ww  w  .  j  a  va  2 s .  co m*/
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }//from  w  ww.j  av  a  2  s.  c om
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:nl.surfnet.mujina.saml.SSOSuccessAuthnResponder.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AuthnRequestInfo info = (AuthnRequestInfo) request.getSession()
            .getAttribute(AuthnRequestInfo.class.getName());

    if (info == null) {
        logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//ww  w  . j  a v a 2 s. c  o  m
    }

    logger.debug("AuthnRequestInfo: {}", info);

    SimpleAuthentication authToken = (SimpleAuthentication) SecurityContextHolder.getContext()
            .getAuthentication();
    DateTime authnInstant = new DateTime(request.getSession().getCreationTime());

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(idpConfiguration.getEntityID()));
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    Credential signingCredential = null;
    try {
        signingCredential = credentialResolver.resolveSingle(criteriaSet);
    } catch (org.opensaml.xml.security.SecurityException e) {
        logger.warn("Unable to resolve EntityID while signing", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Validate.notNull(signingCredential);

    AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(signingCredential,
            idpConfiguration.getEntityID(), timeService, idService, idpConfiguration);
    EndpointGenerator endpointGenerator = new EndpointGenerator();

    final String remoteIP = request.getRemoteAddr();
    String attributeJson = null;

    if (null != request.getCookies()) {
        for (Cookie current : request.getCookies()) {
            if (current.getName().equalsIgnoreCase("mujina-attr")) {
                logger.info("Found a attribute cookie, this is used for the assertion response");
                attributeJson = URLDecoder.decode(current.getValue(), "UTF-8");
            }
        }
    }
    String acsEndpointURL = info.getAssertionConsumerURL();
    if (idpConfiguration.getAcsEndpoint() != null) {
        acsEndpointURL = idpConfiguration.getAcsEndpoint().getUrl();
    }
    Response authResponse = authnResponseGenerator.generateAuthnResponse(remoteIP, authToken, acsEndpointURL,
            responseValidityTimeInSeconds, info.getAuthnRequestID(), authnInstant, attributeJson,
            info.getEntityId());
    Endpoint endpoint = endpointGenerator.generateEndpoint(
            org.opensaml.saml2.metadata.AssertionConsumerService.DEFAULT_ELEMENT_NAME, acsEndpointURL, null);

    request.getSession().removeAttribute(AuthnRequestInfo.class.getName());

    String relayState = request.getParameter("RelayState");

    //we could use a different adapter to send the response based on request issuer...
    try {
        adapter.sendSAMLMessage(authResponse, endpoint, response, relayState, signingCredential);
    } catch (MessageEncodingException mee) {
        logger.error("Exception encoding SAML message", mee);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

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

/**
 * cookie?//w  w  w  .  j a v a  2 s  . c  o  m
 *
 * @param request
 *            
 * @param response
 *            
 * @return ?
 * @throws UnsupportedEncodingException
 */
public int delCookShopCar(Long productId, HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    Integer count = 0;
    Cookie[] cookies = request.getCookies();
    String oldCar = "";
    String[] cars = null;
    String[] car = null;
    Cookie cook;
    String newMid = "";
    StringBuilder bufOldCar = new StringBuilder();
    StringBuilder bufNewMid = new StringBuilder();

    try {
        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("," + productId + "-") != -1) {
                        oldCar = oldCar.substring(1, oldCar.length());
                        oldCar = oldCar.substring(0, oldCar.length() - 1);
                        cars = oldCar.split("e,");
                        oldCar = "";
                        for (int j = 0; j < cars.length; j++) {
                            car = cars[j].split("-");
                            if (!car[0].equals(productId.toString())) {
                                bufOldCar.append(oldCar);
                                bufOldCar.append(",");
                                bufOldCar.append(car[0]);
                                bufOldCar.append("-");
                                bufOldCar.append(car[1]);
                                bufOldCar.append("e");
                                oldCar += bufOldCar.toString();
                            }
                        }
                    }
                }
                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 && !mid[0].equals(productId.toString())) {
                            bufNewMid.append(mIds[j]);
                            bufNewMid.append("-");
                            newMid += bufNewMid.toString();
                        }
                    }
                }

            }
        }
        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, URLEncoder.encode(newMid, "utf-8"));
        cookie.setMaxAge(15 * 24 * 3600);
        cookie.setPath("/");
        response.addCookie(cookie);
        return count;
    } finally {
        cook = null;
        cars = null;
        car = null;
        cookies = null;
        oldCar = null;
    }
}

From source file:org.dspace.webmvc.theme.ThemeChangeInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);
    if (themeResolver == null) {
        throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?");
    }/*from w w  w. ja  v  a 2s.  com*/

    String newTheme = request.getParameter(this.paramName);
    if (newTheme != null) {
        themeResolver.setThemeName(request, response, newTheme);
        response.addCookie(new Cookie("themeName", newTheme));
    } else {
        ThemeMapEntry bestMatch = null;

        for (ThemeMapEntry entry : themeMappings) {

            if (entry.mapType == MapType.VIEW || entry.mapType == MapType.ANY) {
                if (modelAndView != null && pathMatcher.match(entry.path, modelAndView.getViewName())) {
                    if (entry.isBestMatch(bestMatch)) {
                        bestMatch = entry;
                    }
                }
            }

            if (entry.mapType == MapType.URL || entry.mapType == MapType.ANY) {
                String path = urlPathHelper.getLookupPathForRequest(request);
                if (pathMatcher.match(entry.path, path)) {
                    if (entry.isBestMatch(bestMatch)) {
                        bestMatch = entry;
                    }
                }
            }

            if (entry.mapType == MapType.CONTROLLER || entry.mapType == MapType.ANY) {

            }
        }

        if (bestMatch != null) {
            themeResolver.setThemeName(request, response, bestMatch.themeName);
        } else if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("themeName".equals(cookie.getName())) {
                    themeResolver.setThemeName(request, response, cookie.getValue());
                }
            }
        }
    }

    super.postHandle(request, response, handler, modelAndView);
}

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

/**
 * cookie?// w  ww  . ja v a 2  s.  co  m
 *
 * @return 
 * @throws UnsupportedEncodingException
 */
public List<ShopCarUtil> loadCookShopCar(HttpServletRequest request) throws UnsupportedEncodingException {
    List<ShopCarUtil> list = new ArrayList<ShopCarUtil>();
    Cookie[] cookies = request.getCookies();
    String oldCar = "";
    String[] cars = null;
    String[] car = null;
    String[] car2 = null;
    ShopCarUtil carUtil = null;
    boolean checkExists = false;
    try {
        if (null != cookies) {
            for (Cookie cookie : cookies) {

                if (null != cookie && NPSTORE_SHOPCAR.equals(cookie.getName()) && cookie.getValue() != null
                        && !"".equals(cookie.getValue())) {
                    oldCar = URLDecoder.decode(cookie.getValue(), "utf-8");
                    oldCar = oldCar.substring(1, oldCar.length());
                    oldCar = oldCar.substring(0, oldCar.length() - 1);
                    cars = oldCar.split("e,");
                    if (null != cars && cars.length > 0) {
                        for (int i = 0; i < cars.length; i++) {
                            car = cars[i].split("-");
                            carUtil = new ShopCarUtil();

                            /* ?,,?? */
                            if (car[0].length() > 6 && CODE001.equals(car[0].substring(0, 6))) {
                                carUtil.setFitId(Long.parseLong(car[0].substring(6, car[0].length())));
                                carUtil.setProductId(Long.parseLong(car[0]));
                            } else {
                                carUtil.setProductId(Long.parseLong(car[0]));
                                for (Cookie cook : cookies) {
                                    // 
                                    if (cook != null && NPSTORE_MID.equals(cook.getName())
                                            && cook.getValue() != null && !"".equals(cook.getValue())) {
                                        String[] mIds = cook.getValue().split("-");
                                        // ?cookie
                                        for (int j = 0; j < mIds.length; j++) {
                                            String[] mid = mIds[j].split("e");
                                            // ??
                                            if (mid[0] != null && car[0].equals(mid[0])) {
                                                if (mid[1] != null && !"null".equals(mid[1])) {
                                                    carUtil.setMarketId(Long.parseLong(mid[1]));
                                                }

                                                carUtil.setMarketActiveId(Long.parseLong(mid[2]));
                                                carUtil.setStatus(Long.parseLong(mid[3]));
                                            }
                                        }
                                    }
                                }
                                car2 = car[1].split("&");
                                carUtil.setGoodsNum(Integer.parseInt(car2[0]));
                                carUtil.setDistinctId(Long.parseLong(car2[1]));
                                for (int j = 0; j < list.size(); j++) {
                                    if (list.get(j).getProductId().equals(carUtil.getProductId())) {
                                        checkExists = true;
                                    }
                                }
                                if (!checkExists) {
                                    list.add(carUtil);
                                    checkExists = false;
                                }
                            }
                        }
                    }

                }

            }
        }
        return list;
    } finally {
        list = null;
        cookies = null;
        oldCar = null;
        cars = null;
        car = null;
    }
}

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

public void logoffSession(HttpServletRequest request, HttpServletResponse response)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Logging off session " + request.getSession().getId());
    if (request.getSession().getAttribute(Constants.LOGON_TICKET) == null) {
        throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR,
                "The current session does not contain a logon ticket");
    } else {/*w  w  w  . j a v  a  2s.  c om*/
        String ticket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET);
        SessionInfo session = getSessionInfo(ticket);
        logoff(ticket);

        if (request.getCookies() != null) {
            for (int i = 0; i < request.getCookies().length; i++) {
                Cookie cookie = request.getCookies()[i];
                if (cookie.getName().equals(Constants.LOGON_TICKET)
                        || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
        request.getSession().removeAttribute(Constants.LOGON_TICKET);
        session.invalidate();
    }
}

From source file:net.fenyo.mail4hotspot.web.WebController.java

@RequestMapping(value = "/navigation")
public ModelAndView nav(@RequestParam(value = "url", required = false) String target_url,
        HttpServletRequest request) throws IOException {
    log.info("TRACE: navigation;get;" + target_url + ";");

    @SuppressWarnings("unchecked")
    final Map<String, String[]> parameters = request.getParameterMap();

    boolean first_param = true;
    if (target_url == null || target_url.isEmpty())
        target_url = "http://www.bing.com/";
    else if (!parameters.keySet().isEmpty()) {
        for (final String key : parameters.keySet())
            if (!key.equals("url"))
                for (final String val : parameters.get(key)) {
                    if (first_param == false)
                        target_url += "&";
                    if (first_param == true) {
                        target_url += "?";
                        first_param = false;
                    }//w w  w  . j ava  2s  .c o m
                    target_url += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(val, "UTF-8");
                }
    }
    log.info("TRACE: navigation;target url;" + target_url + ";");

    ModelAndView mav = new ModelAndView();
    mav.setViewName("navigation");

    String simple_html;
    try {
        simple_html = Browser.getSimpleHtml(target_url, request.getCookies());
    } catch (final IOException ex) {
        log.info("TRACE: navigation;exception;" + target_url + ";");
        simple_html = "<BODY><center><a href='#en'>english</a> - <a href='#fr'>franais</a></center><p/><hr/>"
                + "<a name='en'/><table><tr><td bgcolor='#A00000'><font color='white'>An error occured while downloading the page your requested from this server</font></td></tr></table>"
                + "<P/><font size='-1'><b>Cause</b>: the internal browser shipped with <i>VPN-over-DNS</i> is optimized to be very efficient on low-bandwith networks. For this purpose, it may disable some features needed by this targeted web site: JavaScript, Cascading Style Sheets, Cookies or SSL/TLS (https) transport protocol support."
                + "<P/>"
                + "<b>Solution</b>: you can browse this site with your prefered full-featured browser installed on this device, simply by using one of those two <b>proxy</b> configurations:<br/>"
                + "<UL>" +

                "    <LI><b>fast browsing proxy</b>" + "        <UL>"
                + "            <LI>remote host : <b>localhost</b></LI>"
                + "            <LI>remote port : <b>8080</b></LI>"
                + "            <LI>supported features: JavaScript, CSS &amp; Cookies</LI>" + "        </UL>"
                + "    </LI><BR/>" +

                "    <LI><b>full-featured browsing proxy</b>" + "        <UL>"
                + "            <LI>remote host : <b>localhost</b></LI>"
                + "            <LI>remote port : <b>8081</b></LI>"
                + "            <LI>supported features: pictures, SSL/TLS (https), JavaScript, CSS &amp; Cookies</LI>"
                + "        </UL>" + "    </LI>" + "</UL>"
                + "<b>Note</b>: you need to let <i>VPN-over-DNS</i> running in the background while using your browser with one of those two proxy configurations, since the implementation of those proxies is made through <i>VPN-over-DNS</i>."
                + "<p/>Support available on www.vpnoverdns.com" +

                "<HR/>" +

                "<BODY><a name='fr'/><table><tr><td bgcolor='#A00000'><font color='white'>Une erreur s'est produite lors du tlchargement de la page</font></td></tr></table>"
                + "<P/><font size='-1'><b>Raison</b>: le navigateur intgr  <i>VPN-over-DNS</i> est optimis pour tre particulirement efficace sur les rseaux  bas dbit. Pour cela, il n'implmente pas certaines fonctions ventuellement ncessaires au site que vous avez slectionn : JavaScript, Cascading Style Sheets, Cookies ou encore le protocole de transport SSL/TLS (https)."
                + "<P/>"
                + "<b>Solution</b>: vous pouvez naviguer sur ce site web avec n'importe quel navigateur install sur ce priphrique et proposant ces fonctionnalits avances, simplement en configurant votre <b>proxy</b> suivant l'une ou l'autre de ces deux alternatives :<br/>"
                + "<UL>" +

                "    <LI><b>navigation rapide</b>" + "        <UL>"
                + "            <LI>hte distant : <b>localhost</b></LI>"
                + "            <LI>port distant : <b>8080</b></LI>"
                + "            <LI>fonctionnalits disponibles : JavaScript, CSS &amp; Cookies</LI>"
                + "        </UL>" + "    </LI><BR/>" +

                "    <LI><b>navigation avec fonctions tendues</b>" + "        <UL>"
                + "            <LI>hte distant : <b>localhost</b></LI>"
                + "            <LI>port distant : <b>8081</b></LI>"
                + "            <LI>fonctionnalits disponibles : images, SSL/TLS (https), JavaScript, CSS &amp; Cookies</LI>"
                + "        </UL>" + "    </LI>" + "</UL>"
                + "<b> noter</b> : vous devez laisser <i>VPN-over-DNS</i> fonctionner en tche de fond lors de l'utilisation de votre navigateur via l'un ou l'autre de ces proxies, ils sont en effet implments  travers <i>VPN-over-DNS</i>."
                + "<p/>Support disponible sur www.vpnoverdns.com" +

                "</BODY>";
    }
    mav.addObject("htmlContent", simple_html);
    log.info("TRACE: navigation;done;" + target_url + ";" + simple_html.length() + ";");

    return mav;
}