Example usage for org.apache.commons.httpclient Cookie getDomain

List of usage examples for org.apache.commons.httpclient Cookie getDomain

Introduction

In this page you can find the example usage for org.apache.commons.httpclient Cookie getDomain.

Prototype

public String getDomain() 

Source Link

Usage

From source file:com.twinsoft.convertigo.engine.util.CookiesUtils.java

public static String formatCookie(Cookie cookie) {
    StringBuffer buf = new StringBuffer();
    Date d = cookie.getExpiryDate();
    String[][] datas = {/*from  w  w w.j  av a 2s .c  o m*/
            // {"$Version",Integer.toString(cookie.getVersion())},
            { cookie.getName(), cookie.getValue() }, { "$Domain", cookie.getDomain() },
            { "$Path", cookie.getPath() }, { "$Secure", Boolean.toString(cookie.getSecure()) },
            { "$Date", d == null ? "null" : DateFormat.getDateTimeInstance().format(d) } };
    buf.append(datas[0][0] + "=" + datas[0][1]);
    for (int i = 1; i < datas.length; i++) {
        if (datas[i][1] != null)
            buf.append("; " + datas[i][0] + "=" + datas[i][1]);
    }
    return buf.toString();
}

From source file:jshm.scraper.Scraper.java

/**
 * Retrieves a NodeList of all elements of interest
 * (and children) from the supplied URL.
 * @param url/*from   www  .java 2s  .  c  om*/
 * @param filters The set of NodeFilters to use to find the 
 * elements of interest. These could be different depending on the page
 * format between Guitar Hero and Rockband scores, for example.
 * @param removeWhitespace Whether to remove TextNodes that
 * contain only whitespace
 * @param cookies Any cookies that should be passed along with
 * the request
 * @return
 * @throws ParserException 
 */
public static NodeList scrape(final String url, final NodeFilter[] filters, final boolean removeWhitespace,
        final org.apache.commons.httpclient.Cookie[] cookies) throws ParserException {

    LOG.finest("entered Scraper.scrape(), url=" + url);

    FilterBean bean = new FilterBean();
    bean.getParser().setFeedback(PARSER_FEEDBACK);

    bean.setFilters(filters);

    // set cookies if necessary
    if (null != cookies) {
        LOG.fine("Setting cookies");
        ConnectionManager cm = Parser.getConnectionManager();
        Cookie cookie = null;

        // have to convert from commons cookie to htmlparser cookie
        for (org.apache.commons.httpclient.Cookie c : cookies) {
            LOG.finer("  " + c);
            cookie = new Cookie(c.getName(), c.getValue());
            cm.setCookie(cookie, c.getDomain());
        }
    }

    LOG.finest("calling bean.setURL()");
    bean.setURL(url);
    LOG.finest("calling bean.getNodes()");
    NodeList nodes = bean.getNodes();

    if (nodes.size() == 0) {
        LOG.warning("No nodes returned for " + url);
    }

    //System.out.println(nodes.toHtml());

    if (removeWhitespace) {
        LOG.finer("Removing whitespace from retrieved nodes");

        // now filter out text nodes that only have whitespace {{{
        RegexFilter filter8 = new RegexFilter();
        filter8.setStrategy(RegexFilter.MATCH);
        filter8.setPattern("^\\s*$");
        NodeClassFilter filter9 = new NodeClassFilter(TextNode.class);
        AndFilter filter10 = new AndFilter(new NodeFilter[] { filter9, filter8 });
        NotFilter filter11 = new NotFilter(filter10);

        LOG.finest("calling nodes.keepAllNodesThatMatch()");
        nodes.keepAllNodesThatMatch(filter11, true);
    }

    LOG.finest("returning from Scraper.scrape()");
    return nodes;
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Before calling the endpoint, set up the cookies found in the request.
 * @param context the context/*from  w  w  w  .  j a  v a2 s .  co  m*/
 */
public static void copyCookiesToEndpoint(ProxyContext context) {
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    context.clearRequestCookies();
    if (clientRequest != null) {
        javax.servlet.http.Cookie[] cookies = clientRequest.getCookies();
        HttpState initState = context.getHttpClient().getState();

        if (cookies != null) {
            // Gather up the cookies keyed on the length of the path.
            // This is done so that if we have two cookies with the same name,
            // we pass the cookie with the longest path first to the endpoint
            TreeMap cookieMap = new TreeMap();
            for (javax.servlet.http.Cookie cookie : cookies) {
                CookieInfo origCookie = new CookieInfo(cookie.getName(), cookie.getDomain(), cookie.getName(),
                        cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), null, cookie.getSecure());
                CookieInfo newCookie = RequestUtil.createCookie(origCookie, context,
                        context.getTarget().getUrl().getHost(), context.getTarget().getUrl().getPath());

                if (newCookie != null) {
                    Integer pathInt = Integer.valueOf(0 - newCookie.path.length());
                    ArrayList list = (ArrayList) cookieMap.get(pathInt);
                    if (list == null) {
                        list = new ArrayList();
                        cookieMap.put(pathInt, list);
                    }
                    list.add(newCookie);
                }
            }

            // loop through (in order) the cookies we've gathered
            for (Object mapValue : cookieMap.values()) {
                ArrayList list = (ArrayList) mapValue;
                for (Object aList : list) {
                    CookieInfo cookieInfo = (CookieInfo) aList;
                    if (Log.isInfo()) {
                        String str = "-- Cookie in request: " + cookieInfo;
                        Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug(str);
                    }

                    Cookie cookie = new Cookie(cookieInfo.domain, cookieInfo.name, cookieInfo.value,
                            cookieInfo.path, cookieInfo.maxAge, cookieInfo.secure);

                    // If this is a session cookie and we're dealing with local domain, make sure the session
                    // cookie has the latest session id. This check is needed when the session was invalidated
                    // and then recreated in this request; we shouldn't be sending the old session id to the endpoint.
                    if (context.isLocalDomain() && STRING_JSESSIONID.equalsIgnoreCase(cookieInfo.clientName)) {
                        FlexSession flexSession = FlexContext.getFlexSession();
                        if (flexSession != null && flexSession.isValid()) {
                            String sessionId = flexSession.getId();
                            String cookieValue = cookie.getValue();
                            if (!cookieValue.contains(sessionId)) {
                                int colonIndex = cookieValue.indexOf(':');
                                if (colonIndex != -1) {
                                    // Websphere changes jsession id to the following format:
                                    // 4 digit cacheId + jsessionId + ":" + cloneId.
                                    ServletContext servletContext = FlexContext.getServletContext();
                                    String serverInfo = servletContext != null ? servletContext.getServerInfo()
                                            : null;
                                    boolean isWebSphere = serverInfo != null
                                            && serverInfo.contains("WebSphere");
                                    if (isWebSphere) {
                                        String cacheId = cookieValue.substring(0, 4);
                                        String cloneId = cookieValue.substring(colonIndex);
                                        String wsSessionId = cacheId + sessionId + cloneId;
                                        cookie.setValue(wsSessionId);
                                    } else {
                                        cookie.setValue(sessionId);
                                    }
                                } else {
                                    cookie.setValue(sessionId);
                                }
                            }
                        }
                    }
                    // finally add the cookie to the current request
                    initState.addCookie(cookie);
                    context.addRequestCookie(cookie);
                }
            }
        }
    }
}

From source file:com.google.gsa.valve.modules.utils.CookieManagement.java

/**
 * Transforms Apache cookies into Servlet Cookies
 * /*from   w ww. j  a v a 2 s  . co  m*/
 * @param apacheCookie apache cookie 
 * 
 * @return servlet cookie
 */
public static javax.servlet.http.Cookie transformApacheCookie(
        org.apache.commons.httpclient.Cookie apacheCookie) {

    javax.servlet.http.Cookie newCookie = null;

    if (apacheCookie != null) {
        Date expire = apacheCookie.getExpiryDate();
        int maxAge = -1;

        if (expire == null) {
            maxAge = -1;
        } else {
            Date now = Calendar.getInstance().getTime();
            // Convert milli-second to second
            Long second = new Long((expire.getTime() - now.getTime()) / 1000);
            maxAge = second.intValue();
        }

        newCookie = new javax.servlet.http.Cookie(apacheCookie.getName(), apacheCookie.getValue());
        //Hardcoding the domain
        newCookie.setDomain(apacheCookie.getDomain());
        newCookie.setPath(apacheCookie.getPath());
        newCookie.setMaxAge(maxAge);
        newCookie.setSecure(apacheCookie.getSecure());
    }
    return newCookie;
}

From source file:com.lazerycode.ebselen.customhandlers.FileDownloader.java

/**
 * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
 *
 * @param seleniumCookieSet//  ww  w .  ja  va  2 s. com
 * @return
 */
private HttpState mimicCookieState(Set<org.openqa.selenium.Cookie> seleniumCookieSet) {
    HttpState mimicWebDriverCookieState = new HttpState();
    for (org.openqa.selenium.Cookie seleniumCookie : seleniumCookieSet) {
        Cookie httpClientCookie = new Cookie(seleniumCookie.getDomain(), seleniumCookie.getName(),
                seleniumCookie.getValue(), seleniumCookie.getPath(), seleniumCookie.getExpiry(),
                seleniumCookie.isSecure());
        mimicWebDriverCookieState.addCookie(httpClientCookie);
    }
    return mimicWebDriverCookieState;
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private HttpState mimicCookieState(Set<org.openqa.selenium.Cookie> seleniumCookieSet) {
    HttpState mimicWebDriverCookieState = new HttpState();
    for (org.openqa.selenium.Cookie seleniumCookie : seleniumCookieSet) {
        Cookie httpClientCookie = new Cookie(seleniumCookie.getDomain(), seleniumCookie.getName(),
                seleniumCookie.getValue(), seleniumCookie.getPath(), seleniumCookie.getExpiry(),
                seleniumCookie.isSecure());
        mimicWebDriverCookieState.addCookie(httpClientCookie);
    }/* ww  w  . j a  v  a2s .  c om*/
    return mimicWebDriverCookieState;
}

From source file:dslab.crawler.pack.CrawlerPack.java

/**
 * Return a Cookie array/*from   www  .  j  a  va  2s. c o m*/
 * and auto importing domain and path when domain was empty.
 *
 * @param uri required Apache Common VFS supported file systems and response JSON format content.
 * @return Cookie[]
 */
Cookie[] getCookies(String uri) {
    if (null == cookies || 0 == cookies.size())
        return null;

    for (Cookie cookie : cookies) {

        if ("".equals(cookie.getDomain())) {
            String domain = uri.replaceAll("^.*:\\/\\/([^\\/]+)[\\/]?.*$", "$1");
            //                System.out.println(domain);
            cookie.setDomain(domain);
            cookie.setPath("/");
            cookie.setExpiryDate(null);
            cookie.setSecure(false);
        }
    }

    return cookies.toArray(new Cookie[cookies.size()]);
}

From source file:at.ait.dme.yuma.suite.apps.core.server.annotation.AnnotationManager.java

private RESTAnnotationServer getAnnotationServer() {
    HttpClient client = new HttpClient();

    // Forward all cookies from the calling request
    if (request != null) {

        javax.servlet.http.Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (javax.servlet.http.Cookie c : cookies) {
                c.setDomain(request.getServerName());
                c.setPath("/");

                Cookie apacheCookie = new Cookie(c.getDomain(), c.getName(), c.getValue(), c.getPath(),
                        c.getMaxAge(), c.getSecure());
                client.getState().addCookie(apacheCookie);
            }//from w w w.j ava 2  s .  co  m
            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }
    }

    return ProxyFactory.create(RESTAnnotationServer.class, annotationServerBaseUrl,
            new ApacheHttpClientExecutor(client));
}

From source file:com.github.abola.crawler.CrawlerPack.java

/**
 * Return a Cookie array//  w w  w  .ja v  a2s. com
 * and auto importing domain and path when domain was empty.
 *
 * @param uri required Apache Common VFS supported file systems and response JSON format content.
 * @return Cookie[]
 */
Cookie[] getCookies(String uri) {
    if (null == cookies || 0 == cookies.size())
        return null;

    for (Cookie cookie : cookies) {

        if ("".equals(cookie.getDomain())) {
            String domain = uri.replaceAll("^.*:\\/\\/([^\\/]+)[\\/]?.*$", "$1");
            cookie.setDomain(domain);
            cookie.setPath("/");
            cookie.setExpiryDate(null);
            cookie.setSecure(false);
        }
    }

    return cookies.toArray(new Cookie[cookies.size()]);
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

protected void debugCookies(Cookie[] cookies) {
    log.debug("Cookie inspector found " + cookies.length + " cookies ------v");
    for (Cookie cookie : cookies)
        log.debug(cookie.toString() + ", domain=" + cookie.getDomain() + ", path=" + cookie.getPath()
                + ", max-age=" + cookie.getExpiryDate() + ", secure=" + cookie.getSecure());
    log.debug("----------------------------");
}