Vanko Vanko - 1 year ago 122
Groovy Question

Groovy pickle alternative

I'm searching for something similar to Python's pickle. I want to do like this example:

saving cookies

import pickle
from selenium import webdriver
driver = webdriver.Firefox()
# login code
pickle.dump(driver.get_cookies() , open("QuoraCookies.pkl","wb"))

loading cookies

import pickle
from selenium import webdriver
driver = webdriver.Firefox()
for cookie in pickle.load(open("QuoraCookies.pkl", "rb")):

I've tried many examples from the web without success. I saw the topics here as well.

In groovy case I'll :

Set<Cookie> allCookies = driver.manage().getCookies();

Variable allCookies should be serialized to file and deserialized later.

Answer Source

Java serialization is an option here. With credit to this post, here is an implementation:

import org.openqa.selenium.Cookie

def loadFile = { filename ->
    def result = null

    try {
        def fis = new FileInputStream(filename)
        def instream= new ObjectInputStream(fis)
        result = (Set<Cookie>) instream.readObject()
    } catch (Exception e) {

    return result

def saveFile = { set, filename ->
    try {
        def fos = new FileOutputStream(filename)
        def out = new ObjectOutputStream(fos)
    } catch (IOException e) {

and a sample driver program:

// ----------------------- main

if (args.size() >= 2) {
    def action = args[0]
    def file = args[1] 

    if (action == "write") {
        def cookies = new HashSet<Cookie>()
        cookies << new Cookie("Toronto", "Canada") 
        cookies << new Cookie("London", "UK") 
        cookies <<  new Cookie("Paris", "France") 

        saveFile(cookies, file)
    } else if (action == "read") {
        def cookies = loadFile(file)
        cookies.each { cookie ->
            println "${} ${cookie.value}"
    } else {
        println "Unknown action: " + action
} else {
    println "Usage: groovy CookieManager.groovy [read|write] filename"

Example usage (a) with all above code in the same script and (b) assuming that client-combined-3.0.0-beta2-nodeps.jar from here is on the classpath:

bash$ groovy CookieManager.groovy write set.dat
bash$ groovy CookieManager.groovy read set.dat
London UK
Toronto Canada
Paris France
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download