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

knowledgepixels / nanodash / 27002740934

05 Jun 2026 07:52AM UTC coverage: 20.916% (-0.008%) from 20.924%
27002740934

Pull #480

github

web-flow
Merge e88114680 into 2994792b0
Pull Request #480: feat: friendly relative dates ("10 minutes ago")

1003 of 6118 branches covered (16.39%)

Branch coverage included in aggregate %.

2586 of 11041 relevant lines covered (23.42%)

3.35 hits per line

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

64.85
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
     * URL-decodes the string representation of the given object using UTF-8 encoding.
165
     *
166
     * @param o the object to be URL-decoded
167
     * @return the URL-decoded string
168
     */
169
    public static String urlDecode(Object o) {
170
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
171
    }
172

173
    /**
174
     * Generates a URL with the given base and appends the provided PageParameters as query parameters.
175
     *
176
     * @param base       the base URL
177
     * @param parameters the PageParameters to append
178
     * @return the complete URL with parameters
179
     */
180
    public static String getUrlWithParameters(String base, PageParameters parameters) {
181
        try {
182
            URIBuilder u = new URIBuilder(base);
15✔
183
            for (String key : parameters.getNamedKeys()) {
33✔
184
                for (StringValue value : parameters.getValues(key)) {
36✔
185
                    if (!value.isNull()) u.addParameter(key, value.toString());
27!
186
                }
3✔
187
            }
3✔
188
            return u.build().toString();
12✔
189
        } catch (URISyntaxException ex) {
3✔
190
            logger.error("Could not build URL with parameters: {} {}", base, parameters, ex);
51✔
191
            return "/";
6✔
192
        }
193
    }
194

195
    /**
196
     * Generates a short name for a public key or public key hash.
197
     *
198
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
199
     * @return a short representation of the public key or public key hash
200
     */
201
    public static String getShortPubkeyName(String pubkeyOrPubkeyhash) {
202
        if (pubkeyOrPubkeyhash.length() == 64) {
12!
203
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
204
        } else {
205
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
15✔
206
        }
207
    }
208

209
    /**
210
     * Generates a short label for a public key or public key hash, including its status (local or approved).
211
     *
212
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
213
     * @param user               the IRI of the user associated with the public key
214
     * @return a short label indicating the public key and its status
215
     */
216
    public static String getShortPubkeyhashLabel(String pubkeyOrPubkeyhash, IRI user) {
217
        String s = getShortPubkeyName(pubkeyOrPubkeyhash);
×
218
        NanodashSession session = NanodashSession.get();
×
219
        List<String> l = new ArrayList<>();
×
220
        if (pubkeyOrPubkeyhash.equals(session.getPubkeyString()) || pubkeyOrPubkeyhash.equals(session.getPubkeyhash()))
×
221
            l.add("local");
×
222
        // TODO: Make this more efficient:
223
        String hashed = Utils.createSha256HexHash(pubkeyOrPubkeyhash);
×
224
        if (User.getPubkeyhashes(user, true).contains(pubkeyOrPubkeyhash) || User.getPubkeyhashes(user, true).contains(hashed))
×
225
            l.add("approved");
×
226
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
227
        return s;
×
228
    }
229

230
    /**
231
     * Retrieves the name of the public key location based on the public key.
232
     *
233
     * @param pubkeyhash the public key string
234
     * @return the name of the public key location
235
     */
236
    public static String getPubkeyLocationName(String pubkeyhash) {
237
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
238
    }
239

240
    /**
241
     * Retrieves the name of the public key location, or returns a fallback name if not found.
242
     * If the key location is localhost, it returns "localhost".
243
     *
244
     * @param pubkeyhash the public key string
245
     * @param fallback   the fallback name to return if the key location is not found
246
     * @return the name of the public key location or the fallback name
247
     */
248
    public static String getPubkeyLocationName(String pubkeyhash, String fallback) {
249
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
250
        if (keyLocation == null) return fallback;
×
251
        if (keyLocation.stringValue().equals("http://localhost:37373/")) return "localhost";
×
252
        return keyLocation.stringValue().replaceFirst("https?://(nanobench\\.)?(nanodash\\.(?=.*\\..))?(.*[^/])/?$", "$3");
×
253
    }
254

255
    /**
256
     * Generates a short label for a public key location, including its status (local or approved).
257
     *
258
     * @param pubkeyhash the public key string
259
     * @param user       the IRI of the user associated with the public key
260
     * @return a short label indicating the public key location and its status
261
     */
262
    public static String getShortPubkeyLocationLabel(String pubkeyhash, IRI user) {
263
        String s = getPubkeyLocationName(pubkeyhash);
×
264
        NanodashSession session = NanodashSession.get();
×
265
        List<String> l = new ArrayList<>();
×
266
        if (pubkeyhash.equals(session.getPubkeyhash())) l.add("local");
×
267
        // TODO: Make this more efficient:
268
        if (User.getPubkeyhashes(user, true).contains(pubkeyhash)) l.add("approved");
×
269
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
270
        return s;
×
271
    }
272

273
    /**
274
     * Checks if a given public key has a Nanodash location.
275
     * A Nanodash location is identified by specific keywords in the key location.
276
     *
277
     * @param pubkeyhash the public key to check
278
     * @return true if the public key has a Nanodash location, false otherwise
279
     */
280
    public static boolean hasNanodashLocation(String pubkeyhash) {
281
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
282
        if (keyLocation == null) return true; // potentially a Nanodash location
×
283
        if (keyLocation.stringValue().contains("nanodash")) return true;
×
284
        if (keyLocation.stringValue().contains("nanobench")) return true;
×
285
        if (keyLocation.stringValue().contains(":37373")) return true;
×
286
        return false;
×
287
    }
288

289
    /**
290
     * Retrieves the short ORCID ID from an IRI object.
291
     *
292
     * @param orcidIri the IRI object representing the ORCID ID
293
     * @return the short ORCID ID as a string
294
     */
295
    public static String getShortOrcidId(IRI orcidIri) {
296
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
18✔
297
    }
298

299
    /**
300
     * Retrieves the URI postfix from a given URI object.
301
     *
302
     * @param uri the URI object from which to extract the postfix
303
     * @return the URI postfix as a string
304
     */
305
    public static String getUriPostfix(Object uri) {
306
        String s = uri.toString();
9✔
307
        if (s.contains("#")) return s.replaceFirst("^.*#(.*)$", "$1");
27✔
308
        return s.replaceFirst("^.*/(.*)$", "$1");
15✔
309
    }
310

311
    /**
312
     * Retrieves the URI prefix from a given URI object.
313
     *
314
     * @param uri the URI object from which to extract the prefix
315
     * @return the URI prefix as a string
316
     */
317
    public static String getUriPrefix(Object uri) {
318
        String s = uri.toString();
9✔
319
        if (s.contains("#")) return s.replaceFirst("^(.*#).*$", "$1");
27✔
320
        return s.replaceFirst("^(.*/).*$", "$1");
15✔
321
    }
322

323
    /**
324
     * Checks if a given string is a valid URI postfix.
325
     * A valid URI postfix does not contain a colon (":").
326
     *
327
     * @param s the string to check
328
     * @return true if the string is a valid URI postfix, false otherwise
329
     */
330
    public static boolean isUriPostfix(String s) {
331
        return !s.contains(":");
24✔
332
    }
333

334
    /**
335
     * Retrieves the location of a given IntroNanopub.
336
     *
337
     * @param inp the IntroNanopub from which to extract the location
338
     * @return the IRI location of the nanopublication, or null if not found
339
     */
340
    public static IRI getLocation(IntroNanopub inp) {
341
        NanopubSignatureElement el = getNanopubSignatureElement(inp);
×
342
        for (KeyDeclaration kd : inp.getKeyDeclarations()) {
×
343
            if (el.getPublicKeyString().equals(kd.getPublicKeyString())) {
×
344
                return kd.getKeyLocation();
×
345
            }
346
        }
×
347
        return null;
×
348
    }
349

350
    /**
351
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
352
     *
353
     * @param inp the IntroNanopub from which to extract the signature element
354
     * @return the NanopubSignatureElement associated with the nanopublication
355
     */
356
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
357
        try {
358
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
359
        } catch (MalformedCryptoElementException ex) {
×
360
            throw new RuntimeException(ex);
×
361
        }
362
    }
363

364
    /**
365
     * Retrieves a Nanopub object from a given URI if it is a potential Trusty URI.
366
     *
367
     * @param uri the URI to check and retrieve the Nanopub from
368
     * @return the Nanopub object if found, or null if not a known nanopublication
369
     */
370
    public static Nanopub getAsNanopub(String uri) {
371
        if (uri == null) return null;
6!
372
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
9!
373
            try {
374
                return Utils.getNanopub(uri);
9✔
375
            } catch (Exception ex) {
×
376
                logger.error("The given URI is not a known nanopublication: {}", uri, ex);
×
377
            }
378
        }
379
        return null;
×
380
    }
381

382
    private static final PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder()
9✔
383
            .allowCommonBlockElements()
3✔
384
            .allowCommonInlineFormattingElements()
45✔
385
            .allowUrlProtocols("https", "http", "mailto")
21✔
386
            .allowElements("a")
21✔
387
            .allowAttributes("href").onElements("a")
42✔
388
            .allowElements("img")
21✔
389
            .allowAttributes("src").onElements("img")
42✔
390
            .allowElements("pre")
3✔
391
            .requireRelNofollowOnLinks()
3✔
392
            .toFactory();
6✔
393

394
    /**
395
     * Sanitizes raw HTML input to ensure safe rendering.
396
     *
397
     * @param rawHtml the raw HTML input to sanitize
398
     * @return sanitized HTML string
399
     */
400
    public static String sanitizeHtml(String rawHtml) {
401
        return htmlSanitizePolicy.sanitize(rawHtml);
12✔
402
    }
403

404
    /**
405
     * Checks if a given string is likely to be HTML content.
406
     *
407
     * @param value the string to check
408
     * @return true if the given string is HTML content, false otherwise
409
     */
410
    public static boolean looksLikeHtml(String value) {
411
        return LEADING_TAG.matcher(value).find();
×
412
    }
413

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

421
    /**
422
     * Checks whether a (raw query-result) string looks like an ISO-8601 date-time literal.
423
     *
424
     * @param value the string to check
425
     * @return true if the string parses as an xsd:dateTime-style value
426
     */
427
    public static boolean isDateTimeLiteral(String value) {
428
        return value != null && DATETIME_LITERAL.matcher(value).matches();
×
429
    }
430

431
    /**
432
     * Renders a {@code <time>} element for an ISO-8601 date-time value. The machine-readable
433
     * value goes in the {@code datetime} attribute; client-side script (nanodash.js) rewrites
434
     * the visible text to a relative form ("10 minutes ago") in the viewer's local timezone and
435
     * puts the absolute date-time in the tooltip. If script does not run, {@code fallbackText}
436
     * remains visible.
437
     *
438
     * @param isoValue     the ISO-8601 date-time string (machine-readable)
439
     * @param fallbackText the human-readable text shown when script is unavailable
440
     * @return an HTML {@code <time>} element string (caller must render with escaping disabled)
441
     */
442
    public static String friendlyDateHtml(String isoValue, String fallbackText) {
443
        return "<time class=\"friendly-date\" datetime=\"" + Strings.escapeMarkup(isoValue) + "\">"
×
444
                + Strings.escapeMarkup(fallbackText) + "</time>";
×
445
    }
446

447
    /**
448
     * Converts PageParameters to a URL-encoded string representation.
449
     *
450
     * @param params the PageParameters to convert
451
     * @return a string representation of the parameters in URL-encoded format
452
     */
453
    public static String getPageParametersAsString(PageParameters params) {
454
        String s = "";
6✔
455
        for (String n : params.getNamedKeys()) {
33✔
456
            if (!s.isEmpty()) s += "&";
18✔
457
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
30✔
458
        }
3✔
459
        return s;
6✔
460
    }
461

462
    /**
463
     * Sets a minimal escape markup function for a Select2Choice component.
464
     * This function replaces certain characters and formats the display of choices.
465
     *
466
     * @param selectItem the Select2Choice component to set the escape markup for
467
     */
468
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
469
        selectItem.getSettings().setEscapeMarkup("function(markup) {" +
15✔
470
                                                 "return markup" +
471
                                                 ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" +
472
                                                 ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" +
473
                                                 ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" +
474
                                                 ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" +
475
                                                 ";}"
476
        );
477
    }
3✔
478

479
    /**
480
     * Checks if a nanopublication is of a specific class.
481
     *
482
     * @param np       the nanopublication to check
483
     * @param classIri the IRI of the class to check against
484
     * @return true if the nanopublication is of the specified class, false otherwise
485
     */
486
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
487
        return NanopubUtils.getTypes(np).contains(classIri);
15✔
488
    }
489

490
    /**
491
     * Checks if a nanopublication uses a specific predicate in its assertion.
492
     *
493
     * @param np           the nanopublication to check
494
     * @param predicateIri the IRI of the predicate to look for
495
     * @return true if the predicate is used in the assertion, false otherwise
496
     */
497
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
498
        for (Statement st : np.getAssertion()) {
33✔
499
            if (predicateIri.equals(st.getPredicate())) {
15✔
500
                return true;
6✔
501
            }
502
        }
3✔
503
        return false;
6✔
504
    }
505

506
    /**
507
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
508
     *
509
     * @param np the nanopublication from which to extract FOAF names
510
     * @return a map where keys are subjects and values are FOAF names
511
     */
512
    public static Map<String, String> getFoafNameMap(Nanopub np) {
513
        Map<String, String> foafNameMap = new HashMap<>();
12✔
514
        for (Statement st : np.getPubinfo()) {
33✔
515
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
42✔
516
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
24✔
517
            }
518
        }
3✔
519
        return foafNameMap;
6✔
520
    }
521

522
    /**
523
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
524
     *
525
     * @param obj the object to hash
526
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
527
     */
528
    public static String createSha256HexHash(Object obj) {
529
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21✔
530
    }
531

532
    /**
533
     * Gets the types of a nanopublication.
534
     *
535
     * @param np the nanopublication from which to extract types
536
     * @return a list of IRI types associated with the nanopublication
537
     */
538
    public static List<IRI> getTypes(Nanopub np) {
539
        List<IRI> l = new ArrayList<>();
12✔
540
        for (IRI t : NanopubUtils.getTypes(np)) {
33✔
541
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) continue;
15✔
542
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED))
12✔
543
                continue;
3✔
544
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) continue;
12!
545
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED))
12!
546
                continue;
×
547
            l.add(t);
12✔
548
        }
3✔
549
        return l;
6✔
550
    }
551

552
    /**
553
     * Gets a label for a type IRI.
554
     *
555
     * @param typeIri the IRI of the type
556
     * @return a label for the type, potentially truncated
557
     */
558
    public static String getTypeLabel(IRI typeIri) {
559
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) return "FER";
18✔
560
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) return "FSR";
18✔
561
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) return "FIP";
18✔
562
        if (typeIri.equals(NPX.DECLARED_BY)) return "user intro";
18✔
563
        String l = typeIri.stringValue();
9✔
564
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
15✔
565
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
15✔
566
        if (l.length() > 25) l = l.substring(0, 20) + "...";
30✔
567
        return l;
6✔
568
    }
569

570
    /**
571
     * Gets a label for a URI.
572
     *
573
     * @param uri the URI to get the label from
574
     * @return a label for the URI, potentially truncated
575
     */
576
    public static String getUriLabel(String uri) {
577
        if (uri == null) return "";
12✔
578
        String uriLabel = uri;
6✔
579
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
12✔
580
            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✔
581
            if (newUriLabel.length() <= 70) return newUriLabel;
18!
582
        }
583
        if (uriLabel.length() > 70) return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
48✔
584
        return uriLabel;
6✔
585
    }
586

587
    /**
588
     * Gets an ExternalLink with a URI label.
589
     *
590
     * @param markupId the markup ID for the link
591
     * @param uri      the URI to link to
592
     * @return an ExternalLink with the URI label
593
     */
594
    public static ExternalLink getUriLink(String markupId, String uri) {
595
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39✔
596
    }
597

598
    /**
599
     * Gets an ExternalLink with a model for the URI label.
600
     *
601
     * @param markupId the markup ID for the link
602
     * @param model    the model containing the URI
603
     * @return an ExternalLink with the URI label
604
     */
605
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
606
        return new ExternalLink(markupId, model, new UriLabelModel(model));
30✔
607
    }
608

609
    private static class UriLabelModel implements IModel<String> {
610

611
        private IModel<String> uriModel;
612

613
        public UriLabelModel(IModel<String> uriModel) {
6✔
614
            this.uriModel = uriModel;
9✔
615
        }
3✔
616

617
        @Override
618
        public String getObject() {
619
            return getUriLabel(uriModel.getObject());
×
620
        }
621

622
    }
623

624
    /**
625
     * Creates a sublist from a list based on the specified indices.
626
     *
627
     * @param list      the list from which to create the sublist
628
     * @param fromIndex the starting index (inclusive) for the sublist
629
     * @param toIndex   the ending index (exclusive) for the sublist
630
     * @param <E>       the type of elements in the list
631
     * @return an ArrayList containing the elements from the specified range
632
     */
633
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
634
        // So the resulting list is serializable:
635
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
×
636
    }
637

638
    /**
639
     * Creates a sublist from an array based on the specified indices.
640
     *
641
     * @param array     the array from which to create the sublist
642
     * @param fromIndex the starting index (inclusive) for the sublist
643
     * @param toIndex   the ending index (exclusive) for the sublist
644
     * @param <E>       the type of elements in the array
645
     * @return an ArrayList containing the elements from the specified range
646
     */
647
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
648
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
649
    }
650

651
    /**
652
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
653
     */
654
    // TODO Move this to ApiResponseEntry class?
655
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
656

657
        private String field;
658
        private boolean descending;
659

660
        /**
661
         * Constructor for ApiResponseEntrySorter.
662
         *
663
         * @param field      the field to sort by
664
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
665
         */
666
        public ApiResponseEntrySorter(String field, boolean descending) {
×
667
            this.field = field;
×
668
            this.descending = descending;
×
669
        }
×
670

671
        /**
672
         * Compares two ApiResponseEntry objects based on the specified field.
673
         *
674
         * @param o1 the first object to be compared.
675
         * @param o2 the second object to be compared.
676
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
677
         */
678
        @Override
679
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
680
            if (descending) {
×
681
                return o2.get(field).compareTo(o1.get(field));
×
682
            } else {
683
                return o1.get(field).compareTo(o2.get(field));
×
684
            }
685
        }
686

687
    }
688

689
    /**
690
     * MIME type for TriG RDF format.
691
     */
692
    public static final String TYPE_TRIG = "application/trig";
693

694
    /**
695
     * MIME type for Jelly RDF format.
696
     */
697
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
698

699
    /**
700
     * MIME type for JSON-LD format.
701
     */
702
    public static final String TYPE_JSONLD = "application/ld+json";
703

704
    /**
705
     * MIME type for N-Quads format.
706
     */
707
    public static final String TYPE_NQUADS = "application/n-quads";
708

709
    /**
710
     * MIME type for Trix format.
711
     */
712
    public static final String TYPE_TRIX = "application/trix";
713

714
    /**
715
     * MIME type for HTML format.
716
     */
717
    public static final String TYPE_HTML = "text/html";
718

719
    /**
720
     * Comma-separated list of supported MIME types for nanopublications.
721
     */
722
    public static final String SUPPORTED_TYPES =
723
            TYPE_TRIG + "," +
724
            TYPE_JELLY + "," +
725
            TYPE_JSONLD + "," +
726
            TYPE_NQUADS + "," +
727
            TYPE_TRIX + "," +
728
            TYPE_HTML;
729

730
    /**
731
     * List of supported MIME types for nanopublications.
732
     */
733
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
18✔
734

735
    private static volatile String resolvedMainRegistryUrl;
736
    private static volatile String resolvedMainQueryUrl;
737

738
    /**
739
     * Eagerly resolves the main registry and query URLs. Call at application startup
740
     * so the (potentially slow) first-time discovery does not happen during a user request.
741
     */
742
    public static void initMainUrls() {
743
        getMainRegistryUrl();
6✔
744
        getMainQueryUrl();
6✔
745
    }
3✔
746

747
    /**
748
     * Returns the URL of the main Nanopub Registry for this nanodash instance.
749
     * <p>
750
     * If {@code NANODASH_MAIN_REGISTRY} is set and matches an entry in the library's
751
     * discovered registry instance list, that URL is used. Otherwise the first entry
752
     * of the library list is used. If the library list is empty, the env var value
753
     * (or built-in default) is used unvalidated. The result is cached for the JVM lifetime.
754
     *
755
     * @return Nanopub Registry URL (with trailing slash)
756
     */
757
    public static String getMainRegistryUrl() {
758
        if (resolvedMainRegistryUrl == null) {
6✔
759
            synchronized (Utils.class) {
12✔
760
                if (resolvedMainRegistryUrl == null) {
6!
761
                    resolvedMainRegistryUrl = resolveMainRegistryUrl();
6✔
762
                }
763
            }
9✔
764
        }
765
        return resolvedMainRegistryUrl;
6✔
766
    }
767

768
    /**
769
     * Returns the URL of the main Nanopub Query API for this nanodash instance.
770
     * <p>
771
     * If {@code NANODASH_MAIN_QUERY} is set and matches an entry in the library's
772
     * discovered query instance list, that URL is used. Otherwise the first entry
773
     * of the library list is used. If the library list is empty, the env var value
774
     * (or built-in default) is used unvalidated. The result is cached for the JVM lifetime.
775
     *
776
     * @return Nanopub Query URL (with trailing slash)
777
     */
778
    public static String getMainQueryUrl() {
779
        if (resolvedMainQueryUrl == null) {
6✔
780
            synchronized (Utils.class) {
12✔
781
                if (resolvedMainQueryUrl == null) {
6!
782
                    resolvedMainQueryUrl = resolveMainQueryUrl();
6✔
783
                }
784
            }
9✔
785
        }
786
        return resolvedMainQueryUrl;
6✔
787
    }
788

789
    private static String resolveMainRegistryUrl() {
790
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_REGISTRY"));
12✔
791
        List<String> instances;
792
        try {
793
            instances = NanopubServerUtils.getRegistryServerList();
6✔
794
        } catch (Exception ex) {
×
795
            logger.warn("Could not retrieve registry instance list from nanopub library: {}", ex.toString());
×
796
            instances = Collections.emptyList();
×
797
        }
3✔
798
        return resolveMainUrl("NANODASH_MAIN_REGISTRY", envValue, instances, DEFAULT_MAIN_REGISTRY_URL);
18✔
799
    }
800

801
    private static String resolveMainQueryUrl() {
802
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_QUERY"));
12✔
803
        List<String> instances;
804
        try {
805
            instances = QueryCall.getApiInstances();
6✔
806
        } catch (NotEnoughAPIInstancesException ex) {
×
807
            logger.warn("Nanopub library reports not enough query API instances available: {}", ex.toString());
×
808
            instances = Collections.emptyList();
×
809
        } catch (Exception ex) {
×
810
            logger.warn("Could not retrieve query instance list from nanopub library: {}", ex.toString());
×
811
            instances = Collections.emptyList();
×
812
        }
3✔
813
        return resolveMainUrl("NANODASH_MAIN_QUERY", envValue, instances, DEFAULT_MAIN_QUERY_URL);
18✔
814
    }
815

816
    private static String resolveMainUrl(String envVarName, String envValue, List<String> instances, String builtInDefault) {
817
        if (envValue != null) {
6!
818
            if (containsNormalized(instances, envValue)) {
×
819
                logger.info("Using main URL from {} (validated against library instance list): {}", envVarName, envValue);
×
820
                return ensureTrailingSlash(envValue);
×
821
            }
822
            if (instances.isEmpty()) {
×
823
                logger.warn("Library instance list is empty; using {} unvalidated: {}", envVarName, envValue);
×
824
                return ensureTrailingSlash(envValue);
×
825
            }
826
            logger.warn("{}={} is not in the library instance list {}; falling back to first library instance",
×
827
                    envVarName, envValue, instances);
828
            return ensureTrailingSlash(instances.get(0));
×
829
        }
830
        if (!instances.isEmpty()) {
9!
831
            String first = instances.get(0);
15✔
832
            logger.info("{} not set; using first library instance: {}", envVarName, first);
15✔
833
            return ensureTrailingSlash(first);
9✔
834
        }
835
        logger.warn("{} not set and library instance list is empty; using built-in default: {}", envVarName, builtInDefault);
×
836
        return builtInDefault;
×
837
    }
838

839
    private static boolean containsNormalized(List<String> urls, String target) {
840
        String normTarget = normalizeUrl(target);
×
841
        for (String url : urls) {
×
842
            if (normalizeUrl(url).equals(normTarget)) return true;
×
843
        }
×
844
        return false;
×
845
    }
846

847
    private static String normalizeUrl(String url) {
848
        if (url == null) return "";
×
849
        return url.trim().replaceFirst("/+$", "").toLowerCase(Locale.ROOT);
×
850
    }
851

852
    private static String ensureTrailingSlash(String url) {
853
        return url.endsWith("/") ? url : url + "/";
21!
854
    }
855

856
    private static String trimToNull(String s) {
857
        if (s == null) return null;
12!
858
        s = s.trim();
×
859
        return s.isEmpty() ? null : s;
×
860
    }
861

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

866
    /**
867
     * Checks whether string is valid literal serialization.
868
     *
869
     * @param literalString the literal string
870
     * @return true if valid
871
     */
872
    public static boolean isValidLiteralSerialization(String literalString) {
873
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
12✔
874
            return true;
6✔
875
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
876
            return true;
6✔
877
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
878
            return true;
6✔
879
        }
880
        return false;
6✔
881
    }
882

883
    /**
884
     * Returns a serialized version of the literal.
885
     *
886
     * @param literal the literal
887
     * @return the String serialization of the literal
888
     */
889
    public static String getSerializedLiteral(Literal literal) {
890
        if (literal.getLanguage().isPresent()) {
12✔
891
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
30✔
892
        } else if (literal.getDatatype().equals(XSD.STRING)) {
15✔
893
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
15✔
894
        } else {
895
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
24✔
896
        }
897
    }
898

899
    /**
900
     * Parses a serialized literal into a Literal object.
901
     *
902
     * @param serializedLiteral The serialized String of the literal
903
     * @return The parse Literal object
904
     */
905
    public static Literal getParsedLiteral(String serializedLiteral) {
906
        if (serializedLiteral.matches(PLAIN_LITERAL_PATTERN)) {
12✔
907
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(PLAIN_LITERAL_PATTERN, "$1")));
24✔
908
        } else if (serializedLiteral.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
909
            String langtag = serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$3");
15✔
910
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$1")), langtag);
27✔
911
        } else if (serializedLiteral.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
912
            IRI datatype = vf.createIRI(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$3"));
21✔
913
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$1")), datatype);
27✔
914
        }
915
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
18✔
916
    }
917

918
    /**
919
     * Escapes quotes (") and slashes (/) of a literal string.
920
     *
921
     * @param unescapedString un-escaped string
922
     * @return escaped string
923
     */
924
    public static String getEscapedLiteralString(String unescapedString) {
925
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
24✔
926
    }
927

928
    /**
929
     * Un-escapes quotes (") and slashes (/) of a literal string.
930
     *
931
     * @param escapedString escaped string
932
     * @return un-escaped string
933
     */
934
    public static String getUnescapedLiteralString(String escapedString) {
935
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
15✔
936
    }
937

938
    /**
939
     * Checks if a given IRI is a local URI.
940
     *
941
     * @param uri the IRI to check
942
     * @return true if the IRI is a local URI, false otherwise
943
     */
944
    public static boolean isLocalURI(IRI uri) {
945
        return uri != null && isLocalURI(uri.stringValue());
30✔
946
    }
947

948
    /**
949
     * Checks if a given string is a local URI.
950
     *
951
     * @param uriAsString the string to check
952
     * @return true if the string is a local URI, false otherwise
953
     */
954
    public static boolean isLocalURI(String uriAsString) {
955
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33✔
956
    }
957

958
    public static String unescapeMultiValue(String s) {
959
        StringBuilder sb = new StringBuilder();
12✔
960
        for (int i = 0; i < s.length(); i++) {
24✔
961
            if (s.charAt(i) == '\\' && i + 1 < s.length()) {
33✔
962
                char next = s.charAt(i + 1);
18✔
963
                if (next == 'n') {
9✔
964
                    sb.append('\n');
15✔
965
                } else if (next == '\\') {
9!
966
                    sb.append('\\');
15✔
967
                } else {
968
                    sb.append(next);
×
969
                }
970
                i++;
3✔
971
            } else {
3✔
972
                sb.append(s.charAt(i));
18✔
973
            }
974
        }
975
        return sb.toString();
9✔
976
    }
977

978
}
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