All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rx.net.http.CookieContainer Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.net.http;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import org.rx.core.Linq;
import org.rx.net.http.cookie.PersistentCookieStorage;
import org.rx.net.http.cookie.VolatileCookieStorage;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public final class CookieContainer implements CookieJar {
    static boolean isCookieExpired(Cookie cookie) {
        return cookie.expiresAt() < System.currentTimeMillis();
    }

    final VolatileCookieStorage volatileStorage;
    final PersistentCookieStorage persistentStorage;

    public CookieContainer() {
        this(new VolatileCookieStorage(), new PersistentCookieStorage());
    }

    public CookieContainer(VolatileCookieStorage cache, PersistentCookieStorage persistentStorage) {
        this.volatileStorage = cache;
        this.persistentStorage = persistentStorage;

        this.volatileStorage.addAll(persistentStorage.loadAll());
    }

    @Override
    public List loadForRequest(HttpUrl url) {
        List cookiesToRemove = new ArrayList<>();
        List validCookies = new ArrayList<>();

        for (Iterator it = volatileStorage.iterator(); it.hasNext(); ) {
            Cookie currentCookie = it.next();
            if (isCookieExpired(currentCookie)) {
                cookiesToRemove.add(currentCookie);
                it.remove();
            } else if (currentCookie.matches(url)) {
                validCookies.add(currentCookie);
            }
        }

        persistentStorage.removeAll(cookiesToRemove);
        return validCookies;
    }

    @Override
    public void saveFromResponse(HttpUrl url, List cookies) {
        volatileStorage.addAll(cookies);
        persistentStorage.saveAll(Linq.from(cookies).where(Cookie::persistent).toList());
    }

    public synchronized void clearSession() {
        volatileStorage.clear();
        volatileStorage.addAll(persistentStorage.loadAll());
    }

    public synchronized void clear() {
        volatileStorage.clear();
        persistentStorage.clear();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy