1
0
Fork 0
mirror of https://github.com/geometer/FBReaderJ.git synced 2025-10-04 18:29:23 +02:00

introduced ZLNetworkContext

This commit is contained in:
Nikolay Pultsin 2014-06-23 18:41:24 +01:00
parent 2cd9a2100a
commit 9e961449d1
37 changed files with 334 additions and 224 deletions

View file

@ -23,6 +23,7 @@ import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.net.Uri;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.zlibrary.text.view.*;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
@ -103,7 +104,7 @@ class ProcessHyperlinkAction extends FBAndroidAction {
new Thread(new Runnable() {
public void run() {
if (!url.startsWith("fbreader-action:")) {
nLibrary.initialize();
nLibrary.initialize(new QuietNetworkContext());
}
intent.setData(Uri.parse(nLibrary.rewriteUrl(url, externalUrl)));
BaseActivity.runOnUiThread(new Runnable() {

View file

@ -40,23 +40,8 @@ import org.apache.http.impl.cookie.BasicClientCookie2;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.android.fbreader.OrientationUtil;
public class BearerAuthenticator extends ZLNetworkManager.BearerAuthenticator {
private static Map<Activity,BearerAuthenticator> ourAuthenticators =
Collections.synchronizedMap(new HashMap<Activity,BearerAuthenticator>());
public static void initBearerAuthenticator(Activity activity) {
synchronized (ourAuthenticators) {
BearerAuthenticator ba = ourAuthenticators.get(activity);
if (ba == null) {
ba = new BearerAuthenticator(activity);
ourAuthenticators.put(activity, ba);
}
ZLNetworkManager.Instance().setBearerAuthenticator(ba);
}
}
static boolean onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
final BearerAuthenticator ba = ourAuthenticators.get(activity);
public final class ActivityNetworkContext extends ZLNetworkContext {
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
boolean processed = true;
try {
switch (requestCode) {
@ -65,17 +50,17 @@ public class BearerAuthenticator extends ZLNetworkManager.BearerAuthenticator {
break;
case NetworkLibraryActivity.REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null) {
ba.myAccount = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
myAccount = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
}
break;
case NetworkLibraryActivity.REQUEST_AUTHORISATION:
if (resultCode == Activity.RESULT_OK) {
ba.myAuthorizationConfirmed = true;
myAuthorizationConfirmed = true;
}
break;
case NetworkLibraryActivity.REQUEST_WEB_AUTHORISATION_SCREEN:
if (resultCode == Activity.RESULT_OK && data != null) {
final CookieStore store = ZLNetworkManager.Instance().cookieStore();
final CookieStore store = cookieStore();
final Map<String,String> cookies =
(Map<String,String>)data.getSerializableExtra(NetworkLibraryActivity.COOKIES_KEY);
if (cookies != null) {
@ -97,8 +82,8 @@ public class BearerAuthenticator extends ZLNetworkManager.BearerAuthenticator {
}
} finally {
if (processed) {
synchronized (ba) {
ba.notifyAll();
synchronized (this) {
notifyAll();
}
}
return processed;
@ -109,12 +94,12 @@ public class BearerAuthenticator extends ZLNetworkManager.BearerAuthenticator {
private volatile String myAccount;
private volatile boolean myAuthorizationConfirmed;
private BearerAuthenticator(Activity activity) {
public ActivityNetworkContext(Activity activity) {
myActivity = activity;
}
@Override
protected boolean authenticate(URI uri, Map<String,String> params) {
public boolean authenticate(URI uri, Map<String,String> params) {
System.err.println("AUTHENTICATE FOR " + uri);
if (!"https".equalsIgnoreCase(uri.getScheme())) {
return false;
@ -184,11 +169,7 @@ public class BearerAuthenticator extends ZLNetworkManager.BearerAuthenticator {
};
request.addPostParameter("auth", authToken);
request.addPostParameter("code", code);
try {
ZLNetworkManager.Instance().perform(request);
} catch (ZLNetworkException e) {
e.printStackTrace();
}
performQuietly(request);
return buffer.toString().trim();
}

View file

@ -49,6 +49,8 @@ public class AddCustomCatalogActivity extends Activity {
private boolean myEditNotAdd;
private INetworkLink.Type myType = INetworkLink.Type.Custom;
private final ActivityNetworkContext myNetworkContext = new ActivityNetworkContext(this);
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
@ -93,7 +95,7 @@ public class AddCustomCatalogActivity extends Activity {
myEditNotAdd = Util.EDIT_CATALOG_ACTION.equals(intent.getAction());
myLink = null;
Util.initLibrary(this, new Runnable() {
Util.initLibrary(this, myNetworkContext, new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
@ -104,15 +106,9 @@ public class AddCustomCatalogActivity extends Activity {
});
}
@Override
protected void onResume() {
super.onResume();
BearerAuthenticator.initBearerAuthenticator(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
BearerAuthenticator.onActivityResult(this, requestCode, resultCode, data);
myNetworkContext.onActivityResult(requestCode, resultCode, data);
}
private void init(Intent intent) {
@ -282,7 +278,7 @@ public class AddCustomCatalogActivity extends Activity {
public void run() {
try {
myError = null;
myLink.reloadInfo(false, false);
myLink.reloadInfo(myNetworkContext, false, false);
} catch (ZLNetworkException e) {
myError = e.getMessage();
}

View file

@ -41,6 +41,8 @@ import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
public class BookDownloaderService extends Service {
private final ZLNetworkContext myNetworkContext = new ServiceNetworkContext(this);
public static final String BOOK_FORMAT_KEY = "org.geometerplus.android.fbreader.network.BookFormat";
public static final String REFERENCE_TYPE_KEY = "org.geometerplus.android.fbreader.network.ReferenceType";
public static final String CLEAN_URL_KEY = "org.geometerplus.android.fbreader.network.CleanURL";
@ -339,7 +341,7 @@ public class BookDownloaderService extends Service {
public void run() {
boolean success = false;
try {
ZLNetworkManager.Instance().perform(request);
myNetworkContext.perform(request);
success = true;
} catch (ZLNetworkException e) {
// TODO: show error message to User

View file

@ -60,6 +60,8 @@ public class NetworkBookInfoActivity extends Activity implements NetworkLibrary.
private final ZLResource myResource = ZLResource.resource("bookInfo");
private final BookDownloaderServiceConnection myConnection = new BookDownloaderServiceConnection();
private final ActivityNetworkContext myNetworkContext = new ActivityNetworkContext(this);
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
@ -90,14 +92,12 @@ public class NetworkBookInfoActivity extends Activity implements NetworkLibrary.
@Override
protected void onResume() {
super.onResume();
BearerAuthenticator.initBearerAuthenticator(this);
NetworkLibrary.Instance().fireModelChangedEvent(NetworkLibrary.ChangeListener.Code.SomeCode);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
BearerAuthenticator.onActivityResult(this, requestCode, resultCode, data);
myNetworkContext.onActivityResult(requestCode, resultCode, data);
}
private volatile boolean myInitializerStarted;
@ -115,13 +115,14 @@ public class NetworkBookInfoActivity extends Activity implements NetworkLibrary.
if (SQLiteNetworkDatabase.Instance() == null) {
new SQLiteNetworkDatabase(getApplication());
}
library.initialize();
library.initialize(myNetworkContext);
}
if (myBook == null) {
final Uri url = getIntent().getData();
if (url != null && "litres-book".equals(url.getScheme())) {
myBook = OPDSBookItem.create(
myNetworkContext,
library.getLinkBySiteName("litres.ru"),
url.toString().replace("litres-book://", "http://")
);
@ -211,7 +212,7 @@ public class NetworkBookInfoActivity extends Activity implements NetworkLibrary.
final NetworkCatalogItem catalogItem =
myBook.createRelatedCatalogItem(relatedInfo);
if (catalogItem != null) {
new OpenCatalogAction(NetworkBookInfoActivity.this)
new OpenCatalogAction(NetworkBookInfoActivity.this, myNetworkContext)
.run(NetworkLibrary.Instance().getFakeCatalogTree(catalogItem));
} else if (MimeType.TEXT_HTML.equals(relatedInfo.Mime)) {
Util.openInBrowser(NetworkBookInfoActivity.this, relatedInfo.Url);

View file

@ -65,6 +65,8 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
private Intent myDeferredIntent;
private boolean mySingleCatalog;
private final ActivityNetworkContext myNetworkContext = new ActivityNetworkContext(this);
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
@ -83,7 +85,7 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
if (getCurrentTree() instanceof RootTree) {
mySingleCatalog = intent.getBooleanExtra("SingleCatalog", false);
if (!NetworkLibrary.Instance().isInitialized()) {
Util.initLibrary(this, new Runnable() {
Util.initLibrary(this, myNetworkContext, new Runnable() {
public void run() {
NetworkLibrary.Instance().runBackgroundUpdate(false);
if (intent != null) {
@ -119,7 +121,6 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
@Override
public void onResume() {
super.onResume();
BearerAuthenticator.initBearerAuthenticator(this);
getListView().setOnCreateContextMenuListener(this);
NetworkLibrary.Instance().fireModelChangedEvent(NetworkLibrary.ChangeListener.Code.SomeCode);
}
@ -145,7 +146,7 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
final NetworkTree tree =
NetworkLibrary.Instance().getCatalogTreeByUrl(uri.toString());
if (tree != null) {
checkAndRun(new OpenCatalogAction(this), tree);
checkAndRun(new OpenCatalogAction(this, myNetworkContext), tree);
return true;
}
}
@ -168,7 +169,7 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
}
});
if (BearerAuthenticator.onActivityResult(this, requestCode, resultCode, data)) {
if (myNetworkContext.onActivityResult(requestCode, resultCode, data)) {
return;
}
@ -227,7 +228,7 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
myOptionsMenuActions.add(new AddCustomCatalogAction(this));
myOptionsMenuActions.add(new RefreshRootCatalogAction(this));
myOptionsMenuActions.add(new ManageCatalogsAction(this));
myOptionsMenuActions.add(new ReloadCatalogAction(this));
myOptionsMenuActions.add(new ReloadCatalogAction(this, myNetworkContext));
myOptionsMenuActions.add(new SignInAction(this));
myOptionsMenuActions.add(new SignUpAction(this));
myOptionsMenuActions.add(new SignOutAction(this));
@ -238,7 +239,7 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
}
private void fillContextMenuList() {
myContextMenuActions.add(new OpenCatalogAction(this));
myContextMenuActions.add(new OpenCatalogAction(this, myNetworkContext));
myContextMenuActions.add(new OpenInBrowserAction(this));
myContextMenuActions.add(new RunSearchAction(this, true));
myContextMenuActions.add(new AddCustomCatalogAction(this));
@ -253,12 +254,12 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
}
private void fillListClickList() {
myListClickActions.add(new OpenCatalogAction(this));
myListClickActions.add(new OpenCatalogAction(this, myNetworkContext));
myListClickActions.add(new OpenInBrowserAction(this));
myListClickActions.add(new RunSearchAction(this, true));
myListClickActions.add(new AddCustomCatalogAction(this));
myListClickActions.add(new TopupAction(this));
myListClickActions.add(new ShowBookInfoAction(this));
myListClickActions.add(new ShowBookInfoAction(this, myNetworkContext));
myListClickActions.add(new ManageCatalogsAction(this));
}
@ -429,7 +430,7 @@ public abstract class NetworkLibraryActivity extends TreeActivity<NetworkTree> i
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
Util.initLibrary(NetworkLibraryActivity.this, null);
Util.initLibrary(NetworkLibraryActivity.this, myNetworkContext, null);
} else {
finish();
}

View file

@ -24,6 +24,7 @@ import android.app.SearchManager;
import android.os.Bundle;
import android.content.Intent;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.zlibrary.core.util.MimeType;
import org.geometerplus.fbreader.network.NetworkLibrary;
@ -50,7 +51,7 @@ public class NetworkSearchActivity extends Activity {
final String pattern = intent.getStringExtra(SearchManager.QUERY);
final MimeType mime = searchTree.getMimeType();
if (MimeType.APP_ATOM_XML.weakEquals(mime)) {
searchTree.startItemsLoader(pattern);
searchTree.startItemsLoader(new QuietNetworkContext(), pattern);
} else if (MimeType.TEXT_HTML.weakEquals(mime)) {
Util.openInBrowser(this, searchTree.getUrl(pattern));
}

View file

@ -0,0 +1,41 @@
/*
* Copyright (C) 2010-2014 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.network;
import java.net.URI;
import java.util.Map;
import android.app.Service;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
public final class ServiceNetworkContext extends ZLNetworkContext {
private final Service myService;
public ServiceNetworkContext(Service service) {
myService = service;
}
@Override
public boolean authenticate(URI uri, Map<String,String> params) {
// TODO: implement
return false;
}
}

View file

@ -24,6 +24,7 @@ import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.options.Config;
import org.geometerplus.fbreader.network.*;
@ -49,7 +50,7 @@ public abstract class Util implements UserRegistrationConstants {
return intent;
}
static void initLibrary(final Activity activity, final Runnable action) {
static void initLibrary(final Activity activity, final ZLNetworkContext nc, final Runnable action) {
Config.Instance().runOnConnect(new Runnable() {
public void run() {
UIUtil.wait("loadingNetworkLibrary", new Runnable() {
@ -60,7 +61,7 @@ public abstract class Util implements UserRegistrationConstants {
final NetworkLibrary library = NetworkLibrary.Instance();
if (!library.isInitialized()) {
library.initialize();
library.initialize(nc);
}
if (action != null) {
action.run();

View file

@ -28,6 +28,7 @@ import android.net.Uri;
import android.content.Intent;
import android.content.DialogInterface;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.ui.android.R;
@ -185,7 +186,7 @@ public abstract class NetworkBookActions {
book.Link.getBasketItem().remove(book);
return true;
case ActionCode.OPEN_BASKET:
new OpenCatalogAction(activity)
new OpenCatalogAction(activity, new QuietNetworkContext())
.run(NetworkLibrary.Instance().getFakeBasketTree(book.Link.getBasketItem()));
return true;
}

View file

@ -25,6 +25,8 @@ import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.fbreader.network.*;
import org.geometerplus.fbreader.network.tree.*;
@ -33,8 +35,11 @@ import org.geometerplus.android.fbreader.network.*;
import org.geometerplus.android.util.PackageUtil;
public class OpenCatalogAction extends Action {
public OpenCatalogAction(Activity activity) {
private final ZLNetworkContext myNetworkContext;
public OpenCatalogAction(Activity activity, ZLNetworkContext nc) {
super(activity, ActionCode.OPEN_CATALOG, "openCatalog", -1);
myNetworkContext = nc;
}
@Override
@ -99,7 +104,7 @@ public class OpenCatalogAction extends Action {
}
}
tree.startItemsLoader(true, resumeNotLoad);
tree.startItemsLoader(myNetworkContext, true, resumeNotLoad);
processExtraData(tree.Item.extraData(), new Runnable() {
public void run() {
doOpenTree(tree);

View file

@ -19,6 +19,7 @@
package org.geometerplus.android.fbreader.network.action;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.ui.android.R;
import org.geometerplus.fbreader.network.*;
@ -28,8 +29,11 @@ import org.geometerplus.fbreader.network.urlInfo.UrlInfo;
import org.geometerplus.android.fbreader.network.NetworkLibraryActivity;
public class ReloadCatalogAction extends CatalogAction {
public ReloadCatalogAction(NetworkLibraryActivity activity) {
private final ZLNetworkContext myNetworkContext;
public ReloadCatalogAction(NetworkLibraryActivity activity, ZLNetworkContext nc) {
super(activity, ActionCode.RELOAD_CATALOG, "reload", R.drawable.ic_menu_refresh);
myNetworkContext = nc;
}
@Override
@ -55,6 +59,6 @@ public class ReloadCatalogAction extends CatalogAction {
return;
}
((NetworkCatalogTree)tree).clearCatalog();
((NetworkCatalogTree)tree).startItemsLoader(false, false);
((NetworkCatalogTree)tree).startItemsLoader(myNetworkContext, false, false);
}
}

View file

@ -22,6 +22,7 @@ package org.geometerplus.android.fbreader.network.action;
import android.app.Activity;
import android.content.Intent;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.fbreader.network.NetworkTree;
@ -34,8 +35,11 @@ import org.geometerplus.android.util.UIUtil;
import org.geometerplus.android.fbreader.OrientationUtil;
public class ShowBookInfoAction extends BookAction {
public ShowBookInfoAction(Activity activity) {
private final ZLNetworkContext myNetworkContext;
public ShowBookInfoAction(Activity activity, ZLNetworkContext nc) {
super(activity, ActionCode.SHOW_BOOK_ACTIVITY, "bookInfo");
myNetworkContext = nc;
}
@Override
@ -45,11 +49,7 @@ public class ShowBookInfoAction extends BookAction {
} else {
UIUtil.wait("loadInfo", new Runnable() {
public void run() {
try {
getBook(tree).loadFullInformation();
} catch (ZLNetworkException e) {
e.printStackTrace();
}
getBook(tree).loadFullInformation(myNetworkContext);
myActivity.runOnUiThread(new Runnable() {
public void run() {
showBookInfo(tree);

View file

@ -31,8 +31,10 @@ import org.json.simple.JSONValue;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.fbreader.book.*;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.fbreader.network.ServiceNetworkContext;
public class SynchroniserService extends Service implements IBookCollection.Listener, Runnable {
private final ZLNetworkContext myNetworkContext = new ServiceNetworkContext(this);
private final BookCollectionShadow myCollection = new BookCollectionShadow();
private static volatile Thread ourSynchronizationThread;
@ -119,14 +121,6 @@ public class SynchroniserService extends Service implements IBookCollection.List
processResponse(JSONValue.parse(buffer.toString()));
}
final void perform() {
try {
ZLNetworkManager.Instance().perform(this);
} catch (ZLNetworkException e) {
e.printStackTrace();
}
}
protected abstract void processResponse(Object response);
}
@ -137,11 +131,11 @@ public class SynchroniserService extends Service implements IBookCollection.List
return;
}
System.err.println("SHA-1: " + uid.Id);
new Request("books.by.hash", Collections.singletonMap("sha1", uid.Id)) {
myNetworkContext.performQuietly(new Request("books.by.hash", Collections.singletonMap("sha1", uid.Id)) {
public void processResponse(Object response) {
System.err.println("RESPONSE = " + response);
}
}.perform();
});
}
@Override

View file

@ -35,7 +35,7 @@ public class AllCatalogsSearchItem extends SearchItem {
}
@Override
public void runSearch(NetworkItemsLoader loader, String pattern) throws ZLNetworkException {
public void runSearch(ZLNetworkContext nc, NetworkItemsLoader loader, String pattern) throws ZLNetworkException {
final LinkedList<ZLNetworkRequest> requestList = new LinkedList<ZLNetworkRequest>();
final LinkedList<NetworkOperationData> dataList = new LinkedList<NetworkOperationData>();
@ -62,7 +62,7 @@ public class AllCatalogsSearchItem extends SearchItem {
}
while (!requestList.isEmpty()) {
ZLNetworkManager.Instance().perform(requestList);
nc.perform(requestList);
requestList.clear();

View file

@ -19,6 +19,7 @@
package org.geometerplus.fbreader.network;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.util.MimeType;
@ -34,7 +35,7 @@ public interface ICustomNetworkLink extends INetworkLink {
void removeUrl(UrlInfo.Type type);
boolean isObsolete(long milliSeconds);
void reloadInfo(boolean urlsOnly, boolean quietly) throws ZLNetworkException;
void reloadInfo(ZLNetworkContext nc, boolean urlsOnly, boolean quietly) throws ZLNetworkException;
// returns true if next methods have changed link's data:
// setSiteName, setTitle, setSummary, setIcon, setLink, removeLink

View file

@ -22,6 +22,7 @@ package org.geometerplus.fbreader.network;
import java.util.*;
import java.io.File;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.fbreader.network.urlInfo.*;
@ -120,7 +121,8 @@ public class NetworkBookItem extends NetworkItem {
return true;
}
public void loadFullInformation() throws ZLNetworkException {
public boolean loadFullInformation(ZLNetworkContext nc) {
return true;
}
public NetworkCatalogItem createRelatedCatalogItem(RelatedUrlInfo info) {

View file

@ -22,9 +22,7 @@ package org.geometerplus.fbreader.network;
import java.util.*;
import org.geometerplus.zlibrary.core.util.ZLBoolean3;
import org.geometerplus.zlibrary.core.network.ZLNetworkManager;
import org.geometerplus.zlibrary.core.network.ZLNetworkRequest;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.fbreader.network.authentication.NetworkAuthenticationManager;
import org.geometerplus.fbreader.network.urlInfo.UrlInfoCollection;
@ -147,7 +145,7 @@ public abstract class NetworkCatalogItem extends NetworkItem {
*/
protected final void doLoadChildren(NetworkOperationData data, ZLNetworkRequest networkRequest) throws ZLNetworkException {
if (networkRequest != null) {
ZLNetworkManager.Instance().perform(networkRequest);
data.Loader.NetworkContext.perform(networkRequest);
data.Loader.confirmInterruption();
}
}

View file

@ -26,7 +26,7 @@ import android.net.Uri;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.image.ZLFileImage;
import org.geometerplus.zlibrary.core.image.ZLLoadableImage;
import org.geometerplus.zlibrary.core.network.ZLNetworkManager;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.util.MimeType;
@ -197,11 +197,7 @@ public final class NetworkImage extends ZLLoadableImage {
if (doFast) {
return;
}
try {
ZLNetworkManager.Instance().downloadToFile(Url, imageFile);
} catch (ZLNetworkException e) {
}
new QuietNetworkContext().downloadToFileQuietly(Url, imageFile);
} finally {
setSynchronized();
}

View file

@ -22,13 +22,13 @@ package org.geometerplus.fbreader.network;
import java.util.*;
import java.lang.ref.WeakReference;
import org.geometerplus.zlibrary.core.image.ZLImage;
import org.geometerplus.zlibrary.core.library.ZLibrary;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.zlibrary.core.options.*;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.util.MimeType;
import org.geometerplus.zlibrary.core.image.ZLImage;
import org.geometerplus.zlibrary.core.options.*;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.fbreader.tree.FBTree;
import org.geometerplus.fbreader.network.tree.*;
@ -236,13 +236,13 @@ public class NetworkLibrary {
return myIsInitialized;
}
public synchronized void initialize() {
public synchronized void initialize(ZLNetworkContext nc) {
if (myIsInitialized) {
return;
}
try {
myLinks.addAll(OPDSLinkReader.loadOPDSLinks(OPDSLinkReader.CacheMode.LOAD));
myLinks.addAll(OPDSLinkReader.loadOPDSLinks(nc, OPDSLinkReader.CacheMode.LOAD));
} catch (ZLNetworkException e) {
removeAllLoadedLinks();
fireModelChangedEvent(ChangeListener.Code.InitializationFailed, e.getMessage());
@ -310,10 +310,11 @@ public class NetworkLibrary {
}
private void runBackgroundUpdateInternal(boolean force) throws ZLNetworkException {
final ZLNetworkContext quietContext = new QuietNetworkContext();
synchronized (myUpdateLock) {
final OPDSLinkReader.CacheMode mode =
force ? OPDSLinkReader.CacheMode.CLEAR : OPDSLinkReader.CacheMode.UPDATE;
final List<INetworkLink> loadedLinks = OPDSLinkReader.loadOPDSLinks(mode);
final List<INetworkLink> loadedLinks = OPDSLinkReader.loadOPDSLinks(quietContext, mode);
if (!loadedLinks.isEmpty()) {
removeAllLoadedLinks();
myLinks.addAll(loadedLinks);
@ -327,7 +328,7 @@ public class NetworkLibrary {
final ICustomNetworkLink customLink = (ICustomNetworkLink)link;
if (force || customLink.isObsolete(12 * 60 * 60 * 1000)) { // 12 hours
try {
customLink.reloadInfo(true, true);
customLink.reloadInfo(quietContext, true, true);
NetworkDatabase.Instance().saveLink(customLink);
} catch (Throwable t) {
// ignore

View file

@ -19,6 +19,7 @@
package org.geometerplus.fbreader.network;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.util.MimeType;
@ -56,7 +57,7 @@ public abstract class SearchItem extends NetworkCatalogItem {
public void loadChildren(NetworkItemsLoader loader) throws ZLNetworkException {
}
public abstract void runSearch(NetworkItemsLoader loader, String pattern) throws ZLNetworkException;
public abstract void runSearch(ZLNetworkContext context, NetworkItemsLoader loader, String pattern) throws ZLNetworkException;
@Override
public String getStringId() {

View file

@ -34,12 +34,12 @@ public class SingleCatalogSearchItem extends SearchItem {
}
@Override
public void runSearch(NetworkItemsLoader loader, String pattern) throws ZLNetworkException {
public void runSearch(ZLNetworkContext nc, NetworkItemsLoader loader, String pattern) throws ZLNetworkException {
final NetworkOperationData data = Link.createOperationData(loader);
ZLNetworkRequest request = Link.simpleSearchRequest(pattern, data);
// TODO: possible infinite loop, use "continue link" instead
while (request != null && MimeType.APP_ATOM_XML.weakEquals(request.Mime)) {
ZLNetworkManager.Instance().perform(request);
nc.perform(request);
if (loader.confirmInterruption()) {
return;
}

View file

@ -33,6 +33,7 @@ import org.geometerplus.fbreader.network.opds.OPDSNetworkLink;
import org.geometerplus.fbreader.network.urlInfo.*;
public class LitResAuthenticationManager extends NetworkAuthenticationManager {
private final ZLNetworkContext myNetworkContext = new QuietNetworkContext();
private volatile boolean myFullyInitialized;
private final ZLStringOption mySidOption;
@ -159,7 +160,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
request.addPostParameter(entry.getKey(), entry.getValue());
}
request.addPostParameter("sid", sid);
ZLNetworkManager.Instance().perform(request);
myNetworkContext.perform(request);
initUser(null, xmlReader.Sid, xmlReader.UserId, xmlReader.CanRebill);
return true;
} catch (ZLNetworkException e) {
@ -190,7 +191,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
}
request.addPostParameter("login", username);
request.addPostParameter("pwd", password);
ZLNetworkManager.Instance().perform(request);
myNetworkContext.perform(request);
NetworkLibrary.Instance().fireModelChangedEvent(NetworkLibrary.ChangeListener.Code.SignedIn);
initUser(null, xmlReader.Sid, xmlReader.UserId, xmlReader.CanRebill);
} catch (ZLNetworkException e) {
@ -242,7 +243,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
try {
final LitResNetworkRequest request = new LitResNetworkRequest(reference.Url, xmlReader);
request.addPostParameter("sid", sid);
ZLNetworkManager.Instance().perform(request);
myNetworkContext.perform(request);
} catch (ZLNetworkException e) {
exception = e;
}
@ -313,7 +314,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
ZLNetworkException exception = null;
try {
ZLNetworkManager.Instance().perform(networkRequest);
myNetworkContext.perform(networkRequest);
} catch (ZLNetworkException e) {
exception = e;
}
@ -369,7 +370,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
requests.add(accountRequest);
try {
ZLNetworkManager.Instance().perform(requests);
myNetworkContext.perform(requests);
final boolean hasMorePages;
synchronized (this) {
myInitializedDataSid = sid;
@ -380,7 +381,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
if (hasMorePages) {
for (int page = 1; ; ++page) {
final LitResNetworkRequest r = loadPurchasedBooksRequest(sid, page);
ZLNetworkManager.Instance().perform(r);
myNetworkContext.perform(r);
synchronized (this) {
if (loadPurchasedBooksOnSuccess(r, false) < BOOKS_PER_PAGE) {
break;
@ -401,7 +402,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
@Override
public void refreshAccountInformation() throws ZLNetworkException {
final LitResNetworkRequest accountRequest = loadAccountRequest(mySidOption.getValue());
ZLNetworkManager.Instance().perform(accountRequest);
myNetworkContext.perform(accountRequest);
synchronized (this) {
myAccount = new Money(((LitResPurchaseXMLReader)accountRequest.Reader).Account, "RUB");
}
@ -463,7 +464,7 @@ public class LitResAuthenticationManager extends NetworkAuthenticationManager {
final LitResPasswordRecoveryXMLReader xmlReader = new LitResPasswordRecoveryXMLReader(Link.getSiteName());
final LitResNetworkRequest request = new LitResNetworkRequest(url, xmlReader);
request.addPostParameter("mail", email);
ZLNetworkManager.Instance().perform(request);
myNetworkContext.perform(request);
}
@Override

View file

@ -21,6 +21,7 @@ package org.geometerplus.fbreader.network.opds;
import java.util.List;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.util.MimeType;
import org.geometerplus.zlibrary.core.util.MiscUtil;

View file

@ -33,14 +33,14 @@ import org.geometerplus.fbreader.network.atom.*;
import org.geometerplus.fbreader.network.urlInfo.*;
public class OPDSBookItem extends NetworkBookItem implements OPDSConstants {
public static OPDSBookItem create(INetworkLink link, String url) {
public static OPDSBookItem create(ZLNetworkContext nc, INetworkLink link, String url) {
if (link == null || url == null) {
return null;
}
final CreateBookHandler handler = new CreateBookHandler(link, url);
try {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(url) {
nc.perform(new ZLNetworkRequest(url) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OPDSXMLReader(handler, true).read(inputStream);
@ -252,18 +252,18 @@ public class OPDSBookItem extends NetworkBookItem implements OPDSConstants {
}
@Override
public synchronized void loadFullInformation() throws ZLNetworkException {
public synchronized boolean loadFullInformation(ZLNetworkContext nc) {
if (myInformationIsFull) {
return;
return true;
}
final String url = getUrl(UrlInfo.Type.SingleEntry);
if (url == null) {
myInformationIsFull = true;
return;
return true;
}
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(url) {
return nc.performQuietly(new ZLNetworkRequest(url) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OPDSXMLReader(new LoadInfoHandler(url), true).read(inputStream);

View file

@ -101,13 +101,13 @@ public class OPDSCustomNetworkLink extends OPDSNetworkLink implements ICustomNet
return false;
}
public void reloadInfo(final boolean urlsOnly, boolean quietly) throws ZLNetworkException {
public void reloadInfo(ZLNetworkContext nc, final boolean urlsOnly, boolean quietly) throws ZLNetworkException {
final LinkedList<String> opensearchDescriptionURLs = new LinkedList<String>();
final List<OpenSearchDescription> descriptions = Collections.synchronizedList(new LinkedList<OpenSearchDescription>());
ZLNetworkException error = null;
try {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(getUrl(UrlInfo.Type.Catalog), quietly) {
nc.perform(new ZLNetworkRequest(getUrl(UrlInfo.Type.Catalog), quietly) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
final OPDSCatalogInfoHandler info = new OPDSCatalogInfoHandler(getURL(), OPDSCustomNetworkLink.this, opensearchDescriptionURLs);
@ -144,7 +144,7 @@ public class OPDSCustomNetworkLink extends OPDSNetworkLink implements ICustomNet
});
}
try {
ZLNetworkManager.Instance().perform(requests);
nc.perform(requests);
} catch (ZLNetworkException e) {
// we do ignore errors in opensearch description loading/parsing
e.printStackTrace();

View file

@ -23,9 +23,7 @@ import java.util.*;
import java.io.*;
import org.geometerplus.zlibrary.core.filesystem.ZLPhysicalFile;
import org.geometerplus.zlibrary.core.network.ZLNetworkManager;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.network.ZLNetworkRequest;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.network.*;
@ -41,12 +39,12 @@ public class OPDSLinkReader {
CLEAR
};
public static List<INetworkLink> loadOPDSLinks(CacheMode cacheMode) throws ZLNetworkException {
public static List<INetworkLink> loadOPDSLinks(ZLNetworkContext nc, CacheMode cacheMode) throws ZLNetworkException {
final OPDSLinkXMLReader xmlReader = new OPDSLinkXMLReader();
final File dirFile = new File(Paths.networkCacheDirectory());
if (!dirFile.exists() && !dirFile.mkdirs()) {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(CATALOGS_URL) {
nc.perform(new ZLNetworkRequest(CATALOGS_URL) {
@Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
xmlReader.read(inputStream);
@ -82,7 +80,7 @@ public class OPDSLinkReader {
if (!cacheIsGood) {
try {
ZLNetworkManager.Instance().downloadToFile(CATALOGS_URL, catalogsFile);
nc.downloadToFile(CATALOGS_URL, catalogsFile);
} catch (ZLNetworkException e) {
if (oldCache == null) {
throw e;

View file

@ -21,6 +21,8 @@ package org.geometerplus.fbreader.network.tree;
import java.util.*;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.fbreader.tree.FBTree;
import org.geometerplus.fbreader.network.*;
@ -30,14 +32,14 @@ public class BasketCatalogTree extends NetworkCatalogTree {
public BasketCatalogTree(NetworkCatalogTree parent, BasketItem item, int position) {
super(parent, parent.getLink(), item, position);
if (!item.bookIds().isEmpty()) {
startItemsLoader(false, false);
startItemsLoader(new QuietNetworkContext(), false, false);
}
}
public BasketCatalogTree(RootTree parent, BasketItem item) {
super(parent, item.Link, item, 0);
if (!item.bookIds().isEmpty()) {
startItemsLoader(false, false);
startItemsLoader(new QuietNetworkContext(), false, false);
}
}

View file

@ -19,6 +19,7 @@
package org.geometerplus.fbreader.network.tree;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.fbreader.network.*;
@ -28,8 +29,8 @@ class CatalogExpander extends NetworkItemsLoader {
private final boolean myAuthenticate;
private final boolean myResumeNotLoad;
CatalogExpander(NetworkCatalogTree tree, boolean authenticate, boolean resumeNotLoad) {
super(tree);
CatalogExpander(ZLNetworkContext nc, NetworkCatalogTree tree, boolean authenticate, boolean resumeNotLoad) {
super(nc, tree);
myAuthenticate = authenticate;
myResumeNotLoad = resumeNotLoad;
}

View file

@ -22,6 +22,8 @@ package org.geometerplus.fbreader.network.tree;
import java.util.*;
import org.geometerplus.zlibrary.core.image.ZLImage;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.util.ZLBoolean3;
import org.geometerplus.fbreader.tree.FBTree;
@ -209,8 +211,8 @@ public class NetworkCatalogTree extends NetworkTree {
return Item.getStringId();
}
public void startItemsLoader(boolean authenticate, boolean resumeNotLoad) {
new CatalogExpander(this, authenticate, resumeNotLoad).start();
public void startItemsLoader(ZLNetworkContext nc, boolean authenticate, boolean resumeNotLoad) {
new CatalogExpander(nc, this, authenticate, resumeNotLoad).start();
}
public synchronized void clearCatalog() {
@ -240,7 +242,7 @@ public class NetworkCatalogTree extends NetworkTree {
&& !NetworkLibrary.Instance().isLoadingInProgress(this)
&& Item.canResumeLoading()) {
myLastTotalChildren = currentTotal;
startItemsLoader(false, true);
startItemsLoader(new QuietNetworkContext(), false, true);
}
}
}

View file

@ -19,6 +19,7 @@
package org.geometerplus.fbreader.network.tree;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.fbreader.network.NetworkLibrary;
@ -29,8 +30,10 @@ public abstract class NetworkItemsLoader implements Runnable {
private volatile Runnable myPostRunnable;
private volatile boolean myFinishedFlag;
public final ZLNetworkContext NetworkContext;
protected NetworkItemsLoader(NetworkCatalogTree tree) {
protected NetworkItemsLoader(ZLNetworkContext nc, NetworkCatalogTree tree) {
NetworkContext = nc;
myTree = tree;
}

View file

@ -19,6 +19,7 @@
package org.geometerplus.fbreader.network.tree;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.util.MimeType;
import org.geometerplus.fbreader.network.NetworkLibrary;
@ -83,7 +84,7 @@ public class SearchCatalogTree extends NetworkCatalogTree {
return ((SearchItem)Item).getUrl(pattern);
}
public void startItemsLoader(String pattern) {
new Searcher(this, pattern).start();
public void startItemsLoader(ZLNetworkContext nc, String pattern) {
new Searcher(nc, this, pattern).start();
}
}

View file

@ -19,6 +19,7 @@
package org.geometerplus.fbreader.network.tree;
import org.geometerplus.zlibrary.core.network.ZLNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.fbreader.network.*;
@ -27,8 +28,8 @@ class Searcher extends NetworkItemsLoader {
private final String myPattern;
private volatile boolean myItemFound;
Searcher(SearchCatalogTree tree, String pattern) {
super(tree);
Searcher(ZLNetworkContext nc, SearchCatalogTree tree, String pattern) {
super(nc, tree);
myPattern = pattern;
}
@ -57,7 +58,7 @@ class Searcher extends NetworkItemsLoader {
);
}
} else {
item.runSearch(this, myPattern);
item.runSearch(NetworkContext, this, myPattern);
}
}

View file

@ -24,7 +24,7 @@ import java.io.File;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.options.*;
import org.geometerplus.zlibrary.core.network.ZLNetworkManager;
import org.geometerplus.zlibrary.core.network.QuietNetworkContext;
import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.fbreader.Paths;
@ -157,13 +157,8 @@ public class TipsManager {
tipsFile.getParentFile().mkdirs();
new Thread(new Runnable() {
public void run() {
try {
ZLNetworkManager.Instance().downloadToFile(getUrl(), tipsFile);
} catch (ZLNetworkException e) {
e.printStackTrace();
} finally {
myDownloadInProgress = false;
}
new QuietNetworkContext().downloadToFileQuietly(getUrl(), tipsFile);
myDownloadInProgress = false;
}
}).start();
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (C) 2010-2014 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.network;
import java.io.File;
import java.net.URI;
import java.util.Map;
public class QuietNetworkContext extends ZLNetworkContext {
@Override
public boolean authenticate(URI uri, Map<String,String> params) {
return false;
}
public final boolean downloadToFileQuietly(String url, final File outFile) {
try {
downloadToFile(url, outFile);
return true;
} catch (ZLNetworkException e) {
return false;
}
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright (C) 2010-2014 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.network;
import java.io.*;
import java.util.HashSet;
import java.util.List;
import org.apache.http.client.CookieStore;
public abstract class ZLNetworkContext implements ZLNetworkManager.BearerAuthenticator {
private final ZLNetworkManager myManager = ZLNetworkManager.Instance();
protected ZLNetworkContext() {
}
protected CookieStore cookieStore() {
return myManager.CookieStore;
}
public boolean performQuietly(ZLNetworkRequest request) {
try {
perform(request);
return true;
} catch (ZLNetworkException e) {
return false;
}
}
public void perform(ZLNetworkRequest request) throws ZLNetworkException {
myManager.perform(request, this, 30000, 15000);
}
public void perform(List<? extends ZLNetworkRequest> requests) throws ZLNetworkException {
if (requests.size() == 0) {
return;
}
if (requests.size() == 1) {
perform(requests.get(0));
return;
}
HashSet<String> errors = new HashSet<String>();
// TODO: implement concurrent execution !!!
for (ZLNetworkRequest r : requests) {
try {
perform(r);
} catch (ZLNetworkException e) {
e.printStackTrace();
errors.add(e.getMessage());
}
}
if (errors.size() > 0) {
StringBuilder message = new StringBuilder();
for (String e : errors) {
if (message.length() != 0) {
message.append(", ");
}
message.append(e);
}
throw new ZLNetworkException(true, message.toString());
}
}
public final void downloadToFile(String url, final File outFile) throws ZLNetworkException {
downloadToFile(url, outFile, 8192);
}
private final void downloadToFile(String url, final File outFile, final int bufferSize) throws ZLNetworkException {
myManager.perform(new ZLNetworkRequest(url) {
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
OutputStream outStream = new FileOutputStream(outFile);
try {
final byte[] buffer = new byte[bufferSize];
while (true) {
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
outStream.write(buffer, 0, size);
}
} finally {
outStream.close();
}
}
}, this, 0, 0);
}
}

View file

@ -155,12 +155,11 @@ public class ZLNetworkManager {
abstract protected void startAuthenticationDialog(String host, String area, String scheme, String username);
}
public static abstract class BearerAuthenticator {
abstract protected boolean authenticate(URI uri, Map<String,String> params);
static interface BearerAuthenticator {
boolean authenticate(URI uri, Map<String,String> params);
}
private volatile CredentialsCreator myCredentialsCreator;
private volatile BearerAuthenticator myBearerAuthenticator;
volatile CredentialsCreator myCredentialsCreator;
private class MyCredentialsProvider extends BasicCredentialsProvider {
private final HttpUriRequest myRequest;
@ -219,11 +218,7 @@ public class ZLNetworkManager {
}
};
public CookieStore cookieStore() {
return myCookieStore;
}
private final CookieStore myCookieStore = new CookieStore() {
final CookieStore CookieStore = new CookieStore() {
private HashMap<Key,Cookie> myCookies;
public synchronized void addCookie(Cookie cookie) {
@ -286,21 +281,13 @@ public class ZLNetworkManager {
return myCredentialsCreator;
}
public void setBearerAuthenticator(BearerAuthenticator authenticator) {
myBearerAuthenticator = authenticator;
}
public void perform(ZLNetworkRequest request) throws ZLNetworkException {
perform(request, 30000, 15000);
}
private void perform(ZLNetworkRequest request, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
void perform(ZLNetworkRequest request, BearerAuthenticator authenticator, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
boolean success = false;
DefaultHttpClient httpClient = null;
HttpEntity entity = null;
try {
final HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, myCookieStore);
httpContext.setAttribute(ClientContext.COOKIE_STORE, CookieStore);
request.doBefore();
final HttpParams params = new BasicHttpParams();
@ -371,7 +358,7 @@ public class ZLNetworkManager {
IOException lastException = null;
for (int retryCounter = 0; retryCounter < 3 && entity == null; ++retryCounter) {
try {
response = execute(httpClient, httpRequest, httpContext);
response = execute(httpClient, httpRequest, httpContext, authenticator);
entity = response.getEntity();
lastException = null;
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
@ -446,69 +433,14 @@ public class ZLNetworkManager {
}
}
private HttpResponse execute(DefaultHttpClient client, HttpRequestBase request, HttpContext context) throws IOException {
private HttpResponse execute(DefaultHttpClient client, HttpRequestBase request, HttpContext context, BearerAuthenticator authenticator) throws IOException {
try {
return client.execute(request, context);
} catch (BearerAuthenticationException e) {
if (myBearerAuthenticator != null
&& myBearerAuthenticator.authenticate(request.getURI(), e.Params)) {
if (authenticator.authenticate(request.getURI(), e.Params)) {
return client.execute(request, context);
}
throw e;
}
}
public void perform(List<? extends ZLNetworkRequest> requests) throws ZLNetworkException {
if (requests.size() == 0) {
return;
}
if (requests.size() == 1) {
perform(requests.get(0));
return;
}
HashSet<String> errors = new HashSet<String>();
// TODO: implement concurrent execution !!!
for (ZLNetworkRequest r : requests) {
try {
perform(r);
} catch (ZLNetworkException e) {
e.printStackTrace();
errors.add(e.getMessage());
}
}
if (errors.size() > 0) {
StringBuilder message = new StringBuilder();
for (String e : errors) {
if (message.length() != 0) {
message.append(", ");
}
message.append(e);
}
throw new ZLNetworkException(true, message.toString());
}
}
public final void downloadToFile(String url, final File outFile) throws ZLNetworkException {
downloadToFile(url, outFile, 8192);
}
public final void downloadToFile(String url, final File outFile, final int bufferSize) throws ZLNetworkException {
perform(new ZLNetworkRequest(url) {
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
OutputStream outStream = new FileOutputStream(outFile);
try {
final byte[] buffer = new byte[bufferSize];
while (true) {
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
outStream.write(buffer, 0, size);
}
} finally {
outStream.close();
}
}
}, 0, 0);
}
}