-
-
Notifications
You must be signed in to change notification settings - Fork 392
/
Connection.java
294 lines (260 loc) · 8.71 KB
/
Connection.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
/*
* Copyright (c) 2010-2020 Mark Allen, Norbert Bartels.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.restfb;
import static com.restfb.util.StringUtils.isBlank;
import static java.util.Collections.unmodifiableList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collectors;
import com.restfb.exception.FacebookJsonMappingException;
import com.restfb.json.Json;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonObject;
import com.restfb.json.ParseException;
import com.restfb.util.ReflectionUtils;
/**
* Represents a <a href="http://developers.facebook.com/docs/api">Graph API Connection type</a>.
*
* @param <T>
* The Facebook type
* @author <a href="http://restfb.com">Mark Allen</a>
*/
public class Connection<T> implements Iterable<List<T>> {
private FacebookClient facebookClient;
private Class<T> connectionType;
private List<T> data;
private String previousPageUrl;
private String nextPageUrl;
private Long totalCount;
private String beforeCursor;
private String afterCursor;
private String order;
/**
* @see java.lang.Iterable#iterator()
* @since 1.6.7
*/
@Override
public ConnectionIterator<T> iterator() {
return new Itr<>(this);
}
/**
* Iterator over connection pages.
*
* @author <a href="http://restfb.com">Mark Allen</a>
* @since 1.6.7
*/
protected static class Itr<T> implements ConnectionIterator<T> {
private Connection<T> connection;
private boolean initialPage = true;
/**
* Creates a new iterator over the given {@code connection}.
*
* @param connection
* The connection over which to iterate.
*/
protected Itr(Connection<T> connection) {
this.connection = connection;
}
/**
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
// Special case: initial page will always have data
return initialPage || connection.hasNext();
}
/**
* @see java.util.Iterator#next()
*/
@Override
public List<T> next() {
// Special case: initial page will always have data, return it
// immediately.
if (initialPage) {
initialPage = false;
return connection.getData();
}
if (!connection.hasNext()) {
throw new NoSuchElementException("There are no more pages in the connection.");
}
connection = connection.fetchNextPage();
return connection.getData();
}
/**
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException(Itr.class.getSimpleName() + " doesn't support the remove() operation.");
}
/**
* @see ConnectionIterator#snapshot()
*/
@Override
public Connection<T> snapshot() {
return connection;
}
}
/**
* Creates a connection with the given {@code jsonObject}.
*
* @param facebookClient
* The {@code FacebookClient} used to fetch additional pages and map data to JSON objects.
* @param json
* Raw JSON which must include a {@code data} field that holds a JSON array and optionally a {@code paging}
* field that holds a JSON object with next/previous page URLs.
* @param connectionType
* Connection type token.
* @throws FacebookJsonMappingException
* If the provided {@code json} is invalid.
* @since 1.6.7
*/
@SuppressWarnings("unchecked")
public Connection(FacebookClient facebookClient, String json, Class<T> connectionType) {
JsonObject jsonObject;
try {
jsonObject = Optional.ofNullable(json).map(j -> Json.parse(j).asObject()).orElseThrow(() -> new FacebookJsonMappingException("You must supply non-null connection JSON."));
} catch (ParseException e) {
throw new FacebookJsonMappingException("The connection JSON you provided was invalid: " + json, e);
}
// Pull out data
JsonArray jsonData = jsonObject.get("data").asArray();
List<T> dataItem = jsonData.valueStream().map(jsonValue -> connectionType.equals(JsonObject.class) ? (T) jsonValue
: facebookClient.getJsonMapper().toJavaObject(jsonValue.toString(), connectionType)).collect(Collectors.toList());
// Pull out paging info, if present
if (jsonObject.contains("paging")) {
JsonObject jsonPaging = jsonObject.get("paging").asObject();
previousPageUrl = fixProtocol(jsonPaging.getString("previous", null));
nextPageUrl = fixProtocol(jsonPaging.getString("next", null));
// handle cursors
if (jsonPaging.contains("cursors")) {
JsonObject jsonCursors = jsonPaging.get("cursors").asObject();
beforeCursor = jsonCursors.getString("before", null);
afterCursor = jsonCursors.getString("after", null);
}
} else {
previousPageUrl = null;
nextPageUrl = null;
}
if (jsonObject.contains("summary")) {
JsonObject jsonSummary = jsonObject.get("summary").asObject();
totalCount = jsonSummary.contains("total_count") ? jsonSummary.getLong("total_count", 0L) : null;
order = jsonSummary.getString("order","");
} else {
totalCount = null;
order = null;
}
this.data = unmodifiableList(dataItem);
this.facebookClient = facebookClient;
this.connectionType = connectionType;
}
/**
* Fetches the next page of the connection. Designed to be used by {@link Itr}.
*
* @return The next page of the connection.
* @since 1.6.7
*/
protected Connection<T> fetchNextPage() {
return facebookClient.fetchConnectionPage(getNextPageUrl(), connectionType);
}
@Override
public String toString() {
return ReflectionUtils.toString(this);
}
@Override
public boolean equals(Object object) {
return ReflectionUtils.equals(this, object);
}
@Override
public int hashCode() {
return ReflectionUtils.hashCode(this);
}
/**
* Data for this connection.
*
* @return Data for this connection.
*/
public List<T> getData() {
return data;
}
/**
* This connection's "previous page of data" URL.
*
* @return This connection's "previous page of data" URL, or {@code null} if there is no previous page.
* @since 1.5.3
*/
public String getPreviousPageUrl() {
return previousPageUrl;
}
/**
* This connection's "next page of data" URL.
*
* @return This connection's "next page of data" URL, or {@code null} if there is no next page.
* @since 1.5.3
*/
public String getNextPageUrl() {
return nextPageUrl;
}
/**
* Does this connection have a previous page of data?
*
* @return {@code true} if there is a previous page of data for this connection, {@code false} otherwise.
*/
public boolean hasPrevious() {
return !isBlank(getPreviousPageUrl());
}
/**
* Does this connection have a next page of data?
*
* @return {@code true} if there is a next page of data for this connection, {@code false} otherwise.
*/
public boolean hasNext() {
return !isBlank(getNextPageUrl()) && !getData().isEmpty();
}
/**
* provides the total count of elements, if FB provides them (API ≥ v2.0)
*
* @return the total count of elements if present
* @since 1.6.16
*/
public Long getTotalCount() {
return totalCount;
}
/**
* returns the order of the elements
*
* @return the order of the elements
*/
public String getOrder() {
return order;
}
public String getBeforeCursor() {
return beforeCursor;
}
public String getAfterCursor() {
return afterCursor;
}
private String fixProtocol(String pageUrl) {
return Optional.ofNullable(pageUrl).filter(s -> s.startsWith("http://")).map(s -> s.replaceFirst("http://", "https://")).orElse(pageUrl);
}
}