Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public JsoupDocumentReader(Resource htmlResource, JsoupDocumentReaderConfig conf
@Override
public List<Document> get() {
try (InputStream inputStream = this.htmlResource.getInputStream()) {
org.jsoup.nodes.Document doc = Jsoup.parse(inputStream, this.config.charset, "");
org.jsoup.nodes.Document doc = Jsoup.parse(inputStream, this.config.charset, resolveBaseUri());

List<Document> documents = new ArrayList<>();

Expand Down Expand Up @@ -108,6 +108,22 @@ else if (this.config.groupByElement) {
}
}

/**
* Returns the base URI used to resolve relative links against, taken from the
* resource itself. Resources that cannot be resolved to a URL, such as a
* {@link org.springframework.core.io.ByteArrayResource}, have no base to resolve
* against and keep an empty one.
*/
private String resolveBaseUri() {
try {
return this.htmlResource.getURL().toString();
}
catch (IOException ignored) {
// A resource without a URL has no base to resolve against.
return "";
}
}

private void addMetadata(org.jsoup.nodes.Document jsoupDoc, Document springDoc) {
Map<String, Object> metadata = new HashMap<>();
metadata.put("title", jsoupDoc.title());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,21 @@ void testWithLinkUrls() {
assertThat(linkUrls).contains("https://spring.io/");
}

@Test
void testWithRelativeLinkUrls() {
JsoupDocumentReader reader = new JsoupDocumentReader(
new DefaultResourceLoader().getResource("classpath:/test-relative-links.html"),
JsoupDocumentReaderConfig.builder().includeLinkUrls(true).build());
List<Document> documents = reader.get();
assertThat(documents).hasSize(1);
Document document = documents.get(0);

List<String> linkUrls = (List<String>) document.getMetadata().get("linkUrls");
assertThat(linkUrls).contains("https://spring.io/");
assertThat(linkUrls).noneMatch(String::isEmpty);
assertThat(linkUrls).anySatisfy(url -> assertThat(url).endsWith("/guide.html"));
}

@Test
void testWithMetadataTags() {
JsoupDocumentReader reader = new JsoupDocumentReader(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Test Relative Links</title>
</head>
<body>
<a href="guide.html">Relative link</a>
<a href="https://spring.io/">Absolute link</a>
</body>
</html>