-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathCustomLinkResolverSample.java
255 lines (225 loc) · 11.2 KB
/
CustomLinkResolverSample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package com.vladsch.flexmark.java.samples;
import com.vladsch.flexmark.ast.Image;
import com.vladsch.flexmark.ast.Link;
import com.vladsch.flexmark.ast.Reference;
import com.vladsch.flexmark.docx.converter.DocxRenderer;
import com.vladsch.flexmark.ext.jekyll.tag.JekyllTagBlock;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.html.HtmlRenderer.Builder;
import com.vladsch.flexmark.html.HtmlRenderer.HtmlRendererExtension;
import com.vladsch.flexmark.html.LinkResolver;
import com.vladsch.flexmark.html.LinkResolverFactory;
import com.vladsch.flexmark.html.renderer.*;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.data.DataKey;
import com.vladsch.flexmark.util.data.MutableDataHolder;
import com.vladsch.flexmark.util.data.MutableDataSet;
import com.vladsch.flexmark.util.misc.Utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class CustomLinkResolverSample {
final private static DataHolder OPTIONS = new MutableDataSet().set(Parser.EXTENSIONS, Collections.singletonList(CustomExtension.create()));
final public static DataKey<String> DOC_RELATIVE_URL = new DataKey<>("DOC_RELATIVE_URL", "");
final public static DataKey<String> DOC_ROOT_URL = new DataKey<>("DOC_ROOT_URL", "");
static final Parser PARSER = Parser.builder(OPTIONS).build();
static final HtmlRenderer RENDERER = HtmlRenderer.builder(OPTIONS).build();
public static class DocxLinkResolver implements LinkResolver {
final private String docRelativeURL;
final private String docRootURL;
final private String[] relativeParts;
final private boolean prefixWwwLinks;
public DocxLinkResolver(LinkResolverBasicContext context) {
// can use context for custom settings
String docRelativeURL = DocxRenderer.DOC_RELATIVE_URL.get(context.getOptions());
String docRootURL = DocxRenderer.DOC_ROOT_URL.get(context.getOptions());
this.docRelativeURL = docRelativeURL;
this.docRootURL = docRootURL;
docRelativeURL = Utils.removePrefix(docRelativeURL, '/');
relativeParts = docRelativeURL.split("/");
prefixWwwLinks = DocxRenderer.PREFIX_WWW_LINKS.get(context.getOptions());
}
@NotNull
@Override
public ResolvedLink resolveLink(@NotNull Node node, @NotNull LinkResolverBasicContext context, @NotNull ResolvedLink link) {
if (node instanceof Image || node instanceof Link || node instanceof Reference || node instanceof JekyllTagBlock) {
String url = link.getUrl();
if (docRelativeURL.isEmpty() && docRootURL.isEmpty()) {
// resolve url, return one of LinkStatus other than LinkStatus.UNKNOWN
return link.withStatus(LinkStatus.VALID)
.withUrl(url);
}
if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://") || url.startsWith("sftp://")) {
// resolve url, return one of LinkStatus other than LinkStatus.UNKNOWN
return link.withStatus(LinkStatus.VALID)
.withUrl(url);
} else if (url.startsWith("file:/")) {
// assume it is good
return link.withStatus(LinkStatus.VALID)
.withUrl(url);
} else if (url.startsWith(DocxRenderer.EMOJI_RESOURCE_PREFIX)) {
// assume it is good
return link.withStatus(LinkStatus.VALID)
.withUrl(url);
} else if (url.startsWith("/")) {
if (docRootURL != null && !docRootURL.isEmpty()) {
// this one is root url, prefix with root url, without the trailing /
url = docRootURL + url;
if (!url.startsWith("file:")) url = "file://" + url;
return link.withStatus(LinkStatus.VALID)
.withUrl(url);
}
} else if (prefixWwwLinks && url.startsWith("www.")) {
// should be prefixed with http://, we will just add it
return link.withStatus(LinkStatus.INVALID)
.withUrl("http://" + url);
} else if (!url.startsWith("data:") && !url.matches("^(?:[a-z]+:|#|\\?)")) {
// relative, we will process it as a relative path to the docRelativeURL
String pageRef = url;
String suffix = "";
int pos = url.indexOf('#');
if (pos == 0) {
return link.withStatus(LinkStatus.VALID);
} else {
if (pos > 0) {
// remove anchor
suffix = url.substring(pos);
pageRef = url.substring(0, pos);
} else if (url.contains("?")) {
// remove query
pos = url.indexOf("?");
suffix = url.substring(pos);
pageRef = url.substring(0, pos);
}
String[] pathParts = pageRef.split("/");
int docParts = relativeParts.length;
int iMax = pathParts.length;
StringBuilder resolved = new StringBuilder();
String sep = "";
for (int i = 0; i < iMax; i++) {
String part = pathParts[i];
if (part.equals(".")) {
// skp
} else if (part.equals("..")) {
// remove one doc part
if (docParts == 0) return link;
docParts--;
} else {
resolved.append(sep);
resolved.append(part);
sep = "/";
}
}
// prefix with remaining docParts
sep = docRelativeURL.startsWith("/") ? "/" : "";
StringBuilder resolvedPath = new StringBuilder();
iMax = docParts;
for (int i = 0; i < iMax; i++) {
resolvedPath.append(sep);
resolvedPath.append(relativeParts[i]);
sep = "/";
}
resolvedPath.append('/').append(resolved).append(suffix);
String resolvedUri = resolvedPath.toString();
if (!resolvedUri.startsWith("file:")) resolvedUri = "file://" + resolvedUri;
return link.withStatus(LinkStatus.VALID)
.withUrl(resolvedUri);
}
}
}
return link;
}
public static class Factory implements LinkResolverFactory {
@Nullable
@Override
public Set<Class<?>> getAfterDependents() {
return null;
}
@Nullable
@Override
public Set<Class<?>> getBeforeDependents() {
return null;
}
@Override
public boolean affectsGlobalScope() {
return false;
}
@NotNull
@Override
public LinkResolver apply(@NotNull LinkResolverBasicContext context) {
return new com.vladsch.flexmark.docx.converter.internal.DocxLinkResolver(context);
}
}
}
static class CustomExtension implements HtmlRendererExtension {
@Override
public void rendererOptions(@NotNull MutableDataHolder options) {
}
@Override
public void extend(@NotNull Builder htmlRendererBuilder, @NotNull String rendererType) {
htmlRendererBuilder.linkResolverFactory(new DocxLinkResolver.Factory());
htmlRendererBuilder.nodeRendererFactory(new CustomLinkRenderer.Factory());
}
static CustomExtension create() {
return new CustomExtension();
}
}
static class CustomLinkRenderer implements NodeRenderer {
public static class Factory implements DelegatingNodeRendererFactory {
@NotNull
@Override
public NodeRenderer apply(@NotNull DataHolder options) {
return new CustomLinkRenderer();
}
@Override
public Set<Class<?>> getDelegates() {
///Set<Class<?>>();
// add node renderer factory classes to which this renderer will delegate some of its rendering
// core node renderer is assumed to have all depend it so there is no need to add it
//set.add(WikiLinkNodeRenderer.Factory.class);
//return set;
// return null if renderer does not delegate or delegates only to core node renderer
return null;
}
}
@Override
public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() {
HashSet<NodeRenderingHandler<?>> set = new HashSet<>();
set.add(new NodeRenderingHandler<>(Link.class, (node, context, html) -> {
// test the node to see if it needs overriding
if (node.getText().equals("bar")) {
html.text("(eliminated)");
} else {
// otherwise pass it for default rendering
context.delegateRender();
}
}));
//set.add(new NodeRenderingHandler<WikiLink>(WikiLink.class, new CustomNodeRenderer<WikiLink>() {
// @Override
// public void render(WikiLink node, NodeRendererContext context, HtmlWriter html) {
// // test the node to see if it needs overriding
// Matcher matcher = CONFLUENCE_WIKI_LINK.matcher(node.getChars());
// if (matcher.find()) {
// String link = "...";
// html.raw(link);
// } else {
// // otherwise pass it for default rendering
// context.delegateRender();
// }
// }
//}));
return set;
}
}
// use the PARSER to parse and RENDERER to render with pegdown compatibility
public static void main(String[] args) {
// You can re-use parser and renderer instances
Node document = PARSER.parse("This is *Sparta* [[document]] and this is not a link [bar](/url)");
String html = RENDERER.render(document); // "<p>This is <em>Sparta</em> <a href="document.html">document</a> and this is not a link (eliminated)</p>\n"
System.out.println(html);
}
}