Java > Persistent cookie store

It uses json-io.

PersistentCookieStore.java
import java.io.*;
import java.net.*;
import java.util.*;
 
import org.apache.logging.log4j.*;
 
import com.cedarsoftware.util.io.*;
import com.cedarsoftware.util.io.JsonReader.ClassFactory;
 
public class PersistentCookieStore {
 
	private final static Map<String, Object> JSON_SETTINGS;
	static {
		JSON_SETTINGS = new HashMap<String, Object>();
		JSON_SETTINGS.put(JsonWriter.PRETTY_PRINT, "true");
 
		JsonReader.assignInstantiator(HttpCookie.class, new ClassFactory() {
			@SuppressWarnings("rawtypes")
			@Override
			public Object newInstance(Class arg0) {
				return new HttpCookie("hello", "world");
			}
		});
	}
 
	private CookieStore cs;
	private File file;
 
	public PersistentCookieStore(CookieStore cs, File file) {
		this.cs = cs;
		this.file = file;
	}
 
	private final static Logger LOGGER = LogManager.getLogger();
 
	public void persist() throws Exception {
		LOGGER.debug(String.format("Persisting cookies to file %s.", file.getAbsolutePath()));
		try (FileOutputStream fos = new FileOutputStream(file); JsonWriter jw = new JsonWriter(fos, JSON_SETTINGS)) {
			jw.write(cs.getCookies());
			LOGGER.info(String.format("Persisted %d cookies.", cs.getCookies().size()));
		}
	}
 
	public void restore() throws Exception {
		LOGGER.debug(String.format("Restoring cookies from file %s.", file.getAbsolutePath()));
 
		try (FileInputStream fis = new FileInputStream(file); JsonReader jr = new JsonReader(fis)) {
			@SuppressWarnings("unchecked")
			List<HttpCookie> cookies = (List<HttpCookie>) jr.readObject();
			for (HttpCookie cookie : cookies) {
				cs.add(null, cookie);
			}
			LOGGER.info(String.format("Restored %d cookies.", cookies.size()));
		}
	}
}

Usage :

private final static CookieManager COOKIE_MANAGER = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
private final static PersistentCookieStore COOKIE_STORE = new PersistentCookieStore(COOKIE_MANAGER.getCookieStore(), new File("cookies.dat"));
...
COOKIE_STORE.restore();
COOKIE_STORE.persist();
Print/export