Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:com.enonic.vertical.adminweb.CategoryHandlerServlet.java

public void handlerMenu(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems, ExtendedMap parameters, User user, Document verticalDoc)
        throws VerticalAdminException, TransformerException, IOException {

    String contentTypeString = formItems.getString("contenttypestring", "");

    String subop = formItems.getString("subop", "");

    final boolean rememberTreeMenuState = subop.equals("insert") || subop.equals("contentfield")
            || subop.equals("addcontenttosection") || subop.equals("relatedcontent")
            || subop.indexOf("relatedimage") > -1 || subop.indexOf("relatedfile") > -1;

    Cookie cookie = CookieUtil.getCookie(request,
            ContentBaseHandlerServlet.getPopupCookieName(contentTypeString));
    int cookieCategoryKey = -1;
    if (cookie != null) {
        cookieCategoryKey = Integer.parseInt(cookie.getValue());
    }//w  w w.j  a  va  2s .c o  m

    int topCategoryKey = formItems.getInt("topcategorykey", -1);

    int selectedParentCategoryKey = -1;
    int selectedCategoryKey;
    boolean redirect;

    if (topCategoryKey != -1 || !rememberTreeMenuState) {
        selectedCategoryKey = topCategoryKey;
        redirect = false;
    } else {
        selectedCategoryKey = cookieCategoryKey;
        redirect = true;
        selectedParentCategoryKey = admin.getSuperCategoryKey(selectedCategoryKey);
    }

    int unitFilterContentType = formItems.getInt("unitfiltercontenttype", -1);
    boolean requireCategoryAdmin = "true".equals(formItems.getString("requirecategoryadmin", ""));
    int excludeCategoryKey = formItems.getInt("excludecategorykey", -1);
    int excludeCategoryKeyWithChildren = formItems.getInt("excludecategorykey_withchildren", -1);

    int[] contentTypes = null;
    if (contentTypeString != null) {
        String[] contentTypeStrings = StringUtil.splitString(contentTypeString, ",");
        contentTypes = ArrayUtil.toIntArray(contentTypeStrings);
    }

    Document doc = XMLTool.domparse(admin.getCategoryMenu(user, selectedCategoryKey, contentTypes, true));
    Element selectedCategoryElem = XMLTool.selectElement(doc.getDocumentElement(),
            "//category[@key = " + selectedCategoryKey + "]");
    if (selectedCategoryElem == null) {
        selectedCategoryKey = -1;
    } else if (contentTypes != null
            && !selectedCategoryHasValidContentType(contentTypes, selectedCategoryElem)) {
        selectedCategoryKey = -1;
    }

    if (contentTypes != null || requireCategoryAdmin) // Dirty hack here, requireCategoryAdmin is set for move
    // category
    {
        doc.getDocumentElement().setAttribute("disabled", "true");
    }

    if (unitFilterContentType != -1) {
        filterUnitsOnContentTypes(admin, doc, unitFilterContentType);
    }

    if (excludeCategoryKeyWithChildren != -1) {
        Element categoryElem = XMLTool.selectElement(doc.getDocumentElement(),
                "//category[@key = '" + excludeCategoryKeyWithChildren + "']");
        disableCategory(categoryElem, true);
    }

    if (excludeCategoryKey != -1) {
        Element categoryElem = XMLTool.selectElement(doc.getDocumentElement(),
                "//category[@key = '" + excludeCategoryKey + "']");
        disableCategory(categoryElem, false);
    }

    if (requireCategoryAdmin) {
        disableCategoriesWithoutAdminRight(doc);
    }

    ExtendedMap xslParams = new ExtendedMap();
    xslParams.put("selectedunitkey", formItems.getString("selectedunitkey", ""));
    xslParams.put("topcategorykey", topCategoryKey);
    xslParams.put("fieldname", formItems.getString("fieldname", ""));
    xslParams.put("fieldrow", formItems.getString("fieldrow", ""));
    if (redirect) {
        xslParams.put("redirect", String.valueOf(redirect));
        xslParams.put("selectedcategorykey", selectedCategoryKey);
        xslParams.put("selectedparentcategorykey", selectedParentCategoryKey);
    }
    if (contentTypeString != null) {
        xslParams.put("contenttypestring", contentTypeString);
    }
    xslParams.put("cat", formItems.getString("cat", null));
    xslParams.put("subop", formItems.getString("subop"));
    xslParams.put("contenthandler", formItems.getString("contenthandler", null));
    xslParams.put("minoccurrence", formItems.getString("minoccurrence", null));
    xslParams.put("maxoccurrence", formItems.getString("maxoccurrence", null));

    transformXML(request, response, doc, "content_selector_frame1.xsl", xslParams);
}

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);//from   w w w  .  j  av a 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:ddf.security.samlp.impl.LogoutMessageImpl.java

@Override
public String sendSamlLogoutRequest(LogoutRequest request, String targetUri, boolean isSoap,
        @Nullable Cookie cookie) throws IOException, WSSecurityException {
    XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage(request) : request;

    Element requestElement = getElementFromSaml(xmlObject);
    String requestMessage = DOM2Writer.nodeToString(requestElement);
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(targetUri);
        post.addHeader("Cache-Control", "no-cache, no-store");
        post.addHeader("Pragma", "no-cache");
        post.addHeader("SOAPAction", SAML_SOAP_ACTION);

        post.addHeader("Content-Type", "application/soap+xml");

        post.setEntity(new StringEntity(requestMessage, "utf-8"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        BasicHttpContext context = new BasicHttpContext();
        if (cookie != null) {
            BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
            basicClientCookie.setDomain(cookie.getDomain());
            basicClientCookie.setPath(cookie.getPath());

            BasicCookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookie(basicClientCookie);
            context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        }/* w  w w . j a  v  a 2s  .  c o  m*/

        return httpClient.execute(post, responseHandler, context);
    }
}

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

protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) {

    org.apache.commons.httpclient.Cookie commonsCookie = new org.apache.commons.httpclient.Cookie(
            cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(),
            cookie.getSecure());//w  w w. j av  a 2  s. c om

    commonsCookie.setVersion(cookie.getVersion());

    return commonsCookie;
}

From source file:ed.net.CookieJar.java

/**
 * Performs RFC 2109 {@link Cookie} validation
 * //  ww  w  .j  a va  2  s. co m
 * @param url the source of the cookie
 * @param cookie The cookie to validate.
 * @throws IllegalArgumentException if an exception occurs during validation
 */
private void validate(URL url, Cookie cookie) {
    String host = url.getHost();
    int port = url.getPort();
    String path = url.getPath();

    // based on org.apache.commons.httpclient.cookie.CookieSpecBase
    if (host == null) {
        throw new IllegalArgumentException("Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException("Host of origin may not be blank");
    }
    if (port < 0)
        port = 80;

    if (path == null) {
        throw new IllegalArgumentException("Path of origin may not be null.");
    }
    if (path.trim().equals("")) {
        path = "/";
    }
    host = host.toLowerCase();
    // check version
    if (cookie.getVersion() < 0) {
        throw new MalformedCookieException("Illegal version number " + cookie.getValue());
    }

    // security check... we musn't allow the server to give us an
    // invalid domain scope

    // Validate the cookies domain attribute. NOTE: Domains without
    // any dots are allowed to support hosts on private LANs that don't
    // have DNS names. Since they have no dots, to domain-match the
    // request-host and domain must be identical for the cookie to sent
    // back to the origin-server.
    if (host.indexOf(".") >= 0) {
        // Not required to have at least two dots. RFC 2965.
        // A Set-Cookie2 with Domain=ajax.com will be accepted.

        // domain must match host
        if (!host.endsWith(cookie.getDomain())) {
            String s = cookie.getDomain();
            if (s.startsWith(".")) {
                s = s.substring(1, s.length());
            }
            if (!host.equals(s)) {
                throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain()
                        + "\". Domain of origin: \"" + host + "\"");
            }
        }
    } else {
        if (!host.equals(cookie.getDomain())) {
            throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain()
                    + "\". Domain of origin: \"" + host + "\"");
        }
    }

    // another security check... we musn't allow the server to give us a
    // cookie that doesn't match this path
    if (!path.startsWith(cookie.getPath())) {
        throw new MalformedCookieException(
                "Illegal path attribute \"" + cookie.getPath() + "\". Path of origin: \"" + path + "\"");
    }

    // Validate using RFC 2109
    // --------------------------------------------------------
    if (cookie.getName().indexOf(' ') != -1) {
        throw new MalformedCookieException("Cookie name may not contain blanks");
    }
    if (cookie.getName().startsWith("$")) {
        throw new MalformedCookieException("Cookie name may not start with $");
    }

    if (cookie.getDomain() != null && (!cookie.getDomain().equals(host))) {

        // domain must start with dot
        if (!cookie.getDomain().startsWith(".")) {
            throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2109: domain must start with a dot");
        }
        // domain must have at least one embedded dot
        int dotIndex = cookie.getDomain().indexOf('.', 1);
        if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) {
            throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2109: domain must contain an embedded dot");
        }
        host = host.toLowerCase();
        if (!host.endsWith(cookie.getDomain())) {
            throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain()
                    + "\". Domain of origin: \"" + host + "\"");
        }
        // host minus domain may not contain any dots
        String hostWithoutDomain = host.substring(0, host.length() - cookie.getDomain().length());
        if (hostWithoutDomain.indexOf('.') != -1) {
            throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2109: host minus domain may not contain any dots");
        }
    }
}

From source file:CookieServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];//from   w w  w  .j ava2 s  .  c  o  m
            }
        }
    }
    if (cookie == null) {
        newCookie = true;
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:com.qut.middleware.esoe.sso.impl.SSOProcessorImpl.java

private void processCookies(SSOProcessorData data) {
    String remoteAddr = data.getRemoteAddress();

    HttpServletRequest request = data.getHttpRequest();

    if (request == null) {
        this.logger.warn(
                "[SSO for {}] No HTTP request object was passed in by the SSO handler. Unable to process cookies.",
                remoteAddr);/*from   w  w  w .  ja va  2  s. c  om*/
        return;
    }

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            this.logger.debug("[SSO for {}] Processing cookie {} = {}",
                    new Object[] { remoteAddr, cookie.getName(), cookie.getValue() });
            if (cookie.getName().equals(this.sessionTokenName)) {
                this.logger.debug("[SSO for {}] Identified ESOE cookie {} = {}",
                        new Object[] { remoteAddr, cookie.getName(), cookie.getValue() });
                data.setSessionID(cookie.getValue());

                // We don't need any further cookies. Remove this if that changes.
                return;
            }
        }
    } else {
        this.logger.debug("[SSO for {}] No cookies in HTTP request.", remoteAddr);
    }
}

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);//  w  w  w.ja  v  a2  s .c  o  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:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * Extract cookies and other global fields into inData
 * /*w  w  w.  ja  v  a2s . com*/
 * @param req
 * @param inData
 */
@SuppressWarnings("unchecked")
private void getStandardFields(HttpServletRequest req, ServiceData inData) {
    // log field
    if (suppressSqlLog) {
        inData.addValue(ExilityConstants.SUPPRESS_SQL_LOG, "1");
    }

    if (AP.cookiesToBeExtracted != null) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (AP.cookiesToBeExtracted.contains(cookie.getName())) {
                    Spit.out(cookie.getName() + " extracted from cookie");
                    inData.addValue(cookie.getName(), cookie.getValue());
                }
            }
        }
    }

    this.extractParametersAndFiles(req, inData);

    /**
     * is there a sessionData object?
     */
    HttpSession session = req.getSession();
    String token = req.getHeader(CommonFieldNames.CSRF_HEADER);
    if (token == null) {
        // try form fields
        token = inData.getValue(CommonFieldNames.CSRF_HEADER);
    }
    if (token == null) {
        // for the sake of jsps that still exist in our system..
        Object obj = session.getAttribute(HttpRequestHandler.SESSION_TOKEN_NAME);
        if (obj != null) {
            token = obj.toString();
        }
    }
    if (token != null) {
        Object obj = session.getAttribute(token);
        if (obj != null && obj instanceof SessionData) {
            Spit.out("Session fields being extracted from new token based object.");
            ((SessionData) obj).extractAll(inData);
        } else {
            Spit.out("CSRF token found to be " + token + " but session data not found");
        }
    } else {
        Spit.out("NO CSRF token. Will try old ways of session data.");
        Object data = session.getAttribute(HtmlRequestHandler.GLOBAL_SERVER_DATA_NAME
                + inData.getValue(HtmlRequestHandler.getUserIdName()));
        if (data != null && data instanceof Map) {
            Map<String, String> sessionData = (Map<String, String>) data;
            for (String name : sessionData.keySet()) {
                // Spit.out("Trying " + name + " as a global field");
                String val = sessionData.get(name);
                if (val != null && val.length() > 0) {
                    inData.addValue(name, val);
                }
            }
        }
    }
}