dnet-docker/dnet-app/libs/dnet-oai-common/src/main/java/eu/dnetlib/common/oai/domain/OaiIterator.java

160 lines
4.7 KiB
Java

package eu.dnetlib.common.oai.domain;
import java.io.StringReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.PriorityBlockingQueue;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.web.client.RestTemplate;
import eu.dnetlib.errors.CollectorException;
import eu.dnetlib.utils.XmlCleaner;
public class OaiIterator implements Iterator<String> {
private static final DateTimeFormatter oaiDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final Queue<String> queue = new PriorityBlockingQueue<>();
private final SAXReader reader = new SAXReader();
private final String baseUrl;
private final String set;
private final String mdFormat;
private final LocalDateTime fromDate;
private final LocalDateTime untilDate;
private String token;
private boolean started;
private static final Log log = LogFactory.getLog(OaiIterator.class);
public OaiIterator(final String baseUrl,
final String mdFormat,
final String set,
final LocalDateTime fromDate,
final LocalDateTime untilDate) {
this.baseUrl = baseUrl;
this.mdFormat = mdFormat;
this.set = set;
this.fromDate = fromDate;
this.untilDate = untilDate;
this.started = false;
}
private void verifyStarted() {
if (!this.started) {
this.started = true;
try {
this.token = firstPage();
} catch (final CollectorException e) {
throw new RuntimeException(e);
}
}
}
@Override
public boolean hasNext() {
synchronized (this.queue) {
verifyStarted();
return !this.queue.isEmpty();
}
}
@Override
public String next() {
synchronized (this.queue) {
verifyStarted();
final String res = this.queue.poll();
while (this.queue.isEmpty() && (this.token != null) && !this.token.isEmpty()) {
try {
this.token = otherPages(this.token);
} catch (final CollectorException e) {
throw new RuntimeException(e);
}
}
return res;
}
}
@Override
public void remove() {}
private String firstPage() throws CollectorException {
final StringBuilder url = new StringBuilder()
.append(this.baseUrl)
.append("?verb=ListRecords&metadataPrefix=")
.append(URLEncoder.encode(this.mdFormat, StandardCharsets.UTF_8));
if (StringUtils.isNotBlank(this.set)) {
url.append("&set=").append(URLEncoder.encode(this.set, StandardCharsets.UTF_8));
}
if (this.fromDate != null) {
url.append("&from=").append(URLEncoder.encode(this.fromDate.format(oaiDateFormatter), StandardCharsets.UTF_8));
}
if (this.untilDate != null) {
url.append("&until=").append(URLEncoder.encode(this.untilDate.format(oaiDateFormatter), StandardCharsets.UTF_8));
}
return downloadPage(url.toString());
}
private String otherPages(final String resumptionToken) throws CollectorException {
return downloadPage(this.baseUrl + "?verb=ListRecords&resumptionToken=" + URLEncoder.encode(resumptionToken, StandardCharsets.UTF_8));
}
private String extractResumptionToken(final String xml) {
final String s = StringUtils.substringAfter(xml, "<resumptionToken");
if (s == null) { return null; }
final String result = StringUtils.substringBetween(s, ">", "</");
if (result == null) { return null; }
return result.trim();
}
private String downloadPage(final String url) throws CollectorException {
log.debug("Invoking url: " + url);
final String xml = new RestTemplate().getForObject(url, String.class);
Document doc;
try {
doc = this.reader.read(new StringReader(xml));
} catch (final DocumentException e) {
final String cleaned = XmlCleaner.cleanAllEntities(xml);
try {
doc = this.reader.read(new StringReader(cleaned));
} catch (final DocumentException e1) {
final String resumptionToken = extractResumptionToken(xml);
if (resumptionToken == null) { throw new CollectorException("Error parsing cleaned document:" + cleaned, e1); }
return resumptionToken;
}
}
final Node errorNode = doc.selectSingleNode("/*[local-name()='OAI-PMH']/*[local-name()='error']");
if (errorNode != null) {
final String code = errorNode.valueOf("@code");
if ("noRecordsMatch".equalsIgnoreCase(code.trim())) { return null; }
throw new CollectorException(code + " - " + errorNode.getText());
}
for (final Object o : doc.selectNodes("//*[local-name()='ListRecords']/*[local-name()='record']")) {
this.queue.add(((Node) o).asXML());
}
return doc.valueOf("//*[local-name()='resumptionToken']");
}
}