org.rx.net.http.cookie.PersistentCookieJar Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rxlib Show documentation
Show all versions of rxlib Show documentation
A set of utilities for Java
/*
* Copyright (C) 2016 Francisco José Montiel Navarro.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rx.net.http.cookie;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import org.rx.net.http.cookie.cache.CookieCache;
import org.rx.net.http.cookie.persistence.CookiePersistor;
public class PersistentCookieJar implements ClearableCookieJar {
private CookieCache cache;
private CookiePersistor persistor;
public PersistentCookieJar(CookieCache cache, CookiePersistor persistor) {
this.cache = cache;
this.persistor = persistor;
this.cache.addAll(persistor.loadAll());
}
@Override
synchronized public void saveFromResponse(HttpUrl url, List cookies) {
cache.addAll(cookies);
persistor.saveAll(filterPersistentCookies(cookies));
}
private static List filterPersistentCookies(List cookies) {
List persistentCookies = new ArrayList<>();
for (Cookie cookie : cookies) {
if (cookie.persistent()) {
persistentCookies.add(cookie);
}
}
return persistentCookies;
}
@Override
synchronized public List loadForRequest(HttpUrl url) {
List cookiesToRemove = new ArrayList<>();
List validCookies = new ArrayList<>();
for (Iterator it = cache.iterator(); it.hasNext(); ) {
Cookie currentCookie = it.next();
if (isCookieExpired(currentCookie)) {
cookiesToRemove.add(currentCookie);
it.remove();
} else if (currentCookie.matches(url)) {
validCookies.add(currentCookie);
}
}
persistor.removeAll(cookiesToRemove);
return validCookies;
}
private static boolean isCookieExpired(Cookie cookie) {
return cookie.expiresAt() < System.currentTimeMillis();
}
@Override
synchronized public void clearSession() {
cache.clear();
cache.addAll(persistor.loadAll());
}
@Override
synchronized public void clear() {
cache.clear();
persistor.clear();
}
}