This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
/
TDChangeTracker.java
316 lines (279 loc) · 11.4 KB
/
TDChangeTracker.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package com.couchbase.touchdb.replicator.changetracker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.couchbase.touchdb.TDDatabase;
import com.couchbase.touchdb.TDServer;
/**
* Reads the continuous-mode _changes feed of a database, and sends the
* individual change entries to its client's changeTrackerReceivedChange()
*/
public class TDChangeTracker implements Runnable {
private URL databaseURL;
private TDChangeTrackerClient client;
private TDChangeTrackerMode mode;
private Object lastSequenceID;
private Thread thread;
private boolean running = false;
private HttpUriRequest request;
private String filterName;
private Map<String, Object> filterParams;
private Throwable error;
public enum TDChangeTrackerMode {
OneShot, LongPoll, Continuous
}
public TDChangeTracker(URL databaseURL, TDChangeTrackerMode mode,
Object lastSequenceID, TDChangeTrackerClient client) {
this.databaseURL = databaseURL;
this.mode = mode;
this.lastSequenceID = lastSequenceID;
this.client = client;
}
public void setFilterName(String filterName) {
this.filterName = filterName;
}
public void setFilterParams(Map<String, Object> filterParams) {
this.filterParams = filterParams;
}
public void setClient(TDChangeTrackerClient client) {
this.client = client;
}
public String getDatabaseName() {
String result = null;
if (databaseURL != null) {
result = databaseURL.getPath();
if (result != null) {
int pathLastSlashPos = result.lastIndexOf('/');
if (pathLastSlashPos > 0) {
result = result.substring(pathLastSlashPos);
}
}
}
return result;
}
public String getChangesFeedPath() {
String path = "_changes?feed=";
switch (mode) {
case OneShot:
path += "normal";
break;
case LongPoll:
path += "longpoll&limit=50";
break;
case Continuous:
path += "continuous";
break;
}
path += "&heartbeat=300000";
if(lastSequenceID != null) {
path += "&since=" + URLEncoder.encode(lastSequenceID.toString());
}
if(filterName != null) {
path += "&filter=" + URLEncoder.encode(filterName);
if(filterParams != null) {
for (String filterParamKey : filterParams.keySet()) {
path += "&" + URLEncoder.encode(filterParamKey) + "=" + URLEncoder.encode(filterParams.get(filterParamKey).toString());
}
}
}
return path;
}
public URL getChangesFeedURL() {
String dbURLString = databaseURL.toExternalForm();
if(!dbURLString.endsWith("/")) {
dbURLString += "/";
}
dbURLString += getChangesFeedPath();
URL result = null;
try {
result = new URL(dbURLString);
} catch(MalformedURLException e) {
Log.e(TDDatabase.TAG, "Changes feed ULR is malformed", e);
}
return result;
}
@Override
public void run() {
running = true;
HttpClient httpClient = client.getHttpClient();
while (running) {
URL url = getChangesFeedURL();
request = new HttpGet(url.toString());
// if the URL contains user info AND if this a DefaultHttpClient
// then preemptively set the auth credentials
if(url.getUserInfo() != null) {
if(url.getUserInfo().contains(":")) {
String[] userInfoSplit = url.getUserInfo().split(":");
final Credentials creds = new UsernamePasswordCredentials(userInfoSplit[0], userInfoSplit[1]);
if(httpClient instanceof DefaultHttpClient) {
DefaultHttpClient dhc = (DefaultHttpClient)httpClient;
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request,
HttpContext context) throws HttpException,
IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
};
dhc.addRequestInterceptor(preemptiveAuth, 0);
}
}
else {
Log.w(TDDatabase.TAG, "Unable to parse user info, not setting credentials");
}
}
try {
String maskedRemoteWithoutCredentials = getChangesFeedURL().toString();
maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll("://.*:.*@","://---:---@");
Log.v(TDDatabase.TAG, "Making request to " + maskedRemoteWithoutCredentials);
HttpResponse response = httpClient.execute(request);
StatusLine status = response.getStatusLine();
if(status.getStatusCode() >= 300) {
Log.e(TDDatabase.TAG, "Change tracker got error " + Integer.toString(status.getStatusCode()));
stop();
}
HttpEntity entity = response.getEntity();
if(entity != null) {
try {
InputStream input = entity.getContent();
if(mode != TDChangeTrackerMode.Continuous) {
Map<String,Object> fullBody = TDServer.getObjectMapper().readValue(input, Map.class);
boolean responseOK = receivedPollResponse(fullBody);
if(mode == TDChangeTrackerMode.LongPoll && responseOK) {
Log.v(TDDatabase.TAG, "Starting new longpoll");
continue;
} else {
Log.w(TDDatabase.TAG, "Change tracker calling stop");
stop();
}
}
else {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = null;
while ((line=reader.readLine()) != null) {
receivedChunk(line);
}
}
} finally {
try { entity.consumeContent(); } catch (IOException e){}
}
}
} catch (ClientProtocolException e) {
Log.e(TDDatabase.TAG, "ClientProtocolException in change tracker", e);
} catch (IOException e) {
if(running) {
//we get an exception when we're shutting down and have to
//close the socket underneath our read, ignore that
Log.e(TDDatabase.TAG, "IOException in change tracker", e);
}
}
}
Log.v(TDDatabase.TAG, "Change tracker run loop exiting");
}
public boolean receivedChunk(String line) {
if(line.length() > 1) {
try {
Map<String,Object> change = (Map)TDServer.getObjectMapper().readValue(line, Map.class);
if(!receivedChange(change)) {
Log.w(TDDatabase.TAG, String.format("Received unparseable change line from server: %s", line));
return false;
}
} catch (Exception e) {
Log.w(TDDatabase.TAG, "Exception parsing JSON in change tracker", e);
return false;
}
}
return true;
}
public boolean receivedChange(final Map<String,Object> change) {
Object seq = change.get("seq");
if(seq == null) {
return false;
}
//pass the change to the client on the thread that created this change tracker
if(client != null) {
client.changeTrackerReceivedChange(change);
}
lastSequenceID = seq;
return true;
}
public boolean receivedPollResponse(Map<String,Object> response) {
List<Map<String,Object>> changes = (List)response.get("results");
if(changes == null) {
return false;
}
for (Map<String,Object> change : changes) {
if(!receivedChange(change)) {
return false;
}
}
return true;
}
public void setUpstreamError(String message) {
Log.w(TDDatabase.TAG, String.format("Server error: %s", message));
this.error = new Throwable(message);
}
public boolean start() {
this.error = null;
thread = new Thread(this, "ChangeTracker-" + databaseURL.toExternalForm());
thread.start();
return true;
}
public void stop() {
Log.d(TDDatabase.TAG, "changed tracker asked to stop");
running = false;
thread.interrupt();
if(request != null) {
request.abort();
}
stopped();
}
public void stopped() {
Log.d(TDDatabase.TAG, "change tracker in stopped");
if (client != null) {
Log.d(TDDatabase.TAG, "posting stopped");
client.changeTrackerStopped(TDChangeTracker.this);
}
client = null;
Log.d(TDDatabase.TAG, "change tracker client should be null now");
}
public boolean isRunning() {
return running;
}
}