Vanko Vanko - 3 months ago 32
Groovy Question

Groovy pickle alternative

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

https://www.quora.com/Is-there-a-way-to-keep-the-session-after-login-with-Selenium-Python

saving cookies

import pickle
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.quora.com')
# login code
pickle.dump(driver.get_cookies() , open("QuoraCookies.pkl","wb"))


loading cookies

import pickle
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.quora.com')
for cookie in pickle.load(open("QuoraCookies.pkl", "rb")):
driver.add_cookie(cookie)


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

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()
        instream.close()
    } catch (Exception e) {
        System.out.println(e)
    }

    return result
}

def saveFile = { set, filename ->
    try {
        def fos = new FileOutputStream(filename)
        def out = new ObjectOutputStream(fos)
        out.writeObject(set)
        out.flush()
        out.close()
    } catch (IOException e) {
        System.out.println(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.name} ${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