1
0
Fork 0
mirror of https://github.com/geometer/FBReaderJ.git synced 2025-10-03 17:59:33 +02:00

ZLNetworkRequest refactoring; httpmime library added; file upload

This commit is contained in:
Nikolay Pultsin 2014-06-25 09:41:35 +01:00
parent 350c4e672c
commit d5021fbfe1
18 changed files with 94 additions and 58 deletions

BIN
libs/httpmime-4.2.5.jar Normal file

Binary file not shown.

View file

@ -155,7 +155,7 @@ public final class ActivityNetworkContext extends AndroidNetworkContext {
private String runTokenAuthorization(String authUrl, String authToken, String code) { private String runTokenAuthorization(String authUrl, String authToken, String code) {
final StringBuilder buffer = new StringBuilder(); final StringBuilder buffer = new StringBuilder();
final ZLNetworkRequest request = new ZLNetworkRequest(authUrl) { final ZLNetworkRequest.PostWithMap request = new ZLNetworkRequest.PostWithMap(authUrl) {
public void handleStream(InputStream stream, int length) throws IOException { public void handleStream(InputStream stream, int length) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
buffer.append(reader.readLine()); buffer.append(reader.readLine());

View file

@ -284,7 +284,7 @@ public class BookDownloaderService extends Service {
} }
}; };
final ZLNetworkRequest request = new ZLNetworkRequest(urlString) { final ZLNetworkRequest request = new ZLNetworkRequest.Get(urlString) {
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
final int updateIntervalMillis = 1000; // FIXME: remove hardcoded time constant final int updateIntervalMillis = 1000; // FIXME: remove hardcoded time constant

View file

@ -105,10 +105,10 @@ public class SynchroniserService extends Service implements IBookCollection.List
return writer.toString(); return writer.toString();
} }
private static abstract class Request extends ZLNetworkRequest { private static abstract class JsonRequest extends ZLNetworkRequest.PostWithBody {
private final static String BASE_URL = "https://demo.fbreader.org/app/"; private final static String BASE_URL = "https://demo.fbreader.org/app/";
Request(String app, Object data) { JsonRequest(String app, Object data) {
super(BASE_URL + app, toJSON(data), false); super(BASE_URL + app, toJSON(data), false);
} }
@ -133,7 +133,7 @@ public class SynchroniserService extends Service implements IBookCollection.List
return; return;
} }
System.err.println("SHA-1: " + uid.Id); System.err.println("SHA-1: " + uid.Id);
myNetworkContext.performQuietly(new Request("books.by.hash", Collections.singletonMap("sha1", uid.Id)) { myNetworkContext.performQuietly(new JsonRequest("books.by.hash", Collections.singletonMap("sha1", uid.Id)) {
public void processResponse(Object response) { public void processResponse(Object response) {
System.err.println("RESPONSE = " + response); System.err.println("RESPONSE = " + response);
} }

View file

@ -55,7 +55,7 @@ public class AllCatalogsSearchItem extends SearchItem {
} }
final NetworkOperationData data = link.createOperationData(loader); final NetworkOperationData data = link.createOperationData(loader);
final ZLNetworkRequest request = link.simpleSearchRequest(pattern, data); final ZLNetworkRequest request = link.simpleSearchRequest(pattern, data);
if (request != null && MimeType.APP_ATOM_XML.weakEquals(request.Mime)) { if (request != null) {
dataList.add(data); dataList.add(data);
requestList.add(request); requestList.add(request);
} }

View file

@ -38,7 +38,7 @@ public class SingleCatalogSearchItem extends SearchItem {
final NetworkOperationData data = Link.createOperationData(loader); final NetworkOperationData data = Link.createOperationData(loader);
ZLNetworkRequest request = Link.simpleSearchRequest(pattern, data); ZLNetworkRequest request = Link.simpleSearchRequest(pattern, data);
// TODO: possible infinite loop, use "continue link" instead // TODO: possible infinite loop, use "continue link" instead
while (request != null && MimeType.APP_ATOM_XML.weakEquals(request.Mime)) { while (request != null) {
nc.perform(request); nc.perform(request);
if (loader.confirmInterruption()) { if (loader.confirmInterruption()) {
return; return;

View file

@ -25,7 +25,7 @@ import java.io.InputStream;
import org.geometerplus.zlibrary.core.network.ZLNetworkException; import org.geometerplus.zlibrary.core.network.ZLNetworkException;
import org.geometerplus.zlibrary.core.network.ZLNetworkRequest; import org.geometerplus.zlibrary.core.network.ZLNetworkRequest;
public class LitResNetworkRequest extends ZLNetworkRequest { public class LitResNetworkRequest extends ZLNetworkRequest.PostWithMap {
public final LitResAuthenticationXMLReader Reader; public final LitResAuthenticationXMLReader Reader;
static String clean(String url) { static String clean(String url) {

View file

@ -58,6 +58,6 @@ class OPDSBasketItem extends BasketItem {
url = url.replace("{ids}", MiscUtil.join(ids, ",")); url = url.replace("{ids}", MiscUtil.join(ids, ","));
final OPDSCatalogItem.State state = opdsLink.createOperationData(loader); final OPDSCatalogItem.State state = opdsLink.createOperationData(loader);
doLoadChildren(state, opdsLink.createNetworkData(url, MimeType.APP_ATOM_XML, state)); doLoadChildren(state, opdsLink.createNetworkData(url, state));
} }
} }

View file

@ -40,7 +40,7 @@ public class OPDSBookItem extends NetworkBookItem implements OPDSConstants {
final CreateBookHandler handler = new CreateBookHandler(link, url); final CreateBookHandler handler = new CreateBookHandler(link, url);
try { try {
nc.perform(new ZLNetworkRequest(url) { nc.perform(new ZLNetworkRequest.Get(url) {
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OPDSXMLReader(handler, true).read(inputStream); new OPDSXMLReader(handler, true).read(inputStream);
@ -263,7 +263,7 @@ public class OPDSBookItem extends NetworkBookItem implements OPDSConstants {
return true; return true;
} }
return nc.performQuietly(new ZLNetworkRequest(url) { return nc.performQuietly(new ZLNetworkRequest.Get(url) {
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OPDSXMLReader(new LoadInfoHandler(url), true).read(inputStream); new OPDSXMLReader(new LoadInfoHandler(url), true).read(inputStream);

View file

@ -81,7 +81,7 @@ public class OPDSCatalogItem extends NetworkURLCatalogItem {
myLoadingState = opdsLink.createOperationData(loader); myLoadingState = opdsLink.createOperationData(loader);
doLoadChildren( doLoadChildren(
opdsLink.createNetworkData(getCatalogUrl(), MimeType.APP_ATOM_XML, myLoadingState) opdsLink.createNetworkData(getCatalogUrl(), myLoadingState)
); );
} }

View file

@ -107,7 +107,7 @@ public class OPDSCustomNetworkLink extends OPDSNetworkLink implements ICustomNet
ZLNetworkException error = null; ZLNetworkException error = null;
try { try {
nc.perform(new ZLNetworkRequest(getUrl(UrlInfo.Type.Catalog), quietly) { nc.perform(new ZLNetworkRequest.Get(getUrl(UrlInfo.Type.Catalog), quietly) {
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
final OPDSCatalogInfoHandler info = new OPDSCatalogInfoHandler(getURL(), OPDSCustomNetworkLink.this, opensearchDescriptionURLs); final OPDSCatalogInfoHandler info = new OPDSCatalogInfoHandler(getURL(), OPDSCustomNetworkLink.this, opensearchDescriptionURLs);
@ -136,7 +136,7 @@ public class OPDSCustomNetworkLink extends OPDSNetworkLink implements ICustomNet
if (!opensearchDescriptionURLs.isEmpty()) { if (!opensearchDescriptionURLs.isEmpty()) {
LinkedList<ZLNetworkRequest> requests = new LinkedList<ZLNetworkRequest>(); LinkedList<ZLNetworkRequest> requests = new LinkedList<ZLNetworkRequest>();
for (String url : opensearchDescriptionURLs) { for (String url : opensearchDescriptionURLs) {
requests.add(new ZLNetworkRequest(url, quietly) { requests.add(new ZLNetworkRequest.Get(url, quietly) {
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
new OpenSearchXMLReader(getURL(), descriptions).read(inputStream); new OpenSearchXMLReader(getURL(), descriptions).read(inputStream);

View file

@ -44,7 +44,7 @@ public class OPDSLinkReader {
final File dirFile = new File(Paths.networkCacheDirectory()); final File dirFile = new File(Paths.networkCacheDirectory());
if (!dirFile.exists() && !dirFile.mkdirs()) { if (!dirFile.exists() && !dirFile.mkdirs()) {
nc.perform(new ZLNetworkRequest(CATALOGS_URL) { nc.perform(new ZLNetworkRequest.Get(CATALOGS_URL) {
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
xmlReader.read(inputStream); xmlReader.read(inputStream);

View file

@ -82,7 +82,7 @@ public abstract class OPDSNetworkLink extends AbstractNetworkLink {
NotChecked NotChecked
*/ */
ZLNetworkRequest createNetworkData(String url, MimeType mime, final OPDSCatalogItem.State state) { ZLNetworkRequest createNetworkData(String url, final OPDSCatalogItem.State state) {
if (url == null) { if (url == null) {
return null; return null;
} }
@ -90,7 +90,7 @@ public abstract class OPDSNetworkLink extends AbstractNetworkLink {
final NetworkCatalogItem catalogItem = state.Loader.getTree().Item; final NetworkCatalogItem catalogItem = state.Loader.getTree().Item;
library.startLoading(catalogItem); library.startLoading(catalogItem);
url = rewriteUrl(url, false); url = rewriteUrl(url, false);
return new ZLNetworkRequest(url, mime, null, false) { return new ZLNetworkRequest.Get(url, false) {
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
if (state.Loader.confirmInterruption()) { if (state.Loader.confirmInterruption()) {
@ -123,18 +123,18 @@ public abstract class OPDSNetworkLink extends AbstractNetworkLink {
public ZLNetworkRequest simpleSearchRequest(String pattern, NetworkOperationData data) { public ZLNetworkRequest simpleSearchRequest(String pattern, NetworkOperationData data) {
final UrlInfo info = getUrlInfo(UrlInfo.Type.Search); final UrlInfo info = getUrlInfo(UrlInfo.Type.Search);
if (info == null || info.Url == null) { if (info == null || info.Url == null || !MimeType.APP_ATOM_XML.weakEquals(info.Mime)) {
return null; return null;
} }
try { try {
pattern = URLEncoder.encode(pattern, "utf-8"); pattern = URLEncoder.encode(pattern, "utf-8");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
} }
return createNetworkData(info.Url.replace("%s", pattern), info.Mime, (OPDSCatalogItem.State)data); return createNetworkData(info.Url.replace("%s", pattern), (OPDSCatalogItem.State)data);
} }
public ZLNetworkRequest resume(NetworkOperationData data) { public ZLNetworkRequest resume(NetworkOperationData data) {
return createNetworkData(data.ResumeURI, MimeType.APP_ATOM_XML, (OPDSCatalogItem.State)data); return createNetworkData(data.ResumeURI, (OPDSCatalogItem.State)data);
} }
public NetworkCatalogItem libraryItem() { public NetworkCatalogItem libraryItem() {

View file

@ -52,7 +52,7 @@ public class RSSCatalogItem extends NetworkURLCatalogItem {
final RSSNetworkLink rssLink = (RSSNetworkLink)Link; final RSSNetworkLink rssLink = (RSSNetworkLink)Link;
myLoadingState = rssLink.createOperationData(loader); myLoadingState = rssLink.createOperationData(loader);
doLoadChildren(rssLink.createNetworkData(getCatalogUrl(), MimeType.APP_RSS_XML, myLoadingState)); doLoadChildren(rssLink.createNetworkData(getCatalogUrl(), myLoadingState));
} }
private void doLoadChildren(ZLNetworkRequest networkRequest) throws ZLNetworkException { private void doLoadChildren(ZLNetworkRequest networkRequest) throws ZLNetworkException {

View file

@ -46,7 +46,7 @@ public class RSSNetworkLink extends AbstractNetworkLink implements IPredefinedNe
myPredefinedId = predefinedId; myPredefinedId = predefinedId;
} }
ZLNetworkRequest createNetworkData(String url, MimeType mime, final RSSCatalogItem.State result) { ZLNetworkRequest createNetworkData(String url, final RSSCatalogItem.State result) {
if (url == null) { if (url == null) {
return null; return null;
} }
@ -55,7 +55,7 @@ public class RSSNetworkLink extends AbstractNetworkLink implements IPredefinedNe
final NetworkCatalogItem catalogItem = result.Loader.getTree().Item; final NetworkCatalogItem catalogItem = result.Loader.getTree().Item;
library.startLoading(catalogItem); library.startLoading(catalogItem);
return new ZLNetworkRequest(url, mime, null, false) { return new ZLNetworkRequest.Get(url, false) {
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
@Override @Override
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
@ -100,8 +100,7 @@ public class RSSNetworkLink extends AbstractNetworkLink implements IPredefinedNe
} }
@Override @Override
public ZLNetworkRequest simpleSearchRequest(String pattern, public ZLNetworkRequest simpleSearchRequest(String pattern, NetworkOperationData data) {
NetworkOperationData data) {
return null; return null;
} }

View file

@ -84,7 +84,7 @@ public abstract class ZLNetworkContext implements ZLNetworkManager.BearerAuthent
} }
private final void downloadToFile(String url, final File outFile, final int bufferSize) throws ZLNetworkException { private final void downloadToFile(String url, final File outFile, final int bufferSize) throws ZLNetworkException {
myManager.perform(new ZLNetworkRequest(url) { myManager.perform(new ZLNetworkRequest.Get(url) {
public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException { public void handleStream(InputStream inputStream, int length) throws IOException, ZLNetworkException {
OutputStream outStream = new FileOutputStream(outFile); OutputStream outStream = new FileOutputStream(outFile);
try { try {

View file

@ -33,15 +33,19 @@ import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.*; import org.apache.http.impl.client.*;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.*; import org.apache.http.params.*;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.options.ZLStringOption;
import org.geometerplus.zlibrary.core.util.MiscUtil; import org.geometerplus.zlibrary.core.util.MiscUtil;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil; import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.options.ZLStringOption;
public class ZLNetworkManager { public class ZLNetworkManager {
private static ZLNetworkManager ourManager; private static ZLNetworkManager ourManager;
@ -320,29 +324,35 @@ public class ZLNetworkManager {
} }
}; };
final HttpRequestBase httpRequest; final HttpRequestBase httpRequest;
if (request.PostData != null) { if (request instanceof ZLNetworkRequest.Get) {
httpRequest = new HttpGet(request.URL);
} else if (request instanceof ZLNetworkRequest.PostWithBody) {
httpRequest = new HttpPost(request.URL); httpRequest = new HttpPost(request.URL);
((HttpPost)httpRequest).setEntity(new StringEntity(request.PostData, "utf-8")); ((HttpPost)httpRequest).setEntity(new StringEntity(((ZLNetworkRequest.PostWithBody)request).Body, "utf-8"));
/* /*
httpConnection.setRequestProperty( httpConnection.setRequestProperty(
"Content-Length", "Content-Length",
Integer.toString(request.PostData.getBytes().length) Integer.toString(request.Body.getBytes().length)
);
httpConnection.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded"
); );
*/ */
} else if (!request.PostParameters.isEmpty()) { } else if (request instanceof ZLNetworkRequest.PostWithMap) {
final Map<String,String> parameters =
((ZLNetworkRequest.PostWithMap)request).PostParameters;
httpRequest = new HttpPost(request.URL); httpRequest = new HttpPost(request.URL);
final List<BasicNameValuePair> list = final List<BasicNameValuePair> list =
new ArrayList<BasicNameValuePair>(request.PostParameters.size()); new ArrayList<BasicNameValuePair>(parameters.size());
for (Map.Entry<String,String> entry : request.PostParameters.entrySet()) { for (Map.Entry<String,String> entry : parameters.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
} }
((HttpPost)httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8")); ((HttpPost)httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8"));
} else if (request instanceof ZLNetworkRequest.FileUpload) {
final ZLFile file = ((ZLNetworkRequest.FileUpload)request).File;
httpRequest = new HttpPost(request.URL);
final MultipartEntity data = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
data.addPart("file", new InputStreamBody(file.getInputStream(), file.getPath()));
((HttpPost)httpRequest).setEntity(data);
} else { } else {
httpRequest = new HttpGet(request.URL); throw new ZLNetworkException(true, "Unknown request type");
} }
httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent()); httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent());
if (!request.isQuiet()) { if (!request.isQuiet()) {

View file

@ -24,40 +24,67 @@ import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import org.geometerplus.zlibrary.core.util.MimeType; import org.geometerplus.zlibrary.core.filesystem.ZLFile;
public abstract class ZLNetworkRequest { public abstract class ZLNetworkRequest {
public static abstract class Get extends ZLNetworkRequest {
protected Get(String url) {
this(url, false);
}
protected Get(String url, boolean quiet) {
super(url, quiet);
}
}
public static abstract class PostWithMap extends ZLNetworkRequest {
public final Map<String,String> PostParameters = new HashMap<String,String>();
protected PostWithMap(String url) {
this(url, false);
}
protected PostWithMap(String url, boolean quiet) {
super(url, quiet);
}
public void addPostParameter(String name, String value) {
PostParameters.put(name, value);
}
}
public static abstract class PostWithBody extends ZLNetworkRequest {
public final String Body;
protected PostWithBody(String url, String body, boolean quiet) {
super(url, quiet);
Body = body;
}
}
public static abstract class FileUpload extends ZLNetworkRequest {
public final ZLFile File;
protected FileUpload(String url, ZLFile file, boolean quiet) {
super(url, quiet);
File = file;
}
}
String URL; String URL;
public final String PostData;
public final Map<String,String> PostParameters = new HashMap<String,String>();
public final MimeType Mime;
public final Map<String,String> Headers = new HashMap<String,String>(); public final Map<String,String> Headers = new HashMap<String,String>();
private final boolean myIsQuiet; private final boolean myIsQuiet;
protected ZLNetworkRequest(String url) { private ZLNetworkRequest(String url) {
this(url, false); this(url, false);
} }
protected ZLNetworkRequest(String url, boolean quiet) { private ZLNetworkRequest(String url, boolean quiet) {
this(url, null, quiet);
}
protected ZLNetworkRequest(String url, String postData, boolean quiet) {
this(url, MimeType.NULL, postData, quiet);
}
protected ZLNetworkRequest(String url, MimeType mime, String postData, boolean quiet) {
URL = url; URL = url;
Mime = mime;
PostData = postData;
myIsQuiet = quiet; myIsQuiet = quiet;
} }
public void addPostParameter(String name, String value) {
PostParameters.put(name, value);
}
public void addHeader(String name, String value) { public void addHeader(String name, String value) {
Headers.put(name, value); Headers.put(name, value);
} }