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

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

Introduction

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

Prototype

public Cookie(String paramString1, String paramString2, String paramString3, String paramString4,
            Date paramDate, boolean paramBoolean) 

Source Link

Usage

From source file:CookieDemoApp.java

/**
 *
 * Usage:/*  w  w  w  . j av a 2  s  .c  o  m*/
 *          java CookieDemoApp http://mywebserver:80/
 *
 *  @param args command line arguments
 *                 Argument 0 is a URL to a web server
 *
 *
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage: java CookieDemoApp <url>");
        System.err.println("<url> The url of a webpage");
        System.exit(1);
    }
    // Get target URL
    String strURL = args[0];
    System.out.println("Target URL: " + strURL);

    // Get initial state object
    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and 
    // re-created, using a persistence mechanism of choice,
    Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);
    // and then added to your HTTP state instance
    initialState.addCookie(mycookie);

    // Get HTTP client instance
    HttpClient httpclient = new HttpClient();
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    httpclient.setState(initialState);

    // RFC 2101 cookie management spec is used per default
    // to parse, validate, format & match cookies
    httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    // A different cookie management spec can be selected
    // when desired

    //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE);
    // Netscape Cookie Draft spec is provided for completeness
    // You would hardly want to use this spec in real life situations
    //httppclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // Compatibility policy is provided in order to mimic cookie
    // management of popular web browsers that is in some areas 
    // not 100% standards compliant

    // Get HTTP GET method
    GetMethod httpget = new GetMethod(strURL);
    // Execute HTTP GET
    int result = httpclient.executeMethod(httpget);
    // Display status code
    System.out.println("Response status code: " + result);
    // Get all the cookies
    Cookie[] cookies = httpclient.getState().getCookies();
    // Display the cookies
    System.out.println("Present cookies: ");
    for (int i = 0; i < cookies.length; i++) {
        System.out.println(" - " + cookies[i].toExternalForm());
    }
    // Release current connection to the connection pool once you are done
    httpget.releaseConnection();
}

From source file:com.gs.jrpip.client.ThankYouWriterTest.java

public void testAddRequest() throws Exception {
    AuthenticatedUrl url = new AuthenticatedUrl(this.getJrpipUrl(),
            new UsernamePasswordCredentials("username"));
    Cookie cookie1 = new Cookie("domain", "cookie1", "val1", "/", 1000, false);
    Cookie cookie2 = new Cookie("domain", "cookie2", "val2", "/", 1000, false);
    Cookie cookie3 = new Cookie("domain", "cookie3", "val3", "/", 1000, false);
    ThankYouWriter thankYouWriter = ThankYouWriter.getINSTANCE();
    thankYouWriter.stopThankYouThread();
    thankYouWriter.addRequest(url, new Cookie[] { cookie1, cookie2, cookie3 }, new RequestId(1));
    thankYouWriter.addRequest(url, new Cookie[] { cookie1, cookie2, cookie3 }, new RequestId(2)); // same combination
    thankYouWriter.addRequest(url, new Cookie[] { cookie3, cookie2, cookie1 }, new RequestId(3)); // cookie order changed
    thankYouWriter.addRequest(url, new Cookie[] { cookie3 }, new RequestId(4)); // mismatch cookies
    thankYouWriter.addRequest(url, new Cookie[] {}, new RequestId(5)); // no cookies
    thankYouWriter.addRequest(url, null, new RequestId(6)); // null cookies

    assertEquals(3, thankYouWriter.getPendingRequests());
}

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

public static void addCookie(HttpState httpState, String cook) {
    String name = "";
    String domain = "";
    String path = "";
    String value = "";
    boolean secure = false;
    Date expires = new Date(Long.MAX_VALUE);

    String[] fields = cook.split(";");
    for (int i = 0; i < fields.length; i++) {
        String[] half = fields[i].trim().split("=");
        if (half.length == 2) {
            if (fields[i].startsWith("$")) {
                if (half[0].equals("$Domain"))
                    domain = half[1];//  w w w.j  ava2s  .c  o m
                else if (half[0].equals("$Path"))
                    path = half[1];
                else if (half[0].equals("$Secure"))
                    secure = Boolean.getBoolean(half[1]);
                else if (half[0].equals("$Date"))
                    try {
                        expires = DateFormat.getDateTimeInstance().parse(half[1]);
                    } catch (ParseException e) {
                    }
            } else {
                name = half[0];
                value = half[1];
            }
        }
    }

    Cookie cookie = null;
    try {
        cookie = new Cookie(domain, name, value, path, expires, secure);
        if (cookie != null)
            httpState.addCookie(cookie);
    } catch (Exception e) {
        Engine.logBeans.debug("(CookiesUtils) failed to parse cookie: " + cook);
    }
}

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//from  ww w  .j av  a2 s  .c om
 * @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:com.zimbra.common.httpclient.HttpClientUtil.java

public static HttpState newHttpState(ZAuthToken authToken, String host, boolean isAdmin) {
    HttpState state = new HttpState();
    if (authToken != null) {
        Map<String, String> cookieMap = authToken.cookieMap(isAdmin);
        if (cookieMap != null) {
            for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
                state.addCookie(new Cookie(host, ck.getKey(), ck.getValue(), "/", null, false));
            }/*from   w  w w .  j  ava 2 s .  c o m*/
        }
    }
    return state;
}

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

public static void addCookie(HttpState httpState, String domain, String name, String value, String path,
        Date expires, boolean secure) {
    Cookie cookie = null;//from  w ww.j a v a 2  s  .  c o  m
    try {
        Engine.logBeans.debug(String.format(
                "(CookiesUtils) Adding cookie: "
                        + "domain=%s, name=%s, value=%s, path=%s, expires=%s, secure=%s",
                domain, name, value, path, expires.toString(), Boolean.toString(secure)));

        cookie = new Cookie(domain, name, value, path, expires, secure);
        if (cookie != null) {
            Engine.logBeans.debug("(CookiesUtils) added cookie: " + cookie);
            httpState.addCookie(cookie);
        }
    } catch (Exception e) {
        Engine.logBeans.debug("(CookiesUtils) failed to parse cookie: " + cookie);
    }
}

From source file:com.twinsoft.convertigo.beans.statements.CookiesAddStatement.java

protected void addCookie(HttpState httpState, String cook) {
    String name = "";
    String domain = "";
    String path = "";
    String value = "";
    boolean secure = false;
    Date expires = new Date(Long.MAX_VALUE);

    String[] fields = cook.split(";");
    for (int i = 0; i < fields.length; i++) {
        String[] half = fields[i].trim().split("=");
        if (half.length == 2) {
            if (fields[i].startsWith("$")) {
                if (half[0].equals("$Domain"))
                    domain = half[1];/*from w w w.j  a  v a2s . c  om*/
                else if (half[0].equals("$Path"))
                    path = half[1];
                else if (half[0].equals("$Secure"))
                    secure = Boolean.getBoolean(half[1]);
                else if (half[0].equals("$Date"))
                    try {
                        expires = DateFormat.getDateTimeInstance().parse(half[1]);
                    } catch (ParseException e) {
                    }
            } else {
                name = half[0];
                value = half[1];
            }
        }
    }

    Cookie cookie = null;
    try {
        cookie = new Cookie(domain, name, value, path, expires, secure);
        if (cookie != null)
            httpState.addCookie(cookie);
    } catch (Exception e) {
        Engine.logBeans.debug("(CookiesAdd) failed to parse those cookies : " + cook);
    }
}

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);
    }/*from   ww w .  j ava  2  s.  c o  m*/
    return mimicWebDriverCookieState;
}

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

/**
 * Creates a cookie with the given name, value, domain attribute,
 * path attribute, expiration attribute, and secure attribute
 *
 * @param name    the cookie name//from   w w w  .ja  v a  2 s  . c  o  m
 * @param value   the cookie value
 * @param domain  the domain this cookie can be sent to
 * @param path    the path prefix for which this cookie can be sent
 * @param expires the {@link Date} at which this cookie expires,
 *                or <tt>null</tt> if the cookie expires at the end
 *                of the session
 * @param secure if true this cookie can only be sent over secure
 * connections
 *
 */
public CrawlerPack addCookie(String domain, String name, String value, String path, Date expires,
        boolean secure) {
    if (null == name) {
        log.warn("Cookie name null.");
        return this;
    }

    cookies.add(new Cookie(domain, name, value, path, expires, secure));
    return this;
}

From source file:com.zimbra.cs.client.soap.LmcSendMsgRequest.java

public String postAttachment(String uploadURL, LmcSession session, File f, String domain, // cookie domain e.g. ".example.zimbra.com"
        int msTimeout) throws LmcSoapClientException, IOException {
    String aid = null;/*from  w w w  . ja v a  2  s . com*/

    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread()
                + " LmcSendMsgRequest.postAttachment session=null");

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(uploadURL);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        HttpState initialState = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            Cookie cookie = new Cookie(domain, ck.getKey(), ck.getValue(), "/", -1, false);
            initialState.addCookie(cookie);
        }
        client.setState(initialState);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    post.getParams().setSoTimeout(msTimeout);
    int statusCode = -1;
    try {
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName());
        Part[] parts = { new FilePart(f.getName(), f, contentType, "UTF-8") };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        statusCode = HttpClientUtil.executeMethod(client, post);

        // parse the response
        if (statusCode == 200) {
            // paw through the returned HTML and get the attachment id
            String response = post.getResponseBodyAsString();
            //System.out.println("response is\n" + response);
            int lastQuote = response.lastIndexOf("'");
            int firstQuote = response.indexOf("','") + 3;
            if (lastQuote == -1 || firstQuote == -1)
                throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response);
            aid = response.substring(firstQuote, lastQuote);
        } else {
            throw new LmcSoapClientException("Attachment post failed, status=" + statusCode);
        }
    } catch (IOException e) {
        System.err.println("Attachment post failed");
        e.printStackTrace();
        throw e;
    } finally {
        post.releaseConnection();
    }

    return aid;
}