Example usage for javax.servlet.http Cookie setValue

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

Introduction

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

Prototype

public void setValue(String newValue) 

Source Link

Document

Assigns a new value to this Cookie.

Usage

From source file:com.enonic.vertical.userservices.UserHandlerController.java

private void processLogout(SiteContext siteContext, HttpServletRequest request, HttpServletResponse response,
        HttpSession session, ExtendedMap formItems, UserServicesService userServices)
        throws VerticalUserServicesException, RemoteException {

    UserStoreKey userStoreKey = parseUserStoreKeyFromUidAndUserstore(formItems);

    if (session != null) {
        // Create log entry:
        User user = securityService.getOldUserObject();
        if (user != null && !user.isAnonymous()) {
            if (siteContext.isAuthenticationLoggingEnabled()) {
                createLogEntry(siteContext, user, userServices, request.getRemoteAddr(),
                        LogType.LOGOUT.asInteger(), userStoreKey);
            }/*from   w w w.  java 2 s.c  o  m*/
        } else {
            String message = "User is not logged in.";
            VerticalUserServicesLogger.warn(this.getClass(), 0, message, null);
            redirectToErrorPage(request, response, formItems, ERR_USER_NOT_LOGGED_IN, null);
            return;
        }

        // Remove GUID cookie if present
        String cookieName = "guid-" + siteContext.getSiteKey();
        Cookie cookie = CookieUtil.getCookie(request, cookieName);
        if (cookie != null) {
            cookie.setValue(null);
            response.addCookie(cookie);
        }

        removeGuidCookie(response, DeploymentPathResolver.getSiteDeploymentPath(request), siteContext);
        securityService.logoutPortalUser();

        redirectToPage(request, response, formItems);
    }
}

From source file:com.enonic.cms.web.portal.services.UserServicesProcessor.java

private void processLogout(SiteContext siteContext, HttpServletRequest request, HttpServletResponse response,
        ExtendedMap formItems) throws VerticalUserServicesException, RemoteException {
    final HttpSession session = ServletRequestAccessor.getSession(false);

    if (session != null) {
        // Create log entry:
        User user = securityService.getLoggedInPortalUser();
        if (user != null && !user.isAnonymous()) {
            if (siteContext.isAuthenticationLoggingEnabled()) {
                logLogout(siteContext, user, request.getRemoteAddr());
            }//ww w.  j ava  2 s  .co  m
        } else {
            String message = "User is not logged in.";
            VerticalUserServicesLogger.warn(message);
            redirectToErrorPage(request, response, formItems, ERR_USER_NOT_LOGGED_IN);
            return;
        }

        // Remove GUID cookie if present
        String cookieName = "guid-" + siteContext.getSiteKey();
        Cookie cookie = CookieUtil.getCookie(request, cookieName);
        if (cookie != null) {
            cookie.setValue(null);
            response.addCookie(cookie);
        }

        removeGuidCookie(response, DeploymentPathResolver.getSiteDeploymentPath(request), siteContext);
        this.securityService.logoutPortalUser();
        this.loginService.removeRememberedLogin(user.getKey());

        redirectToPage(request, response, formItems);
    }
}

From source file:uk.ac.ox.webauth.FilterWorker.java

/**
 * Try to grab an app token and get the username from there.
 * @param   privateKey  The most suitable key to decrypt the token with.
 *//*from   w ww .ja  v a2  s .  c  o  m*/
private void handleAppCookie(WebauthKey privateKey) throws ServletException {
    if (!cookies.containsKey("webauth_at")) {
        return;
    }
    Cookie webauth_at = cookies.get("webauth_at");
    Token app = null;
    try {
        app = decrypt(webauth_at.getValue(), "app");
    }
    // if the user has a bad app cookie then return
    catch (ServletException se) {
        return;
    }
    if (logger.debug()) {
        debug(app.toString());
    }
    username = app.getString("s");
    if (username == null || username.length() < 1) {
        return;
    }
    if (app.getBinary("lt") != null) {
        app.add("lt", Token.unixTimestampBytes(System.currentTimeMillis()));
        String encrypted = null;
        try {
            encrypted = app.encrypt(privateKey.key());
        } catch (GeneralSecurityException gse) {
            throw new ServletException("Could not encrypt app-token.", gse);
        }
        webauth_at.setValue(encrypted);
        webauth_at.setSecure(true);
        webauth_at.setMaxAge(-1);
        webauth_at.setPath("/");
        response.addCookie(webauth_at);
        debug("Setting a new last-used time on app token cookie.");
    }
    debug("Found a valid app-token cookie.");
}

From source file:org.opencms.workplace.CmsLogin.java

/**
 * Returns the HTML for the login dialog in it's current state.<p>
 * //from ww w.  j  a v a2  s.co m
 * @return the HTML for the login dialog
 * 
 * @throws IOException in case a redirect fails
 */
public String displayDialog() throws IOException {

    if ((OpenCms.getSiteManager().getSites().size() > 1)
            && !OpenCms.getSiteManager().isWorkplaceRequest(getRequest())) {

        // this is a multi site-configuration, but not a request to the configured Workplace site
        StringBuffer loginLink = new StringBuffer(256);
        loginLink.append(OpenCms.getSiteManager().getWorkplaceSiteMatcher().toString());
        loginLink.append(getFormLink());
        // send a redirect to the workplace site
        getResponse().sendRedirect(loginLink.toString());
        return null;
    }

    CmsObject cms = getCmsObject();

    m_message = null;
    if (cms.getRequestContext().getCurrentUser().isGuestUser()) {
        // user is not currently logged in
        m_action = ACTION_DISPLAY;
        m_username = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_USERNAME);
        if (m_username != null) {
            // remove white spaces, can only lead to confusion on user name
            m_username = m_username.trim();
        }
        m_password = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_PASSWORD);
        m_actionLogin = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_LOGIN);
        m_oufqn = getRequest().getParameter(PARAM_OUFQN);
        if (m_oufqn == null) {
            m_oufqn = getPreDefOuFqn();
        }
        if (OpenCms.getLoginManager().isEnableSecurity()) {
            // security option is enabled, try to get PC type from request parameter
            m_pcType = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_PCTYPE);
        } else {
            // if security option is disabled, just set PC type to "private" to get common login dialog
            m_pcType = PCTYPE_PRIVATE;
        }
        // try to get some info from a cookie
        getCookieData();

        // set PC type to "public" as default if not already set by cookie, request or if security option is disabled
        if (m_pcType == null) {
            m_pcType = PCTYPE_PUBLIC;
        }
    } else {
        // user is already logged in
        m_oufqn = cms.getRequestContext().getOuFqn();
        m_action = ACTION_LOGIN;
        m_actionLogout = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_LOGOUT);
    }

    if (m_oufqn == null) {
        m_oufqn = CmsOrganizationalUnit.SEPARATOR;
    }

    String actionGetOus = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_GETOULIST);
    if (Boolean.TRUE.toString().equals(actionGetOus)) {
        return getJsonOrgUnitList();
    }

    // initialize the right ou
    m_ou = null;
    try {
        m_ou = OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn);
    } catch (CmsException e) {
        m_oufqn = CmsOrganizationalUnit.SEPARATOR;
        try {
            m_ou = OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn);
        } catch (CmsException exc) {
            LOG.error(exc.getLocalizedMessage(), exc);
        }
    }

    // initialize the requested resource
    m_requestedResource = CmsRequestUtil.getNotEmptyParameter(getRequest(),
            CmsWorkplaceManager.PARAM_LOGIN_REQUESTED_RESOURCE);
    if (m_requestedResource == null) {
        // no resource was requested, use default workplace URI
        m_requestedResource = CmsFrameset.JSP_WORKPLACE_URI;
    }

    if (Boolean.valueOf(m_actionLogin).booleanValue()) {
        // login was requested
        if ((m_username == null) && (m_password == null)) {
            m_message = Messages.get().container(Messages.GUI_LOGIN_NO_DATA_0);
        } else if (m_username == null) {
            m_message = Messages.get().container(Messages.GUI_LOGIN_NO_NAME_0);
        } else if (m_password == null) {
            m_message = Messages.get().container(Messages.GUI_LOGIN_NO_PASSWORD_0);
        } else if ((m_username != null) && (m_password != null)) {

            // try to login with the given user information
            login((m_oufqn == null ? CmsOrganizationalUnit.SEPARATOR : m_oufqn) + m_username, m_password);

            if (getLoginException() == null) {
                // the login was successful
                m_action = ACTION_LOGIN;

                // set the default project of the user
                CmsUserSettings settings = new CmsUserSettings(cms);

                // get the direct edit path
                m_directEditPath = getDirectEditPath(settings);

                try {
                    CmsProject project = cms.readProject(settings.getStartProject());
                    if (OpenCms.getOrgUnitManager().getAllAccessibleProjects(cms, project.getOuFqn(), false)
                            .contains(project)) {
                        // user has access to the project, set this as current project
                        cms.getRequestContext().setCurrentProject(project);
                    }
                } catch (CmsException e) {
                    // unable to set the startup project, bad but not critical
                    LOG.warn(Messages.get().getBundle().key(Messages.LOG_LOGIN_NO_STARTUP_PROJECT_2, m_username,
                            settings.getStartProject()), e);
                }
            } else {
                // there was an error during login

                if (org.opencms.security.Messages.ERR_LOGIN_FAILED_DISABLED_2 == getLoginException()
                        .getMessageContainer().getKey()) {
                    // the user account is disabled
                    m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_DISABLED_0);
                } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_TEMP_DISABLED_4 == getLoginException()
                        .getMessageContainer().getKey()) {
                    // the user account is temporarily disabled because of too many login failures
                    m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_TEMP_DISABLED_0);
                } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1 == getLoginException()
                        .getMessageContainer().getKey()) {
                    // all logins have been disabled be the Administration
                    CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
                    if (loginMessage != null) {
                        m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_WITH_MESSAGE_1,
                                loginMessage.getMessage());
                    }
                }
                if (m_message == null) {
                    // any other error - display default message
                    m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_0);
                }
            }
        }
    } else if (Boolean.valueOf(m_actionLogout).booleanValue()) {
        m_action = ACTION_LOGOUT;
        // store the workplace window data
        Cookie wpDataCookie = getCookie(COOKIE_WP_DATA);
        String wpData = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_WPDATA);
        if (wpData != null) {
            wpData = CmsEncoder.escapeXml(wpData);
            wpDataCookie.setValue(wpData);
            setCookie(wpDataCookie, false);
        }
        // after logout this will automatically redirect to the login form again
        logout();
        return null;
    }

    if (m_action == ACTION_LOGIN) {
        // clear message
        m_message = null;
        // login is successful, check if the requested resource can be read
        CmsUriSplitter splitter = new CmsUriSplitter(m_requestedResource, true);
        String resource = splitter.getPrefix();
        if (CmsStringUtil.isEmptyOrWhitespaceOnly(resource)) {
            // bad resource name, use workplace as default
            resource = CmsFrameset.JSP_WORKPLACE_URI;
        }
        if (!getCmsObject().existsResource(resource, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
            // requested resource does either not exist or is not readable by user
            if (CmsFrameset.JSP_WORKPLACE_URI.equals(resource)) {
                // we know the Workplace exists, so the user does not have access to the Workplace
                // probably this is a "Guest" user in a default setup where "Guest" has no access to the Workplace
                m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_NO_WORKPLACE_PERMISSIONS_0);
                m_action = ACTION_DISPLAY;
            } else if (getCmsObject().existsResource(CmsFrameset.JSP_WORKPLACE_URI)) {
                // resource does either not exist or is not readable, but general workplace permissions are granted
                m_message = Messages.get().container(Messages.GUI_LOGIN_UNKNOWN_RESOURCE_1,
                        m_requestedResource);
                m_requestedResource = CmsFrameset.JSP_WORKPLACE_URI;
            } else {
                // resource does not exist and no general workplace permissions granted
                m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_NO_TARGET_PERMISSIONS_1,
                        m_requestedResource);
                m_action = ACTION_DISPLAY;
            }
        }
        if (m_action == ACTION_DISPLAY) {
            // the login was invalid
            m_requestedResource = null;
            // destroy the generated session
            HttpSession session = getRequest().getSession(false);
            if (session != null) {
                session.invalidate();
            }
        } else {
            // successfully logged in, so set the cookie
            setCookieData();
        }
    }

    return displayLoginForm();
}

From source file:org.orcid.frontend.web.controllers.BaseController.java

protected void logoutCurrentUser(HttpServletRequest request, HttpServletResponse response) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (internalSSOManager.enableCookie()) {
        Cookie[] cookies = request.getCookies();
        // Delete cookie and token associated with that cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (InternalSSOManager.COOKIE_NAME.equals(cookie.getName())) {
                    try {
                        // If it is a valid cookie, extract the orcid value
                        // and
                        // remove the token and the cookie
                        @SuppressWarnings("unchecked")
                        HashMap<String, String> cookieValues = JsonUtils
                                .readObjectFromJsonString(cookie.getValue(), HashMap.class);
                        if (cookieValues.containsKey(InternalSSOManager.COOKIE_KEY_ORCID)
                                && !PojoUtil.isEmpty(cookieValues.get(InternalSSOManager.COOKIE_KEY_ORCID))) {
                            internalSSOManager.deleteToken(
                                    cookieValues.get(InternalSSOManager.COOKIE_KEY_ORCID), request, response);
                        } else {
                            // If it is not valid, just remove the cookie
                            cookie.setValue(StringUtils.EMPTY);
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }//from   w  w w  .  j av a 2  s  .  co m
                    } catch (RuntimeException re) {
                        // If any exception happens, but, the cookie exists,
                        // remove the cookie
                        cookie.setValue(StringUtils.EMPTY);
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                    break;
                }
            }
        }
        // Delete token if exists
        if (authentication != null && !PojoUtil.isEmpty(authentication.getName())) {
            internalSSOManager.deleteToken(authentication.getName());
        }
    }
    if (authentication != null && authentication.isAuthenticated()) {
        new SecurityContextLogoutHandler().logout(request, response, authentication);
    }
    CsrfToken token = csrfTokenRepository.generateToken(request);
    csrfTokenRepository.saveToken(token, request, response);
    request.setAttribute("_csrf", token);
}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP//  ww  w .ja v  a2  s  . c o  m
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String raceFleetKeyStr = request.getParameter("RaceFleetKey");
        if (raceFleetKeyStr == null) {
            throw new ServletException("no RaceFleetKey");
        }
        Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr);
        Entity raceFleetEntity = datastore.get(raceFleetKey);
        Key raceSeriesKey = raceFleetKey.getParent();
        Entity raceseriesEntity = datastore.get(raceSeriesKey);
        RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity);
        RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity);
        RaceEntry raceEntry = new RaceEntry(raceFleet);
        raceEntry.populate(request.getParameterMap());

        String fn = request.getParameter(RaceEntry.FIRSTNAME);
        String ln = request.getParameter(RaceEntry.LASTNAME);
        raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln);

        String sa = request.getParameter(RaceEntry.STREETADDRESS);
        String zc = request.getParameter(RaceEntry.ZIPCODE);
        String ct = request.getParameter(RaceEntry.CITY);
        String cn = request.getParameter(RaceEntry.COUNTRY);
        if (cn == null || cn.isEmpty()) {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct);
        } else {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn);
        }

        Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate);
        Number fee = 0.0;
        if (closingDay != null) {
            Day now = new Day();
            if (closingDay.before(now)) {
                fee = (Number) raceFleet.get(RaceFleet.Fee2);
            } else {
                fee = (Number) raceFleet.get(RaceFleet.Fee);
            }
        }
        Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT);
        String clubname = repositoryBundle.getString("Clubname");
        if (clubDiscount != null && clubDiscount
                && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) {
            fee = new Double(0);
        }
        raceEntry.set(RaceEntry.FEE, fee);
        raceEntry.set(RaceEntry.TIMESTAMP, new Date());

        entities.put(raceEntry);

        String payingInstructions = "";
        String payingInstructionsHtml = "";
        BankingBarcode bb = races.getBarcode(raceEntry);
        if (bb != null) {
            Day dueDay = new Day(bb.getDueDate());
            String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8");
            String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8");
            payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode
                    bb.getAccount().getIBAN(), // 2 = account
                    bb.getReference().toFormattedRFString(), // 3 = ref
                    dueDay, // 4 = due date
                    String.format("%.2f", bb.getTotal()), // 5 = total
                    bic // 6 = bic
            );
            payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"),
                    "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode
                    "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account
                    "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref
                    "<span id='due'>" + dueDay + "</span>", // 4 = due date
                    "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total
                    "<span id='bic'>" + bic + "</span>" // 6 = bic
            );
        }
        URL base = new URL(request.getRequestURL().toString());
        URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString());
        String name = (String) raceEntry.get(RaceEntry.HELMNAME);
        String email = (String) raceEntry.get(RaceEntry.HELMEMAIL);
        String confirmation = msg(Messages.RACEENTRYCONFIRMATION);
        String plainMessage = "";
        String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation)
                + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src="
                + barcodeUrl.toString() + "/>" + "</body></html>";
        if (email != null) {
            InternetAddress recipient = new InternetAddress(email, name);
            String senderStr = msg(Messages.RACEENTRYFROMADDRESS);
            InternetAddress sender;
            try {
                sender = new InternetAddress(senderStr);
                plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields();

                String subject = msg(Messages.RACEENTRYSUBJECT);
                mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient);
            } catch (Exception ex) {
                log(senderStr, ex);
            }
        }
        Cookie cookie = null;
        Cookie[] cookies = null;
        if (useCookies) {
            cookies = request.getCookies();
        }
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if (COOKIENAME.equals(ck.getName())) {
                    cookie = ck;
                }
            }
        }
        JSONObject json = null;
        if (useCookies && cookie != null) {
            Base64 decoder = new Base64();
            String str = new String(decoder.decode(cookie.getValue()));
            json = new JSONObject(str);
        } else {
            json = new JSONObject();
        }
        for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            String property = entry.getKey();
            String[] values = entry.getValue();
            if (values.length == 1) {
                json.put(property, values[0]);
            }
        }
        Base64 encoder = new Base64();
        String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8"));
        if (useCookies) {
            if (cookie == null) {
                cookie = new Cookie(COOKIENAME, base64);
                cookie.setPath("/");
                cookie.setMaxAge(400 * 24 * 60 * 60);
            } else {
                cookie.setValue(base64);
            }
            response.addCookie(cookie);
        }
        sendError(response, HttpServletResponse.SC_OK,
                "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>");
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eJSON\">Internal error.</div>");
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eEntityNotFound\">Internal error.</div>");
    } catch (NumberFormatException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>");
    }
}

From source file:org.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

@Override
public void addOrUpdateRecentProductToCookie(final Long productId, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    Cookie info = null;
    Cookie[] cookies = request.getCookies();
    Boolean found = false;/*from  w  ww  .ja  v  a2s .c  o  m*/
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            info = cookies[i];
            if (Constants.COOKIE_RECENT_PRODUCT_COOKIE_NAME.equals(info.getName())) {
                found = true;
                break;
            }
        }
    }
    if (found) {
        Boolean flag = false;
        String[] splits = info.getValue().split(" ");
        for (String value : splits) {
            if (value.equals(Long.toString(productId))) {
                flag = true;
            }
        }
        if (!flag) {
            String values = info.getValue();
            values += " " + Long.toString(productId);
            info.setValue(values);
            info.setPath("/");
            info.setMaxAge(Constants.COOKIES_LENGTH);
            info.setDomain(request.getServerName());
            response.addCookie(info);
        }
    } else {
        info = new Cookie(Constants.COOKIE_RECENT_PRODUCT_COOKIE_NAME, Long.toString(productId));
        info.setMaxAge(Constants.COOKIES_LENGTH);
        info.setPath("/");
        info.setDomain(request.getServerName());
        response.addCookie(info);
    }
}

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

@Override
public void createResultCookie(Cookie cookie, HttpServletRequest request, HttpServletResponse response)
        throws ServletException {

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    ConfigManager mgr = holder.getConfig();

    HashSet<String> mechs = new HashSet<String>();

    for (String mechName : mgr.getAuthMechs().keySet()) {
        MechanismType mech = mgr.getAuthMechs().get(mechName);
        if (mech.getClassName()
                .equalsIgnoreCase("com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie")) {
            mechs.add(mechName);/* www.j a v  a2  s .c om*/
        }
    }

    AuthController authCtl = (AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL);
    String chainName = authCtl.getAuthInfo().getAuthChain();

    AuthChainType chain = mgr.getAuthChains().get(chainName);

    int millisToLive = 0;
    String keyAlias = "";

    boolean useSSLSession = false;

    for (AuthMechType amt : chain.getAuthMech()) {
        if (mechs.contains(amt.getName())) {
            for (ParamType pt : amt.getParams().getParam()) {
                if (pt.getName().equalsIgnoreCase("millisToLive")) {
                    millisToLive = Integer.parseInt(pt.getValue());
                }
                if (pt.getName().equalsIgnoreCase("useSSLSessionID")
                        && pt.getValue().equalsIgnoreCase("true")) {
                    useSSLSession = true;
                } else if (pt.getName().equalsIgnoreCase("keyAlias")) {
                    keyAlias = pt.getValue();
                }
            }
        }
    }

    DateTime now = new DateTime();
    DateTime expires = now.plusMillis(millisToLive);

    com.tremolosecurity.lastmile.LastMile lastmile = null;

    try {
        lastmile = new com.tremolosecurity.lastmile.LastMile("/", now, expires, 0, "NONE");
    } catch (URISyntaxException e) {
        //not possible
    }

    lastmile.getAttributes().add(new Attribute("DN", authCtl.getAuthInfo().getUserDN()));
    lastmile.getAttributes().add(new Attribute("CLIENT_IP", request.getRemoteAddr()));

    if (useSSLSession) {

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

        lastmile.getAttributes().add(new Attribute("SSL_SESSION_ID", (String) sessionID));
    }

    try {
        cookie.setValue(new StringBuilder().append('"')
                .append(lastmile.generateLastMileToken(mgr.getSecretKey(keyAlias))).append('"').toString());
    } catch (Exception e) {
        throw new ServletException("Could not encrypt persistent cookie", e);
    }

    cookie.setMaxAge(millisToLive / 1000);

}

From source file:org.hoteia.qalingo.core.web.util.RequestUtil.java

public void addOrUpdateRecentProductToCookie(final HttpServletRequest request,
        final HttpServletResponse response, final String catalogCode, final String virtualCategoryCode,
        final String productMarketingCode, final String productSkuCode) throws Exception {
    Cookie info = null;
    String cookieProductValue = catalogCode + Constants.SEMI_COLON + virtualCategoryCode + Constants.SEMI_COLON
            + productMarketingCode + Constants.SEMI_COLON + productSkuCode;
    Cookie[] cookies = request.getCookies();
    Boolean found = false;/*  w ww  . ja  v a  2s. c om*/
    String domain = request.getServerName();
    if (cookies != null) {
        for (Cookie cooky : cookies) {
            info = cooky;
            if (getRecentProductsCookieName().equals(info.getName())) {
                found = true;
                break;
            }
        }
    }
    if (found) {
        Boolean flag = false;
        String value = URLDecoder.decode(info.getValue(), Constants.UTF8);
        if (value.contains(Constants.PIPE)) {
            String[] splits = value.split(Constants.PIPE);
            for (String cookieProductValueIt : splits) {
                if (cookieProductValueIt.contains(Constants.SEMI_COLON)) {
                    if (cookieProductValueIt.contains(cookieProductValue)) {
                        flag = true;
                    }
                } else {
                    // VALUE DOESN'T CONTAIN SEMI COLON : CLEAN THE COOKIE - NON COMPATIBLE VALUE
                    info.setValue("");
                    info.setPath("/");
                    info.setMaxAge(Constants.COOKIES_LENGTH);
                    info.setDomain(domain);
                    response.addCookie(info);
                }
            }
        } else {
            if (value.contains(Constants.SEMI_COLON)) {
                if (value.contains(cookieProductValue)) {
                    flag = true;
                }
            } else {
                // VALUE DOESN'T CONTAIN SEMI COLON : CLEAN THE COOKIE - NON COMPATIBLE VALUE
                value = "";
                info.setValue("");
                info.setPath("/");
                info.setMaxAge(Constants.COOKIES_LENGTH);
                info.setDomain(domain);
                response.addCookie(info);
            }
        }
        if (!flag) {
            String values = value;
            if (StringUtils.isNotEmpty(values)) {
                values += Constants.PIPE;
            }
            values += cookieProductValue;
            info.setValue(URLEncoder.encode(values, Constants.UTF8));
            info.setPath("/");
            info.setMaxAge(Constants.COOKIES_LENGTH);
            info.setDomain(domain);
            response.addCookie(info);
        }
    } else {
        info = new Cookie(getRecentProductsCookieName(), cookieProductValue);
        info.setPath("/");
        info.setMaxAge(Constants.COOKIES_LENGTH);
        info.setDomain(domain);
        response.addCookie(info);
    }
}