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

knowledgepixels / nanodash / 27622930007

16 Jun 2026 01:58PM UTC coverage: 26.963% (+6.3%) from 20.697%
27622930007

push

github

web-flow
Merge pull request #483 from knowledgepixels/feat/spaces-about-and-ref-identity

Space/resource About pages, ref-aware spaces, and magic query params

1542 of 6717 branches covered (22.96%)

Branch coverage included in aggregate %.

3407 of 11638 relevant lines covered (29.27%)

4.31 hits per line

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

61.49
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.utils.URIBuilder;
9
import org.apache.wicket.markup.html.link.ExternalLink;
10
import org.apache.wicket.model.IModel;
11
import org.apache.wicket.request.mapper.parameter.PageParameters;
12
import org.apache.wicket.util.string.StringValue;
13
import org.apache.wicket.util.string.Strings;
14
import org.eclipse.rdf4j.model.IRI;
15
import org.eclipse.rdf4j.model.Literal;
16
import org.eclipse.rdf4j.model.Statement;
17
import org.eclipse.rdf4j.model.ValueFactory;
18
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
19
import org.eclipse.rdf4j.model.util.Literals;
20
import org.eclipse.rdf4j.model.vocabulary.FOAF;
21
import org.eclipse.rdf4j.model.vocabulary.XSD;
22
import org.nanopub.Nanopub;
23
import org.nanopub.NanopubUtils;
24
import org.nanopub.extra.security.KeyDeclaration;
25
import org.nanopub.extra.security.MalformedCryptoElementException;
26
import org.nanopub.extra.security.NanopubSignatureElement;
27
import org.nanopub.extra.security.SignatureUtils;
28
import org.nanopub.extra.server.GetNanopub;
29
import org.nanopub.extra.server.NanopubServerUtils;
30
import org.nanopub.extra.services.ApiResponseEntry;
31
import org.nanopub.extra.services.NotEnoughAPIInstancesException;
32
import org.nanopub.extra.services.QueryCall;
33
import org.nanopub.extra.setting.IntroNanopub;
34
import org.nanopub.vocabulary.FIP;
35
import org.nanopub.vocabulary.NPX;
36
import org.owasp.html.HtmlPolicyBuilder;
37
import org.owasp.html.PolicyFactory;
38
import org.slf4j.Logger;
39
import org.slf4j.LoggerFactory;
40
import org.wicketstuff.select2.Select2Choice;
41

42
import java.io.Serializable;
43
import java.net.URISyntaxException;
44
import java.net.URLDecoder;
45
import java.net.URLEncoder;
46
import java.nio.charset.StandardCharsets;
47
import java.util.*;
48
import java.util.regex.Pattern;
49

50
import static java.nio.charset.StandardCharsets.UTF_8;
51

52
/**
53
 * Utility class providing various helper methods for handling nanopublications, URIs, and other related functionalities.
54
 */
55
public class Utils {
56

57
    private Utils() {
58
    }  // no instances allowed
59

60
    /**
61
     * ValueFactory instance for creating RDF model objects.
62
     */
63
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
64
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
9✔
65
    private static final Pattern LEADING_TAG = Pattern.compile("^\\s*<(p|div|span|img|pre)(\\s|>|/).*", Pattern.CASE_INSENSITIVE);
12✔
66
    private static final String DEFAULT_MAIN_QUERY_URL = "https://query.knowledgepixels.com/";
67
    private static final String DEFAULT_MAIN_REGISTRY_URL = "https://registry.knowledgepixels.com/";
68

69
    /**
70
     * Generates a short name from a given IRI object.
71
     *
72
     * @param uri the IRI object
73
     * @return a short representation of the URI
74
     */
75
    public static String getShortNameFromURI(IRI uri) {
76
        return getShortNameFromURI(uri.stringValue());
12✔
77
    }
78

79
    /**
80
     * Generates a short name from a given URI string.
81
     *
82
     * @param uri the URI string
83
     * @return a short representation of the URI
84
     */
85
    public static String getShortNameFromURI(String uri) {
86
        if (uri.startsWith("https://doi.org/") || uri.startsWith("http://dx.doi.org/")) {
24✔
87
            return uri.replaceFirst("^https?://(dx\\.)?doi.org/", "doi:");
15✔
88
        }
89
        uri = uri.replaceFirst("\\?.*$", "");
15✔
90
        uri = uri.replaceFirst("[/#]$", "");
15✔
91
        uri = uri.replaceFirst("^.*[/#]([^/#]*)[/#]([0-9]+)$", "$1/$2");
15✔
92
        if (uri.contains("#")) {
12✔
93
            uri = uri.replaceFirst("^.*#(.*[^0-9].*)$", "$1");
18✔
94
        } else {
95
            uri = uri.replaceFirst("^.*/([^/]*[^0-9/][^/]*)$", "$1");
15✔
96
        }
97
        uri = uri.replaceFirst("((^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{8})[A-Za-z0-9\\-_]{35}$", "$1");
15✔
98
        uri = uri.replaceFirst("(^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{43}[^A-Za-z0-9\\-_](.+)$", "$2");
15✔
99
        uri = URLDecoder.decode(uri, UTF_8);
12✔
100
        return uri;
6✔
101
    }
102

103
    /**
104
     * Generates a short nanopublication ID from a given nanopublication ID or URI.
105
     *
106
     * @param npId the nanopublication ID or URI
107
     * @return the first 10 characters of the artifact code
108
     */
109
    public static String getShortNanopubId(Object npId) {
110
        return TrustyUriUtils.getArtifactCode(npId.toString()).substring(0, 10);
21✔
111
    }
112

113
    private static Map<String, Nanopub> nanopubs = new HashMap<>();
12✔
114

115
    /**
116
     * Adds a nanopublication to the local cache so it can be retrieved immediately
117
     * without needing to fetch it from the registry.
118
     *
119
     * @param np the nanopublication to cache
120
     */
121
    public static void cacheNanopub(Nanopub np) {
122
        String artifactCode = GetNanopub.getArtifactCode(np.getUri().stringValue()).toString();
×
123
        nanopubs.put(artifactCode, np);
×
124
    }
×
125

126
    /**
127
     * Retrieves a Nanopub object based on the given URI or artifact code.
128
     *
129
     * @param uriOrArtifactCode the URI or artifact code of the nanopublication
130
     * @return the Nanopub object, or null if not found
131
     */
132
    public static Nanopub getNanopub(String uriOrArtifactCode) {
133
        String artifactCode = GetNanopub.getArtifactCode(uriOrArtifactCode).toString();
12✔
134
        if (!nanopubs.containsKey(artifactCode)) {
12✔
135
            for (int i = 0; i < 3; i++) {  // Try 3 times to get nanopub
15!
136
                Nanopub np = GetNanopub.get(artifactCode);
9✔
137
                if (np != null) {
6!
138
                    nanopubs.put(artifactCode, np);
15✔
139
                    break;
3✔
140
                }
141
            }
142
        }
143
        return nanopubs.get(artifactCode);
15✔
144
    }
145

146
    /**
147
     * URL-encodes the string representation of the given object using UTF-8 encoding.
148
     *
149
     * @param o the object to be URL-encoded
150
     * @return the URL-encoded string
151
     */
152
    public static String urlEncode(Object o) {
153
        return URLEncoder.encode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
154
    }
155

156
    public static String truncateLabel(String label) {
157
        if (label != null && label.length() > 120) {
×
158
            return label.substring(0, 100) + "...";
×
159
        }
160
        return label;
×
161
    }
162

163
    /**
164
     * Builds the HTML body for a menu entry whose label may begin with a leading
165
     * symbol/emoji used as the entry's icon. If {@code label} starts with a token
166
     * of symbol/emoji characters (no letters or digits) followed by whitespace,
167
     * that token is wrapped in the {@code .actionmenu-icon} slot and the remaining
168
     * text follows it (both escaped). Returns {@code null} when there is no such
169
     * leading icon, so callers can fall back to the plain (escaped) label.
170
     *
171
     * @param label the menu entry label
172
     * @return the icon+text HTML body to render with escaping disabled, or null
173
     */
174
    public static String menuEntryIconBodyHtml(String label) {
175
        if (label == null) return null;
×
176
        int sp = -1;
×
177
        for (int i = 0; i < label.length(); i++) {
×
178
            if (Character.isWhitespace(label.charAt(i))) {
×
179
                sp = i;
×
180
                break;
×
181
            }
182
        }
183
        if (sp <= 0) return null;
×
184
        String icon = label.substring(0, sp);
×
185
        String rest = label.substring(sp).replaceFirst("^\\s+", "");
×
186
        if (rest.isEmpty()) return null;
×
187
        // Only a pure symbol/emoji token (no letters or digits) counts as an icon.
188
        if (icon.codePoints().anyMatch(Character::isLetterOrDigit)) return null;
×
189
        return "<span class=\"actionmenu-icon\">" + Strings.escapeMarkup(icon) + "</span>"
×
190
                + Strings.escapeMarkup(rest);
×
191
    }
192

193
    /**
194
     * URL-decodes the string representation of the given object using UTF-8 encoding.
195
     *
196
     * @param o the object to be URL-decoded
197
     * @return the URL-decoded string
198
     */
199
    public static String urlDecode(Object o) {
200
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
201
    }
202

203
    /**
204
     * Generates a URL with the given base and appends the provided PageParameters as query parameters.
205
     *
206
     * @param base       the base URL
207
     * @param parameters the PageParameters to append
208
     * @return the complete URL with parameters
209
     */
210
    public static String getUrlWithParameters(String base, PageParameters parameters) {
211
        try {
212
            URIBuilder u = new URIBuilder(base);
15✔
213
            for (String key : parameters.getNamedKeys()) {
33✔
214
                for (StringValue value : parameters.getValues(key)) {
36✔
215
                    if (!value.isNull()) u.addParameter(key, value.toString());
27!
216
                }
3✔
217
            }
3✔
218
            return u.build().toString();
12✔
219
        } catch (URISyntaxException ex) {
3✔
220
            logger.error("Could not build URL with parameters: {} {}", base, parameters, ex);
51✔
221
            return "/";
6✔
222
        }
223
    }
224

225
    /**
226
     * Generates a short name for a public key or public key hash.
227
     *
228
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
229
     * @return a short representation of the public key or public key hash
230
     */
231
    public static String getShortPubkeyName(String pubkeyOrPubkeyhash) {
232
        if (pubkeyOrPubkeyhash.length() == 64) {
12!
233
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
234
        } else {
235
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
15✔
236
        }
237
    }
238

239
    /**
240
     * Generates a short label for a public key or public key hash, including its status (local or approved).
241
     *
242
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
243
     * @param user               the IRI of the user associated with the public key
244
     * @return a short label indicating the public key and its status
245
     */
246
    public static String getShortPubkeyhashLabel(String pubkeyOrPubkeyhash, IRI user) {
247
        String s = getShortPubkeyName(pubkeyOrPubkeyhash);
×
248
        NanodashSession session = NanodashSession.get();
×
249
        List<String> l = new ArrayList<>();
×
250
        if (pubkeyOrPubkeyhash.equals(session.getPubkeyString()) || pubkeyOrPubkeyhash.equals(session.getPubkeyhash()))
×
251
            l.add("local");
×
252
        // TODO: Make this more efficient:
253
        String hashed = Utils.createSha256HexHash(pubkeyOrPubkeyhash);
×
254
        if (User.getPubkeyhashes(user, true).contains(pubkeyOrPubkeyhash) || User.getPubkeyhashes(user, true).contains(hashed))
×
255
            l.add("approved");
×
256
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
257
        return s;
×
258
    }
259

260
    /**
261
     * Retrieves the name of the public key location based on the public key.
262
     *
263
     * @param pubkeyhash the public key string
264
     * @return the name of the public key location
265
     */
266
    public static String getPubkeyLocationName(String pubkeyhash) {
267
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
268
    }
269

270
    /**
271
     * Retrieves the name of the public key location, or returns a fallback name if not found.
272
     * If the key location is localhost, it returns "localhost".
273
     *
274
     * @param pubkeyhash the public key string
275
     * @param fallback   the fallback name to return if the key location is not found
276
     * @return the name of the public key location or the fallback name
277
     */
278
    public static String getPubkeyLocationName(String pubkeyhash, String fallback) {
279
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
280
        if (keyLocation == null) return fallback;
×
281
        if (keyLocation.stringValue().equals("http://localhost:37373/")) return "localhost";
×
282
        return keyLocation.stringValue().replaceFirst("https?://(nanobench\\.)?(nanodash\\.(?=.*\\..))?(.*[^/])/?$", "$3");
×
283
    }
284

285
    /**
286
     * Generates a short label for a public key location, including its status (local or approved).
287
     *
288
     * @param pubkeyhash the public key string
289
     * @param user       the IRI of the user associated with the public key
290
     * @return a short label indicating the public key location and its status
291
     */
292
    public static String getShortPubkeyLocationLabel(String pubkeyhash, IRI user) {
293
        String s = getPubkeyLocationName(pubkeyhash);
×
294
        NanodashSession session = NanodashSession.get();
×
295
        List<String> l = new ArrayList<>();
×
296
        if (pubkeyhash.equals(session.getPubkeyhash())) l.add("local");
×
297
        // TODO: Make this more efficient:
298
        if (User.getPubkeyhashes(user, true).contains(pubkeyhash)) l.add("approved");
×
299
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
300
        return s;
×
301
    }
302

303
    /**
304
     * Checks if a given public key has a Nanodash location.
305
     * A Nanodash location is identified by specific keywords in the key location.
306
     *
307
     * @param pubkeyhash the public key to check
308
     * @return true if the public key has a Nanodash location, false otherwise
309
     */
310
    public static boolean hasNanodashLocation(String pubkeyhash) {
311
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
312
        if (keyLocation == null) return true; // potentially a Nanodash location
×
313
        if (keyLocation.stringValue().contains("nanodash")) return true;
×
314
        if (keyLocation.stringValue().contains("nanobench")) return true;
×
315
        if (keyLocation.stringValue().contains(":37373")) return true;
×
316
        return false;
×
317
    }
318

319
    /**
320
     * Retrieves the short ORCID ID from an IRI object.
321
     *
322
     * @param orcidIri the IRI object representing the ORCID ID
323
     * @return the short ORCID ID as a string
324
     */
325
    public static String getShortOrcidId(IRI orcidIri) {
326
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
18✔
327
    }
328

329
    /**
330
     * Retrieves the URI postfix from a given URI object.
331
     *
332
     * @param uri the URI object from which to extract the postfix
333
     * @return the URI postfix as a string
334
     */
335
    public static String getUriPostfix(Object uri) {
336
        String s = uri.toString();
9✔
337
        if (s.contains("#")) return s.replaceFirst("^.*#(.*)$", "$1");
27✔
338
        return s.replaceFirst("^.*/(.*)$", "$1");
15✔
339
    }
340

341
    /**
342
     * Retrieves the URI prefix from a given URI object.
343
     *
344
     * @param uri the URI object from which to extract the prefix
345
     * @return the URI prefix as a string
346
     */
347
    public static String getUriPrefix(Object uri) {
348
        String s = uri.toString();
9✔
349
        if (s.contains("#")) return s.replaceFirst("^(.*#).*$", "$1");
27✔
350
        return s.replaceFirst("^(.*/).*$", "$1");
15✔
351
    }
352

353
    /**
354
     * Checks if a given string is a valid URI postfix.
355
     * A valid URI postfix does not contain a colon (":").
356
     *
357
     * @param s the string to check
358
     * @return true if the string is a valid URI postfix, false otherwise
359
     */
360
    public static boolean isUriPostfix(String s) {
361
        return !s.contains(":");
24✔
362
    }
363

364
    /**
365
     * Retrieves the location of a given IntroNanopub.
366
     *
367
     * @param inp the IntroNanopub from which to extract the location
368
     * @return the IRI location of the nanopublication, or null if not found
369
     */
370
    public static IRI getLocation(IntroNanopub inp) {
371
        NanopubSignatureElement el = getNanopubSignatureElement(inp);
×
372
        for (KeyDeclaration kd : inp.getKeyDeclarations()) {
×
373
            if (el.getPublicKeyString().equals(kd.getPublicKeyString())) {
×
374
                return kd.getKeyLocation();
×
375
            }
376
        }
×
377
        return null;
×
378
    }
379

380
    /**
381
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
382
     *
383
     * @param inp the IntroNanopub from which to extract the signature element
384
     * @return the NanopubSignatureElement associated with the nanopublication
385
     */
386
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
387
        try {
388
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
389
        } catch (MalformedCryptoElementException ex) {
×
390
            throw new RuntimeException(ex);
×
391
        }
392
    }
393

394
    /**
395
     * Retrieves a Nanopub object from a given URI if it is a potential Trusty URI.
396
     *
397
     * @param uri the URI to check and retrieve the Nanopub from
398
     * @return the Nanopub object if found, or null if not a known nanopublication
399
     */
400
    public static Nanopub getAsNanopub(String uri) {
401
        if (uri == null) return null;
6!
402
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
9!
403
            try {
404
                return Utils.getNanopub(uri);
9✔
405
            } catch (Exception ex) {
×
406
                logger.error("The given URI is not a known nanopublication: {}", uri, ex);
×
407
            }
408
        }
409
        return null;
×
410
    }
411

412
    private static final PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder()
9✔
413
            .allowCommonBlockElements()
3✔
414
            .allowCommonInlineFormattingElements()
45✔
415
            .allowUrlProtocols("https", "http", "mailto")
21✔
416
            .allowElements("a")
21✔
417
            .allowAttributes("href").onElements("a")
42✔
418
            .allowElements("img")
21✔
419
            .allowAttributes("src").onElements("img")
42✔
420
            .allowElements("pre")
3✔
421
            .requireRelNofollowOnLinks()
3✔
422
            .toFactory();
6✔
423

424
    /**
425
     * Sanitizes raw HTML input to ensure safe rendering.
426
     *
427
     * @param rawHtml the raw HTML input to sanitize
428
     * @return sanitized HTML string
429
     */
430
    public static String sanitizeHtml(String rawHtml) {
431
        return htmlSanitizePolicy.sanitize(rawHtml);
12✔
432
    }
433

434
    /**
435
     * Checks if a given string is likely to be HTML content.
436
     *
437
     * @param value the string to check
438
     * @return true if the given string is HTML content, false otherwise
439
     */
440
    public static boolean looksLikeHtml(String value) {
441
        return LEADING_TAG.matcher(value).find();
×
442
    }
443

444
    /**
445
     * Matches an xsd:dateTime-style literal with a time component, e.g.
446
     * "2026-04-16T08:27:12.954Z" or "2026-04-16T08:27:12+02:00".
447
     */
448
    private static final Pattern DATETIME_LITERAL =
3✔
449
            Pattern.compile("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$");
6✔
450

451
    /**
452
     * Checks whether a (raw query-result) string looks like an ISO-8601 date-time literal.
453
     *
454
     * @param value the string to check
455
     * @return true if the string parses as an xsd:dateTime-style value
456
     */
457
    public static boolean isDateTimeLiteral(String value) {
458
        return value != null && DATETIME_LITERAL.matcher(value).matches();
×
459
    }
460

461
    /**
462
     * Renders a {@code <time>} element for an ISO-8601 date-time value. The machine-readable
463
     * value goes in the {@code datetime} attribute; client-side script (nanodash.js) rewrites
464
     * the visible text to a relative form ("10 minutes ago") in the viewer's local timezone and
465
     * puts the absolute date-time in the tooltip. If script does not run, {@code fallbackText}
466
     * remains visible.
467
     *
468
     * @param isoValue     the ISO-8601 date-time string (machine-readable)
469
     * @param fallbackText the human-readable text shown when script is unavailable
470
     * @return an HTML {@code <time>} element string (caller must render with escaping disabled)
471
     */
472
    public static String friendlyDateHtml(String isoValue, String fallbackText) {
473
        return "<time class=\"friendly-date\" datetime=\"" + Strings.escapeMarkup(isoValue) + "\">"
×
474
                + Strings.escapeMarkup(fallbackText) + "</time>";
×
475
    }
476

477
    /**
478
     * Converts PageParameters to a URL-encoded string representation.
479
     *
480
     * @param params the PageParameters to convert
481
     * @return a string representation of the parameters in URL-encoded format
482
     */
483
    public static String getPageParametersAsString(PageParameters params) {
484
        String s = "";
6✔
485
        for (String n : params.getNamedKeys()) {
33✔
486
            if (!s.isEmpty()) s += "&";
18✔
487
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
30✔
488
        }
3✔
489
        return s;
6✔
490
    }
491

492
    /**
493
     * Sets a minimal escape markup function for a Select2Choice component.
494
     * This function replaces certain characters and formats the display of choices.
495
     *
496
     * @param selectItem the Select2Choice component to set the escape markup for
497
     */
498
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
499
        selectItem.getSettings().setEscapeMarkup("function(markup) {" +
15✔
500
                                                 "return markup" +
501
                                                 ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" +
502
                                                 ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" +
503
                                                 ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" +
504
                                                 ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" +
505
                                                 ";}"
506
        );
507
    }
3✔
508

509
    /**
510
     * Checks if a nanopublication is of a specific class.
511
     *
512
     * @param np       the nanopublication to check
513
     * @param classIri the IRI of the class to check against
514
     * @return true if the nanopublication is of the specified class, false otherwise
515
     */
516
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
517
        return NanopubUtils.getTypes(np).contains(classIri);
15✔
518
    }
519

520
    /**
521
     * Checks if a nanopublication uses a specific predicate in its assertion.
522
     *
523
     * @param np           the nanopublication to check
524
     * @param predicateIri the IRI of the predicate to look for
525
     * @return true if the predicate is used in the assertion, false otherwise
526
     */
527
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
528
        for (Statement st : np.getAssertion()) {
33✔
529
            if (predicateIri.equals(st.getPredicate())) {
15✔
530
                return true;
6✔
531
            }
532
        }
3✔
533
        return false;
6✔
534
    }
535

536
    /**
537
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
538
     *
539
     * @param np the nanopublication from which to extract FOAF names
540
     * @return a map where keys are subjects and values are FOAF names
541
     */
542
    public static Map<String, String> getFoafNameMap(Nanopub np) {
543
        Map<String, String> foafNameMap = new HashMap<>();
12✔
544
        for (Statement st : np.getPubinfo()) {
33✔
545
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
42✔
546
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
24✔
547
            }
548
        }
3✔
549
        return foafNameMap;
6✔
550
    }
551

552
    /**
553
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
554
     *
555
     * @param obj the object to hash
556
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
557
     */
558
    public static String createSha256HexHash(Object obj) {
559
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21✔
560
    }
561

562
    /**
563
     * Gets the types of a nanopublication.
564
     *
565
     * @param np the nanopublication from which to extract types
566
     * @return a list of IRI types associated with the nanopublication
567
     */
568
    public static List<IRI> getTypes(Nanopub np) {
569
        List<IRI> l = new ArrayList<>();
12✔
570
        for (IRI t : NanopubUtils.getTypes(np)) {
33✔
571
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) continue;
15✔
572
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED))
12✔
573
                continue;
3✔
574
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) continue;
12!
575
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED))
12!
576
                continue;
×
577
            l.add(t);
12✔
578
        }
3✔
579
        return l;
6✔
580
    }
581

582
    /**
583
     * Gets a label for a type IRI.
584
     *
585
     * @param typeIri the IRI of the type
586
     * @return a label for the type, potentially truncated
587
     */
588
    public static String getTypeLabel(IRI typeIri) {
589
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) return "FER";
18✔
590
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) return "FSR";
18✔
591
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) return "FIP";
18✔
592
        if (typeIri.equals(NPX.DECLARED_BY)) return "user intro";
18✔
593
        String l = typeIri.stringValue();
9✔
594
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
15✔
595
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
15✔
596
        if (l.length() > 25) l = l.substring(0, 20) + "...";
30✔
597
        return l;
6✔
598
    }
599

600
    /**
601
     * Gets a label for a URI.
602
     *
603
     * @param uri the URI to get the label from
604
     * @return a label for the URI, potentially truncated
605
     */
606
    public static String getUriLabel(String uri) {
607
        if (uri == null) return "";
12✔
608
        String uriLabel = uri;
6✔
609
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
12✔
610
            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✔
611
            if (newUriLabel.length() <= 70) return newUriLabel;
18!
612
        }
613
        if (uriLabel.length() > 70) return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
48✔
614
        return uriLabel;
6✔
615
    }
616

617
    /**
618
     * Gets an ExternalLink with a URI label.
619
     *
620
     * @param markupId the markup ID for the link
621
     * @param uri      the URI to link to
622
     * @return an ExternalLink with the URI label
623
     */
624
    public static ExternalLink getUriLink(String markupId, String uri) {
625
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39✔
626
    }
627

628
    /**
629
     * Gets an ExternalLink with a model for the URI label.
630
     *
631
     * @param markupId the markup ID for the link
632
     * @param model    the model containing the URI
633
     * @return an ExternalLink with the URI label
634
     */
635
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
636
        return new ExternalLink(markupId, model, new UriLabelModel(model));
30✔
637
    }
638

639
    private static class UriLabelModel implements IModel<String> {
640

641
        private IModel<String> uriModel;
642

643
        public UriLabelModel(IModel<String> uriModel) {
6✔
644
            this.uriModel = uriModel;
9✔
645
        }
3✔
646

647
        @Override
648
        public String getObject() {
649
            return getUriLabel(uriModel.getObject());
×
650
        }
651

652
    }
653

654
    /**
655
     * Creates a sublist from a list based on the specified indices.
656
     *
657
     * @param list      the list from which to create the sublist
658
     * @param fromIndex the starting index (inclusive) for the sublist
659
     * @param toIndex   the ending index (exclusive) for the sublist
660
     * @param <E>       the type of elements in the list
661
     * @return an ArrayList containing the elements from the specified range
662
     */
663
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
664
        // So the resulting list is serializable:
665
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
×
666
    }
667

668
    /**
669
     * Creates a sublist from an array based on the specified indices.
670
     *
671
     * @param array     the array from which to create the sublist
672
     * @param fromIndex the starting index (inclusive) for the sublist
673
     * @param toIndex   the ending index (exclusive) for the sublist
674
     * @param <E>       the type of elements in the array
675
     * @return an ArrayList containing the elements from the specified range
676
     */
677
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
678
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
679
    }
680

681
    /**
682
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
683
     */
684
    // TODO Move this to ApiResponseEntry class?
685
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
686

687
        private String field;
688
        private boolean descending;
689

690
        /**
691
         * Constructor for ApiResponseEntrySorter.
692
         *
693
         * @param field      the field to sort by
694
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
695
         */
696
        public ApiResponseEntrySorter(String field, boolean descending) {
×
697
            this.field = field;
×
698
            this.descending = descending;
×
699
        }
×
700

701
        /**
702
         * Compares two ApiResponseEntry objects based on the specified field.
703
         *
704
         * @param o1 the first object to be compared.
705
         * @param o2 the second object to be compared.
706
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
707
         */
708
        @Override
709
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
710
            if (descending) {
×
711
                return o2.get(field).compareTo(o1.get(field));
×
712
            } else {
713
                return o1.get(field).compareTo(o2.get(field));
×
714
            }
715
        }
716

717
    }
718

719
    /**
720
     * MIME type for TriG RDF format.
721
     */
722
    public static final String TYPE_TRIG = "application/trig";
723

724
    /**
725
     * MIME type for Jelly RDF format.
726
     */
727
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
728

729
    /**
730
     * MIME type for JSON-LD format.
731
     */
732
    public static final String TYPE_JSONLD = "application/ld+json";
733

734
    /**
735
     * MIME type for N-Quads format.
736
     */
737
    public static final String TYPE_NQUADS = "application/n-quads";
738

739
    /**
740
     * MIME type for Trix format.
741
     */
742
    public static final String TYPE_TRIX = "application/trix";
743

744
    /**
745
     * MIME type for HTML format.
746
     */
747
    public static final String TYPE_HTML = "text/html";
748

749
    /**
750
     * Comma-separated list of supported MIME types for nanopublications.
751
     */
752
    public static final String SUPPORTED_TYPES =
753
            TYPE_TRIG + "," +
754
            TYPE_JELLY + "," +
755
            TYPE_JSONLD + "," +
756
            TYPE_NQUADS + "," +
757
            TYPE_TRIX + "," +
758
            TYPE_HTML;
759

760
    /**
761
     * List of supported MIME types for nanopublications.
762
     */
763
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
18✔
764

765
    private static volatile String resolvedMainRegistryUrl;
766
    private static volatile String resolvedMainQueryUrl;
767

768
    /**
769
     * Eagerly resolves the main registry and query URLs. Call at application startup
770
     * so the (potentially slow) first-time discovery does not happen during a user request.
771
     */
772
    public static void initMainUrls() {
773
        getMainRegistryUrl();
6✔
774
        getMainQueryUrl();
6✔
775
    }
3✔
776

777
    /**
778
     * Returns the URL of the main Nanopub Registry for this nanodash instance.
779
     * <p>
780
     * If {@code NANODASH_MAIN_REGISTRY} is set and matches an entry in the library's
781
     * discovered registry instance list, that URL is used. Otherwise the first entry
782
     * of the library list is used. If the library list is empty, the env var value
783
     * (or built-in default) is used unvalidated. The result is cached for the JVM lifetime.
784
     *
785
     * @return Nanopub Registry URL (with trailing slash)
786
     */
787
    public static String getMainRegistryUrl() {
788
        if (resolvedMainRegistryUrl == null) {
6✔
789
            synchronized (Utils.class) {
12✔
790
                if (resolvedMainRegistryUrl == null) {
6!
791
                    resolvedMainRegistryUrl = resolveMainRegistryUrl();
6✔
792
                }
793
            }
9✔
794
        }
795
        return resolvedMainRegistryUrl;
6✔
796
    }
797

798
    /**
799
     * Returns the URL of the main Nanopub Query API for this nanodash instance.
800
     * <p>
801
     * If {@code NANODASH_MAIN_QUERY} is set and matches an entry in the library's
802
     * discovered query instance list, that URL is used. Otherwise the first entry
803
     * of the library list is used. If the library list is empty, the env var value
804
     * (or built-in default) is used unvalidated. The result is cached for the JVM lifetime.
805
     *
806
     * @return Nanopub Query URL (with trailing slash)
807
     */
808
    public static String getMainQueryUrl() {
809
        if (resolvedMainQueryUrl == null) {
6✔
810
            synchronized (Utils.class) {
12✔
811
                if (resolvedMainQueryUrl == null) {
6!
812
                    resolvedMainQueryUrl = resolveMainQueryUrl();
6✔
813
                }
814
            }
9✔
815
        }
816
        return resolvedMainQueryUrl;
6✔
817
    }
818

819
    private static String resolveMainRegistryUrl() {
820
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_REGISTRY"));
12✔
821
        List<String> instances;
822
        try {
823
            instances = NanopubServerUtils.getRegistryServerList();
6✔
824
        } catch (Exception ex) {
×
825
            logger.warn("Could not retrieve registry instance list from nanopub library: {}", ex.toString());
×
826
            instances = Collections.emptyList();
×
827
        }
3✔
828
        return resolveMainUrl("NANODASH_MAIN_REGISTRY", envValue, instances, DEFAULT_MAIN_REGISTRY_URL);
18✔
829
    }
830

831
    private static String resolveMainQueryUrl() {
832
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_QUERY"));
12✔
833
        List<String> instances;
834
        try {
835
            instances = QueryCall.getApiInstances();
6✔
836
        } catch (NotEnoughAPIInstancesException ex) {
×
837
            logger.warn("Nanopub library reports not enough query API instances available: {}", ex.toString());
×
838
            instances = Collections.emptyList();
×
839
        } catch (Exception ex) {
×
840
            logger.warn("Could not retrieve query instance list from nanopub library: {}", ex.toString());
×
841
            instances = Collections.emptyList();
×
842
        }
3✔
843
        return resolveMainUrl("NANODASH_MAIN_QUERY", envValue, instances, DEFAULT_MAIN_QUERY_URL);
18✔
844
    }
845

846
    private static String resolveMainUrl(String envVarName, String envValue, List<String> instances, String builtInDefault) {
847
        if (envValue != null) {
6!
848
            if (containsNormalized(instances, envValue)) {
×
849
                logger.info("Using main URL from {} (validated against library instance list): {}", envVarName, envValue);
×
850
                return ensureTrailingSlash(envValue);
×
851
            }
852
            if (instances.isEmpty()) {
×
853
                logger.warn("Library instance list is empty; using {} unvalidated: {}", envVarName, envValue);
×
854
                return ensureTrailingSlash(envValue);
×
855
            }
856
            logger.warn("{}={} is not in the library instance list {}; falling back to first library instance",
×
857
                    envVarName, envValue, instances);
858
            return ensureTrailingSlash(instances.get(0));
×
859
        }
860
        if (!instances.isEmpty()) {
9!
861
            String first = instances.get(0);
15✔
862
            logger.info("{} not set; using first library instance: {}", envVarName, first);
15✔
863
            return ensureTrailingSlash(first);
9✔
864
        }
865
        logger.warn("{} not set and library instance list is empty; using built-in default: {}", envVarName, builtInDefault);
×
866
        return builtInDefault;
×
867
    }
868

869
    private static boolean containsNormalized(List<String> urls, String target) {
870
        String normTarget = normalizeUrl(target);
×
871
        for (String url : urls) {
×
872
            if (normalizeUrl(url).equals(normTarget)) return true;
×
873
        }
×
874
        return false;
×
875
    }
876

877
    private static String normalizeUrl(String url) {
878
        if (url == null) return "";
×
879
        return url.trim().replaceFirst("/+$", "").toLowerCase(Locale.ROOT);
×
880
    }
881

882
    private static String ensureTrailingSlash(String url) {
883
        return url.endsWith("/") ? url : url + "/";
21!
884
    }
885

886
    private static String trimToNull(String s) {
887
        if (s == null) return null;
12!
888
        s = s.trim();
×
889
        return s.isEmpty() ? null : s;
×
890
    }
891

892
    private static final String PLAIN_LITERAL_PATTERN = "^\"(([^\\\\\\\"]|\\\\\\\\|\\\\\")*)\"";
893
    private static final String LANGTAG_LITERAL_PATTERN = "^\"(([^\\\\\\\"]|\\\\\\\\|\\\\\")*)\"@([0-9a-zA-Z-]{2,})$";
894
    private static final String DATATYPE_LITERAL_PATTERN = "^\"(([^\\\\\\\"]|\\\\\\\\|\\\\\")*)\"\\^\\^<([^ ><\"^]+)>";
895

896
    /**
897
     * Checks whether string is valid literal serialization.
898
     *
899
     * @param literalString the literal string
900
     * @return true if valid
901
     */
902
    public static boolean isValidLiteralSerialization(String literalString) {
903
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
12✔
904
            return true;
6✔
905
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
906
            return true;
6✔
907
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
908
            return true;
6✔
909
        }
910
        return false;
6✔
911
    }
912

913
    /**
914
     * Returns a serialized version of the literal.
915
     *
916
     * @param literal the literal
917
     * @return the String serialization of the literal
918
     */
919
    public static String getSerializedLiteral(Literal literal) {
920
        if (literal.getLanguage().isPresent()) {
12✔
921
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
30✔
922
        } else if (literal.getDatatype().equals(XSD.STRING)) {
15✔
923
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
15✔
924
        } else {
925
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
24✔
926
        }
927
    }
928

929
    /**
930
     * Parses a serialized literal into a Literal object.
931
     *
932
     * @param serializedLiteral The serialized String of the literal
933
     * @return The parse Literal object
934
     */
935
    public static Literal getParsedLiteral(String serializedLiteral) {
936
        if (serializedLiteral.matches(PLAIN_LITERAL_PATTERN)) {
12✔
937
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(PLAIN_LITERAL_PATTERN, "$1")));
24✔
938
        } else if (serializedLiteral.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
939
            String langtag = serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$3");
15✔
940
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$1")), langtag);
27✔
941
        } else if (serializedLiteral.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
942
            IRI datatype = vf.createIRI(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$3"));
21✔
943
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$1")), datatype);
27✔
944
        }
945
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
18✔
946
    }
947

948
    /**
949
     * Escapes quotes (") and slashes (/) of a literal string.
950
     *
951
     * @param unescapedString un-escaped string
952
     * @return escaped string
953
     */
954
    public static String getEscapedLiteralString(String unescapedString) {
955
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
24✔
956
    }
957

958
    /**
959
     * Un-escapes quotes (") and slashes (/) of a literal string.
960
     *
961
     * @param escapedString escaped string
962
     * @return un-escaped string
963
     */
964
    public static String getUnescapedLiteralString(String escapedString) {
965
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
15✔
966
    }
967

968
    /**
969
     * Checks if a given IRI is a local URI.
970
     *
971
     * @param uri the IRI to check
972
     * @return true if the IRI is a local URI, false otherwise
973
     */
974
    public static boolean isLocalURI(IRI uri) {
975
        return uri != null && isLocalURI(uri.stringValue());
30✔
976
    }
977

978
    /**
979
     * Checks if a given string is a local URI.
980
     *
981
     * @param uriAsString the string to check
982
     * @return true if the string is a local URI, false otherwise
983
     */
984
    public static boolean isLocalURI(String uriAsString) {
985
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33✔
986
    }
987

988
    public static String unescapeMultiValue(String s) {
989
        StringBuilder sb = new StringBuilder();
12✔
990
        for (int i = 0; i < s.length(); i++) {
24✔
991
            if (s.charAt(i) == '\\' && i + 1 < s.length()) {
33✔
992
                char next = s.charAt(i + 1);
18✔
993
                if (next == 'n') {
9✔
994
                    sb.append('\n');
15✔
995
                } else if (next == '\\') {
9!
996
                    sb.append('\\');
15✔
997
                } else {
998
                    sb.append(next);
×
999
                }
1000
                i++;
3✔
1001
            } else {
3✔
1002
                sb.append(s.charAt(i));
18✔
1003
            }
1004
        }
1005
        return sb.toString();
9✔
1006
    }
1007

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

© 2026 Coveralls, Inc