1
0
Fork 0
mirror of https://github.com/geometer/FBReaderJ.git synced 2025-10-05 19:42:17 +02:00

using zlibrary network layer

git-svn-id: https://only.mawhrin.net/repos/FBReaderJ/trunk@1211 6a642e6f-84f6-412e-ac94-c4a38d5a04b0
This commit is contained in:
Vasiliy Bout 2010-04-10 18:20:52 +00:00
parent 0434b0a1fa
commit a36601299c
14 changed files with 125 additions and 167 deletions

View file

@ -2,8 +2,8 @@ DONE Shucang catalog -> второй пункт сверху -> открывае
DONE И после загрузки в notification для первого файла из этого списка -- название файла
DONE И в библиотеке тоже название файла, вместо названия книги
DONE При первом открытии network library activity около 2 секунд показывается черный экран. Должен быть wait message.
** Когда сети нет появляется сообщение "somthing goes wrong". Должно быть что-то более понятное.
** Синхронизировать ресурсы (русские и французские)
DONE Когда сети нет появляется сообщение "somthing goes wrong". Должно быть что-то более понятное.
DONE Синхронизировать ресурсы (русские и французские)
DONE http://groups.google.com/group/fbreader/browse_thread/thread/a439a8994a88a636

View file

@ -240,7 +240,6 @@
<node name="loadingNetworkLibrary" value="Opening library. Please, wait..." />
</node>
<node name="networkError">
<node name="authenticationFailed" value="Authentication failed" />
<node name="internalError" value="Internal server error" />
<node name="purchaseNotEnoughMoney" value="Not enough money" />
<node name="purchaseMissingBook" value="Missing book" />

View file

@ -241,7 +241,6 @@
<node name="loadingNetworkLibrary" value="Ouverture de la bibliothèque. Patientez, s'il-vous plait..." />
</node>
<node name="networkError">
<node name="authenticationFailed" value="Authentification échouée"/>
<node name="internalError" value="Erreur interne du serveur"/>
<node name="purchaseNotEnoughMoney" value="Pas assez de crédit"/>
<node name="purchaseMissingBook" value="Livre manquant"/>

View file

@ -240,7 +240,6 @@
<node name="loadingNetworkLibrary" value="Открывается библиотека. Подождите, пожалуйста..." />
</node>
<node name="networkError">
<node name="authenticationFailed" value="Ошибка авторизации" />
<node name="internalError" value="Внутренняя ошибка сервера" />
<node name="purchaseNotEnoughMoney" value="Не достаточно средств на счету" />
<node name="purchaseMissingBook" value="Книга отсутствует в продаже" />

View file

@ -20,12 +20,13 @@
<node name="couldntCreateDirectoryMessage" value="Couldn&apos;t create a directory&#10;%s" />
<node name="couldntCreateFileMessage" value="Couldn&apos;t create a file&#10;%s" />
<node name="couldntConnectToNetworkMessage" value="Couldn&apos;t connect to the network" />
<node name="couldntConnectMessage" value="Couldn&apos;t connect to host %s" />
<node name="couldntResolveHostMessage" value="Couldn&apos;t resolve host %s" />
<node name="couldntConnectMessage" value="Couldn&apos;t connect to host&#10;%s" />
<node name="couldntResolveHostMessage" value="Couldn&apos;t resolve host&#10;%s" />
<node name="authenticationFailed" value="Authentication failed" />
<node name="unsupportedURL" value="Unsupported URL" />
<node name="invalidURL" value="Invalid URL" />
<node name="hostCantBeReached" value="Host %s cannot be reached" />
<node name="connectionRefused" value="Connection was refused by %s" />
<node name="hostCantBeReached" value="Host %s&#10;cannot be reached" />
<node name="connectionRefused" value="Connection was refused by&#10;%s" />
</node>
</node>
<node name="color">

View file

@ -23,6 +23,11 @@
<node name="couldntConnectToNetworkMessage" value="Connexion au réseau impossible"/>
<node name="couldntConnectMessage" value="Impossible de se connecter à l'hôte %s"/>
<node name="couldntResolveHostMessage" value="Résolution du nom %s impossible"/>
<node name="authenticationFailed" value="Authentification échouée"/>
<node name="unsupportedURL" toBeTranslated="true" value="Unsupported URL" />
<node name="invalidURL" toBeTranslated="true" value="Invalid URL" />
<node name="hostCantBeReached" toBeTranslated="true" value="Host %s&#10;cannot be reached" />
<node name="connectionRefused" toBeTranslated="true" value="Connection was refused by&#10;%s" />
</node>
</node>
<node name="color">

View file

@ -20,8 +20,13 @@
<node name="couldntCreateDirectoryMessage" value="Не удалось создать каталог&#10;%s" />
<node name="couldntCreateFileMessage" value="Не удалось создать файл&#10;%s" />
<node name="couldntConnectToNetworkMessage" value="Не удалось соединиться с сетью" />
<node name="couldntConnectMessage" value="Не удалось соединиться с сайтом %s" />
<node name="couldntResolveHostMessage" value="Не удается найти сайт %s" />
<node name="couldntConnectMessage" value="Не удалось соединиться с сайтом&#10;%s" />
<node name="couldntResolveHostMessage" value="Не удается найти сайт&#10;%s" />
<node name="authenticationFailed" value="Ошибка авторизации" />
<node name="unsupportedURL" value="Неподдерживаемый URL" />
<node name="invalidURL" value="Неправильный URL" />
<node name="hostCantBeReached" value="Сайт %s недоступен" />
<node name="connectionRefused" value="Соединение закрыто сайтом&#10;%s" />
</node>
</node>
<node name="color">

View file

@ -39,6 +39,8 @@ import android.widget.Toast;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.zlibrary.ui.android.R;
import org.geometerplus.fbreader.network.BookReference;
@ -274,73 +276,62 @@ public class BookDownloaderService extends Service {
}
};
final ZLNetworkRequest request = new ZLNetworkRequest(urlString) {
public String handleStream(URLConnection connection, InputStream inputStream) throws IOException {
final int updateIntervalMillis = 1000; // FIXME: remove hardcoded time constant
final int fileLength = connection.getContentLength();
int downloadedPart = 0;
long progressTime = System.currentTimeMillis() + updateIntervalMillis;
if (fileLength <= 0) {
progressHandler.sendEmptyMessage(-1);
}
OutputStream outStream;
try {
outStream = new FileOutputStream(file);
} catch (FileNotFoundException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CREATE_FILE, file.getPath());
}
try {
final byte[] buffer = new byte[8192];
while (true) {
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
downloadedPart += size;
if (fileLength > 0) {
final long currentTime = System.currentTimeMillis();
if (currentTime > progressTime) {
progressTime = currentTime + updateIntervalMillis;
progressHandler.sendEmptyMessage(downloadedPart * 100 / fileLength);
}
/*if (downloadedPart * 100 / fileLength > 95) {
throw new IOException("debug exception");
}*/
}
outStream.write(buffer, 0, size);
/*try {
Thread.currentThread().sleep(200);
} catch (InterruptedException ex) {
}*/
}
} finally {
outStream.close();
}
return null;
}
};
new Thread(new Runnable() {
public void run() {
final int updateIntervalMillis = 1000; // FIXME: remove hardcoded time constant
boolean downloadSuccess = false;
try {
final URL url = new URL(urlString);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return; // TODO: return error/information message???
}
final HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(15000); // FIXME: hardcoded timeout value!!!
httpConnection.setReadTimeout(30000); // FIXME: hardcoded timeout value!!!
httpConnection.setRequestProperty("Connection", "Close");
httpConnection.setRequestProperty("User-Agent", ZLNetworkUtil.getUserAgent());
final int response = httpConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
final int fileLength = httpConnection.getContentLength();
int downloadedPart = 0;
long progressTime = System.currentTimeMillis() + updateIntervalMillis;
if (fileLength <= 0) {
progressHandler.sendEmptyMessage(-1);
}
OutputStream outStream = new FileOutputStream(file);
try {
InputStream inStream = httpConnection.getInputStream();
final byte[] buffer = new byte[8192];
while (true) {
final int size = inStream.read(buffer);
if (size <= 0) {
break;
}
downloadedPart += size;
if (fileLength > 0) {
final long currentTime = System.currentTimeMillis();
if (currentTime > progressTime) {
progressTime = currentTime + updateIntervalMillis;
progressHandler.sendEmptyMessage(downloadedPart * 100 / fileLength);
}
/*if (downloadedPart * 100 / fileLength > 95) {
throw new IOException();
}*/
}
outStream.write(buffer, 0, size);
/*try {
Thread.currentThread().sleep(200);
} catch (InterruptedException ex) {
}*/
}
inStream.close();
} finally {
outStream.close();
}
downloadSuccess = true;
}
} catch (MalformedURLException e) {
// TODO: error message
} catch (SocketTimeoutException ex) {
// TODO: error message
// error message : NetworkErrors.errorMessage("operationTimedOutMessage");
} catch (IOException e) {
// TODO: error message
} finally {
downloadFinishHandler.sendEmptyMessage(downloadSuccess ? 1 : 0);
if (!downloadSuccess) {
file.delete();
}
final String err = ZLNetworkManager.Instance().perform(request);
// TODO: show error message to User
final boolean success = (err == null);
downloadFinishHandler.sendEmptyMessage(success ? 1 : 0);
if (!success) {
file.delete();
}
}
}).start();

View file

@ -23,7 +23,6 @@ import org.geometerplus.zlibrary.core.network.ZLNetworkErrors;
public final class NetworkErrors extends ZLNetworkErrors {
public static final String ERROR_AUTHENTICATION_FAILED = "authenticationFailed";
public static final String ERROR_INTERNAL = "internalError";
public static final String ERROR_PURCHASE_NOT_ENOUGH_MONEY = "purchaseNotEnoughMoney";
public static final String ERROR_PURCHASE_MISSING_BOOK = "purchaseMissingBook";

View file

@ -24,6 +24,7 @@ import java.net.*;
import org.geometerplus.zlibrary.core.image.ZLSingleImage;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.fbreader.Constants;
@ -179,39 +180,25 @@ public final class NetworkImage extends ZLSingleImage {
}
imageFile.delete();
}
try {
final URL url = new URL(myUrl);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
// TODO: error message ???
return;
}
final HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(15000); // FIXME: hardcoded timeout value!!!
httpConnection.setReadTimeout(30000); // FIXME: hardcoded timeout value!!!
httpConnection.setRequestProperty("Connection", "Close");
httpConnection.setRequestProperty("User-Agent", ZLNetworkUtil.getUserAgent());
final int response = httpConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
ZLNetworkManager.Instance().perform(new ZLNetworkRequest(myUrl) {
public String handleStream(URLConnection connection, InputStream inputStream) throws IOException {
OutputStream outStream = new FileOutputStream(imageFile);
try {
InputStream inStream = httpConnection.getInputStream();
final byte[] buffer = new byte[8192];
while (true) {
final int size = inStream.read(buffer);
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
outStream.write(buffer, 0, size);
}
inStream.close();
} finally {
outStream.close();
}
return null;
}
} catch (MalformedURLException e) {
} catch (IOException e) {
}
});
} finally {
mySynchronized = true;
}

View file

@ -24,6 +24,7 @@ import java.io.*;
import java.net.*;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.network.*;
import org.geometerplus.fbreader.network.*;
@ -44,52 +45,31 @@ class OPDSCatalogItem extends NetworkCatalogItem {
@Override
public String loadChildren(CatalogListener listener) {
OperationData data = new OperationData(Link, listener);
String urlString = URLByType.get(URL_CATALOG);
if (urlString == null) {
return null; // TODO: return error/information message???
}
try {
while (data.ResumeCount < 10 // FIXME: hardcoded resume limit constant!!!
&& urlString != null) {
urlString = Link.rewriteUrl(urlString, false);
final URL url = new URL(urlString);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return null; // TODO: return error/information message???
}
final HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(15000); // FIXME: hardcoded timeout value!!!
httpConnection.setReadTimeout(30000); // FIXME: hardcoded timeout value!!!
httpConnection.setRequestProperty("Connection", "Close");
httpConnection.setRequestProperty("User-Agent", ZLNetworkUtil.getUserAgent());
final int response = httpConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
InputStream inStream = httpConnection.getInputStream();
try {
final NetworkOPDSFeedReader feedReader = new NetworkOPDSFeedReader(urlString, data);
final OPDSXMLReader xmlReader = new OPDSXMLReader(feedReader);
xmlReader.read(inStream);
} finally {
inStream.close();
}
} else {
return null; // return error???
}
final OperationData data = new OperationData(Link, listener);
urlString = data.ResumeURI;
data.clear();
}
} catch (MalformedURLException ex) {
// return error???
return null;
} catch (SocketTimeoutException ex) {
return NetworkErrors.errorMessage("operationTimedOutMessage");
} catch (IOException ex) {
return NetworkErrors.errorMessage(NetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(urlString));
String errorMessage = null;
while (data.ResumeCount < 10 // FIXME: hardcoded resume limit constant!!!
&& urlString != null && errorMessage == null) {
urlString = Link.rewriteUrl(urlString, false);
errorMessage = ZLNetworkManager.Instance().perform(new ZLNetworkRequest(urlString) {
public String handleStream(URLConnection connection, InputStream inputStream) throws IOException {
new OPDSXMLReader(
new NetworkOPDSFeedReader(URL, data)
).read(inputStream);
return null;
}
});
urlString = data.ResumeURI;
data.clear();
}
return null;
return errorMessage;
}
}

View file

@ -30,6 +30,7 @@ public class ZLNetworkErrors {
public static final String ERROR_CONNECT_TO_NETWORK = "couldntConnectToNetworkMessage";
public static final String ERROR_UNSUPPORTED_URL = "unsupportedURL";
public static final String ERROR_INVALID_URL = "invalidURL";
public static final String ERROR_AUTHENTICATION_FAILED = "authenticationFailed";
// Messages with one parameter:
public static final String ERROR_SOMETHING_WRONG = "somethingWrongMessage";

View file

@ -38,12 +38,9 @@ public class ZLNetworkManager {
private String doBeforeRequest(ZLNetworkRequest request) {
if (!request.doBefore()) {
final String err = request.getErrorMessage();
if (err != null) {
return err;
}
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
final String err = request.doBefore();
if (err != null) {
return err;
}
/*if (request.isInstanceOf(ZLNetworkPostRequest::TYPE_ID)) {
@ -76,17 +73,16 @@ public class ZLNetworkManager {
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
if (!request.handleStream(stream)) {
final String err = request.getErrorMessage();
if (err != null) {
return err;
}
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
final String err = request.handleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
sucess = true;
} else if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
@ -103,13 +99,9 @@ public class ZLNetworkManager {
} catch (IOException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
boolean res = request.doAfter(sucess);
if (sucess && !res) {
final String err = request.getErrorMessage();
if (err != null) {
return err;
}
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
final String err = request.doAfter(sucess);
if (sucess && err != null) {
return err;
}
}
return null;

View file

@ -21,6 +21,7 @@ package org.geometerplus.zlibrary.core.network;
import java.io.InputStream;
import java.io.IOException;
import java.net.URLConnection;
public abstract class ZLNetworkRequest {
@ -38,25 +39,24 @@ public abstract class ZLNetworkRequest {
public boolean FollowRedirects = true;
private String myErrorMessage;
protected ZLNetworkRequest(String url) {
this(url, null);
}
protected ZLNetworkRequest(String url, String sslCertificate) {
URL = url;
SSLCertificate = sslCertificate;
}
public String getErrorMessage() {
return myErrorMessage;
// callbacks return error messages
public String doBefore() {
return null;
}
protected void setErrorMessage(String errorMessage) {
myErrorMessage = errorMessage;
public abstract String handleStream(URLConnection connection, InputStream inputStream) throws IOException;
public String doAfter(boolean success) { // returned error message is ignored when `success == false`
return null;
}
public abstract boolean doBefore();
public abstract boolean handleStream(InputStream inputStream) throws IOException;
// When `success == true` return false MUST make request fail; when `success == false` return value MUST be ignored.
public abstract boolean doAfter(boolean success);
}