1
|
/**
|
2
|
* log.debug(...) equal to log.trace(...) in the application-logs
|
3
|
* <p>
|
4
|
* known bug: at resumptionType 'discover' if the (resultTotal % resultSizeValue) == 0 the collecting fails -> change the resultSizeValue
|
5
|
*/
|
6
|
package eu.dnetlib.data.collector.plugins.rest;
|
7
|
|
8
|
import java.io.InputStream;
|
9
|
import java.io.StringWriter;
|
10
|
import java.io.UnsupportedEncodingException;
|
11
|
import java.net.URL;
|
12
|
import java.net.URLEncoder;
|
13
|
import java.nio.charset.StandardCharsets;
|
14
|
import java.net.HttpURLConnection;
|
15
|
import java.util.Iterator;
|
16
|
import java.util.Map;
|
17
|
import java.util.Queue;
|
18
|
import java.util.concurrent.PriorityBlockingQueue;
|
19
|
import java.util.regex.Pattern;
|
20
|
import java.util.regex.Matcher;
|
21
|
import javax.xml.transform.OutputKeys;
|
22
|
import javax.xml.transform.Transformer;
|
23
|
import javax.xml.transform.TransformerConfigurationException;
|
24
|
import javax.xml.transform.TransformerFactory;
|
25
|
import javax.xml.transform.dom.DOMSource;
|
26
|
import javax.xml.transform.stream.StreamResult;
|
27
|
import javax.xml.xpath.*;
|
28
|
|
29
|
import com.google.common.collect.Maps;
|
30
|
import eu.dnetlib.data.collector.plugins.utils.JsonUtils;
|
31
|
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
|
32
|
import org.apache.commons.io.IOUtils;
|
33
|
import org.apache.commons.lang3.StringUtils;
|
34
|
import org.apache.commons.logging.Log;
|
35
|
import org.apache.commons.logging.LogFactory;
|
36
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
37
|
import org.apache.http.client.methods.HttpGet;
|
38
|
import org.apache.http.impl.client.HttpClients;
|
39
|
import org.w3c.dom.Node;
|
40
|
import org.w3c.dom.NodeList;
|
41
|
import org.xml.sax.InputSource;
|
42
|
|
43
|
/**
|
44
|
* @author Jochen Schirrwagen, Aenne Loehden, Andreas Czerniak, Alessia Bardi, Miriam Baglioni
|
45
|
* @date 2020-04-09
|
46
|
*/
|
47
|
public class RestIterator implements Iterator<String> {
|
48
|
private final String AUTHBASIC = "basic";
|
49
|
|
50
|
// TODO: clean up the comments of replaced source code
|
51
|
private static final Log log = LogFactory.getLog(RestIterator.class); // NOPMD by marko on 11/24/08 5:02 PM
|
52
|
private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
|
53
|
private static final String EMPTY_XML = XML_HEADER + JsonUtils.wrapName + "></" + JsonUtils.wrapName + ">";
|
54
|
private JsonUtils jsonUtils;
|
55
|
|
56
|
private String baseUrl;
|
57
|
private String resumptionType;
|
58
|
private String resumptionParam;
|
59
|
private String resultFormatValue;
|
60
|
private String queryParams = "";
|
61
|
private int resultSizeValue;
|
62
|
private int resumptionInt = 0; // integer resumption token (first record to harvest)
|
63
|
private int resultTotal = -1;
|
64
|
private String resumptionStr = Integer.toString(resumptionInt); // string resumption token (first record to harvest or token scanned from results)
|
65
|
private InputStream resultStream;
|
66
|
private Transformer transformer;
|
67
|
private XPath xpath;
|
68
|
private String query;
|
69
|
private XPathExpression xprResultTotalPath;
|
70
|
private XPathExpression xprResumptionPath;
|
71
|
private XPathExpression xprEntity;
|
72
|
private String queryFormat;
|
73
|
private String querySize;
|
74
|
private String authMethod;
|
75
|
private String authToken;
|
76
|
private Queue<String> recordQueue = new PriorityBlockingQueue<String>();
|
77
|
private int discoverResultSize = 0;
|
78
|
private int pagination = 1;
|
79
|
/*
|
80
|
While resultFormatValue is added to the request parameter, this is used to say that the results are retrieved in json.
|
81
|
useful for cases when the target API expects a resultFormatValue != json, but the results are returned in json.
|
82
|
An example is the EU Open Data Portal API: resultFormatValue=standard, results are in json format.
|
83
|
*/
|
84
|
private String resultOutputFormat;
|
85
|
/*
|
86
|
Can be used to set additional request headers, like for content negotiation
|
87
|
*/
|
88
|
private Map<String, String> requestHeaders;
|
89
|
|
90
|
|
91
|
public RestIterator(
|
92
|
final String baseUrl,
|
93
|
final String resumptionType,
|
94
|
final String resumptionParam,
|
95
|
final String resumptionXpath,
|
96
|
final String resultTotalXpath,
|
97
|
final String resultFormatParam,
|
98
|
final String resultFormatValue,
|
99
|
final String resultSizeParam,
|
100
|
final String resultSizeValueStr,
|
101
|
final String queryParams,
|
102
|
final String entityXpath,
|
103
|
final String authMethod,
|
104
|
final String authToken,
|
105
|
final String resultOutputFormat,
|
106
|
final Map<String, String> requestHeaders
|
107
|
) {
|
108
|
this.jsonUtils = new JsonUtils();
|
109
|
this.baseUrl = baseUrl;
|
110
|
this.resumptionType = resumptionType;
|
111
|
this.resumptionParam = resumptionParam;
|
112
|
this.resultFormatValue = resultFormatValue;
|
113
|
this.queryParams = queryParams;
|
114
|
this.resultSizeValue = Integer.valueOf(resultSizeValueStr);
|
115
|
this.authMethod = authMethod;
|
116
|
this.authToken = authToken;
|
117
|
this.resultOutputFormat = resultOutputFormat;
|
118
|
this.requestHeaders = requestHeaders != null ? requestHeaders : Maps.newHashMap();
|
119
|
|
120
|
queryFormat = StringUtils.isNotBlank(resultFormatParam) ? "&" + resultFormatParam + "=" + resultFormatValue : "";
|
121
|
querySize = StringUtils.isNotBlank(resultSizeParam) ? "&" + resultSizeParam + "=" + resultSizeValueStr : "";
|
122
|
|
123
|
try {
|
124
|
initXmlTransformation(resultTotalXpath, resumptionXpath, entityXpath);
|
125
|
} catch (Exception e) {
|
126
|
throw new IllegalStateException("xml transformation init failed: " + e.getMessage());
|
127
|
}
|
128
|
initQueue();
|
129
|
}
|
130
|
|
131
|
|
132
|
private void initXmlTransformation(String resultTotalXpath, String resumptionXpath, String entityXpath)
|
133
|
throws TransformerConfigurationException, XPathExpressionException {
|
134
|
transformer = TransformerFactory.newInstance().newTransformer();
|
135
|
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
136
|
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
|
137
|
xpath = XPathFactory.newInstance().newXPath();
|
138
|
xprResultTotalPath = xpath.compile(resultTotalXpath);
|
139
|
xprResumptionPath = xpath.compile(StringUtils.isBlank(resumptionXpath) ? "/" : resumptionXpath);
|
140
|
xprEntity = xpath.compile(entityXpath);
|
141
|
}
|
142
|
|
143
|
private void initQueue() {
|
144
|
if (queryParams.equals("") && querySize.equals("") && queryFormat.equals("")) {
|
145
|
query = baseUrl;
|
146
|
} else {
|
147
|
query = baseUrl + "?" + queryParams + querySize + queryFormat;
|
148
|
}
|
149
|
|
150
|
log.info("RestIterator.initQueue():: REST calls starting with " + query);
|
151
|
}
|
152
|
|
153
|
private void disconnect() {
|
154
|
// TODO close inputstream
|
155
|
}
|
156
|
|
157
|
/* (non-Javadoc)
|
158
|
* @see java.util.Iterator#hasNext()
|
159
|
*/
|
160
|
@Override
|
161
|
public boolean hasNext() {
|
162
|
if (recordQueue.isEmpty() && query.isEmpty()) {
|
163
|
disconnect();
|
164
|
return false;
|
165
|
} else {
|
166
|
return true;
|
167
|
}
|
168
|
}
|
169
|
|
170
|
/* (non-Javadoc)
|
171
|
* @see java.util.Iterator#next()
|
172
|
*/
|
173
|
@Override
|
174
|
public String next() {
|
175
|
synchronized (recordQueue) {
|
176
|
while (recordQueue.isEmpty() && !query.isEmpty()) {
|
177
|
try {
|
178
|
log.debug("RestIterator.next():: get Query: " + query);
|
179
|
query = downloadPage(query);
|
180
|
log.debug("RestIterator.next():: next queryURL from downloadPage(): " + query);
|
181
|
} catch (CollectorServiceException e) {
|
182
|
log.debug("RestIterator.next():: CollectorPlugin.next()-Exception: " + e);
|
183
|
throw new RuntimeException(e);
|
184
|
}
|
185
|
}
|
186
|
return recordQueue.poll();
|
187
|
}
|
188
|
}
|
189
|
|
190
|
/*
|
191
|
* download page and return nextQuery
|
192
|
*/
|
193
|
private String downloadPage(String query) throws CollectorServiceException {
|
194
|
String resultJson;
|
195
|
String resultXml = XML_HEADER;
|
196
|
String nextQuery = "";
|
197
|
Node resultNode = null;
|
198
|
NodeList nodeList = null;
|
199
|
String qUrlArgument = "";
|
200
|
int urlOldResumptionSize = 0;
|
201
|
InputStream theHttpInputStream;
|
202
|
|
203
|
// modifying request URL
|
204
|
// check if cursor=* is initial set otherwise add it to the queryParam URL
|
205
|
if (resumptionType.equalsIgnoreCase("deep-cursor")) {
|
206
|
log.debug("RestIterator.downloadPage():: check resumptionType deep-cursor and check cursor=*?" + query);
|
207
|
if (!query.contains("&cursor=")) {
|
208
|
query += "&cursor=*";
|
209
|
}
|
210
|
}
|
211
|
// find pagination page start number in queryParam and remove before start the first query
|
212
|
if((resumptionType.toLowerCase().equals("pagination")) && (query.contains("paginationStart="))) {
|
213
|
|
214
|
final Matcher m = Pattern.compile("paginationStart=([0-9]+)").matcher(query);
|
215
|
m.find(); // guaranteed to be true for this regex
|
216
|
|
217
|
String[] pageVal = m.group(0).split("=");
|
218
|
pagination = Integer.parseInt(pageVal[1]);
|
219
|
|
220
|
// remove page start number from queryParams
|
221
|
query = query.replaceFirst("&?paginationStart=[0-9]+", "");
|
222
|
|
223
|
}
|
224
|
|
225
|
|
226
|
try {
|
227
|
|
228
|
URL qUrl = new URL(query);
|
229
|
log.debug("authMethod :" + authMethod);
|
230
|
if (this.authMethod == "bearer") {
|
231
|
log.trace("RestIterator.downloadPage():: authMethod before inputStream: " + resultXml);
|
232
|
requestHeaders.put("Authorization", "Bearer " + authToken);
|
233
|
//requestHeaders.put("Content-Type", "application/json");
|
234
|
} else if (AUTHBASIC.equalsIgnoreCase(this.authMethod)) {
|
235
|
log.trace("RestIterator.downloadPage():: authMethod before inputStream: " + resultXml);
|
236
|
requestHeaders.put("Authorization", "Basic " + authToken);
|
237
|
//requestHeaders.put("accept", "application/xml");
|
238
|
}
|
239
|
|
240
|
HttpURLConnection conn = (HttpURLConnection) qUrl.openConnection();
|
241
|
conn.setRequestMethod("GET");
|
242
|
this.setRequestHeader(conn);
|
243
|
resultStream = conn.getInputStream();
|
244
|
|
245
|
if ("json".equals(resultOutputFormat)) {
|
246
|
resultJson = IOUtils.toString(resultStream, "UTF-8");
|
247
|
resultXml = jsonUtils.convertToXML(resultJson);
|
248
|
resultStream = IOUtils.toInputStream(resultXml, "UTF-8");
|
249
|
}
|
250
|
|
251
|
if (!isEmptyXml(resultXml)) {
|
252
|
resultNode = (Node) xpath.evaluate("/", new InputSource(resultStream), XPathConstants.NODE);
|
253
|
nodeList = (NodeList) xprEntity.evaluate(resultNode, XPathConstants.NODESET);
|
254
|
log.debug("RestIterator.downloadPage():: nodeList.length=" + nodeList.getLength());
|
255
|
for (int i = 0; i < nodeList.getLength(); i++) {
|
256
|
StringWriter sw = new StringWriter();
|
257
|
transformer.transform(new DOMSource(nodeList.item(i)), new StreamResult(sw));
|
258
|
String toEnqueue = sw.toString();
|
259
|
if (toEnqueue == null || StringUtils.isBlank(toEnqueue) || isEmptyXml(toEnqueue)) {
|
260
|
log.warn("RestIterator.downloadPage():: The following record resulted in empty item for the feeding queue: " + resultXml);
|
261
|
} else {
|
262
|
recordQueue.add(sw.toString());
|
263
|
}
|
264
|
}
|
265
|
} else {
|
266
|
log.warn("resultXml is equal with emptyXml");
|
267
|
}
|
268
|
|
269
|
resumptionInt += resultSizeValue;
|
270
|
|
271
|
switch (resumptionType.toLowerCase()) {
|
272
|
case "scan": // read of resumptionToken , evaluate next results, e.g. OAI, iterate over items
|
273
|
resumptionStr = xprResumptionPath.evaluate(resultNode);
|
274
|
break;
|
275
|
|
276
|
case "count": // begin at one step for all records, iterate over items
|
277
|
resumptionStr = Integer.toString(resumptionInt);
|
278
|
break;
|
279
|
|
280
|
case "discover": // size of result items unknown, iterate over items (for openDOAR - 201808)
|
281
|
if (resultSizeValue < 2) {
|
282
|
log.debug("RestIterator.downloadPage().discover:: ode: discover, Param 'resultSizeValue' must greater then 1");
|
283
|
throw new CollectorServiceException("Mode: discover, Param 'resultSizeValue' must greater then 1");
|
284
|
}
|
285
|
log.debug("RestIterator.downloadPage().discover:: resumptionInt="+Integer.toString(resumptionInt)+"; ");
|
286
|
qUrlArgument = qUrl.getQuery();
|
287
|
|
288
|
if( qUrlArgument != null ) {
|
289
|
String[] arrayQUrlArgument = qUrlArgument.split("&");
|
290
|
|
291
|
// check if URL arguments given
|
292
|
if( arrayQUrlArgument != null ) {
|
293
|
for (String arrayUrlArgStr : arrayQUrlArgument) {
|
294
|
log.debug("RestIterator.downloadPage/discover:: "+arrayUrlArgStr);
|
295
|
if (arrayUrlArgStr.startsWith(resumptionParam)) {
|
296
|
String[] resumptionKeyValue = arrayUrlArgStr.split("=");
|
297
|
if (isInteger(resumptionKeyValue[1])) {
|
298
|
urlOldResumptionSize = Integer.parseInt(resumptionKeyValue[1]);
|
299
|
log.debug("RestIterator.downloadPage():discover:: OldResumptionSize from Url (int): " + urlOldResumptionSize);
|
300
|
} else {
|
301
|
log.debug("RestIterator.downloadPage().discover:: OldResumptionSize from Url (str): " + resumptionKeyValue[1]);
|
302
|
}
|
303
|
}
|
304
|
}
|
305
|
}
|
306
|
}
|
307
|
log.debug("RestIterator.downloadPage().discover:: nodeList.length=" + nodeList.getLength());
|
308
|
|
309
|
if (isEmptyXml(resultXml) || ((nodeList != null) && (nodeList.getLength() < resultSizeValue))
|
310
|
) {
|
311
|
// resumptionStr = "";
|
312
|
if (nodeList != null) {
|
313
|
discoverResultSize += nodeList.getLength();
|
314
|
}
|
315
|
resultTotal = discoverResultSize;
|
316
|
} else {
|
317
|
resumptionStr = Integer.toString(resumptionInt);
|
318
|
resultTotal = resumptionInt + 1;
|
319
|
if (nodeList != null) {
|
320
|
discoverResultSize += nodeList.getLength();
|
321
|
}
|
322
|
}
|
323
|
log.debug("RestIterator.downloadPage().discover:: discoverResultSize=" + discoverResultSize);
|
324
|
break;
|
325
|
|
326
|
case "pagination":
|
327
|
case "page": // pagination, iterate over page numbers
|
328
|
// find start page number
|
329
|
pagination += 1;
|
330
|
if (nodeList != null) {
|
331
|
discoverResultSize += nodeList.getLength();
|
332
|
} else {
|
333
|
resultTotal = discoverResultSize;
|
334
|
pagination = discoverResultSize;
|
335
|
}
|
336
|
resumptionInt = pagination;
|
337
|
resumptionStr = Integer.toString(resumptionInt);
|
338
|
|
339
|
log.debug("RestIterator.downloadPage().pagination:: resumptionStr=" + resumptionStr + " ; queryParams=" + queryParams + " ; resultTotal: " + resultTotal + " ; discoverResultSize: " + discoverResultSize);
|
340
|
|
341
|
break;
|
342
|
|
343
|
case "deep-cursor": // size of result items unknown, iterate over items (for supporting deep cursor in solr)
|
344
|
// isn't relevant -- if (resultSizeValue < 2) {throw new CollectorServiceException("Mode: deep-cursor, Param 'resultSizeValue' is less than 2");}
|
345
|
|
346
|
resumptionStr = encodeValue(xprResumptionPath.evaluate(resultNode));
|
347
|
queryParams = queryParams.replace("&cursor=*", "");
|
348
|
|
349
|
// terminating if length of nodeList is 0
|
350
|
if ((nodeList != null) && (nodeList.getLength() < discoverResultSize)) {
|
351
|
resumptionInt += (nodeList.getLength() + 1 - resultSizeValue);
|
352
|
} else {
|
353
|
resumptionInt += (nodeList.getLength() - resultSizeValue); // subtract the resultSizeValue because the iteration is over real length and the resultSizeValue is added before the switch()
|
354
|
}
|
355
|
|
356
|
discoverResultSize = nodeList.getLength();
|
357
|
|
358
|
log.debug("RestIterator.downloadPage().deep-cursor:: resumptionStr=" + resumptionStr + " ; queryParams=" + queryParams + " resumptionLengthIncreased: " + resumptionInt);
|
359
|
|
360
|
break;
|
361
|
|
362
|
default: // otherwise: abort
|
363
|
// resultTotal = resumptionInt;
|
364
|
break;
|
365
|
}
|
366
|
|
367
|
} catch (Exception e) {
|
368
|
log.error(e);
|
369
|
throw new IllegalStateException("collection failed: " + e.getMessage());
|
370
|
}
|
371
|
|
372
|
try {
|
373
|
String resultTotalXpathEval = xprResultTotalPath.evaluate(resultNode);
|
374
|
|
375
|
log.debug("downloadPage():: resInt: " +resumptionInt + "; resultTotal: " + resultTotal + " ; resultTotalXpath eval.: " + resultTotalXpathEval + "/" + resultTotalXPathEval1);
|
376
|
if ((resultTotal == -1) && (!resultTotalXpathEval.isEmpty())) {
|
377
|
resultTotal = Integer.parseInt(xprResultTotalPath.evaluate(resultNode));
|
378
|
if (resumptionType.toLowerCase().equals("page") && !AUTHBASIC.equalsIgnoreCase(authMethod)) {
|
379
|
resultTotal += 1;
|
380
|
} // to correct the upper bound
|
381
|
log.info("resultTotal was -1 is now: " + resultTotal);
|
382
|
}
|
383
|
} catch (Exception e) {
|
384
|
log.error(e);
|
385
|
throw new IllegalStateException("downloadPage() resultTotal couldn't parse: " + e.getMessage());
|
386
|
}
|
387
|
log.debug("resultTotal: " + resultTotal + " ; resInt: " + resumptionInt);
|
388
|
if (resumptionInt <= resultTotal) {
|
389
|
nextQuery = baseUrl + "?" + queryParams + querySize + "&" + resumptionParam + "=" + resumptionStr + queryFormat;
|
390
|
} else {
|
391
|
nextQuery = "";
|
392
|
// if (resumptionType.toLowerCase().equals("deep-cursor")) { resumptionInt -= 1; } // correct the resumptionInt and prevent a NullPointer Exception at mdStore
|
393
|
}
|
394
|
log.debug("downloadPage() nextQueryUrl: " + nextQuery);
|
395
|
return nextQuery;
|
396
|
|
397
|
|
398
|
}
|
399
|
|
400
|
private boolean isEmptyXml(String s){
|
401
|
return EMPTY_XML.equalsIgnoreCase(s);
|
402
|
}
|
403
|
|
404
|
|
405
|
private boolean isInteger(String s) {
|
406
|
boolean isValidInteger = false;
|
407
|
try {
|
408
|
Integer.parseInt(s);
|
409
|
|
410
|
// s is a valid integer
|
411
|
|
412
|
isValidInteger = true;
|
413
|
} catch (NumberFormatException ex) {
|
414
|
// s is not an integer
|
415
|
}
|
416
|
|
417
|
return isValidInteger;
|
418
|
}
|
419
|
|
420
|
// Method to encode a string value using `UTF-8` encoding scheme
|
421
|
private String encodeValue(String value) {
|
422
|
try {
|
423
|
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
|
424
|
} catch (UnsupportedEncodingException ex) {
|
425
|
throw new RuntimeException(ex.getCause());
|
426
|
}
|
427
|
}
|
428
|
|
429
|
/**
|
430
|
* setRequestHeader
|
431
|
*
|
432
|
* setRequestProperty: Sets the general request property. If a property with the key already exists, overwrite its value with the new value.
|
433
|
* @param conn
|
434
|
*/
|
435
|
private void setRequestHeader(HttpURLConnection conn) {
|
436
|
if (requestHeaders != null) {
|
437
|
for (String key : requestHeaders.keySet()) {
|
438
|
conn.setRequestProperty(key, requestHeaders.get(key));
|
439
|
}
|
440
|
log.debug("Set Request Header with: " + requestHeaders);
|
441
|
}
|
442
|
|
443
|
}
|
444
|
|
445
|
public String getResultFormatValue() {
|
446
|
return resultFormatValue;
|
447
|
}
|
448
|
|
449
|
public String getResultOutputFormat() {
|
450
|
return resultOutputFormat;
|
451
|
}
|
452
|
|
453
|
}
|