• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanodash / 42271484420

06 Nov 2026 06:31PM UTC coverage: 55.026% (+0.2%) from 54.813%
42271484420

push

github

web-flow
Merge pull request #896 from knowledgepixels/fix/startup-space-and-seed-locks

fix: fetch space roots in parallel and seed resources off the monitor

6637 of 12894 branches covered (51.47%)

Branch coverage included in aggregate %.

11456 of 19987 relevant lines covered (57.32%)

9.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.9
src/main/java/com/knowledgepixels/nanodash/Utils.java
1
package com.knowledgepixels.nanodash;
2

3
import com.google.common.hash.Hashing;
4
import com.knowledgepixels.nanodash.domain.User;
5
import net.trustyuri.TrustyUriUtils;
6
import org.apache.commons.codec.Charsets;
7
import org.apache.commons.lang.StringUtils;
8
import org.apache.http.client.config.RequestConfig;
9
import org.apache.http.client.utils.URIBuilder;
10
import org.apache.http.impl.client.CloseableHttpClient;
11
import org.apache.http.impl.client.HttpClientBuilder;
12
import org.apache.wicket.markup.html.link.ExternalLink;
13
import org.apache.wicket.model.IModel;
14
import org.apache.wicket.request.Url;
15
import com.google.common.cache.Cache;
16
import com.google.common.cache.CacheBuilder;
17
import org.apache.wicket.request.cycle.RequestCycle;
18
import org.apache.wicket.request.mapper.parameter.PageParameters;
19
import org.apache.wicket.util.string.StringValue;
20
import org.apache.wicket.util.string.Strings;
21
import org.eclipse.rdf4j.common.net.ParsedIRI;
22
import org.eclipse.rdf4j.model.IRI;
23
import org.eclipse.rdf4j.model.Literal;
24
import org.eclipse.rdf4j.model.Statement;
25
import org.eclipse.rdf4j.model.Value;
26
import org.eclipse.rdf4j.model.ValueFactory;
27
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
28
import org.eclipse.rdf4j.model.util.Literals;
29
import org.eclipse.rdf4j.model.vocabulary.FOAF;
30
import org.eclipse.rdf4j.model.vocabulary.RDF;
31
import org.eclipse.rdf4j.model.vocabulary.XSD;
32
import org.nanopub.Nanopub;
33
import org.nanopub.NanopubUtils;
34
import org.nanopub.UriSchemes;
35
import org.nanopub.extra.security.KeyDeclaration;
36
import org.nanopub.extra.security.MalformedCryptoElementException;
37
import org.nanopub.extra.security.NanopubSignatureElement;
38
import org.nanopub.extra.security.SignatureUtils;
39
import org.nanopub.extra.server.GetNanopub;
40
import org.nanopub.extra.server.NanopubServerUtils;
41
import org.nanopub.extra.server.PublishNanopub;
42
import org.nanopub.extra.services.ApiResponseEntry;
43
import org.nanopub.extra.services.NotEnoughAPIInstancesException;
44
import org.nanopub.extra.services.QueryCall;
45
import org.nanopub.extra.setting.IntroNanopub;
46
import org.nanopub.vocabulary.FIP;
47
import org.nanopub.vocabulary.NPX;
48
import org.owasp.html.Encoding;
49
import org.owasp.html.HtmlPolicyBuilder;
50
import org.owasp.html.PolicyFactory;
51
import org.slf4j.Logger;
52
import org.slf4j.LoggerFactory;
53
import org.wicketstuff.select2.Select2Choice;
54

55
import java.io.IOException;
56
import java.io.Serializable;
57
import java.math.BigDecimal;
58
import java.net.URI;
59
import java.net.URISyntaxException;
60
import java.net.URLDecoder;
61
import java.net.URLEncoder;
62
import java.nio.charset.StandardCharsets;
63
import java.time.LocalDateTime;
64
import java.time.OffsetDateTime;
65
import java.time.format.DateTimeFormatter;
66
import java.time.format.DateTimeParseException;
67
import java.util.*;
68
import java.util.concurrent.Callable;
69
import java.util.concurrent.ConcurrentHashMap;
70
import java.util.concurrent.ExecutionException;
71
import java.util.concurrent.ExecutorService;
72
import java.util.concurrent.Future;
73
import java.util.concurrent.LinkedBlockingQueue;
74
import java.util.concurrent.ThreadPoolExecutor;
75
import java.util.concurrent.TimeUnit;
76
import java.util.concurrent.atomic.AtomicInteger;
77
import java.util.function.Function;
78
import java.util.regex.Matcher;
79
import java.util.regex.Pattern;
80

81
import static java.nio.charset.StandardCharsets.UTF_8;
82

83
/**
84
 * Utility class providing various helper methods for handling nanopublications, URIs, and other related functionalities.
85
 */
86
public class Utils {
87

88
    private Utils() {
89
    }  // no instances allowed
90

91
    /**
92
     * ValueFactory instance for creating RDF model objects.
93
     */
94
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
6 ✔
95
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
9 ✔
96
    private static final Pattern LEADING_TAG = Pattern.compile("^\\s*<(p|div|span|img|pre|svg)(\\s|>|/).*", Pattern.CASE_INSENSITIVE);
12 ✔
97
    private static final String DEFAULT_MAIN_QUERY_URL = "https://query.knowledgepixels.com/";
98
    private static final String DEFAULT_MAIN_REGISTRY_URL = "https://registry.knowledgepixels.com/";
99

100
    /**
101
     * Generates a short name from a given IRI object.
102
     *
103
     * @param uri the IRI object
104
     * @return a short representation of the URI
105
     */
106
    public static String getShortNameFromURI(IRI uri) {
107
        return getShortNameFromURI(uri.stringValue());
12 ✔
108
    }
109

110
    /**
111
     * Generates a short name from a given URI string.
112
     *
113
     * @param uri the URI string
114
     * @return a short representation of the URI
115
     */
116
    public static String getShortNameFromURI(String uri) {
117
        if (uri.startsWith("https://doi.org/") || uri.startsWith("http://dx.doi.org/")) {
24 ✔
118
            return uri.replaceFirst("^https?://(dx\\.)?doi.org/", "doi:");
15 ✔
119
        }
120
        String nonHierarchicalName = getNonHierarchicalShortName(uri);
9 ✔
121
        if (nonHierarchicalName != null) return nonHierarchicalName;
12 ✔
122
        uri = uri.replaceFirst("\\?.*$", "");
15 ✔
123
        uri = uri.replaceFirst("[/#]$", "");
15 ✔
124
        uri = uri.replaceFirst("^.*[/#]([^/#]*)[/#]([0-9]+)$", "$1/$2");
15 ✔
125
        if (uri.contains("#")) {
12 ✔
126
            uri = uri.replaceFirst("^.*#(.*[^0-9].*)$", "$1");
18 ✔
127
        } else {
128
            uri = uri.replaceFirst("^.*/([^/]*[^0-9/][^/]*)$", "$1");
15 ✔
129
        }
130
        uri = uri.replaceFirst("((^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{8})[A-Za-z0-9\\-_]{35}$", "$1");
15 ✔
131
        uri = uri.replaceFirst("(^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{43}[^A-Za-z0-9\\-_](.+)$", "$2");
15 ✔
132
        uri = URLDecoder.decode(uri, UTF_8);
12 ✔
133
        return uri;
6 ✔
134
    }
135

136
    // Length below which an identifier is shown whole rather than elided.
137
    private static final int SHORT_NAME_ELISION_THRESHOLD = 14;
138

139
    /**
140
     * Short label for the URI schemes whose identifiers are opaque rather than hierarchical
141
     * (issue #655). The general logic in {@link #getShortNameFromURI(String)} splits on "/" and
142
     * "#", which a DID has neither of, and which leaves a bare CID as a 59-character "short"
143
     * name. The scheme is kept — it is the part that says what kind of thing this is — and the
144
     * identifier is elided in the middle, keeping its start (for a CID, the multibase and codec
145
     * prefix) and its end (enough to tell two of them apart).
146
     *
147
     * @param uri the URI to shorten
148
     * @return the short label, or null if the URI is hierarchical and handled by the caller
149
     */
150
    private static String getNonHierarchicalShortName(String uri) {
151
        String scheme = UriSchemes.getScheme(uri);
9 ✔
152
        if (scheme == null) return null;
6 !
153
        if (scheme.equals("ipfs") || scheme.equals("ipns")) {
24 ✔
154
            String id = uri.substring(scheme.length() + 1).replaceFirst("^//", "");
30 ✔
155
            // A path under the CID is hierarchical after all, so the general rules apply.
156
            if (id.contains("/")) return null;
18 ✔
157
            return scheme + ":" + elideMiddle(id);
15 ✔
158
        }
159
        if (scheme.equals("did")) {
12 ✔
160
            // did:<method>:<method-specific-id> -- the method is short and meaningful, so only
161
            // the identifier after it is elided.
162
            String rest = uri.substring(4);
12 ✔
163
            int colon = rest.indexOf(':');
12 ✔
164
            if (colon < 1) return "did:" + elideMiddle(rest);
9 !
165
            return "did:" + rest.substring(0, colon + 1) + elideMiddle(rest.substring(colon + 1));
42 ✔
166
        }
167
        if (scheme.equals("at")) {
12 ✔
168
            // at://<did>/<collection>/<rkey> -- the record key identifies the record, and is
169
            // what the general rules would pick out too, but they choke on a URI without a path.
170
            String rest = uri.substring(3).replaceFirst("^//", "");
21 ✔
171
            int lastSlash = rest.lastIndexOf('/');
12 ✔
172
            if (lastSlash >= 0) return "at:" + rest.substring(lastSlash + 1);
27 ✔
173
            // No record key: what is left is the repository, which is a DID, so it shortens by
174
            // the rule above rather than being elided as one opaque blob.
175
            String repository = getNonHierarchicalShortName(rest);
9 ✔
176
            return "at:" + (repository != null ? repository : elideMiddle(rest));
18 !
177
        }
178
        return null;
6 ✔
179
    }
180

181
    private static String elideMiddle(String id) {
182
        if (id.length() <= SHORT_NAME_ELISION_THRESHOLD) return id;
18 ✔
183
        return id.substring(0, 4) + "…" + id.substring(id.length() - 4);
36 ✔
184
    }
185

186
    /**
187
     * Generates a short nanopublication ID from a given nanopublication ID or URI.
188
     *
189
     * @param npId the nanopublication ID or URI
190
     * @return the first 10 characters of the artifact code
191
     */
192
    public static String getShortNanopubId(Object npId) {
193
        return TrustyUriUtils.getArtifactCode(npId.toString()).substring(0, 10);
21 ✔
194
    }
195

196
    // Nanopublications are immutable, so a cached one never goes out of date and the only
197
    // reason to drop one is to keep the cache from growing without end — which it used to,
198
    // being a plain map that never evicted. Bounded like the query caches in ApiCache, and
199
    // concurrent, as retrieval also happens on background threads (see NanopubLookup).
200
    private static final int MAX_CACHED_NANOPUBS = 10_000;
201

202
    private static final Cache<String, Nanopub> nanopubs = CacheBuilder.newBuilder()
6 ✔
203
            .maximumSize(MAX_CACHED_NANOPUBS)
9 ✔
204
            .expireAfterAccess(24, TimeUnit.HOURS)
3 ✔
205
            .build();
6 ✔
206

207
    // Registry fetches go through our own client rather than the library's shared one
208
    // (NanopubUtils.getHttpClient), which allows 10 seconds for each of connecting, reading
209
    // and waiting for a pooled connection — up to 30 seconds for a single fetch, on a thread
210
    // that may be rendering a page. These bounds are tighter, and in particular a saturated
211
    // pool fails fast here instead of queueing threads up behind it.
212
    private static final int REGISTRY_CONNECT_TIMEOUT_MS = 5_000;
213
    private static final int REGISTRY_SOCKET_TIMEOUT_MS = 10_000;
214
    private static final int REGISTRY_CONNECTION_REQUEST_TIMEOUT_MS = 2_000;
215

216
    private static final CloseableHttpClient registryHttpClient = HttpClientBuilder.create()
3 ✔
217
            .setDefaultRequestConfig(RequestConfig.custom()
12 ✔
218
                    .setConnectTimeout(REGISTRY_CONNECT_TIMEOUT_MS)
6 ✔
219
                    .setSocketTimeout(REGISTRY_SOCKET_TIMEOUT_MS)
6 ✔
220
                    .setConnectionRequestTimeout(REGISTRY_CONNECTION_REQUEST_TIMEOUT_MS)
3 ✔
221
                    .build())
3 ✔
222
            .setMaxConnTotal(64)
6 ✔
223
            .setMaxConnPerRoute(16)
3 ✔
224
            .build();
6 ✔
225

226
    /**
227
     * The HTTP client to use for registry requests: same behaviour as the library's shared
228
     * one, but with tighter timeouts (see {@link #getNanopub(String)}).
229
     *
230
     * @return the shared registry HTTP client
231
     */
232
    public static CloseableHttpClient getRegistryHttpClient() {
233
        return registryHttpClient;
×
234
    }
235

236
    /**
237
     * The current nanopub cache content, for persisting across restarts (issue #570; see
238
     * {@link ApiCachePersistence}). Nanopubs are immutable, so unlike the query responses
239
     * they carry no staleness concerns at all.
240
     *
241
     * @return a copy of the cached nanopubs, keyed by artifact code
242
     */
243
    static Map<String, Nanopub> exportCachedNanopubs() {
244
        return new HashMap<>(nanopubs.asMap());
18 ✔
245
    }
246

247
    /**
248
     * Restores previously exported nanopubs into the cache, skipping any that are already
249
     * cached. Meant to run once at startup, before the instance serves requests.
250
     *
251
     * @param map the nanopubs to restore, keyed by artifact code
252
     * @return the number of restored nanopubs
253
     */
254
    static int importCachedNanopubs(Map<String, Nanopub> map) {
255
        int count = 0;
6 ✔
256
        for (Map.Entry<String, Nanopub> e : map.entrySet()) {
33 ✔
257
            if (e.getKey() == null || e.getValue() == null) continue;
18 !
258
            if (nanopubs.getIfPresent(e.getKey()) != null) continue;
15 !
259
            nanopubs.put(e.getKey(), e.getValue());
24 ✔
260
            count++;
3 ✔
261
        }
3 ✔
262
        return count;
6 ✔
263
    }
264

265
    /**
266
     * Adds a nanopublication to the local cache so it can be retrieved immediately
267
     * without needing to fetch it from the registry.
268
     *
269
     * @param np the nanopublication to cache
270
     */
271
    public static void cacheNanopub(Nanopub np) {
272
        String artifactCode = GetNanopub.getArtifactCode(np.getUri().stringValue()).toString();
18 ✔
273
        nanopubs.put(artifactCode, np);
12 ✔
274
    }
3 ✔
275

276
    /**
277
     * Publishes a nanopublication, choosing where it goes.
278
     * <p>
279
     * A protected nanopublication has exactly one possible destination: the local instance this
280
     * Nanodash is configured against, which has already been checked to report itself as one (see
281
     * {@link ProtectedNanopubs#isOffered()}). Naming it directly means {@code NANODASH_MAIN_REGISTRY}
282
     * is enough on such a deployment, instead of also needing {@code NANOPUB_REGISTRY_INSTANCES} to
283
     * steer the library's own dispatch list (#671, #680).
284
     * <p>
285
     * Everything else goes to that list as before, and deliberately so: registries pull from their
286
     * peers rather than pushing to them, so an openly published nanopublication sent only to a
287
     * private registry would never reach the public network — the opposite of what publishing it
288
     * unprotected means.
289
     *
290
     * @param signedNp the signed nanopublication to publish
291
     * @return the URL the nanopublication was published at
292
     * @throws IOException if publishing fails
293
     */
294
    public static String publishNanopub(Nanopub signedNp) throws IOException {
295
        if (ProtectedNanopubs.isProtected(signedNp) && ProtectedNanopubs.isOffered()) {
15 ✔
296
            String registryUrl = getMainRegistryUrl();
6 ✔
297
            logger.info("Publishing protected nanopublication to the configured local instance: {}", registryUrl);
12 ✔
298
            return PublishNanopub.publish(signedNp, registryUrl);
12 ✔
299
        }
300
        return PublishNanopub.publish(signedNp);
9 ✔
301
    }
302

303
    /**
304
     * Retrieves a Nanopub object based on the given URI or artifact code.
305
     *
306
     * @param uriOrArtifactCode the URI or artifact code of the nanopublication
307
     * @return the Nanopub object, or null if not found
308
     */
309
    public static Nanopub getNanopub(String uriOrArtifactCode) {
310
        String artifactCode = GetNanopub.getArtifactCode(uriOrArtifactCode).toString();
12 ✔
311
        Nanopub cached = nanopubs.getIfPresent(artifactCode);
15 ✔
312
        if (cached != null) return cached;
12 ✔
313
        // A request thread gets one attempt: the retries are there to ride out a flaky
314
        // registry, and doing that while a user waits only multiplies the time they spend
315
        // looking at nothing. Background threads keep the full three.
316
        int attempts = RequestCycle.get() != null ? 1 : 3;
18 ✔
317
        for (int i = 0; i < attempts; i++) {
21 ✔
318
            Nanopub np = GetNanopub.get(artifactCode, registryHttpClient);
12 ✔
319
            if (np != null) {
6 ✔
320
                nanopubs.put(artifactCode, np);
12 ✔
321
                return np;
6 ✔
322
            }
323
        }
324
        return null;
6 ✔
325
    }
326

327
    // How many nanopubs getNanopubs fetches at a time: enough to turn a startup's few hundred
328
    // fetches into a matter of seconds, while leaving half of the registry client's
329
    // connections per registry (setMaxConnPerRoute above) to everything else.
330
    private static final int PARALLEL_FETCHES = 8;
331

332
    private static final ExecutorService fetchExecutor = newFetchExecutor();
6 ✔
333

334
    private static ExecutorService newFetchExecutor() {
335
        AtomicInteger count = new AtomicInteger();
12 ✔
336
        ThreadPoolExecutor executor = new ThreadPoolExecutor(PARALLEL_FETCHES, PARALLEL_FETCHES,
39 ✔
337
                30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), task -> {
338
            Thread thread = new Thread(task, "nanodash-fetch-" + count.incrementAndGet());
24 ✔
339
            thread.setDaemon(true);
9 ✔
340
            return thread;
6 ✔
341
        });
342
        // Idle between builds, which is most of the time.
343
        executor.allowCoreThreadTimeOut(true);
9 ✔
344
        return executor;
6 ✔
345
    }
346

347
    /**
348
     * Retrieves several nanopublications, fetching those not cached several at a time
349
     * rather than one after the other, and returns once each has been tried. For building
350
     * something out of many nanopubs at once: the spaces after a restart need a few hundred,
351
     * and fetching them one by one kept every page waiting for minutes (issue #892).
352
     *
353
     * @param ids the URIs of the nanopublications
354
     * @return the nanopublications found, keyed by the URI they were asked for; a URI that is
355
     * not a nanopublication's, or whose nanopublication could not be fetched, is missing
356
     */
357
    public static Map<String, Nanopub> getNanopubs(Collection<String> ids) {
358
        return getNanopubs(ids, Utils::getAsNanopub);
12 ✔
359
    }
360

361
    static Map<String, Nanopub> getNanopubs(Collection<String> ids, Function<String, Nanopub> fetch) {
362
        Map<String, Nanopub> found = new HashMap<>();
12 ✔
363
        List<String> toFetch = new ArrayList<>();
12 ✔
364
        for (String id : new LinkedHashSet<>(ids)) {
39 ✔
365
            if (id == null || !TrustyUriUtils.isPotentialTrustyUri(id)) continue;
18 !
366
            Nanopub cached = nanopubs.getIfPresent(GetNanopub.getArtifactCode(id).toString());
21 ✔
367
            if (cached != null) {
6 ✔
368
                found.put(id, cached);
18 ✔
369
            } else {
370
                toFetch.add(id);
12 ✔
371
            }
372
        }
3 ✔
373
        if (toFetch.size() == 1) {
12 ✔
374
            Nanopub np = fetch.apply(toFetch.getFirst());
21 ✔
375
            if (np != null) found.put(toFetch.getFirst(), np);
27 !
376
        } else if (!toFetch.isEmpty()) {
12 !
377
            List<Callable<Nanopub>> tasks = new ArrayList<>();
12 ✔
378
            for (String id : toFetch) tasks.add(() -> fetch.apply(id));
66 ✔
379
            try {
380
                List<Future<Nanopub>> results = fetchExecutor.invokeAll(tasks);
12 ✔
381
                for (int i = 0; i < results.size(); i++) {
24 ✔
382
                    try {
383
                        Nanopub np = results.get(i).get();
21 ✔
384
                        if (np != null) found.put(toFetch.get(i), np);
30 ✔
385
                    } catch (ExecutionException ex) {
×
386
                        logger.error("Could not fetch nanopublication {}", toFetch.get(i), ex.getCause());
×
387
                    }
3 ✔
388
                }
389
            } catch (InterruptedException ex) {
×
390
                Thread.currentThread().interrupt();
×
391
            }
3 ✔
392
        }
393
        return found;
6 ✔
394
    }
395

396
    /**
397
     * Strips a sub-IRI of a nanopublication (e.g. an embedded resource IRI like
398
     * {@code <np-uri>/template}) down to the nanopublication ID itself, i.e. up to
399
     * and including the trusty artifact code. An ID without a sub-path is returned
400
     * unchanged.
401
     *
402
     * @param id the ID to strip
403
     * @return the nanopublication ID
404
     */
405
    public static String stripToNanopubId(String id) {
406
        return id.replaceFirst("^(.*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43})[^A-Za-z0-9-_].*$", "$1");
15 ✔
407
    }
408

409
    // Wicket URL-encodes the session into a path parameter when the client has not (yet)
410
    // returned a cookie. Harmless for a link the browser follows, poisonous for a URL that
411
    // outlives the request — see absolutePageUrl.
412
    private static final Pattern JSESSIONID_PATTERN = Pattern.compile(";jsessionid=[^?/;]*", Pattern.CASE_INSENSITIVE);
12 ✔
413

414
    // Splits an absolute URL into its origin (scheme and authority) and everything after it.
415
    private static final Pattern ORIGIN_PATTERN = Pattern.compile("^([a-zA-Z][a-zA-Z0-9+.\\-]*://[^/?#]*)(.*)$");
9 ✔
416

417
    /**
418
     * The absolute URL of a mounted page, for handing to something outside this request:
419
     * embedding in a downloaded file, giving to a third-party service to fetch, or showing
420
     * the user to copy.
421
     *
422
     * <p>Any {@code ;jsessionid=} Wicket added is stripped. Such a URL is not merely ugly —
423
     * it is bound to one visitor's session, so a calendar feed URL carrying one would break
424
     * once the session expired, and would hand out a live session identifier to anyone the
425
     * user shared it with.</p>
426
     *
427
     * <p>The host comes from the configured website URL where there is one, not from the
428
     * request. Behind a reverse proxy the request reveals only how the proxy reached this
429
     * container — {@code http://127.0.1.1:37373/} — which is useless to a calendar client or
430
     * to Google, both of which have to fetch the URL themselves from outside.</p>
431
     *
432
     * @param pageClass the mounted page
433
     * @param params    the page parameters
434
     * @return the full URL, including scheme and host
435
     */
436
    public static String absolutePageUrl(Class<? extends org.apache.wicket.Page> pageClass, PageParameters params) {
437
        RequestCycle cycle = RequestCycle.get();
6 ✔
438
        String url = cycle.urlFor(pageClass, params).toString();
18 ✔
439
        String requestUrl = stripSessionId(cycle.getUrlRenderer().renderFullUrl(Url.parse(url)));
21 ✔
440
        return rebaseOnWebsiteUrl(requestUrl, NanodashPreferences.get().getConfiguredWebsiteUrl());
15 ✔
441
    }
442

443
    /**
444
     * Moves a request-derived absolute URL onto the address this instance is published at.
445
     *
446
     * <p>Only the origin is taken from the website URL; the path and query stay as Wicket
447
     * rendered them, so the mount paths remain the single source of truth for where a page
448
     * lives. A website URL that carries a path of its own (an instance published under
449
     * {@code /nanodash/}, say) has it prefixed, unless the request path already includes it
450
     * because the servlet container is mounted there too.</p>
451
     *
452
     * @param requestUrl the absolute URL derived from the current request
453
     * @param websiteUrl the configured website URL, or null when this instance has none
454
     * @return the URL rebased on the website URL, or {@code requestUrl} unchanged if there is
455
     *         no usable website URL
456
     */
457
    static String rebaseOnWebsiteUrl(String requestUrl, String websiteUrl) {
458
        if (websiteUrl == null || websiteUrl.isBlank()) return requestUrl;
21 ✔
459
        Matcher website = ORIGIN_PATTERN.matcher(websiteUrl.trim());
15 ✔
460
        Matcher request = ORIGIN_PATTERN.matcher(requestUrl);
12 ✔
461
        if (!website.matches() || !request.matches()) {
18 !
462
            logger.warn("Cannot rebase '{}' on website URL '{}'; leaving it as it is", requestUrl, websiteUrl);
15 ✔
463
            return requestUrl;
6 ✔
464
        }
465
        String prefix = website.group(2).replaceFirst("[?#].*$", "").replaceFirst("/+$", "");
30 ✔
466
        String rest = request.group(2);
12 ✔
467
        boolean alreadyPrefixed = rest.equals(prefix) || rest.startsWith(prefix + "/")
36 !
468
                || rest.startsWith(prefix + "?") || rest.startsWith(prefix + "#");
33 !
469
        return website.group(1) + (alreadyPrefixed ? "" : prefix) + rest;
33 ✔
470
    }
471

472
    /**
473
     * Removes a {@code ;jsessionid=...} path parameter from a URL. See
474
     * {@link #absolutePageUrl} for why this must happen before a URL leaves the request.
475
     *
476
     * @param url the URL, possibly session-decorated
477
     * @return the URL without its session id
478
     */
479
    static String stripSessionId(String url) {
480
        return JSESSIONID_PATTERN.matcher(url).replaceAll("");
18 ✔
481
    }
482

483
    /**
484
     * URL-encodes the string representation of the given object using UTF-8 encoding.
485
     *
486
     * @param o the object to be URL-encoded
487
     * @return the URL-encoded string
488
     */
489
    public static String urlEncode(Object o) {
490
        return URLEncoder.encode((o == null ? "" : o.toString()), Charsets.UTF_8);
27 ✔
491
    }
492

493
    public static String truncateLabel(String label) {
494
        if (label != null && label.length() > 120) {
18 !
495
            return label.substring(0, 100) + "...";
×
496
        }
497
        return label;
6 ✔
498
    }
499

500
    /**
501
     * Truncates an over-long entity label for display in a link or breadcrumb:
502
     * labels longer than 60 characters are cut to 47 characters with an ellipsis
503
     * ("...") appended, so a single long label (e.g. a full IRI tail) never blows
504
     * up the surrounding UI. Shorter labels are returned unchanged. The full label
505
     * stays available on the entity's own page, which shows it as the title.
506
     *
507
     * @param label the label to truncate, or null
508
     * @return the truncated label, or the original if 60 characters or shorter
509
     */
510
    public static String truncateLinkLabel(String label) {
511
        if (label == null || label.length() <= 60) {
18 ✔
512
            return label;
6 ✔
513
        }
514
        return label.substring(0, 47).stripTrailing() + "...";
21 ✔
515
    }
516

517
    /**
518
     * Builds the HTML body for a menu entry whose label may begin with a leading
519
     * symbol/emoji used as the entry's icon. If {@code label} starts with a token
520
     * of symbol/emoji characters (no letters or digits) followed by whitespace,
521
     * that token is wrapped in the {@code .actionmenu-icon} slot and the remaining
522
     * text follows it (both escaped). Returns {@code null} when there is no such
523
     * leading icon, so callers can fall back to the plain (escaped) label.
524
     *
525
     * @param label the menu entry label
526
     * @return the icon+text HTML body to render with escaping disabled, or null
527
     */
528
    public static String menuEntryIconBodyHtml(String label) {
529
        if (label == null) {
×
530
            return null;
×
531
        }
532
        int sp = -1;
×
533
        for (int i = 0; i < label.length(); i++) {
×
534
            if (Character.isWhitespace(label.charAt(i))) {
×
535
                sp = i;
×
536
                break;
×
537
            }
538
        }
539
        if (sp <= 0) {
×
540
            return null;
×
541
        }
542
        String icon = label.substring(0, sp);
×
543
        String rest = label.substring(sp).replaceFirst("^\\s+", "");
×
544
        if (rest.isEmpty()) {
×
545
            return null;
×
546
        }
547
        // Only a pure symbol/emoji token (no letters or digits) counts as an icon.
548
        if (icon.codePoints().anyMatch(Character::isLetterOrDigit)) {
×
549
            return null;
×
550
        }
551
        return "<span class=\"actionmenu-icon\">" + Strings.escapeMarkup(icon) + "</span>" + Strings.escapeMarkup(rest);
×
552
    }
553

554
    /**
555
     * URL-decodes the string representation of the given object using UTF-8 encoding.
556
     *
557
     * @param o the object to be URL-decoded
558
     * @return the URL-decoded string
559
     */
560
    public static String urlDecode(Object o) {
561
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
27 ✔
562
    }
563

564
    /**
565
     * Generates a URL with the given base and appends the provided PageParameters as query parameters.
566
     *
567
     * @param base       the base URL
568
     * @param parameters the PageParameters to append
569
     * @return the complete URL with parameters
570
     */
571
    public static String getUrlWithParameters(String base, PageParameters parameters) {
572
        try {
573
            URIBuilder u = new URIBuilder(base);
15 ✔
574
            for (String key : parameters.getNamedKeys()) {
33 ✔
575
                for (StringValue value : parameters.getValues(key)) {
36 ✔
576
                    if (!value.isNull()) {
9 !
577
                        u.addParameter(key, value.toString());
18 ✔
578
                    }
579
                }
3 ✔
580
            }
3 ✔
581
            return u.build().toString();
12 ✔
582
        } catch (URISyntaxException ex) {
3 ✔
583
            logger.error("Could not build URL with parameters: {} {}", base, parameters, ex);
51 ✔
584
            return "/";
6 ✔
585
        }
586
    }
587

588
    /**
589
     * Generates a short name for a public key or public key hash.
590
     *
591
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
592
     * @return a short representation of the public key or public key hash
593
     */
594
    public static String getShortPubkeyName(String pubkeyOrPubkeyhash) {
595
        if (pubkeyOrPubkeyhash.length() == 64) {
12 !
596
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
597
        } else {
598
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
15 ✔
599
        }
600
    }
601

602
    /**
603
     * Generates a short label for a public key or public key hash, including its status (local or approved).
604
     *
605
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
606
     * @param user               the IRI of the user associated with the public key
607
     * @return a short label indicating the public key and its status
608
     */
609
    public static String getShortPubkeyhashLabel(String pubkeyOrPubkeyhash, IRI user) {
610
        String s = getShortPubkeyName(pubkeyOrPubkeyhash);
×
611
        NanodashSession session = NanodashSession.get();
×
612
        List<String> l = new ArrayList<>();
×
613
        if (pubkeyOrPubkeyhash.equals(session.getPubkeyString()) || pubkeyOrPubkeyhash.equals(session.getPubkeyhash())) {
×
614
            l.add("local");
×
615
        }
616
        // TODO: Make this more efficient:
617
        String hashed = Utils.createSha256HexHash(pubkeyOrPubkeyhash);
×
618
        if (User.getPubkeyhashes(user, true).contains(pubkeyOrPubkeyhash) || User.getPubkeyhashes(user, true).contains(hashed)) {
×
619
            l.add("approved");
×
620
        }
621
        if (!l.isEmpty()) {
×
622
            s += " (" + String.join("/", l) + ")";
×
623
        }
624
        return s;
×
625
    }
626

627
    /**
628
     * Retrieves the name of the public key location based on the public key.
629
     *
630
     * @param pubkeyhash the public key string
631
     * @return the name of the public key location
632
     */
633
    public static String getPubkeyLocationName(String pubkeyhash) {
634
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
635
    }
636

637
    /**
638
     * Retrieves the name of the public key location, or returns a fallback name if not found.
639
     * If the key location is localhost, it returns "localhost".
640
     *
641
     * @param pubkeyhash the public key string
642
     * @param fallback   the fallback name to return if the key location is not found
643
     * @return the name of the public key location or the fallback name
644
     */
645
    public static String getPubkeyLocationName(String pubkeyhash, String fallback) {
646
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
647
        if (keyLocation == null) {
×
648
            return fallback;
×
649
        }
650
        if (keyLocation.stringValue().equals("http://localhost:37373/")) {
×
651
            return "localhost";
×
652
        }
653
        return keyLocation.stringValue().replaceFirst("https?://(nanobench\\.)?(nanodash\\.(?=.*\\..))?(.*[^/])/?$", "$3");
×
654
    }
655

656
    /**
657
     * Generates a short label for a public key location, including its status (local or approved).
658
     *
659
     * @param pubkeyhash the public key string
660
     * @param user       the IRI of the user associated with the public key
661
     * @return a short label indicating the public key location and its status
662
     */
663
    public static String getShortPubkeyLocationLabel(String pubkeyhash, IRI user) {
664
        String s = getPubkeyLocationName(pubkeyhash);
×
665
        NanodashSession session = NanodashSession.get();
×
666
        List<String> l = new ArrayList<>();
×
667
        if (pubkeyhash.equals(session.getPubkeyhash())) {
×
668
            l.add("local");
×
669
        }
670
        // TODO: Make this more efficient:
671
        if (User.getPubkeyhashes(user, true).contains(pubkeyhash)) {
×
672
            l.add("approved");
×
673
        }
674
        if (!l.isEmpty()) {
×
675
            s += " (" + String.join("/", l) + ")";
×
676
        }
677
        return s;
×
678
    }
679

680
    /**
681
     * Checks if a given public key has a Nanodash location.
682
     * A Nanodash location is identified by specific keywords in the key location.
683
     *
684
     * @param pubkeyhash the public key to check
685
     * @return true if the public key has a Nanodash location, false otherwise
686
     */
687
    public static boolean hasNanodashLocation(String pubkeyhash) {
688
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
689
        if (keyLocation == null) {
×
690
            return true; // potentially a Nanodash location
×
691
        }
692
        if (keyLocation.stringValue().contains("nanodash")) {
×
693
            return true;
×
694
        }
695
        if (keyLocation.stringValue().contains("nanobench")) {
×
696
            return true;
×
697
        }
698
        if (keyLocation.stringValue().contains(":37373")) {
×
699
            return true;
×
700
        }
701
        return false;
×
702
    }
703

704
    /**
705
     * Retrieves the short ORCID ID from an IRI object.
706
     *
707
     * @param orcidIri the IRI object representing the ORCID ID
708
     * @return the short ORCID ID as a string
709
     */
710
    public static String getShortOrcidId(IRI orcidIri) {
711
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
18 ✔
712
    }
713

714
    /**
715
     * Retrieves the URI postfix from a given URI object.
716
     *
717
     * @param uri the URI object from which to extract the postfix
718
     * @return the URI postfix as a string
719
     */
720
    public static String getUriPostfix(Object uri) {
721
        String s = uri.toString();
9 ✔
722
        if (s.contains("#")) {
12 ✔
723
            return s.replaceFirst("^.*#(.*)$", "$1");
15 ✔
724
        }
725
        return s.replaceFirst("^.*/(.*)$", "$1");
15 ✔
726
    }
727

728
    /**
729
     * Retrieves the URI prefix from a given URI object.
730
     *
731
     * @param uri the URI object from which to extract the prefix
732
     * @return the URI prefix as a string
733
     */
734
    public static String getUriPrefix(Object uri) {
735
        String s = uri.toString();
9 ✔
736
        if (s.contains("#")) {
12 ✔
737
            return s.replaceFirst("^(.*#).*$", "$1");
15 ✔
738
        }
739
        return s.replaceFirst("^(.*/).*$", "$1");
15 ✔
740
    }
741

742
    /**
743
     * Checks if a given string is a valid URI postfix.
744
     * A valid URI postfix does not contain a colon (":").
745
     *
746
     * @param s the string to check
747
     * @return true if the string is a valid URI postfix, false otherwise
748
     */
749
    public static boolean isUriPostfix(String s) {
750
        return !s.contains(":");
24 ✔
751
    }
752

753
    /**
754
     * Retrieves the location of a given IntroNanopub.
755
     *
756
     * @param inp the IntroNanopub from which to extract the location
757
     * @return the IRI location of the nanopublication, or null if not found
758
     */
759
    public static IRI getLocation(IntroNanopub inp) {
760
        NanopubSignatureElement el = getNanopubSignatureElement(inp);
×
761
        for (KeyDeclaration kd : inp.getKeyDeclarations()) {
×
762
            if (el.getPublicKeyString().equals(kd.getPublicKeyString())) {
×
763
                return kd.getKeyLocation();
×
764
            }
765
        }
×
766
        return null;
×
767
    }
768

769
    /**
770
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
771
     *
772
     * @param inp the IntroNanopub from which to extract the signature element
773
     * @return the NanopubSignatureElement associated with the nanopublication
774
     */
775
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
776
        try {
777
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
778
        } catch (MalformedCryptoElementException ex) {
×
779
            throw new RuntimeException(ex);
×
780
        }
781
    }
782

783
    /**
784
     * Retrieves a Nanopub object from a given URI if it is a potential Trusty URI.
785
     *
786
     * @param uri the URI to check and retrieve the Nanopub from
787
     * @return the Nanopub object if found, or null if not a known nanopublication
788
     */
789
    public static Nanopub getAsNanopub(String uri) {
790
        if (uri == null) {
6 !
791
            return null;
×
792
        }
793
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
9 ✔
794
            try {
795
                return Utils.getNanopub(uri);
9 ✔
796
            } catch (Exception ex) {
×
797
                logger.error("The given URI is not a known nanopublication: {}", uri, ex);
×
798
            }
799
        }
800
        return null;
6 ✔
801
    }
802

803
    // A conservative static-SVG subset: basic shapes, text, grouping, and links.
804
    // Everything not allowed is dropped — in particular script/foreignObject/style
805
    // and all event handlers, plus use/image, whose href would reach outside the
806
    // sanitized document. Used by SVG views (QueryResultSvg) and, folded into the
807
    // HTML policy below, by inline SVG in HTML snippets coming from queries.
808
    // Attribute-name matching is case-sensitive and the matched spelling is emitted
809
    // verbatim, so the camelCase SVG attributes are listed in both spellings
810
    // (browsers also map the lowercase form back via the SVG attribute-adjustment
811
    // table, but the camelCase form works everywhere, including XML contexts).
812
    private static final String[] SVG_ELEMENTS = {"svg", "g", "defs", "marker", "title", "desc",
189 ✔
813
            "rect", "circle", "ellipse", "line", "polyline", "polygon", "path", "text", "tspan"};
814

815
    // The SVG elements plus the link element they can be wrapped in, which is
816
    // shared with HTML and therefore allowed separately by each policy.
817
    private static final String[] SVG_ELEMENTS_WITH_LINK = concat(SVG_ELEMENTS, "a");
27 ✔
818

819
    private static final String[] SVG_ATTRIBUTES = {"viewbox", "viewBox", "width", "height",
705 ✔
820
            "preserveaspectratio", "preserveAspectRatio", "xmlns",
821
            "x", "y", "x1", "y1", "x2", "y2", "cx", "cy", "r", "rx", "ry",
822
            "d", "points", "dx", "dy", "transform",
823
            "fill", "fill-opacity", "fill-rule",
824
            "stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
825
            "stroke-linejoin", "stroke-dasharray", "stroke-dashoffset",
826
            "stroke-miterlimit", "clip-rule", "opacity",
827
            "font-family", "font-size", "font-weight", "font-style",
828
            "text-anchor", "dominant-baseline", "text-decoration",
829
            "marker-start", "marker-mid", "marker-end",
830
            "markerwidth", "markerWidth", "markerheight", "markerHeight",
831
            "refx", "refX", "refy", "refY", "orient", "markerunits", "markerUnits",
832
            "id"};
833

834
    // Drawing tools export SVG with the paint in a style attribute
835
    // (style="fill:rgb(120,184,134);") rather than in presentation attributes. The
836
    // sanitizer allows no style attribute -- it is the one attribute whose value can pull
837
    // in external resources -- so those declarations used to be dropped, and every shape
838
    // fell back to the SVG default fill: an all-black figure. They are therefore rewritten
839
    // into the equivalent presentation attributes first, which the existing allow-list
840
    // then validates like any other: nothing new is allowed through, and a declaration
841
    // whose property is not on the list (or whose value could reference something, i.e.
842
    // contains a function call other than a colour) is dropped as before.
843
    private static final Set<String> STYLE_PROPERTIES_AS_ATTRIBUTES = Set.of(
252 ✔
844
            "fill", "fill-opacity", "fill-rule",
845
            "stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
846
            "stroke-linejoin", "stroke-dasharray", "stroke-dashoffset",
847
            "stroke-miterlimit", "clip-rule", "opacity",
848
            "font-family", "font-size", "font-weight", "font-style",
849
            "text-anchor", "dominant-baseline", "text-decoration");
850

851
    // A style attribute on any element, with either quoting style.
852
    private static final Pattern STYLE_ATTRIBUTE = Pattern.compile(
12 ✔
853
            "\\sstyle\\s*=\\s*(\"[^\"]*\"|'[^']*')", Pattern.CASE_INSENSITIVE);
854

855
    // A value safe to move into a presentation attribute: no function call other than the
856
    // colour functions, so url(...) and expression(...) can never survive.
857
    private static final Pattern SAFE_STYLE_VALUE = Pattern.compile(
9 ✔
858
            "(?:[-#%.,0-9a-zA-Z_ ]|(?:rgb|rgba|hsl|hsla)\\([-0-9%.,\\s]*\\))+");
859

860
    private static String styleToPresentationAttributes(String raw) {
861
        if (raw == null || !raw.contains("style")) return raw;
24 !
862
        Matcher m = STYLE_ATTRIBUTE.matcher(raw);
12 ✔
863
        StringBuilder sb = new StringBuilder();
12 ✔
864
        while (m.find()) {
9 ✔
865
            String quoted = m.group(1);
12 ✔
866
            String declarations = quoted.substring(1, quoted.length() - 1);
24 ✔
867
            StringBuilder attributes = new StringBuilder();
12 ✔
868
            for (String declaration : declarations.split(";")) {
54 ✔
869
                int colon = declaration.indexOf(':');
12 ✔
870
                if (colon < 0) continue;
6 !
871
                String property = declaration.substring(0, colon).trim().toLowerCase();
21 ✔
872
                String value = declaration.substring(colon + 1).trim();
21 ✔
873
                if (!STYLE_PROPERTIES_AS_ATTRIBUTES.contains(property)) continue;
15 ✔
874
                if (value.isEmpty() || !SAFE_STYLE_VALUE.matcher(value).matches()) continue;
27 !
875
                attributes.append(' ').append(property).append("=\"").append(value).append('"');
36 ✔
876
            }
877
            m.appendReplacement(sb, Matcher.quoteReplacement(attributes.toString()));
21 ✔
878
        }
3 ✔
879
        m.appendTail(sb);
12 ✔
880
        return sb.toString();
9 ✔
881
    }
882

883
    private static String[] concat(String[] values, String... more) {
884
        String[] result = Arrays.copyOf(values, values.length + more.length);
27 ✔
885
        System.arraycopy(more, 0, result, values.length, more.length);
24 ✔
886
        return result;
6 ✔
887
    }
888

889
    /**
890
     * Adds the static-SVG subset (elements and presentation attributes, but not the
891
     * {@code a} element itself, whose link handling differs per policy) to a policy
892
     * builder.
893
     *
894
     * @param builder the policy builder to extend
895
     * @return the given builder
896
     */
897
    private static HtmlPolicyBuilder allowSvgSubset(HtmlPolicyBuilder builder) {
898
        return builder
9 ✔
899
                .allowElements(SVG_ELEMENTS)
93 ✔
900
                .allowWithoutAttributes("svg", "g", "defs", "title", "desc", "text", "tspan")
6 ✔
901
                .allowAttributes(SVG_ATTRIBUTES).onElements(SVG_ELEMENTS_WITH_LINK);
9 ✔
902
    }
903

904
    // Links a view emits may point at any scheme a nanopublication is allowed to reference
905
    // (issue #655); without them here the sanitizer silently strips the href. All of these are
906
    // inert reference schemes -- nothing script-executing is added.
907
    private static final String[] SANITIZER_URL_PROTOCOLS =
3 ✔
908
            UriSchemes.ALLOWED_SCHEMES.stream().sorted().toArray(String[]::new);
27 ✔
909

910
    private static final PolicyFactory htmlSanitizePolicy = allowSvgSubset(new HtmlPolicyBuilder()
12 ✔
911
            .allowCommonBlockElements().allowCommonInlineFormattingElements()
9 ✔
912
            .allowUrlProtocols(SANITIZER_URL_PROTOCOLS).allowUrlProtocols("mailto")
42 ✔
913
            .allowElements("a").allowAttributes("href").onElements("a")
63 ✔
914
            .allowElements("img").allowAttributes("src").onElements("img")
63 ✔
915
            .allowElements("pre")
3 ✔
916
            .requireRelNofollowOnLinks()).toFactory();
9 ✔
917

918
    /**
919
     * The text of an HTML fragment, with block-level boundaries kept as spaces so that
920
     * paragraphs and list items do not run into each other.
921
     *
922
     * @param html the HTML fragment, or plain text
923
     * @return the text, with markup removed and entities decoded
924
     */
925
    public static String toPlainText(String html) {
926
        String spaced = BLOCK_BOUNDARY.matcher(html).replaceAll(" ");
18 ✔
927
        return Encoding.decodeHtml(TEXT_ONLY_POLICY.sanitize(spaced));
15 ✔
928
    }
929

930
    private static final PolicyFactory TEXT_ONLY_POLICY = new HtmlPolicyBuilder().toFactory();
15 ✔
931

932
    private static final Pattern BLOCK_BOUNDARY = Pattern.compile(
12 ✔
933
            "</?(?:p|div|br|li|ul|ol|h[1-6]|tr|td|th|table|blockquote|pre|section|article)\\b[^>]*>",
934
            Pattern.CASE_INSENSITIVE);
935

936
    /**
937
     * Sanitizes raw HTML input to ensure safe rendering. Inline SVG is kept, reduced
938
     * to the same static subset as in {@link #sanitizeSvg(String)}.
939
     *
940
     * @param rawHtml the raw HTML input to sanitize
941
     * @return sanitized HTML string
942
     */
943
    public static String sanitizeHtml(String rawHtml) {
944
        return htmlSanitizePolicy.sanitize(styleToPresentationAttributes(normalizeSelfClosedSvgTags(rawHtml)));
18 ✔
945
    }
946

947
    private static final PolicyFactory svgSanitizePolicy = allowSvgSubset(new HtmlPolicyBuilder()
15 ✔
948
            .allowUrlProtocols(SANITIZER_URL_PROTOCOLS)
21 ✔
949
            .allowElements("a")
21 ✔
950
            .allowWithoutAttributes("a")
21 ✔
951
            .allowAttributes("href").onElements("a")).toFactory();
30 ✔
952

953
    // XML-style self-closed SVG tags (<rect .../>): the HTML-parsing sanitizer
954
    // ignores the slash on non-void elements and would re-parent all following
955
    // siblings as children of the "unclosed" element — which in SVG makes them
956
    // invisible (shape elements don't render children). Expanded to explicit end
957
    // tags before sanitizing. Quoted attribute values (which may contain ">") are
958
    // matched as units so the tag end is found correctly, and the attribute part
959
    // must start with whitespace so that a longer element name is not matched as
960
    // one of the listed ones plus attributes. Only SVG element names are expanded,
961
    // so that HTML void elements (<br/>, <img/>) and self-closed links keep their
962
    // HTML parsing.
963
    private static final Pattern SELF_CLOSED_SVG_TAG = Pattern.compile(
12 ✔
964
            "<(" + String.join("|", SVG_ELEMENTS) + ")((?:\\s(?:[^<>\"']|\"[^\"]*\"|'[^']*')*)?)/>",
9 ✔
965
            Pattern.CASE_INSENSITIVE);
966

967
    private static String normalizeSelfClosedSvgTags(String raw) {
968
        if (raw == null) return null;
6 !
969
        return SELF_CLOSED_SVG_TAG.matcher(raw).replaceAll("<$1$2></$1>");
18 ✔
970
    }
971

972
    /**
973
     * Sanitizes SVG markup (as produced by an SVG view's query) down to a static
974
     * subset that is safe to embed inline: shapes, text, grouping, and http(s)
975
     * links, with no scripting, styling, or external-reference capability.
976
     *
977
     * @param rawSvg the raw SVG markup
978
     * @return sanitized SVG markup
979
     */
980
    public static String sanitizeSvg(String rawSvg) {
981
        return svgSanitizePolicy.sanitize(styleToPresentationAttributes(normalizeSelfClosedSvgTags(rawSvg)));
18 ✔
982
    }
983

984
    // A whole inline SVG figure, dropped wherever HTML is reduced to text: its
985
    // labels would come out as a run of disconnected words.
986
    private static final Pattern SVG_FRAGMENT = Pattern.compile("<svg\\b.*?</svg\\s*>",
12 ✔
987
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
988

989
    private static final Pattern NUMERIC_ENTITY = Pattern.compile("&#(?:([0-9]{1,7})|[xX]([0-9a-fA-F]{1,6}));");
9 ✔
990

991
    /**
992
     * Reduces an HTML fragment to plain text: SVG figures are dropped entirely, the
993
     * remaining tags are stripped, the named and numeric entities are unescaped (the
994
     * sanitizer emits quotes etc. as numeric entities like {@code &#34;}), and
995
     * whitespace is collapsed.
996
     *
997
     * @param html the HTML fragment
998
     * @return the plain text
999
     */
1000
    public static String htmlToPlainText(String html) {
1001
        String text = SVG_FRAGMENT.matcher(html).replaceAll(" ");
18 ✔
1002
        text = text.replaceAll("<[^>]*>", " ");
15 ✔
1003
        text = text.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"")
36 ✔
1004
                .replace("&nbsp;", " ");
6 ✔
1005
        text = NUMERIC_ENTITY.matcher(text).replaceAll(m -> {
18 ✔
1006
            int codePoint = m.group(1) != null
12 ✔
1007
                    ? Integer.parseInt(m.group(1))
15 ✔
1008
                    : Integer.parseInt(m.group(2), 16);
18 ✔
1009
            return Matcher.quoteReplacement(new String(Character.toChars(codePoint)));
21 ✔
1010
        });
1011
        text = text.replace("&amp;", "&");
15 ✔
1012
        return text.replaceAll("\\s+", " ").trim();
18 ✔
1013
    }
1014

1015
    /**
1016
     * Reduces a value to the text to use for it in a label. HTML is a rendering
1017
     * detail that has no place in a label, so an SVG figure is dropped wherever it
1018
     * occurs, and a value that is HTML is further reduced to its text.
1019
     *
1020
     * @param value the raw value
1021
     * @return the value as label text
1022
     */
1023
    public static String toLabelText(String value) {
1024
        if (value == null) return null;
6 !
1025
        if (looksLikeHtml(value)) {
9 ✔
1026
            return htmlToPlainText(value);
9 ✔
1027
        }
1028
        return SVG_FRAGMENT.matcher(value).replaceAll(" ").replaceAll("\\s+", " ").trim();
30 ✔
1029
    }
1030

1031
    /**
1032
     * Checks if a given string is likely to be HTML content.
1033
     *
1034
     * <p>This is a heuristic, needed wherever the RDF datatype is not available (query
1035
     * results arrive as flat strings). Where an actual literal is at hand, prefer
1036
     * {@link #isHtmlLiteral(Value)}, which relies on the declared datatype instead.
1037
     *
1038
     * @param value the string to check
1039
     * @return true if the given string is HTML content, false otherwise
1040
     */
1041
    public static boolean looksLikeHtml(String value) {
1042
        return LEADING_TAG.matcher(value).find();
15 ✔
1043
    }
1044

1045
    /**
1046
     * Checks whether a value is a literal explicitly tagged with the {@code rdf:HTML}
1047
     * datatype, i.e. whose content is meant to be rendered as HTML.
1048
     *
1049
     * @param value the value to check
1050
     * @return true if the value is an rdf:HTML literal, false otherwise
1051
     */
1052
    public static boolean isHtmlLiteral(Value value) {
1053
        return value instanceof Literal literal && RDF.HTML.equals(literal.getDatatype());
45 ✔
1054
    }
1055

1056
    public static boolean isDate(String value) {
1057
        return isDateLiteral(value) || isDateTimeLiteral(value);
30 ✔
1058
    }
1059

1060
    public static boolean isDateLiteral(String value) {
1061
        if (value == null || value.isBlank() || value.contains("T")) {
27 ✔
1062
            return false;
6 ✔
1063
        }
1064
        try {
1065
            DateTimeFormatter.ISO_DATE.parse(value);
12 ✔
1066
            return true;
6 ✔
1067
        } catch (DateTimeParseException ex) {
3 ✔
1068
            return false;
6 ✔
1069
        }
1070
    }
1071

1072
    /**
1073
     * Checks whether a (raw query-result) string looks like an ISO-8601 date-time literal.
1074
     *
1075
     * @param value the string to check
1076
     * @return true if the string parses as a xsd:dateTime-style value
1077
     */
1078
    public static boolean isDateTimeLiteral(String value) {
1079
        if (value == null || value.isBlank()) {
15 ✔
1080
            return false;
6 ✔
1081
        }
1082

1083
        try {
1084
            OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
12 ✔
1085
            return true;
6 ✔
1086
        } catch (DateTimeParseException ignored) {
3 ✔
1087
        }
1088

1089
        try {
1090
            LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
12 ✔
1091
            return true;
6 ✔
1092
        } catch (DateTimeParseException ignored) {
3 ✔
1093
            return false;
6 ✔
1094
        }
1095
    }
1096

1097
    /**
1098
     * Renders a {@code <time>} element for an ISO-8601 date-time value. The machine-readable
1099
     * value goes in the {@code datetime} attribute; client-side script (nanodash.js) rewrites
1100
     * the visible text to a relative form ("10 minutes ago") in the viewer's local timezone and
1101
     * puts the absolute date-time in the tooltip. If script does not run, {@code fallbackText}
1102
     * remains visible.
1103
     *
1104
     * @param isoValue     the ISO-8601 date-time string (machine-readable)
1105
     * @param fallbackText the human-readable text shown when script is unavailable
1106
     * @return an HTML {@code <time>} element string (caller must render with escaping disabled)
1107
     */
1108
    public static String friendlyDateHtml(String isoValue, String fallbackText) {
1109
        return "<time class=\"friendly-date\" datetime=\"" + Strings.escapeMarkup(isoValue) + "\">" + Strings.escapeMarkup(fallbackText) + "</time>";
×
1110
    }
1111

1112
    /**
1113
     * Converts PageParameters to a URL-encoded string representation.
1114
     *
1115
     * @param params the PageParameters to convert
1116
     * @return a string representation of the parameters in URL-encoded format
1117
     */
1118
    public static String getPageParametersAsString(PageParameters params) {
1119
        String s = "";
6 ✔
1120
        for (String n : params.getNamedKeys()) {
33 ✔
1121
            if (!s.isEmpty()) {
9 ✔
1122
                s += "&";
9 ✔
1123
            }
1124
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
30 ✔
1125
        }
3 ✔
1126
        return s;
6 ✔
1127
    }
1128

1129
    /**
1130
     * How long a dropdown that searches as the user types waits after the last keystroke before
1131
     * it searches. Its lookups run in parallel and are cached (issue #88), so this pause is most
1132
     * of what the user waits for; a request still running when the user types on is cancelled
1133
     * by Select2 in the browser.
1134
     */
1135
    public static final int SELECT2_SEARCH_DELAY_MS = 250;
1136

1137
    /**
1138
     * Makes a Select2Choice search as the user types, after {@link #SELECT2_SEARCH_DELAY_MS}.
1139
     *
1140
     * @param selectItem the Select2Choice component that searches as the user types
1141
     */
1142
    public static void setSelect2SearchAsYouType(Select2Choice<?> selectItem) {
1143
        selectItem.getSettings().getAjax(true).setDelay(SELECT2_SEARCH_DELAY_MS);
18 ✔
1144
    }
3 ✔
1145

1146
    /**
1147
     * Sets a minimal escape markup function for a Select2Choice component.
1148
     * This function replaces certain characters and formats the display of choices.
1149
     *
1150
     * @param selectItem the Select2Choice component to set the escape markup for
1151
     */
1152
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
1153
        // The note of a to-be-minted value is not part of the value, so it is set in its own
1154
        // span and styled as an aside rather than as the term itself (issue #652).
1155
        // The note on where a value comes from goes on a line of its own as well, with the date
1156
        // in it put in the short relative form used elsewhere ("3 days ago") by nanodash.js,
1157
        // which knows the viewer's timezone (issue #817).
1158
        String noteRegex = TO_BE_MINTED_NOTE.replace("(", "\\(").replace(")", "\\)");
24 ✔
1159
        selectItem.getSettings().setEscapeMarkup("function(markup) {" + "return markup" + ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" + ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" + ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" + ".replace(/" + ORIGIN_NOTE_SEPARATOR + "((?:by |\\d{4}-)[^<]*)(<br><code>|$)/, function(m, note, tail) {" + "return '<br><span class=\"origin-note\">' + (typeof friendlyDateTextIn === 'function' ? friendlyDateTextIn(note) : note) + '</span>' + tail; })" + ".replace(/^(.*) " + noteRegex + "$/, '<span class=\"term\">$1</span> <span class=\"mint-note\">" + TO_BE_MINTED_NOTE + "</span>')" + ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" + ";}");
18 ✔
1160
    }
3 ✔
1161

1162
    /**
1163
     * Checks if a nanopublication is of a specific class.
1164
     *
1165
     * @param np       the nanopublication to check
1166
     * @param classIri the IRI of the class to check against
1167
     * @return true if the nanopublication is of the specified class, false otherwise
1168
     */
1169
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
1170
        return NanopubUtils.getTypes(np).contains(classIri);
15 ✔
1171
    }
1172

1173
    /**
1174
     * Checks if a nanopublication uses a specific predicate in its assertion.
1175
     *
1176
     * @param np           the nanopublication to check
1177
     * @param predicateIri the IRI of the predicate to look for
1178
     * @return true if the predicate is used in the assertion, false otherwise
1179
     */
1180
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
1181
        for (Statement st : np.getAssertion()) {
33 ✔
1182
            if (predicateIri.equals(st.getPredicate())) {
15 ✔
1183
                return true;
6 ✔
1184
            }
1185
        }
3 ✔
1186
        return false;
6 ✔
1187
    }
1188

1189
    /**
1190
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
1191
     *
1192
     * @param np the nanopublication from which to extract FOAF names
1193
     * @return a map where keys are subjects and values are FOAF names
1194
     */
1195
    public static Map<String, String> getFoafNameMap(Nanopub np) {
1196
        Map<String, String> foafNameMap = new HashMap<>();
12 ✔
1197
        for (Statement st : np.getPubinfo()) {
33 ✔
1198
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
42 ✔
1199
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
24 ✔
1200
            }
1201
        }
3 ✔
1202
        return foafNameMap;
6 ✔
1203
    }
1204

1205
    /**
1206
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
1207
     *
1208
     * @param obj the object to hash
1209
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
1210
     */
1211
    public static String createSha256HexHash(Object obj) {
1212
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21 ✔
1213
    }
1214

1215
    /**
1216
     * Gets the types of a nanopublication.
1217
     *
1218
     * @param np the nanopublication from which to extract types
1219
     * @return a list of IRI types associated with the nanopublication
1220
     */
1221
    public static List<IRI> getTypes(Nanopub np) {
1222
        List<IRI> l = new ArrayList<>();
12 ✔
1223
        for (IRI t : NanopubUtils.getTypes(np)) {
33 ✔
1224
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) {
12 ✔
1225
                continue;
3 ✔
1226
            }
1227
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED)) {
12 ✔
1228
                continue;
3 ✔
1229
            }
1230
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) {
12 !
1231
                continue;
×
1232
            }
1233
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED)) {
12 !
1234
                continue;
×
1235
            }
1236
            if (t.equals(NPX.PROTECTED_NANOPUB)) {
12 ✔
1237
                // Not a type of the content but a statement about where the nanopub may be
1238
                // stored, and shown as its own flag instead (see NanopubItem). As a type tag
1239
                // it would also link to a listing of all nanopubs of that type, which says
1240
                // nothing about them beyond that they are all protected.
1241
                continue;
3 ✔
1242
            }
1243
            l.add(t);
12 ✔
1244
        }
3 ✔
1245
        return l;
6 ✔
1246
    }
1247

1248
    /**
1249
     * Gets a label for a type IRI.
1250
     *
1251
     * @param typeIri the IRI of the type
1252
     * @return a label for the type, potentially truncated
1253
     */
1254
    public static String getTypeLabel(IRI typeIri) {
1255
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) {
12 ✔
1256
            return "FER";
6 ✔
1257
        }
1258
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) {
12 ✔
1259
            return "FSR";
6 ✔
1260
        }
1261
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) {
12 ✔
1262
            return "FIP";
6 ✔
1263
        }
1264
        if (typeIri.equals(NPX.DECLARED_BY)) {
12 ✔
1265
            return "user intro";
6 ✔
1266
        }
1267
        String l = typeIri.stringValue();
9 ✔
1268
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
15 ✔
1269
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
15 ✔
1270
        if (l.length() > 25) {
12 ✔
1271
            l = l.substring(0, 20) + "...";
18 ✔
1272
        }
1273
        return l;
6 ✔
1274
    }
1275

1276
    /**
1277
     * Gets the label a datatype is shown with beside a literal. The namespaces every
1278
     * nanopublication declares are abbreviated with the prefix they are written with; anything
1279
     * else is named by its full IRI, which is all there is to name it by.
1280
     *
1281
     * @param datatype the datatype IRI
1282
     * @return the label for the datatype, or an empty string if there is none
1283
     */
1284
    public static String getDatatypeLabel(IRI datatype) {
1285
        if (datatype == null) return "";
6 !
1286
        return datatype.stringValue()
15 ✔
1287
                .replace(XSD.NAMESPACE, "xsd:")
9 ✔
1288
                .replace(RDF.NAMESPACE, "rdf:");
3 ✔
1289
    }
1290

1291
    /**
1292
     * Gets a label for a URI.
1293
     *
1294
     * @param uri the URI to get the label from
1295
     * @return a label for the URI, potentially truncated
1296
     */
1297
    public static String getUriLabel(String uri) {
1298
        if (uri == null) {
6 ✔
1299
            return "";
6 ✔
1300
        }
1301
        String uriLabel = uri;
6 ✔
1302
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
12 ✔
1303
            String newUriLabel = uriLabel.replaceFirst("(.*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{8})[A-Za-z0-9-_]{35}([^A-Za-z0-9-_].*)?", "$1...$2");
15 ✔
1304
            if (newUriLabel.length() <= 70) {
12 ✔
1305
                return newUriLabel;
6 ✔
1306
            }
1307
        }
1308
        if (uriLabel.length() > 70) {
12 ✔
1309
            return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
36 ✔
1310
        }
1311
        return uriLabel;
6 ✔
1312
    }
1313

1314
    /**
1315
     * Compares two result-table values the way a reader expects a column to be ordered.
1316
     * Plain text order alone puts "10" before "9", because it never gets past the first
1317
     * digit (issue #673); this compares numbers by their value instead. Values that are
1318
     * numbers throughout are compared as numbers, and text with numbers in it run by run,
1319
     * so that "Session #9" comes before "Session #34" too. Anything else is ordered as
1320
     * text, ignoring case, as before.
1321
     *
1322
     * @param value1 the first value
1323
     * @param value2 the second value
1324
     * @return a negative number, zero or a positive number as the first value orders
1325
     * before, with, or after the second
1326
     */
1327
    public static int compareValues(String value1, String value2) {
1328
        String s1 = value1 == null ? "" : value1.trim();
15 !
1329
        String s2 = value2 == null ? "" : value2.trim();
15 !
1330
        BigDecimal n1 = asNumber(s1);
9 ✔
1331
        BigDecimal n2 = asNumber(s2);
9 ✔
1332
        if (n1 != null && n2 != null) {
12 ✔
1333
            // Whole values that are numbers are compared as such, which is the only way to
1334
            // get decimals right: run by run, "1.25" would come out below "1.5".
1335
            int c = n1.compareTo(n2);
12 ✔
1336
            return c != 0 ? c : s1.compareToIgnoreCase(s2);
24 ✔
1337
        }
1338
        return compareAlphanumerically(s1, s2);
12 ✔
1339
    }
1340

1341
    // The value as a number, or null if it is not one throughout.
1342
    private static BigDecimal asNumber(String value) {
1343
        if (value.isEmpty()) return null;
15 ✔
1344
        try {
1345
            return new BigDecimal(value);
15 ✔
1346
        } catch (NumberFormatException ex) {
3 ✔
1347
            return null;
6 ✔
1348
        }
1349
    }
1350

1351
    // Text order, except that two runs of digits meeting at the same position are compared
1352
    // by their numeric value. Kept to plain character comparisons: this runs once per pair
1353
    // of rows compared, for every column sorted.
1354
    private static int compareAlphanumerically(String s1, String s2) {
1355
        int i1 = 0;
6 ✔
1356
        int i2 = 0;
6 ✔
1357
        while (i1 < s1.length() && i2 < s2.length()) {
24 ✔
1358
            char c1 = s1.charAt(i1);
12 ✔
1359
            char c2 = s2.charAt(i2);
12 ✔
1360
            if (isAsciiDigit(c1) && isAsciiDigit(c2)) {
18 ✔
1361
                int end1 = digitRunEnd(s1, i1);
12 ✔
1362
                int end2 = digitRunEnd(s2, i2);
12 ✔
1363
                // Leading zeros carry no value, so they are skipped before the two runs are
1364
                // compared; the shorter run is then the smaller number, and equally long
1365
                // runs compare digit by digit.
1366
                int start1 = skipZeros(s1, i1, end1);
15 ✔
1367
                int start2 = skipZeros(s2, i2, end2);
15 ✔
1368
                if (end1 - start1 != end2 - start2) return (end1 - start1) - (end2 - start2);
45 ✔
1369
                int c = s1.substring(start1, end1).compareTo(s2.substring(start2, end2));
30 ✔
1370
                if (c != 0) return c;
12 ✔
1371
                i1 = end1;
6 ✔
1372
                i2 = end2;
6 ✔
1373
            } else {
3 ✔
1374
                int c = Character.compare(fold(c1), fold(c2));
18 ✔
1375
                if (c != 0) return c;
12 ✔
1376
                i1++;
3 ✔
1377
                i2++;
3 ✔
1378
            }
1379
        }
3 ✔
1380
        // Whatever is left over of the longer value orders after the shorter one.
1381
        return (s1.length() - i1) - (s2.length() - i2);
30 ✔
1382
    }
1383

1384
    private static boolean isAsciiDigit(char c) {
1385
        return c >= '0' && c <= '9';
30 ✔
1386
    }
1387

1388
    private static int digitRunEnd(String s, int from) {
1389
        int i = from;
6 ✔
1390
        while (i < s.length() && isAsciiDigit(s.charAt(i))) i++;
33 ✔
1391
        return i;
6 ✔
1392
    }
1393

1394
    // The first digit that carries value, keeping the last one so that "000" stays a digit.
1395
    private static int skipZeros(String s, int from, int end) {
1396
        int i = from;
6 ✔
1397
        while (i < end - 1 && s.charAt(i) == '0') i++;
36 ✔
1398
        return i;
6 ✔
1399
    }
1400

1401
    // Case folded the same way String.compareToIgnoreCase does it.
1402
    private static char fold(char c) {
1403
        return Character.toLowerCase(Character.toUpperCase(c));
12 ✔
1404
    }
1405

1406
    /**
1407
     * Whether a term typed into a choice field can be entered as a plain name for a resource that
1408
     * has no identifier yet (issue #652): it is not a URI already, and the IRI validator accepts
1409
     * it once a prefix is put in front of it -- the field's own, or the local one when it has
1410
     * none, in which case the nanopublication mints it under its own namespace.
1411
     *
1412
     * @param term the term typed into the field
1413
     * @return true if the term can be offered as a plain name
1414
     */
1415
    public static boolean isPlainName(String term) {
1416
        if (term == null || term.isBlank()) return false;
15 !
1417
        if (isUriValue(term)) return false;
15 ✔
1418
        // Same rule as the validator: no colon, hash or whitespace, and well-formed as a URI once
1419
        // prefixed.
1420
        if (!term.matches("[^:#\\s]+")) return false;
18 ✔
1421
        return isWellFormedUri(LocalUri.PREFIX + term);
12 ✔
1422
    }
1423

1424
    /**
1425
     * How a value that a nanopublication will mint under its own namespace is shown in a choice
1426
     * field: with the local prefix in front of it and marked as not being an identifier yet, e.g.
1427
     * "local:john (to be minted)" (issue #652). See
1428
     * {@link com.knowledgepixels.nanodash.template.TemplateContext#isToBeMinted(IRI, String)} for
1429
     * which values these are.
1430
     *
1431
     * @param value the plain name held for the placeholder
1432
     * @return the label to show for it
1433
     */
1434
    public static String getToBeMintedLabel(String value) {
1435
        return LocalUri.PREFIX + value + " " + TO_BE_MINTED_NOTE;
9 ✔
1436
    }
1437

1438
    /**
1439
     * The note appended to a to-be-minted value, set apart from the value itself by
1440
     * {@link #setSelect2ChoiceMinimalEscapeMarkup(Select2Choice)}.
1441
     */
1442
    private static final String TO_BE_MINTED_NOTE = "(mint locally)";
1443

1444
    /**
1445
     * What separates the note on who a value comes from and when it was published from the label
1446
     * of the value, and its two parts from each other, so that
1447
     * {@link #setSelect2ChoiceMinimalEscapeMarkup(Select2Choice)} can set the note on a line of
1448
     * its own.
1449
     */
1450
    public static final String ORIGIN_NOTE_SEPARATOR = " \u00b7 ";
1451

1452
    /**
1453
     * Returns the note on who a value comes from and when it was published as it is appended to
1454
     * the label of the value in a dropdown (issues #765 and #817).
1455
     *
1456
     * @param originNote the note, e.g. "by Jane Doe \u00b7 2026-10-17T09:12:00Z", or null
1457
     * @return the note with its separator, or an empty string if there is no note
1458
     */
1459
    public static String getOriginNoteSuffix(String originNote) {
1460
        if (originNote == null || originNote.isEmpty()) return "";
21 !
1461
        return ORIGIN_NOTE_SEPARATOR + originNote;
9 ✔
1462
    }
1463

1464
    /**
1465
     * Returns the URI of a choice as it is appended to the label of the choice in a dropdown.
1466
     * It is shortened the way a URI shown as a link is, so that the artifact code of a trusty
1467
     * URI does not fill a line on its own.
1468
     *
1469
     * @param uri the URI of the choice
1470
     * @return the shortened URI in brackets, or an empty string if there is no URI
1471
     */
1472
    public static String getUriSuffix(String uri) {
1473
        if (uri == null || uri.isEmpty()) return "";
21 ✔
1474
        return " (" + getUriLabel(uri) + ")";
12 ✔
1475
    }
1476

1477
    /**
1478
     * Gets an ExternalLink with a URI label.
1479
     *
1480
     * @param markupId the markup ID for the link
1481
     * @param uri      the URI to link to
1482
     * @return an ExternalLink with the URI label
1483
     */
1484
    public static ExternalLink getUriLink(String markupId, String uri) {
1485
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39 ✔
1486
    }
1487

1488
    /**
1489
     * Gets an ExternalLink with a model for the URI label.
1490
     *
1491
     * @param markupId the markup ID for the link
1492
     * @param model    the model containing the URI
1493
     * @return an ExternalLink with the URI label
1494
     */
1495
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
1496
        return new ExternalLink(markupId, new UriHrefModel(model), new UriLabelModel(model));
39 ✔
1497
    }
1498

1499
    /**
1500
     * Gets an ExternalLink that spells the URI out in full, for the places where the whole URI is
1501
     * what the link is there to show and the abbreviation {@link #getUriLink(String, IModel)}
1502
     * applies would hide it (issue #786). The element it is given has to let the text wrap, as a
1503
     * URI of any length lands in it.
1504
     *
1505
     * @param markupId the markup ID for the link
1506
     * @param model    the model containing the URI
1507
     * @return an ExternalLink labelled with the whole URI
1508
     */
1509
    public static ExternalLink getFullUriLink(String markupId, IModel<String> model) {
1510
        return new ExternalLink(markupId, new UriHrefModel(model), model);
30 ✔
1511
    }
1512

1513
    /**
1514
     * The href of a URI link: empty for anything that isn't a URI to link to, so that a local
1515
     * URI or a locally minted name (issue #652) isn't turned into a relative link. This mirrors
1516
     * what {@link #getUriLink(String, String)} does with local URIs.
1517
     */
1518
    private static class UriHrefModel implements IModel<String> {
1519

1520
        private IModel<String> uriModel;
1521

1522
        public UriHrefModel(IModel<String> uriModel) {
6 ✔
1523
            this.uriModel = uriModel;
9 ✔
1524
        }
3 ✔
1525

1526
        @Override
1527
        public String getObject() {
1528
            String uri = uriModel.getObject();
15 ✔
1529
            if (uri == null || isLocalURI(uri) || !isUriValue(uri)) return "";
30 !
1530
            return uri;
6 ✔
1531
        }
1532

1533
    }
1534

1535
    private static class UriLabelModel implements IModel<String> {
1536

1537
        private IModel<String> uriModel;
1538

1539
        public UriLabelModel(IModel<String> uriModel) {
6 ✔
1540
            this.uriModel = uriModel;
9 ✔
1541
        }
3 ✔
1542

1543
        @Override
1544
        public String getObject() {
1545
            return getUriLabel(uriModel.getObject());
18 ✔
1546
        }
1547

1548
    }
1549

1550
    /**
1551
     * Creates a sublist from a list based on the specified indices.
1552
     *
1553
     * @param list      the list from which to create the sublist
1554
     * @param fromIndex the starting index (inclusive) for the sublist
1555
     * @param toIndex   the ending index (exclusive) for the sublist
1556
     * @param <E>       the type of elements in the list
1557
     * @return an ArrayList containing the elements from the specified range
1558
     */
1559
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
1560
        // So the resulting list is serializable:
1561
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
30 ✔
1562
    }
1563

1564
    /**
1565
     * Creates a sublist from an array based on the specified indices.
1566
     *
1567
     * @param array     the array from which to create the sublist
1568
     * @param fromIndex the starting index (inclusive) for the sublist
1569
     * @param toIndex   the ending index (exclusive) for the sublist
1570
     * @param <E>       the type of elements in the array
1571
     * @return an ArrayList containing the elements from the specified range
1572
     */
1573
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
1574
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
1575
    }
1576

1577
    /**
1578
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
1579
     */
1580
    // TODO Move this to ApiResponseEntry class?
1581
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
1582

1583
        private String field;
1584
        private boolean descending;
1585

1586
        /**
1587
         * Constructor for ApiResponseEntrySorter.
1588
         *
1589
         * @param field      the field to sort by
1590
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
1591
         */
1592
        public ApiResponseEntrySorter(String field, boolean descending) {
×
1593
            this.field = field;
×
1594
            this.descending = descending;
×
1595
        }
×
1596

1597
        /**
1598
         * Compares two ApiResponseEntry objects based on the specified field.
1599
         *
1600
         * @param o1 the first object to be compared.
1601
         * @param o2 the second object to be compared.
1602
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
1603
         */
1604
        @Override
1605
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
1606
            if (descending) {
×
1607
                return o2.get(field).compareTo(o1.get(field));
×
1608
            } else {
1609
                return o1.get(field).compareTo(o2.get(field));
×
1610
            }
1611
        }
1612

1613
    }
1614

1615
    /**
1616
     * MIME type for TriG RDF format.
1617
     */
1618
    public static final String TYPE_TRIG = "application/trig";
1619

1620
    /**
1621
     * MIME type for Jelly RDF format.
1622
     */
1623
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
1624

1625
    /**
1626
     * MIME type for JSON-LD format.
1627
     */
1628
    public static final String TYPE_JSONLD = "application/ld+json";
1629

1630
    /**
1631
     * MIME type for N-Quads format.
1632
     */
1633
    public static final String TYPE_NQUADS = "application/n-quads";
1634

1635
    /**
1636
     * MIME type for Trix format.
1637
     */
1638
    public static final String TYPE_TRIX = "application/trix";
1639

1640
    /**
1641
     * MIME type for HTML format.
1642
     */
1643
    public static final String TYPE_HTML = "text/html";
1644

1645
    /**
1646
     * Comma-separated list of supported MIME types for nanopublications.
1647
     */
1648
    public static final String SUPPORTED_TYPES = TYPE_TRIG + "," + TYPE_JELLY + "," + TYPE_JSONLD + "," + TYPE_NQUADS + "," + TYPE_TRIX + "," + TYPE_HTML;
1649

1650
    /**
1651
     * List of supported MIME types for nanopublications.
1652
     */
1653
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
15 ✔
1654

1655
    private static volatile String resolvedMainRegistryUrl;
1656
    private static volatile String resolvedMainQueryUrl;
1657

1658
    /**
1659
     * Eagerly resolves the main registry and query URLs. Call at application startup
1660
     * so the (potentially slow) first-time discovery does not happen during a user request.
1661
     */
1662
    public static void initMainUrls() {
1663
        getMainRegistryUrl();
6 ✔
1664
        getMainQueryUrl();
6 ✔
1665
    }
3 ✔
1666

1667
    /**
1668
     * Returns the URL of the main Nanopub Registry for this nanodash instance.
1669
     * <p>
1670
     * If {@code NANODASH_MAIN_REGISTRY} is set, that URL is used. Otherwise the first entry
1671
     * of the library's discovered registry instance list is used, or the built-in default if
1672
     * that list is empty. The result is cached for the JVM lifetime.
1673
     *
1674
     * @return Nanopub Registry URL (with trailing slash)
1675
     */
1676
    public static String getMainRegistryUrl() {
1677
        if (resolvedMainRegistryUrl == null) {
6 ✔
1678
            synchronized (Utils.class) {
12 ✔
1679
                if (resolvedMainRegistryUrl == null) {
6 !
1680
                    resolvedMainRegistryUrl = resolveMainRegistryUrl();
6 ✔
1681
                }
1682
            }
9 ✔
1683
        }
1684
        return resolvedMainRegistryUrl;
6 ✔
1685
    }
1686

1687
    /**
1688
     * Returns the URL of the main Nanopub Query API for this nanodash instance.
1689
     * <p>
1690
     * If {@code NANODASH_MAIN_QUERY} is set, that URL is used. Otherwise the first entry of the
1691
     * library's discovered query instance list is used, or the built-in default if that list is
1692
     * empty. The result is cached for the JVM lifetime.
1693
     *
1694
     * @return Nanopub Query URL (with trailing slash)
1695
     */
1696
    public static String getMainQueryUrl() {
1697
        if (resolvedMainQueryUrl == null) {
6 ✔
1698
            synchronized (Utils.class) {
12 ✔
1699
                if (resolvedMainQueryUrl == null) {
6 !
1700
                    resolvedMainQueryUrl = resolveMainQueryUrl();
6 ✔
1701
                }
1702
            }
9 ✔
1703
        }
1704
        return resolvedMainQueryUrl;
6 ✔
1705
    }
1706

1707
    private static String resolveMainRegistryUrl() {
1708
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_REGISTRY"));
12 ✔
1709
        List<String> instances;
1710
        try {
1711
            instances = NanopubServerUtils.getRegistryServerList();
6 ✔
1712
        } catch (Exception ex) {
×
1713
            logger.warn("Could not retrieve registry instance list from nanopub library: {}", ex.toString());
×
1714
            instances = Collections.emptyList();
×
1715
        }
3 ✔
1716
        return resolveMainUrl("NANODASH_MAIN_REGISTRY", envValue, instances, "NANOPUB_REGISTRY_INSTANCES", DEFAULT_MAIN_REGISTRY_URL);
21 ✔
1717
    }
1718

1719
    private static String resolveMainQueryUrl() {
1720
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_QUERY"));
12 ✔
1721
        List<String> instances;
1722
        try {
1723
            instances = QueryCall.getApiInstances();
6 ✔
1724
        } catch (NotEnoughAPIInstancesException ex) {
×
1725
            logger.warn("Nanopub library reports not enough query API instances available: {}", ex.toString());
×
1726
            instances = Collections.emptyList();
×
1727
        } catch (Exception ex) {
×
1728
            logger.warn("Could not retrieve query instance list from nanopub library: {}", ex.toString());
×
1729
            instances = Collections.emptyList();
×
1730
        }
3 ✔
1731
        return resolveMainUrl("NANODASH_MAIN_QUERY", envValue, instances, "NANOPUB_QUERY_INSTANCES", DEFAULT_MAIN_QUERY_URL);
21 ✔
1732
    }
1733

1734
    /**
1735
     * Resolves one main URL. An explicitly configured value always wins: an operator who names a
1736
     * service -- a private registry or query API, say -- must not have that overruled by a list
1737
     * discovered from the public ones (issue #680). The list is still consulted, but only to warn
1738
     * that the library will keep dispatching elsewhere unless it is pointed at the same service.
1739
     * Package-private for testing.
1740
     */
1741
    static String resolveMainUrl(String envVarName, String envValue, List<String> instances, String libraryVarName, String builtInDefault) {
1742
        if (envValue != null) {
6 ✔
1743
            if (containsNormalized(instances, envValue)) {
12 ✔
1744
                logger.info("Using main URL from {} (also in the library instance list): {}", envVarName, envValue);
18 ✔
1745
            } else if (instances.isEmpty()) {
9 ✔
1746
                logger.info("Using main URL from {}; library instance list is empty: {}", envVarName, envValue);
18 ✔
1747
            } else {
1748
                logger.warn("Using main URL from {}={}, but it is not in the library instance list {}; the library itself " +
63 ✔
1749
                        "(nanopub retrieval, query dispatch) keeps using that list, so set {} to the same service as well",
1750
                        envVarName, envValue, instances, libraryVarName);
1751
            }
1752
            return ensureTrailingSlash(envValue);
9 ✔
1753
        }
1754
        if (!instances.isEmpty()) {
9 ✔
1755
            String first = instances.get(0);
15 ✔
1756
            logger.info("{} not set; using first library instance: {}", envVarName, first);
15 ✔
1757
            return ensureTrailingSlash(first);
9 ✔
1758
        }
1759
        logger.warn("{} not set and library instance list is empty; using built-in default: {}", envVarName, builtInDefault);
15 ✔
1760
        return builtInDefault;
6 ✔
1761
    }
1762

1763
    private static boolean containsNormalized(List<String> urls, String target) {
1764
        String normTarget = normalizeUrl(target);
9 ✔
1765
        for (String url : urls) {
30 ✔
1766
            if (normalizeUrl(url).equals(normTarget)) {
15 ✔
1767
                return true;
6 ✔
1768
            }
1769
        }
3 ✔
1770
        return false;
6 ✔
1771
    }
1772

1773
    private static String normalizeUrl(String url) {
1774
        if (url == null) {
6 !
1775
            return "";
×
1776
        }
1777
        return url.trim().replaceFirst("/+$", "").toLowerCase(Locale.ROOT);
24 ✔
1778
    }
1779

1780
    private static String ensureTrailingSlash(String url) {
1781
        return url.endsWith("/") ? url : url + "/";
27 ✔
1782
    }
1783

1784
    private static String trimToNull(String s) {
1785
        if (s == null) {
6 !
1786
            return null;
6 ✔
1787
        }
1788
        s = s.trim();
×
1789
        return s.isEmpty() ? null : s;
×
1790
    }
1791

1792
    // The part after the quoted string: a language tag, or a datatype IRI. The quoted
1793
    // string itself is scanned rather than matched (see scanQuotedString): expressed as a
1794
    // regex it costs one stack frame per character, so a literal of a few thousand
1795
    // characters -- e.g. a profile picture given as SVG markup, issue #634 -- overflowed
1796
    // the stack and turned publish-form validation into a 500.
1797
    private static final Pattern LANGTAG_SUFFIX = Pattern.compile("^@([0-9a-zA-Z-]{2,})$");
9 ✔
1798
    private static final Pattern DATATYPE_SUFFIX = Pattern.compile("^\\^\\^<([^ ><\"^]+)>$");
9 ✔
1799

1800
    /**
1801
     * The characters a literal string escapes, each with the letter that follows the backslash
1802
     * for it: Turtle's short string escapes ({@code ECHAR}).
1803
     */
1804
    private static final Map<Character, Character> LITERAL_ESCAPE_LETTERS = Map.of(
9 ✔
1805
            '\\', '\\',
12 ✔
1806
            '"', '"',
12 ✔
1807
            '\n', 'n',
12 ✔
1808
            '\r', 'r',
12 ✔
1809
            '\t', 't',
12 ✔
1810
            '\b', 'b',
12 ✔
1811
            '\f', 'f');
9 ✔
1812

1813
    /**
1814
     * The letters that may follow a backslash in a literal string, each with the character it
1815
     * stands for: the inverse of {@link #LITERAL_ESCAPE_LETTERS}, plus the single quote, which
1816
     * Turtle allows to be escaped but which never needs it here.
1817
     */
1818
    private static final Map<Character, Character> LITERAL_ESCAPED_CHARS = Map.of(
12 ✔
1819
            '\\', '\\',
12 ✔
1820
            '"', '"',
12 ✔
1821
            '\'', '\'',
12 ✔
1822
            'n', '\n',
12 ✔
1823
            'r', '\r',
12 ✔
1824
            't', '\t',
12 ✔
1825
            'b', '\b',
12 ✔
1826
            'f', '\f');
9 ✔
1827

1828
    /**
1829
     * Scans a leading quoted string, in which a backslash starts one of Turtle's string
1830
     * escapes, and returns the index just past its closing quote.
1831
     *
1832
     * @param s the string to scan
1833
     * @return the index just past the closing quote, or -1 if the string does not start
1834
     * with a well-formed quoted string
1835
     */
1836
    private static int scanQuotedString(String s) {
1837
        if (s.isEmpty() || s.charAt(0) != '"') return -1;
30 ✔
1838
        int i = 1;
6 ✔
1839
        while (i < s.length()) {
12 ✔
1840
            char c = s.charAt(i);
12 ✔
1841
            if (c == '\\') {
9 ✔
1842
                if (i + 1 >= s.length()) return -1;
18 !
1843
                char next = s.charAt(i + 1);
18 ✔
1844
                if (!LITERAL_ESCAPED_CHARS.containsKey(next)) return -1;
21 ✔
1845
                i += 2;
3 ✔
1846
            } else if (c == '"') {
12 ✔
1847
                return i + 1;
12 ✔
1848
            } else {
1849
                i++;
3 ✔
1850
            }
1851
        }
3 ✔
1852
        return -1;
6 ✔
1853
    }
1854

1855
    /**
1856
     * Checks whether string is valid literal serialization.
1857
     *
1858
     * @param literalString the literal string
1859
     * @return true if valid
1860
     */
1861
    public static boolean isValidLiteralSerialization(String literalString) {
1862
        int end = scanQuotedString(literalString);
9 ✔
1863
        if (end < 0) return false;
12 ✔
1864
        String suffix = literalString.substring(end);
12 ✔
1865
        return suffix.isEmpty()
18 ✔
1866
                || LANGTAG_SUFFIX.matcher(suffix).matches()
15 ✔
1867
                || DATATYPE_SUFFIX.matcher(suffix).matches();
18 ✔
1868
    }
1869

1870
    /**
1871
     * Returns a serialized version of the literal.
1872
     *
1873
     * @param literal the literal
1874
     * @return the String serialization of the literal
1875
     */
1876
    public static String getSerializedLiteral(Literal literal) {
1877
        if (literal.getLanguage().isPresent()) {
12 ✔
1878
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
30 ✔
1879
        } else if (literal.getDatatype().equals(XSD.STRING)) {
15 ✔
1880
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
15 ✔
1881
        } else {
1882
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
24 ✔
1883
        }
1884
    }
1885

1886
    /**
1887
     * Parses a serialized literal into a Literal object.
1888
     *
1889
     * @param serializedLiteral The serialized String of the literal
1890
     * @return The parse Literal object
1891
     */
1892
    public static Literal getParsedLiteral(String serializedLiteral) {
1893
        int end = scanQuotedString(serializedLiteral);
9 ✔
1894
        if (end >= 0) {
6 ✔
1895
            String value = getUnescapedLiteralString(serializedLiteral.substring(1, end - 1));
24 ✔
1896
            String suffix = serializedLiteral.substring(end);
12 ✔
1897
            if (suffix.isEmpty()) return vf.createLiteral(value);
21 ✔
1898
            Matcher langtag = LANGTAG_SUFFIX.matcher(suffix);
12 ✔
1899
            if (langtag.matches()) return vf.createLiteral(value, langtag.group(1));
30 ✔
1900
            Matcher datatype = DATATYPE_SUFFIX.matcher(suffix);
12 ✔
1901
            if (datatype.matches()) return vf.createLiteral(value, vf.createIRI(datatype.group(1)));
36 !
1902
        }
1903
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
18 ✔
1904
    }
1905

1906
    /**
1907
     * Escapes a literal string the way Turtle does: backslashes, quotes and the control
1908
     * characters that have a short escape. A value field is a single line, which a browser
1909
     * strips line breaks from, so a newline has to be written as {@code \n} to survive it
1910
     * (issue #103).
1911
     *
1912
     * @param unescapedString un-escaped string
1913
     * @return escaped string
1914
     */
1915
    public static String getEscapedLiteralString(String unescapedString) {
1916
        StringBuilder escaped = new StringBuilder(unescapedString.length());
18 ✔
1917
        for (char c : unescapedString.toCharArray()) {
51 ✔
1918
            Character escapeLetter = LITERAL_ESCAPE_LETTERS.get(c);
18 ✔
1919
            if (escapeLetter == null) {
6 ✔
1920
                escaped.append(c);
15 ✔
1921
            } else {
1922
                escaped.append('\\').append(escapeLetter.charValue());
21 ✔
1923
            }
1924
        }
1925
        return escaped.toString();
9 ✔
1926
    }
1927

1928
    /**
1929
     * Un-escapes a literal string escaped the way Turtle does (see
1930
     * {@link #getEscapedLiteralString(String)}). A backslash before a character that has no
1931
     * escape is kept as it is.
1932
     *
1933
     * @param escapedString escaped string
1934
     * @return un-escaped string
1935
     */
1936
    public static String getUnescapedLiteralString(String escapedString) {
1937
        StringBuilder unescaped = new StringBuilder(escapedString.length());
18 ✔
1938
        for (int i = 0; i < escapedString.length(); i++) {
24 ✔
1939
            Character escapedChar = escapedCharAt(escapedString, i);
12 ✔
1940
            if (escapedChar == null) {
6 ✔
1941
                unescaped.append(escapedString.charAt(i));
21 ✔
1942
            } else {
1943
                unescaped.append(escapedChar.charValue());
15 ✔
1944
                i++;
3 ✔
1945
            }
1946
        }
1947
        return unescaped.toString();
9 ✔
1948
    }
1949

1950
    /**
1951
     * The character that an escape starting at the given index stands for.
1952
     *
1953
     * @param s     the escaped string
1954
     * @param index the index of a possible backslash
1955
     * @return the character, or null if no escape starts there
1956
     */
1957
    private static Character escapedCharAt(String s, int index) {
1958
        if (s.charAt(index) != '\\' || index + 1 >= s.length()) return null;
39 ✔
1959
        return LITERAL_ESCAPED_CHARS.get(s.charAt(index + 1));
30 ✔
1960
    }
1961

1962
    /**
1963
     * Checks if a given IRI is a local URI.
1964
     *
1965
     * @param uri the IRI to check
1966
     * @return true if the IRI is a local URI, false otherwise
1967
     */
1968
    public static boolean isLocalURI(IRI uri) {
1969
        return uri != null && isLocalURI(uri.stringValue());
30 ✔
1970
    }
1971

1972
    /**
1973
     * Checks if a given string is a local URI.
1974
     *
1975
     * @param uriAsString the string to check
1976
     * @return true if the string is a local URI, false otherwise
1977
     */
1978
    public static boolean isLocalURI(String uriAsString) {
1979
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33 ✔
1980
    }
1981

1982
    /**
1983
     * Checks whether a string should be treated as a URI reference rather than as plain text.
1984
     * This is the single discriminator used across the code base, replacing the ad-hoc
1985
     * {@code matches("https?://.+")} tests that only recognized http(s) (issue #655).
1986
     * <p>
1987
     * The set of accepted schemes comes from {@link UriSchemes} in nanopub-java, so that Nanodash
1988
     * and the nanopublication verifier agree on what counts as a URI.
1989
     * <p>
1990
     * {@link UriSchemes#isAllowedUriScheme(String)} on its own only inspects the scheme, so it
1991
     * accepts strings such as {@code "at: home"} that happen to start with an allowed scheme name
1992
     * and a colon. Since many call sites use this method to decide between a literal and an IRI,
1993
     * that would silently turn ordinary prose into a link. The extra conditions below reject such
1994
     * values: a URI contains no whitespace, and must have something after the scheme -- which,
1995
     * for the {@code scheme://} form, means something after the slashes, so that a bare
1996
     * {@code "http://"} is no more a URI than it was under the {@code "https?://.+"} test.
1997
     *
1998
     * @param value the string to check
1999
     * @return true if the string is a URI in one of the allowed schemes
2000
     */
2001
    public static boolean isUriValue(String value) {
2002
        if (value == null || value.isBlank()) return false;
21 ✔
2003
        if (!UriSchemes.isAllowedUriScheme(value)) return false;
15 ✔
2004
        for (int i = 0; i < value.length(); i++) {
24 ✔
2005
            if (Character.isWhitespace(value.charAt(i))) return false;
21 ✔
2006
        }
2007
        String rest = value.substring(value.indexOf(':') + 1);
24 ✔
2008
        if (rest.startsWith("//")) rest = rest.substring(2);
24 ✔
2009
        return !rest.isEmpty();
21 ✔
2010
    }
2011

2012
    /**
2013
     * The external web URL where a URI Nanodash cannot display itself can be looked up, from the
2014
     * scheme-to-template map in {@link NanodashPreferences#getUriResolvers()} (issue #655).
2015
     * http(s) URIs are never resolved this way: they are their own web address.
2016
     *
2017
     * @param uri the URI to resolve
2018
     * @return the resolver URL, or null if the scheme has no configured resolver
2019
     */
2020
    public static String getExternalResolverUrl(String uri) {
2021
        String scheme = UriSchemes.getScheme(uri);
9 ✔
2022
        if (scheme == null || scheme.equals("http") || scheme.equals("https")) return null;
36 ✔
2023
        String template = NanodashPreferences.get().getUriResolvers().get(scheme);
18 ✔
2024
        if (template == null || template.isBlank()) return null;
21 !
2025
        String rest = uri.substring(scheme.length() + 1);
21 ✔
2026
        if (rest.startsWith("//")) rest = rest.substring(2);
24 ✔
2027
        return template.replace("$rest", encodeForPath(rest)).replace("$uri", encodeForPath(uri));
30 ✔
2028
    }
2029

2030
    // The resolvers substitute into the path of a URL, where the colons of a DID and the slashes
2031
    // of an AT-URI or IPFS path are legal and load-bearing -- form encoding them (as urlEncode
2032
    // does) would produce a URL the resolver cannot read. So only what is unsafe in a path is
2033
    // escaped, which importantly includes "?" and "#": left as they are, a crafted URI could
2034
    // append a query or fragment to the resolver URL rather than being resolved by it.
2035
    private static final String PATH_SAFE_PUNCTUATION = "-._~!$&'()*+,;=:@/";
2036

2037
    private static String encodeForPath(String s) {
2038
        StringBuilder sb = new StringBuilder();
12 ✔
2039
        int i = 0;
6 ✔
2040
        while (i < s.length()) {
12 ✔
2041
            int codePoint = s.codePointAt(i);
12 ✔
2042
            int width = Character.charCount(codePoint);
9 ✔
2043
            char c = s.charAt(i);
12 ✔
2044
            boolean alnum = width == 1
66 !
2045
                    && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'));
2046
            // An existing percent-escape is passed through, so that an already-encoded URI does
2047
            // not come out double-encoded.
2048
            boolean keptEscape = width == 1 && c == '%' && i + 2 < s.length()
48 !
2049
                    && isHexDigit(s.charAt(i + 1)) && isHexDigit(s.charAt(i + 2));
42 !
2050
            if (alnum || keptEscape || (width == 1 && PATH_SAFE_PUNCTUATION.indexOf(c) >= 0)) {
33 !
2051
                sb.append(c);
15 ✔
2052
            } else {
2053
                for (byte b : new String(Character.toChars(codePoint)).getBytes(UTF_8)) {
66 ✔
2054
                    sb.append(String.format("%%%02X", b));
36 ✔
2055
                }
2056
            }
2057
            i += width;
12 ✔
2058
        }
3 ✔
2059
        return sb.toString();
9 ✔
2060
    }
2061

2062
    private static boolean isHexDigit(char c) {
2063
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
27 !
2064
    }
2065

2066
    /**
2067
     * The allowed URI schemes as a sorted, comma-separated list, for use in validation messages.
2068
     *
2069
     * @return the allowed schemes, e.g. "at, did, http, https, ipfs, ipns"
2070
     */
2071
    public static String getAllowedUriSchemesLabel() {
2072
        return UriSchemes.ALLOWED_SCHEMES.stream().sorted().collect(java.util.stream.Collectors.joining(", "));
24 ✔
2073
    }
2074

2075
    /**
2076
     * Checks whether a string is a well-formed absolute URI.
2077
     * <p>
2078
     * {@link ParsedIRI} is tried first, so that http(s) input is judged exactly as it was before
2079
     * issue #655. It cannot parse AT-URIs: in {@code at://did:plc:abc/app.bsky.feed.post/3k} the
2080
     * authority is {@code did:plc:abc}, and it reads the colon as introducing a port, which then
2081
     * fails to be a number. {@link URI} allows a registry-based authority and accepts these, while
2082
     * still rejecting genuinely malformed input such as {@code at://}, {@code did:} or embedded
2083
     * spaces, so it serves as the fallback rather than as a blanket exemption.
2084
     *
2085
     * @param uri the string to check
2086
     * @return true if the string is a well-formed absolute URI
2087
     */
2088
    public static boolean isWellFormedUri(String uri) {
2089
        if (uri == null || uri.isBlank()) return false;
21 ✔
2090
        try {
2091
            if (new ParsedIRI(uri).isAbsolute()) return true;
24 ✔
2092
        } catch (URISyntaxException ex) {
3 ✔
2093
            // fall through to the more permissive parser below
2094
        }
3 ✔
2095
        try {
2096
            return new URI(uri).isAbsolute();
18 ✔
2097
        } catch (URISyntaxException ex) {
3 ✔
2098
            return false;
6 ✔
2099
        }
2100
    }
2101

2102
    public static String unescapeMultiValue(String s) {
2103
        StringBuilder sb = new StringBuilder();
12 ✔
2104
        for (int i = 0; i < s.length(); i++) {
24 ✔
2105
            if (s.charAt(i) == '\\' && i + 1 < s.length()) {
33 ✔
2106
                char next = s.charAt(i + 1);
18 ✔
2107
                if (next == 'n') {
9 ✔
2108
                    sb.append('\n');
15 ✔
2109
                } else if (next == '\\') {
9 !
2110
                    sb.append('\\');
15 ✔
2111
                } else {
2112
                    sb.append(next);
×
2113
                }
2114
                i++;
3 ✔
2115
            } else {
3 ✔
2116
                sb.append(s.charAt(i));
18 ✔
2117
            }
2118
        }
2119
        return sb.toString();
9 ✔
2120
    }
2121

2122
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc