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.net.URL;
|
11
|
import java.util.Iterator;
|
12
|
import java.util.Queue;
|
13
|
import java.util.concurrent.PriorityBlockingQueue;
|
14
|
import javax.xml.transform.OutputKeys;
|
15
|
import javax.xml.transform.Transformer;
|
16
|
import javax.xml.transform.TransformerConfigurationException;
|
17
|
import javax.xml.transform.TransformerFactory;
|
18
|
import javax.xml.transform.dom.DOMSource;
|
19
|
import javax.xml.transform.stream.StreamResult;
|
20
|
import javax.xml.xpath.*;
|
21
|
|
22
|
import eu.dnetlib.data.collector.plugins.oai.engine.XmlCleaner;
|
23
|
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
|
24
|
import org.apache.commons.io.IOUtils;
|
25
|
import org.apache.commons.lang3.StringUtils;
|
26
|
import org.apache.commons.logging.Log;
|
27
|
import org.apache.commons.logging.LogFactory;
|
28
|
import org.w3c.dom.Node;
|
29
|
import org.w3c.dom.NodeList;
|
30
|
import org.xml.sax.InputSource;
|
31
|
|
32
|
/**
|
33
|
* @author Jochen Schirrwagen, Aenne Loehden, Andreas Czerniak
|
34
|
* @date 2018-09-03
|
35
|
*
|
36
|
*/
|
37
|
public class RestIterator implements Iterator<String> {
|
38
|
|
39
|
// TODO: clean up the comments of replaced source code
|
40
|
private static final Log log = LogFactory.getLog(RestIterator.class); // NOPMD by marko on 11/24/08 5:02 PM
|
41
|
|
42
|
private static final String wrapName = "recordWrap";
|
43
|
private String baseUrl;
|
44
|
private String resumptionType;
|
45
|
private String resumptionParam;
|
46
|
private String resultFormatValue;
|
47
|
private String queryParams;
|
48
|
private int resultSizeValue;
|
49
|
private int resumptionInt = 0; // integer resumption token (first record to harvest)
|
50
|
private int resultTotal = -1;
|
51
|
private String resumptionStr = Integer.toString(resumptionInt); // string resumption token (first record to harvest or token scanned from results)
|
52
|
private InputStream resultStream;
|
53
|
private Transformer transformer;
|
54
|
private XPath xpath;
|
55
|
private String query;
|
56
|
private XPathExpression xprResultTotalPath;
|
57
|
private XPathExpression xprResumptionPath;
|
58
|
private XPathExpression xprEntity;
|
59
|
private String queryFormat;
|
60
|
private String querySize;
|
61
|
private Queue<String> recordQueue = new PriorityBlockingQueue<String>();
|
62
|
private int discoverResultSize = 0;
|
63
|
private int pagination = 1;
|
64
|
|
65
|
public RestIterator(
|
66
|
final String baseUrl,
|
67
|
final String resumptionType,
|
68
|
final String resumptionParam,
|
69
|
final String resumptionXpath,
|
70
|
final String resultTotalXpath,
|
71
|
final String resultFormatParam,
|
72
|
final String resultFormatValue,
|
73
|
final String resultSizeParam,
|
74
|
final String resultSizeValueStr,
|
75
|
final String queryParams,
|
76
|
final String entityXpath
|
77
|
) {
|
78
|
this.baseUrl = baseUrl;
|
79
|
this.resumptionType = resumptionType;
|
80
|
this.resumptionParam = resumptionParam;
|
81
|
this.resultFormatValue = resultFormatValue;
|
82
|
this.queryParams = queryParams;
|
83
|
this.resultSizeValue = Integer.valueOf(resultSizeValueStr);
|
84
|
|
85
|
queryFormat = StringUtils.isNotBlank(resultFormatParam) ? "&" + resultFormatParam + "=" + resultFormatValue : "";
|
86
|
querySize = StringUtils.isNotBlank(resultSizeParam) ? "&" + resultSizeParam + "=" + resultSizeValueStr : "";
|
87
|
|
88
|
try {
|
89
|
initXmlTransformation(resultTotalXpath, resumptionXpath, entityXpath);
|
90
|
} catch (Exception e) {
|
91
|
throw new IllegalStateException("xml transformation init failed: " + e.getMessage());
|
92
|
}
|
93
|
initQueue();
|
94
|
}
|
95
|
|
96
|
private void initXmlTransformation(String resultTotalXpath, String resumptionXpath, String entityXpath)
|
97
|
throws TransformerConfigurationException, XPathExpressionException {
|
98
|
transformer = TransformerFactory.newInstance().newTransformer();
|
99
|
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
100
|
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
|
101
|
xpath = XPathFactory.newInstance().newXPath();
|
102
|
xprResultTotalPath = xpath.compile(resultTotalXpath);
|
103
|
xprResumptionPath = xpath.compile(StringUtils.isBlank(resumptionXpath) ? "/" : resumptionXpath);
|
104
|
xprEntity = xpath.compile(entityXpath);
|
105
|
}
|
106
|
|
107
|
private void initQueue() {
|
108
|
query = baseUrl + "?" + queryParams + querySize + queryFormat;
|
109
|
}
|
110
|
|
111
|
private void disconnect() {
|
112
|
// TODO close inputstream
|
113
|
}
|
114
|
|
115
|
/* (non-Javadoc)
|
116
|
* @see java.util.Iterator#hasNext()
|
117
|
*/
|
118
|
@Override
|
119
|
public boolean hasNext() {
|
120
|
if (recordQueue.isEmpty() && query.isEmpty()) {
|
121
|
disconnect();
|
122
|
return false;
|
123
|
} else {
|
124
|
return true;
|
125
|
}
|
126
|
}
|
127
|
|
128
|
/* (non-Javadoc)
|
129
|
* @see java.util.Iterator#next()
|
130
|
*/
|
131
|
@Override
|
132
|
public String next() {
|
133
|
synchronized (recordQueue) {
|
134
|
while (recordQueue.isEmpty() && !query.isEmpty()) {
|
135
|
try {
|
136
|
log.info("get Query: " + query);
|
137
|
query = downloadPage(query);
|
138
|
log.debug("next queryURL from downloadPage(): " + query);
|
139
|
} catch (CollectorServiceException e) {
|
140
|
log.debug("CollectorPlugin.next()-Exception: " + e);
|
141
|
throw new RuntimeException(e);
|
142
|
}
|
143
|
}
|
144
|
return recordQueue.poll();
|
145
|
}
|
146
|
}
|
147
|
|
148
|
/*
|
149
|
* download page and return nextQuery
|
150
|
*/
|
151
|
private String downloadPage(String query) throws CollectorServiceException {
|
152
|
String resultJson;
|
153
|
String resultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
|
154
|
String nextQuery = "";
|
155
|
String emptyXml = resultXml + "<" + wrapName + "></" + wrapName + ">";
|
156
|
Node resultNode = null;
|
157
|
NodeList nodeList = null;
|
158
|
String qUrlArgument = "";
|
159
|
int urlOldResumptionSize = 0;
|
160
|
|
161
|
try {
|
162
|
URL qUrl = new URL(query);
|
163
|
|
164
|
resultStream = qUrl.openStream();
|
165
|
if ("json".equals(resultFormatValue.toLowerCase())) {
|
166
|
|
167
|
resultJson = IOUtils.toString(resultStream, "UTF-8");
|
168
|
resultJson = syntaxConvertJsonKeyNamens(resultJson);
|
169
|
org.json.JSONObject jsonObject = new org.json.JSONObject(resultJson);
|
170
|
resultXml += org.json.XML.toString(jsonObject, wrapName); // wrap xml in single root element
|
171
|
log.trace("before inputStream: " + resultXml);
|
172
|
resultXml = XmlCleaner.cleanAllEntities(resultXml);
|
173
|
log.trace("after cleaning: " + resultXml);
|
174
|
resultStream = IOUtils.toInputStream(resultXml, "UTF-8");
|
175
|
}
|
176
|
|
177
|
if (!(emptyXml.toLowerCase()).equals(resultXml.toLowerCase())) {
|
178
|
resultNode = (Node) xpath.evaluate("/", new InputSource(resultStream), XPathConstants.NODE);
|
179
|
nodeList = (NodeList) xprEntity.evaluate(resultNode, XPathConstants.NODESET);
|
180
|
log.debug("nodeList.length: " + nodeList.getLength());
|
181
|
for (int i = 0; i < nodeList.getLength(); i++) {
|
182
|
StringWriter sw = new StringWriter();
|
183
|
transformer.transform(new DOMSource(nodeList.item(i)), new StreamResult(sw));
|
184
|
recordQueue.add(sw.toString());
|
185
|
}
|
186
|
} else { log.info("resultXml is equal with emptyXml"); }
|
187
|
|
188
|
resumptionInt += resultSizeValue;
|
189
|
|
190
|
switch (resumptionType.toLowerCase()) {
|
191
|
case "scan": // read of resumptionToken , evaluate next results, e.g. OAI, iterate over items
|
192
|
resumptionStr = xprResumptionPath.evaluate(resultNode);
|
193
|
break;
|
194
|
|
195
|
case "count": // begin at one step for all records, iterate over items
|
196
|
resumptionStr = Integer.toString(resumptionInt);
|
197
|
break;
|
198
|
|
199
|
case "discover": // size of result items unknown, iterate over items (for openDOAR - 201808)
|
200
|
if (resultSizeValue < 2) {throw new CollectorServiceException("Mode: discover, Param 'resultSizeValue' is less than 2");}
|
201
|
qUrlArgument = qUrl.getQuery();
|
202
|
String[] arrayQUrlArgument = qUrlArgument.split("&");
|
203
|
for (String arrayUrlArgStr : arrayQUrlArgument) {
|
204
|
if (arrayUrlArgStr.startsWith(resumptionParam)) {
|
205
|
String[] resumptionKeyValue = arrayUrlArgStr.split("=");
|
206
|
urlOldResumptionSize = Integer.parseInt(resumptionKeyValue[1]);
|
207
|
log.debug("discover OldResumptionSize from Url: " + urlOldResumptionSize);
|
208
|
}
|
209
|
}
|
210
|
|
211
|
if (((emptyXml.toLowerCase()).equals(resultXml.toLowerCase()))
|
212
|
|| ((nodeList != null) && (nodeList.getLength() < resultSizeValue))
|
213
|
) {
|
214
|
// resumptionStr = "";
|
215
|
if (nodeList != null) { discoverResultSize += nodeList.getLength(); }
|
216
|
resultTotal = discoverResultSize;
|
217
|
} else {
|
218
|
resumptionStr = Integer.toString(resumptionInt);
|
219
|
resultTotal = resumptionInt + 1;
|
220
|
if (nodeList != null) { discoverResultSize += nodeList.getLength(); }
|
221
|
}
|
222
|
log.info("discoverResultSize: " + discoverResultSize);
|
223
|
break;
|
224
|
|
225
|
case "pagination":
|
226
|
case "page": // pagination, iterate over pages
|
227
|
pagination += 1;
|
228
|
if (nodeList != null) {
|
229
|
discoverResultSize += nodeList.getLength();
|
230
|
} else {
|
231
|
resultTotal = discoverResultSize;
|
232
|
pagination = discoverResultSize;
|
233
|
}
|
234
|
resumptionInt = pagination;
|
235
|
resumptionStr = Integer.toString(resumptionInt);
|
236
|
break;
|
237
|
|
238
|
default: // otherwise: abort
|
239
|
// resultTotal = resumptionInt;
|
240
|
break;
|
241
|
}
|
242
|
|
243
|
if (resultTotal == -1) {
|
244
|
resultTotal = Integer.parseInt(xprResultTotalPath.evaluate(resultNode));
|
245
|
if (resumptionType.toLowerCase().equals("page")) { resultTotal += 1; } // to correct the upper bound
|
246
|
log.info("resultTotal was -1 is now: " + resultTotal);
|
247
|
}
|
248
|
log.info("resultTotal: " + resultTotal);
|
249
|
log.info("resInt: " + resumptionInt);
|
250
|
if (resumptionInt < resultTotal) {
|
251
|
nextQuery = baseUrl + "?" + queryParams + querySize + "&" + resumptionParam + "=" + resumptionStr + queryFormat;
|
252
|
} else
|
253
|
nextQuery = "";
|
254
|
|
255
|
log.debug("nextQueryUrl: " + nextQuery);
|
256
|
return nextQuery;
|
257
|
|
258
|
} catch (Exception e) {
|
259
|
log.error(e);
|
260
|
throw new IllegalStateException("collection failed: " + e.getMessage());
|
261
|
}
|
262
|
}
|
263
|
|
264
|
/**
|
265
|
* convert in JSON-KeyName 'whitespace(s)' to '_' and '/' to '_', '(' and ')' to ''
|
266
|
* check W3C XML syntax: https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-starttags for valid tag names
|
267
|
* and work-around for the JSON to XML converting of org.json.XML-package.
|
268
|
*
|
269
|
* known bugs: doesn't prevent "key name":" ["sexy name",": penari","erotic dance"],
|
270
|
*
|
271
|
* @param jsonInput
|
272
|
* @return convertedJsonKeynameOutput
|
273
|
*/
|
274
|
private String syntaxConvertJsonKeyNamens(String jsonInput) {
|
275
|
|
276
|
log.trace("before convertJsonKeyNames: " + jsonInput);
|
277
|
// pre-clean json - rid spaces of element names (misinterpreted as elements with attributes in xml)
|
278
|
// replace ' 's in JSON Namens with '_'
|
279
|
while (jsonInput.matches(".*\"([^\"]*)\\s+([^\"]*)\":.*")) {
|
280
|
jsonInput = jsonInput.replaceAll("\"([^\"]*)\\s+([^\"]*)\":", "\"$1_$2\":");
|
281
|
}
|
282
|
|
283
|
// replace forward-slash (sign '/' ) in JSON Names with '_'
|
284
|
while (jsonInput.matches(".*\"([^\"]*)/([^\"]*)\":.*")) {
|
285
|
jsonInput = jsonInput.replaceAll("\"([^\"]*)/([^\"]*)\":", "\"$1_$2\":");
|
286
|
}
|
287
|
|
288
|
// replace '(' in JSON Names with ''
|
289
|
while (jsonInput.matches(".*\"([^\"]*)[(]([^\"]*)\":.*")) {
|
290
|
jsonInput = jsonInput.replaceAll("\"([^\"]*)[(]([^\"]*)\":", "\"$1$2\":");
|
291
|
}
|
292
|
|
293
|
// replace ')' in JSON Names with ''
|
294
|
while (jsonInput.matches(".*\"([^\"]*)[)]([^\"]*)\":.*")) {
|
295
|
jsonInput = jsonInput.replaceAll("\"([^\"]*)[)]([^\"]*)\":", "\"$1$2\":");
|
296
|
}
|
297
|
|
298
|
// replace startNumbers in JSON Keynames with 'n_'
|
299
|
while (jsonInput.matches(".*\"([^\"][0-9])([^\"]*)\":.*")) {
|
300
|
jsonInput = jsonInput.replaceAll("\"([^\"][0-9])([^\"]*)\":", "\"n_$1$2\":");
|
301
|
}
|
302
|
|
303
|
// replace ':' between number like '2018-08-28T11:05:00Z' in JSON keynames with ''
|
304
|
while (jsonInput.matches(".*\"([^\"]*[0-9]):([0-9][^\"]*)\":.*")) {
|
305
|
jsonInput = jsonInput.replaceAll("\"([^\"]*[0-9]):([0-9][^\"]*)\":", "\"$1$2\":");
|
306
|
}
|
307
|
|
308
|
// replace ',' in JSON Keynames with '.' to prevent , in xml tagnames.
|
309
|
// while (jsonInput.matches(".*\"([^\"]*),([^\"]*)\":.*")) {
|
310
|
// jsonInput = jsonInput.replaceAll("\"([^\"]*),([^\"]*)\":", "\"$1.$2\":");
|
311
|
// }
|
312
|
|
313
|
// replace '=' in JSON Keynames with '-'
|
314
|
while (jsonInput.matches(".*\"([^\"]*)=([^\"]*)\":.*")) {
|
315
|
jsonInput = jsonInput.replaceAll("\"([^\"]*)=([^\"]*)\":", "\"$1-$2\":");
|
316
|
}
|
317
|
|
318
|
log.trace("after syntaxConvertJsonKeyNames: " + jsonInput);
|
319
|
return jsonInput;
|
320
|
}
|
321
|
|
322
|
/**
|
323
|
*
|
324
|
* https://www.w3.org/TR/REC-xml/#charencoding shows character enoding in entities
|
325
|
* *
|
326
|
* @param bufferStr - XML string
|
327
|
* @return
|
328
|
*/
|
329
|
private static String cleanUnwantedJsonCharsInXmlTagnames(String bufferStr) {
|
330
|
|
331
|
while (bufferStr.matches(".*<([^<>].*),(.)>.*")) {
|
332
|
bufferStr = bufferStr.replaceAll("<([^<>.*),(.*)>", "<$1$2>");
|
333
|
}
|
334
|
|
335
|
// replace [#x10-#x1f] with ''
|
336
|
// while (bufferStr.matches(".*[0-9a-f].*")) {
|
337
|
// bufferStr = bufferStr.replaceAll("([0-9a-fA-F])", "");
|
338
|
// }
|
339
|
|
340
|
return bufferStr;
|
341
|
}
|
342
|
|
343
|
}
|