Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:com.liferay.portal.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    String domain = commonsCookie.getDomain();

    if (Validator.isNotNull(domain)) {
        cookie.setDomain(domain);//w  ww .  j  ava  2 s  .  c o m
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}

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;/*  w  w w.  j  av a2s  . 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:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP/*from w w w  .j  a v a  2 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:net.lightbody.bmp.proxy.jetty.jetty.servlet.AbstractSessionManager.java

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

        if (domain != null)
            cookie.setDomain(domain);/*from  www .j av a2 s. co m*/
        if (maxAge != null)
            cookie.setMaxAge(Integer.parseInt(maxAge));
        else
            cookie.setMaxAge(-1);

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

        return cookie;
    }
    return null;
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private Cookie getAuthenticationCookie(HttpServletRequest request, String name, String value, int age) {
    Cookie cookie = new Cookie(name, value);
    cookie.setHttpOnly(true);/*w  w w  .j a  v  a 2  s.  c  o  m*/
    cookie.setPath("/");
    cookie.setMaxAge(age);
    return cookie;
}

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

/**
 * Sets the cookie in the response.<p>
 * // w  ww .ja v  a 2 s .c  o m
 * @param cookie the cookie to set
 * @param delete flag to determine if the cookir should be deleted
 */
protected void setCookie(Cookie cookie, boolean delete) {

    if (getRequest().getAttribute(PARAM_PREDEF_OUFQN) != null) {
        // prevent the use of cookies if using a direct ou login url
        return;
    }
    int maxAge = 0;
    if (!delete) {
        // set the expiration date of the cookie to six months from today
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.MONTH, 6);
        maxAge = (int) ((cal.getTimeInMillis() - System.currentTimeMillis()) / 1000);
    }
    cookie.setMaxAge(maxAge);
    // set the path
    cookie.setPath(link("/system/login"));
    // set the cookie
    getResponse().addCookie(cookie);
}

From source file:com.google.gsa.Kerberos.java

/**
 * Setting the authentication cookie and the user session
 * //from   w  w  w  .  ja v a2s  .  c  o m
 * @param username username
 * @param creationTime creation time
 * @param encodedSessionID encoded session id
 * 
 * @return if the setting process was successful
 */
private boolean settingSession(UserSession userSession, Cookie gsaAuthCookie, Credentials creds,
        String username, KerberosAuthenticationProcess krbAuthN, long creationTime, String encodedSessionID,
        Vector<Cookie> krbCookies, Vector<Cookie> nonKrbCookies) {

    boolean result = false;

    logger.debug("Creating auth cookie with value: " + encodedSessionID);

    // Instantiate authentication cookie with default value
    gsaAuthCookie = new Cookie(authCookieName, encodedSessionID);

    // Set cookie domain
    gsaAuthCookie.setDomain(authCookieDomain);

    // Set cookie path
    gsaAuthCookie.setPath(authCookiePath);

    // Set expiration time
    gsaAuthCookie.setMaxAge(authMaxAge);

    logger.debug("Creating Session");

    userSession.setUserName(username);
    userSession.setSessionCreationTime(creationTime);
    userSession.setSessionLastAccessTime(creationTime);
    userSession.setUserCredentials(creds);

    //Cookies
    settingSessionCookies(krbCookies, nonKrbCookies, gsaAuthCookie, userSession);

    if (krbAuthN.getUserSubject() != null) {
        logger.debug("Kerberos Subject exists");

        userSession.setKerberosCredentials(krbAuthN.getUserSubject());

        result = true;

    } else {
        // Log error
        logger.error("Kerberos Subject has not been created properly");

        // Return
        return result;

    }

    return result;
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) {
        String domain = commonsCookie.getDomain();

        if (Validator.isNotNull(domain)) {
            cookie.setDomain(domain);//w  w  w  . ja  v a2 s  . co m
        }
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}