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.Queue;
|
17
|
import java.util.concurrent.PriorityBlockingQueue;
|
18
|
import javax.xml.transform.OutputKeys;
|
19
|
import javax.xml.transform.Transformer;
|
20
|
import javax.xml.transform.TransformerConfigurationException;
|
21
|
import javax.xml.transform.TransformerFactory;
|
22
|
import javax.xml.transform.dom.DOMSource;
|
23
|
import javax.xml.transform.stream.StreamResult;
|
24
|
import javax.xml.xpath.*;
|
25
|
|
26
|
import eu.dnetlib.data.collector.plugins.oai.engine.XmlCleaner;
|
27
|
import eu.dnetlib.data.collector.plugins.utils.JsonUtils;
|
28
|
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
|
29
|
import org.apache.commons.io.IOUtils;
|
30
|
import org.apache.commons.lang3.StringUtils;
|
31
|
import org.apache.commons.logging.Log;
|
32
|
import org.apache.commons.logging.LogFactory;
|
33
|
import org.w3c.dom.Node;
|
34
|
import org.w3c.dom.NodeList;
|
35
|
import org.xml.sax.InputSource;
|
36
|
|
37
|
/**
|
38
|
* @author Jochen Schirrwagen, Aenne Loehden, Andreas Czerniak
|
39
|
* @date 2020-04-09
|
40
|
*
|
41
|
*/
|
42
|
public class RestIterator implements Iterator<String> {
|
43
|
|
44
|
// TODO: clean up the comments of replaced source code
|
45
|
private static final Log log = LogFactory.getLog(RestIterator.class); // NOPMD by marko on 11/24/08 5:02 PM
|
46
|
|
47
|
private JsonUtils jsonUtils;
|
48
|
|
49
|
private String baseUrl;
|
50
|
private String resumptionType;
|
51
|
private String resumptionParam;
|
52
|
private String resultFormatValue;
|
53
|
private String queryParams;
|
54
|
private int resultSizeValue;
|
55
|
private int resumptionInt = 0; // integer resumption token (first record to harvest)
|
56
|
private int resultTotal = -1;
|
57
|
private String resumptionStr = Integer.toString(resumptionInt); // string resumption token (first record to harvest or token scanned from results)
|
58
|
private InputStream resultStream;
|
59
|
private Transformer transformer;
|
60
|
private XPath xpath;
|
61
|
private String query;
|
62
|
private XPathExpression xprResultTotalPath;
|
63
|
private XPathExpression xprResumptionPath;
|
64
|
private XPathExpression xprEntity;
|
65
|
private String queryFormat;
|
66
|
private String querySize;
|
67
|
private String authMethod;
|
68
|
private String authToken;
|
69
|
private Queue<String> recordQueue = new PriorityBlockingQueue<String>();
|
70
|
private int discoverResultSize = 0;
|
71
|
private int pagination = 1;
|
72
|
|
73
|
|
74
|
/**
|
75
|
* RestIterator class
|
76
|
*
|
77
|
* compatible to version before 1.3.33
|
78
|
*
|
79
|
* @param baseUrl
|
80
|
* @param resumptionType
|
81
|
* @param resumptionParam
|
82
|
* @param resumptionXpath
|
83
|
* @param resultTotalXpath
|
84
|
* @param resultFormatParam
|
85
|
* @param resultFormatValue
|
86
|
* @param resultSizeParam
|
87
|
* @param resultSizeValueStr
|
88
|
* @param queryParams
|
89
|
* @param entityXpath
|
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
|
) {
|
104
|
this(baseUrl,resumptionType,resumptionParam,resumptionXpath,resultTotalXpath,resultFormatParam,resultFormatValue,resultSizeParam,resultSizeValueStr,queryParams,entityXpath,"", "");
|
105
|
}
|
106
|
|
107
|
public RestIterator(
|
108
|
final String baseUrl,
|
109
|
final String resumptionType,
|
110
|
final String resumptionParam,
|
111
|
final String resumptionXpath,
|
112
|
final String resultTotalXpath,
|
113
|
final String resultFormatParam,
|
114
|
final String resultFormatValue,
|
115
|
final String resultSizeParam,
|
116
|
final String resultSizeValueStr,
|
117
|
final String queryParams,
|
118
|
final String entityXpath,
|
119
|
final String authMethod,
|
120
|
final String authToken,
|
121
|
final String resultOffsetParam
|
122
|
) {
|
123
|
this(baseUrl,resumptionType,resumptionParam,resumptionXpath,resultTotalXpath,resultFormatParam,resultFormatValue,resultSizeParam,resultSizeValueStr,queryParams,entityXpath,"", "");
|
124
|
}
|
125
|
|
126
|
/** RestIterator class
|
127
|
* compatible to version 1.3.33
|
128
|
* @param baseUrl
|
129
|
* @param resumptionType
|
130
|
* @param resumptionParam
|
131
|
* @param resumptionXpath
|
132
|
* @param resultTotalXpath
|
133
|
* @param resultFormatParam
|
134
|
* @param resultFormatValue
|
135
|
* @param resultSizeParam
|
136
|
* @param resultSizeValueStr
|
137
|
* @param queryParams
|
138
|
* @param entityXpath
|
139
|
* @param authMethod
|
140
|
* @param authToken
|
141
|
*/
|
142
|
public RestIterator(
|
143
|
final String baseUrl,
|
144
|
final String resumptionType,
|
145
|
final String resumptionParam,
|
146
|
final String resumptionXpath,
|
147
|
final String resultTotalXpath,
|
148
|
final String resultFormatParam,
|
149
|
final String resultFormatValue,
|
150
|
final String resultSizeParam,
|
151
|
final String resultSizeValueStr,
|
152
|
final String queryParams,
|
153
|
final String entityXpath,
|
154
|
final String authMethod,
|
155
|
final String authToken
|
156
|
) {
|
157
|
this.jsonUtils = new JsonUtils();
|
158
|
this.baseUrl = baseUrl;
|
159
|
this.resumptionType = resumptionType;
|
160
|
this.resumptionParam = resumptionParam;
|
161
|
this.resultFormatValue = resultFormatValue;
|
162
|
this.queryParams = queryParams;
|
163
|
this.resultSizeValue = Integer.valueOf(resultSizeValueStr);
|
164
|
this.authMethod = authMethod;
|
165
|
this.authToken = authToken;
|
166
|
|
167
|
queryFormat = StringUtils.isNotBlank(resultFormatParam) ? "&" + resultFormatParam + "=" + resultFormatValue : "";
|
168
|
querySize = StringUtils.isNotBlank(resultSizeParam) ? "&" + resultSizeParam + "=" + resultSizeValueStr : "";
|
169
|
|
170
|
try {
|
171
|
initXmlTransformation(resultTotalXpath, resumptionXpath, entityXpath);
|
172
|
} catch (Exception e) {
|
173
|
throw new IllegalStateException("xml transformation init failed: " + e.getMessage());
|
174
|
}
|
175
|
initQueue();
|
176
|
}
|
177
|
|
178
|
|
179
|
private void initXmlTransformation(String resultTotalXpath, String resumptionXpath, String entityXpath)
|
180
|
throws TransformerConfigurationException, XPathExpressionException {
|
181
|
transformer = TransformerFactory.newInstance().newTransformer();
|
182
|
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
183
|
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
|
184
|
xpath = XPathFactory.newInstance().newXPath();
|
185
|
xprResultTotalPath = xpath.compile(resultTotalXpath);
|
186
|
xprResumptionPath = xpath.compile(StringUtils.isBlank(resumptionXpath) ? "/" : resumptionXpath);
|
187
|
xprEntity = xpath.compile(entityXpath);
|
188
|
}
|
189
|
|
190
|
private void initQueue() {
|
191
|
query = baseUrl + "?" + queryParams + querySize + queryFormat;
|
192
|
}
|
193
|
|
194
|
private void disconnect() {
|
195
|
// TODO close inputstream
|
196
|
}
|
197
|
|
198
|
/* (non-Javadoc)
|
199
|
* @see java.util.Iterator#hasNext()
|
200
|
*/
|
201
|
@Override
|
202
|
public boolean hasNext() {
|
203
|
if (recordQueue.isEmpty() && query.isEmpty()) {
|
204
|
disconnect();
|
205
|
return false;
|
206
|
} else {
|
207
|
return true;
|
208
|
}
|
209
|
}
|
210
|
|
211
|
/* (non-Javadoc)
|
212
|
* @see java.util.Iterator#next()
|
213
|
*/
|
214
|
@Override
|
215
|
public String next() {
|
216
|
synchronized (recordQueue) {
|
217
|
while (recordQueue.isEmpty() && !query.isEmpty()) {
|
218
|
try {
|
219
|
log.debug("get Query: " + query);
|
220
|
query = downloadPage(query);
|
221
|
log.debug("next queryURL from downloadPage(): " + query);
|
222
|
} catch (CollectorServiceException e) {
|
223
|
log.debug("CollectorPlugin.next()-Exception: " + e);
|
224
|
throw new RuntimeException(e);
|
225
|
}
|
226
|
}
|
227
|
return recordQueue.poll();
|
228
|
}
|
229
|
}
|
230
|
|
231
|
/*
|
232
|
* download page and return nextQuery
|
233
|
*/
|
234
|
private String downloadPage(String query) throws CollectorServiceException {
|
235
|
String resultJson;
|
236
|
String resultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
|
237
|
String nextQuery = "";
|
238
|
String emptyXml = resultXml + "<" + JsonUtils.wrapName + "></" + JsonUtils.wrapName + ">";
|
239
|
Node resultNode = null;
|
240
|
NodeList nodeList = null;
|
241
|
String qUrlArgument = "";
|
242
|
int urlOldResumptionSize = 0;
|
243
|
InputStream theHttpInputStream;
|
244
|
|
245
|
// check if cursor=* is initial set otherwise add it to the queryParam URL
|
246
|
if( resumptionType.equalsIgnoreCase("deep-cursor") ) {
|
247
|
log.debug("check resumptionType deep-cursor and check cursor=*?" + query);
|
248
|
if(!query.contains("&cursor=")) {
|
249
|
query += "&cursor=*";
|
250
|
}
|
251
|
}
|
252
|
|
253
|
try {
|
254
|
URL qUrl = new URL(query);
|
255
|
log.debug("authMethod :" + authMethod);
|
256
|
if (this.authMethod == "bearer") {
|
257
|
log.trace("authMethod before inputStream: " + resultXml);
|
258
|
log.debug("authMethod :" + authMethod);
|
259
|
HttpURLConnection conn = (HttpURLConnection) qUrl.openConnection();
|
260
|
conn.setRequestProperty("Authorization","Bearer "+authToken);
|
261
|
conn.setRequestProperty("Content-Type","application/json");
|
262
|
conn.setRequestMethod("GET");
|
263
|
theHttpInputStream = conn.getInputStream();
|
264
|
}else if (this.authMethod == "basic") {
|
265
|
log.trace("authMethod before inputStream: " + resultXml);
|
266
|
log.debug("authMethod :" + authMethod);
|
267
|
HttpURLConnection conn = (HttpURLConnection) qUrl.openConnection();
|
268
|
conn.setRequestProperty("Authorization","Basic "+authToken);
|
269
|
conn.setRequestProperty("accept","application/xml");
|
270
|
conn.setRequestMethod("GET");
|
271
|
log.debug("header :" + conn.getHeaderFields());
|
272
|
log.debug("url : " + qUrl.getPath());
|
273
|
theHttpInputStream = conn.getInputStream();
|
274
|
} else {
|
275
|
theHttpInputStream = qUrl.openStream();
|
276
|
}
|
277
|
|
278
|
resultStream = theHttpInputStream;
|
279
|
if ("json".equals(resultFormatValue.toLowerCase())) {
|
280
|
resultJson = IOUtils.toString(resultStream, "UTF-8");
|
281
|
resultXml = jsonUtils.convertToXML(resultJson);
|
282
|
resultStream = IOUtils.toInputStream(resultXml, "UTF-8");
|
283
|
}
|
284
|
|
285
|
if (!(emptyXml.toLowerCase()).equals(resultXml.toLowerCase())) {
|
286
|
resultNode = (Node) xpath.evaluate("/", new InputSource(resultStream), XPathConstants.NODE);
|
287
|
nodeList = (NodeList) xprEntity.evaluate(resultNode, XPathConstants.NODESET);
|
288
|
log.debug("nodeList.length: " + nodeList.getLength());
|
289
|
for (int i = 0; i < nodeList.getLength(); i++) {
|
290
|
StringWriter sw = new StringWriter();
|
291
|
transformer.transform(new DOMSource(nodeList.item(i)), new StreamResult(sw));
|
292
|
recordQueue.add(sw.toString());
|
293
|
}
|
294
|
} else { log.info("resultXml is equal with emptyXml"); }
|
295
|
|
296
|
resumptionInt += resultSizeValue;
|
297
|
|
298
|
switch (resumptionType.toLowerCase()) {
|
299
|
case "scan": // read of resumptionToken , evaluate next results, e.g. OAI, iterate over items
|
300
|
resumptionStr = xprResumptionPath.evaluate(resultNode);
|
301
|
break;
|
302
|
|
303
|
case "count": // begin at one step for all records, iterate over items
|
304
|
resumptionStr = Integer.toString(resumptionInt);
|
305
|
break;
|
306
|
|
307
|
case "discover": // size of result items unknown, iterate over items (for openDOAR - 201808)
|
308
|
if (resultSizeValue < 2) {throw new CollectorServiceException("Mode: discover, Param 'resultSizeValue' is less than 2");}
|
309
|
qUrlArgument = qUrl.getQuery();
|
310
|
String[] arrayQUrlArgument = qUrlArgument.split("&");
|
311
|
for (String arrayUrlArgStr : arrayQUrlArgument) {
|
312
|
if (arrayUrlArgStr.startsWith(resumptionParam)) {
|
313
|
String[] resumptionKeyValue = arrayUrlArgStr.split("=");
|
314
|
if(isInteger(resumptionKeyValue[1])) {
|
315
|
urlOldResumptionSize = Integer.parseInt(resumptionKeyValue[1]);
|
316
|
log.debug("discover OldResumptionSize from Url (int): " + urlOldResumptionSize);
|
317
|
} else {
|
318
|
log.debug("discover OldResumptionSize from Url (str): " + resumptionKeyValue[1]);
|
319
|
}
|
320
|
}
|
321
|
}
|
322
|
|
323
|
if (((emptyXml.toLowerCase()).equals(resultXml.toLowerCase()))
|
324
|
|| ((nodeList != null) && (nodeList.getLength() < resultSizeValue))
|
325
|
) {
|
326
|
// resumptionStr = "";
|
327
|
if (nodeList != null) { discoverResultSize += nodeList.getLength(); }
|
328
|
resultTotal = discoverResultSize;
|
329
|
} else {
|
330
|
resumptionStr = Integer.toString(resumptionInt);
|
331
|
resultTotal = resumptionInt + 1;
|
332
|
if (nodeList != null) { discoverResultSize += nodeList.getLength(); }
|
333
|
}
|
334
|
log.debug("discoverResultSize: " + discoverResultSize);
|
335
|
break;
|
336
|
|
337
|
case "pagination":
|
338
|
case "page": // pagination, iterate over page numbers
|
339
|
pagination += 1;
|
340
|
if (nodeList != null) {
|
341
|
discoverResultSize += nodeList.getLength();
|
342
|
} else {
|
343
|
resultTotal = discoverResultSize;
|
344
|
pagination = discoverResultSize;
|
345
|
}
|
346
|
resumptionInt = pagination;
|
347
|
resumptionStr = Integer.toString(resumptionInt);
|
348
|
break;
|
349
|
|
350
|
case "deep-cursor": // size of result items unknown, iterate over items (for supporting deep cursor in solr)
|
351
|
// isn't relevant -- if (resultSizeValue < 2) {throw new CollectorServiceException("Mode: deep-cursor, Param 'resultSizeValue' is less than 2");}
|
352
|
|
353
|
resumptionStr = encodeValue(xprResumptionPath.evaluate(resultNode));
|
354
|
queryParams = queryParams.replace("&cursor=*", "");
|
355
|
|
356
|
// terminating if length of nodeList is 0
|
357
|
if( (nodeList != null) && (nodeList.getLength() < discoverResultSize) ) {
|
358
|
resumptionInt += ( nodeList.getLength() + 1 - resultSizeValue);
|
359
|
} else {
|
360
|
resumptionInt += (nodeList.getLength() - resultSizeValue); // subtract the resultSizeValue because the iteration is over real length and the resultSizeValue is added before the switch()
|
361
|
}
|
362
|
|
363
|
discoverResultSize = nodeList.getLength();
|
364
|
|
365
|
log.debug("downloadPage().deep-cursor: resumptionStr=" + resumptionStr + " ; queryParams=" + queryParams + " resumptionLengthIncreased: " + resumptionInt);
|
366
|
|
367
|
break;
|
368
|
|
369
|
default: // otherwise: abort
|
370
|
// resultTotal = resumptionInt;
|
371
|
break;
|
372
|
}
|
373
|
|
374
|
} catch (Exception e) {
|
375
|
log.error(e);
|
376
|
throw new IllegalStateException("collection failed: " + e.getMessage());
|
377
|
}
|
378
|
|
379
|
try {
|
380
|
if (resultTotal == -1) {
|
381
|
resultTotal = Integer.parseInt(xprResultTotalPath.evaluate(resultNode));
|
382
|
if (resumptionType.toLowerCase().equals("page")) { resultTotal += 1; } // to correct the upper bound
|
383
|
log.info("resultTotal was -1 is now: " + resultTotal);
|
384
|
}
|
385
|
} catch(Exception e) {
|
386
|
log.error(e);
|
387
|
throw new IllegalStateException("downloadPage resultTotal couldn't parse: " + e.getMessage());
|
388
|
}
|
389
|
log.debug("resultTotal: " + resultTotal);
|
390
|
log.debug("resInt: " + resumptionInt);
|
391
|
if (resumptionInt <= resultTotal) {
|
392
|
nextQuery = baseUrl + "?" + queryParams + querySize + "&" + resumptionParam + "=" + resumptionStr + queryFormat;
|
393
|
} else {
|
394
|
nextQuery = "";
|
395
|
// if (resumptionType.toLowerCase().equals("deep-cursor")) { resumptionInt -= 1; } // correct the resumptionInt and prevent a NullPointer Exception at mdStore
|
396
|
}
|
397
|
log.debug("nextQueryUrl: " + nextQuery);
|
398
|
return nextQuery;
|
399
|
|
400
|
|
401
|
}
|
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
|
}
|