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

knowledgepixels / nanodash / 18774433971

24 Oct 2025 08:38AM UTC coverage: 12.864% (-0.8%) from 13.626%
18774433971

push

github

tkuhn
fix(SpacePage): Avoid force-refresh of maintained resources

452 of 4402 branches covered (10.27%)

Branch coverage included in aggregate %.

1174 of 8238 relevant lines covered (14.25%)

0.64 hits per line

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

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

3
import com.google.common.hash.Hashing;
4
import net.trustyuri.TrustyUriUtils;
5
import org.apache.commons.codec.Charsets;
6
import org.apache.commons.exec.environment.EnvironmentUtils;
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.eclipse.rdf4j.model.IRI;
14
import org.eclipse.rdf4j.model.Literal;
15
import org.eclipse.rdf4j.model.Statement;
16
import org.eclipse.rdf4j.model.ValueFactory;
17
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
18
import org.eclipse.rdf4j.model.util.Literals;
19
import org.eclipse.rdf4j.model.vocabulary.FOAF;
20
import org.eclipse.rdf4j.model.vocabulary.XSD;
21
import org.nanopub.Nanopub;
22
import org.nanopub.NanopubUtils;
23
import org.nanopub.extra.security.KeyDeclaration;
24
import org.nanopub.extra.security.MalformedCryptoElementException;
25
import org.nanopub.extra.security.NanopubSignatureElement;
26
import org.nanopub.extra.security.SignatureUtils;
27
import org.nanopub.extra.server.GetNanopub;
28
import org.nanopub.extra.services.ApiResponseEntry;
29
import org.nanopub.extra.setting.IntroNanopub;
30
import org.nanopub.vocabulary.FIP;
31
import org.nanopub.vocabulary.NPX;
32
import org.owasp.html.HtmlPolicyBuilder;
33
import org.owasp.html.PolicyFactory;
34
import org.slf4j.Logger;
35
import org.slf4j.LoggerFactory;
36
import org.wicketstuff.select2.Select2Choice;
37

38
import java.io.IOException;
39
import java.io.Serializable;
40
import java.net.URISyntaxException;
41
import java.net.URLDecoder;
42
import java.net.URLEncoder;
43
import java.nio.charset.StandardCharsets;
44
import java.util.*;
45

46
/**
47
 * Utility class providing various helper methods for handling nanopublications, URIs, and other related functionalities.
48
 */
49
public class Utils {
50

51
    private Utils() {
52
    }  // no instances allowed
53

54
    /**
55
     * ValueFactory instance for creating RDF model objects.
56
     */
57
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
2✔
58
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
3✔
59

60
    // TODO Merge with IriItem.getShortNameFromURI
61

62
    /**
63
     * Generates a short name from a given IRI object.
64
     *
65
     * @param uri the IRI object
66
     * @return a short representation of the URI
67
     */
68
    public static String getShortNameFromURI(IRI uri) {
69
        return getShortNameFromURI(uri.stringValue());
4✔
70
    }
71

72
    /**
73
     * Generates a short name from a given URI string.
74
     *
75
     * @param u the URI string
76
     * @return a short representation of the URI
77
     */
78
    public static String getShortNameFromURI(String u) {
79
        u = u.replaceFirst("\\?.*$", "");
5✔
80
        u = u.replaceFirst("[/#]$", "");
5✔
81
        u = u.replaceFirst("^.*[/#]([^/#]*)[/#]([0-9]+)$", "$1/$2");
5✔
82
        u = u.replaceFirst("^.*[/#]([^/#]*[^0-9][^/#]*)$", "$1");
5✔
83
        u = u.replaceFirst("((^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{8})[A-Za-z0-9\\-_]{35}$", "$1");
5✔
84
        u = u.replaceFirst("(^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{43}[^A-Za-z0-9\\-_](.+)$", "$2");
5✔
85
        return u;
2✔
86
    }
87

88
    /**
89
     * Generates a short nanopublication ID from a given nanopublication ID or URI.
90
     *
91
     * @param npId the nanopublication ID or URI
92
     * @return the first 10 characters of the artifact code
93
     */
94
    public static String getShortNanopubId(Object npId) {
95
        return TrustyUriUtils.getArtifactCode(npId.toString()).substring(0, 10);
7✔
96
    }
97

98
    private static Map<String, Nanopub> nanopubs = new HashMap<>();
4✔
99

100
    /**
101
     * Retrieves a Nanopub object based on the given URI or artifact code.
102
     *
103
     * @param uriOrArtifactCode the URI or artifact code of the nanopublication
104
     * @return the Nanopub object, or null if not found
105
     */
106
    public static Nanopub getNanopub(String uriOrArtifactCode) {
107
        String artifactCode = getArtifactCode(uriOrArtifactCode);
3✔
108
        if (!nanopubs.containsKey(artifactCode)) {
4✔
109
            for (int i = 0; i < 3; i++) {  // Try 3 times to get nanopub
5!
110
                Nanopub np = GetNanopub.get(artifactCode);
3✔
111
                if (np != null) {
2!
112
                    nanopubs.put(artifactCode, np);
5✔
113
                    break;
1✔
114
                }
115
            }
116
        }
117
        return nanopubs.get(artifactCode);
5✔
118
    }
119

120
    /**
121
     * Extracts the artifact code from a given URI or artifact code string.
122
     *
123
     * @param uriOrArtifactCode the URI or artifact code string
124
     * @return the extracted artifact code
125
     */
126
    public static String getArtifactCode(String uriOrArtifactCode) {
127
        return uriOrArtifactCode.replaceFirst("^.*(RA[0-9a-zA-Z\\-_]{43})(\\?.*)?$", "$1");
5✔
128
    }
129

130
    /**
131
     * URL-encodes the string representation of the given object using UTF-8 encoding.
132
     *
133
     * @param o the object to be URL-encoded
134
     * @return the URL-encoded string
135
     */
136
    public static String urlEncode(Object o) {
137
        return URLEncoder.encode((o == null ? "" : o.toString()), Charsets.UTF_8);
9✔
138
    }
139

140
    /**
141
     * URL-decodes the string representation of the given object using UTF-8 encoding.
142
     *
143
     * @param o the object to be URL-decoded
144
     * @return the URL-decoded string
145
     */
146
    public static String urlDecode(Object o) {
147
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
9✔
148
    }
149

150
    /**
151
     * Generates a URL with the given base and appends the provided PageParameters as query parameters.
152
     *
153
     * @param base       the base URL
154
     * @param parameters the PageParameters to append
155
     * @return the complete URL with parameters
156
     */
157
    public static String getUrlWithParameters(String base, PageParameters parameters) {
158
        try {
159
            URIBuilder u = new URIBuilder(base);
5✔
160
            for (String key : parameters.getNamedKeys()) {
11✔
161
                for (StringValue value : parameters.getValues(key)) {
12✔
162
                    if (!value.isNull()) u.addParameter(key, value.toString());
9!
163
                }
1✔
164
            }
1✔
165
            return u.build().toString();
4✔
166
        } catch (URISyntaxException ex) {
1✔
167
            logger.error("Could not build URL with parameters: {} {}", base, parameters, ex);
17✔
168
            return "/";
2✔
169
        }
170
    }
171

172
    /**
173
     * Generates a short name for a public key or public key hash.
174
     *
175
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
176
     * @return a short representation of the public key or public key hash
177
     */
178
    public static String getShortPubkeyName(String pubkeyOrPubkeyhash) {
179
        if (pubkeyOrPubkeyhash.length() == 64) {
4!
180
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
181
        } else {
182
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
5✔
183
        }
184
    }
185

186
    /**
187
     * Generates a short label for a public key or public key hash, including its status (local or approved).
188
     *
189
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
190
     * @param user               the IRI of the user associated with the public key
191
     * @return a short label indicating the public key and its status
192
     */
193
    public static String getShortPubkeyhashLabel(String pubkeyOrPubkeyhash, IRI user) {
194
        String s = getShortPubkeyName(pubkeyOrPubkeyhash);
×
195
        NanodashSession session = NanodashSession.get();
×
196
        List<String> l = new ArrayList<>();
×
197
        if (pubkeyOrPubkeyhash.equals(session.getPubkeyString()) || pubkeyOrPubkeyhash.equals(session.getPubkeyhash()))
×
198
            l.add("local");
×
199
        // TODO: Make this more efficient:
200
        String hashed = Utils.createSha256HexHash(pubkeyOrPubkeyhash);
×
201
        if (User.getPubkeyhashes(user, true).contains(pubkeyOrPubkeyhash) || User.getPubkeyhashes(user, true).contains(hashed))
×
202
            l.add("approved");
×
203
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
204
        return s;
×
205
    }
206

207
    /**
208
     * Retrieves the name of the public key location based on the public key.
209
     *
210
     * @param pubkeyhash the public key string
211
     * @return the name of the public key location
212
     */
213
    public static String getPubkeyLocationName(String pubkeyhash) {
214
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
215
    }
216

217
    /**
218
     * Retrieves the name of the public key location, or returns a fallback name if not found.
219
     * If the key location is localhost, it returns "localhost".
220
     *
221
     * @param pubkeyhash the public key string
222
     * @param fallback   the fallback name to return if the key location is not found
223
     * @return the name of the public key location or the fallback name
224
     */
225
    public static String getPubkeyLocationName(String pubkeyhash, String fallback) {
226
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyhash(pubkeyhash);
×
227
        if (keyLocation == null) return fallback;
×
228
        if (keyLocation.stringValue().equals("http://localhost:37373/")) return "localhost";
×
229
        return keyLocation.stringValue().replaceFirst("https?://(nanobench\\.)?(nanodash\\.)?(.*[^/])/?$", "$3");
×
230
    }
231

232
    /**
233
     * Generates a short label for a public key location, including its status (local or approved).
234
     *
235
     * @param pubkeyhash the public key string
236
     * @param user       the IRI of the user associated with the public key
237
     * @return a short label indicating the public key location and its status
238
     */
239
    public static String getShortPubkeyLocationLabel(String pubkeyhash, IRI user) {
240
        String s = getPubkeyLocationName(pubkeyhash);
×
241
        NanodashSession session = NanodashSession.get();
×
242
        List<String> l = new ArrayList<>();
×
243
        if (pubkeyhash.equals(session.getPubkeyhash())) l.add("local");
×
244
        // TODO: Make this more efficient:
245
        if (User.getPubkeyhashes(user, true).contains(pubkeyhash)) l.add("approved");
×
246
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
247
        return s;
×
248
    }
249

250
    /**
251
     * Checks if a given public key has a Nanodash location.
252
     * A Nanodash location is identified by specific keywords in the key location.
253
     *
254
     * @param pubkeyhash the public key to check
255
     * @return true if the public key has a Nanodash location, false otherwise
256
     */
257
    public static boolean hasNanodashLocation(String pubkeyhash) {
258
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyhash(pubkeyhash);
×
259
        if (keyLocation == null) return true; // potentially a Nanodash location
×
260
        if (keyLocation.stringValue().contains("nanodash")) return true;
×
261
        if (keyLocation.stringValue().contains("nanobench")) return true;
×
262
        if (keyLocation.stringValue().contains(":37373")) return true;
×
263
        return false;
×
264
    }
265

266
    /**
267
     * Retrieves the short ORCID ID from an IRI object.
268
     *
269
     * @param orcidIri the IRI object representing the ORCID ID
270
     * @return the short ORCID ID as a string
271
     */
272
    public static String getShortOrcidId(IRI orcidIri) {
273
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
6✔
274
    }
275

276
    /**
277
     * Retrieves the URI postfix from a given URI object.
278
     *
279
     * @param uri the URI object from which to extract the postfix
280
     * @return the URI postfix as a string
281
     */
282
    public static String getUriPostfix(Object uri) {
283
        String s = uri.toString();
3✔
284
        if (s.contains("#")) return s.replaceFirst("^.*#(.*)$", "$1");
9✔
285
        return s.replaceFirst("^.*/(.*)$", "$1");
5✔
286
    }
287

288
    /**
289
     * Retrieves the URI prefix from a given URI object.
290
     *
291
     * @param uri the URI object from which to extract the prefix
292
     * @return the URI prefix as a string
293
     */
294
    public static String getUriPrefix(Object uri) {
295
        String s = uri.toString();
3✔
296
        if (s.contains("#")) return s.replaceFirst("^(.*#).*$", "$1");
9✔
297
        return s.replaceFirst("^(.*/).*$", "$1");
5✔
298
    }
299

300
    /**
301
     * Checks if a given string is a valid URI postfix.
302
     * A valid URI postfix does not contain a colon (":").
303
     *
304
     * @param s the string to check
305
     * @return true if the string is a valid URI postfix, false otherwise
306
     */
307
    public static boolean isUriPostfix(String s) {
308
        return !s.contains(":");
8✔
309
    }
310

311
    /**
312
     * Retrieves the location of a given IntroNanopub.
313
     *
314
     * @param inp the IntroNanopub from which to extract the location
315
     * @return the IRI location of the nanopublication, or null if not found
316
     */
317
    public static IRI getLocation(IntroNanopub inp) {
318
        NanopubSignatureElement el = getNanopubSignatureElement(inp);
×
319
        for (KeyDeclaration kd : inp.getKeyDeclarations()) {
×
320
            if (el.getPublicKeyString().equals(kd.getPublicKeyString())) {
×
321
                return kd.getKeyLocation();
×
322
            }
323
        }
×
324
        return null;
×
325
    }
326

327
    /**
328
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
329
     *
330
     * @param inp the IntroNanopub from which to extract the signature element
331
     * @return the NanopubSignatureElement associated with the nanopublication
332
     */
333
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
334
        try {
335
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
336
        } catch (MalformedCryptoElementException ex) {
×
337
            throw new RuntimeException(ex);
×
338
        }
339
    }
340

341
    /**
342
     * Retrieves a Nanopub object from a given URI if it is a potential Trusty URI.
343
     *
344
     * @param uri the URI to check and retrieve the Nanopub from
345
     * @return the Nanopub object if found, or null if not a known nanopublication
346
     */
347
    public static Nanopub getAsNanopub(String uri) {
348
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
×
349
            try {
350
                return Utils.getNanopub(uri);
×
351
            } catch (Exception ex) {
×
352
                logger.error("The given URI is not a known nanopublication: {}", uri, ex);
×
353
            }
354
        }
355
        return null;
×
356
    }
357

358
    private static final PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder()
3✔
359
            .allowCommonBlockElements()
1✔
360
            .allowCommonInlineFormattingElements()
15✔
361
            .allowUrlProtocols("https", "http", "mailto")
7✔
362
            .allowElements("a")
7✔
363
            .allowAttributes("href").onElements("a")
14✔
364
            .allowElements("img")
7✔
365
            .allowAttributes("src").onElements("img")
8✔
366
            .requireRelNofollowOnLinks()
1✔
367
            .toFactory();
2✔
368

369
    /**
370
     * Sanitizes raw HTML input to ensure safe rendering.
371
     *
372
     * @param rawHtml the raw HTML input to sanitize
373
     * @return sanitized HTML string
374
     */
375
    public static String sanitizeHtml(String rawHtml) {
376
        return htmlSanitizePolicy.sanitize(rawHtml);
4✔
377
    }
378

379
    /**
380
     * Converts PageParameters to a URL-encoded string representation.
381
     *
382
     * @param params the PageParameters to convert
383
     * @return a string representation of the parameters in URL-encoded format
384
     */
385
    public static String getPageParametersAsString(PageParameters params) {
386
        String s = "";
2✔
387
        for (String n : params.getNamedKeys()) {
11✔
388
            if (!s.isEmpty()) s += "&";
6✔
389
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
10✔
390
        }
1✔
391
        return s;
2✔
392
    }
393

394
    /**
395
     * Sets a minimal escape markup function for a Select2Choice component.
396
     * This function replaces certain characters and formats the display of choices.
397
     *
398
     * @param selectItem the Select2Choice component to set the escape markup for
399
     */
400
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
401
        selectItem.getSettings().setEscapeMarkup("function(markup) {" +
×
402
                                                 "return markup" +
403
                                                 ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" +
404
                                                 ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" +
405
                                                 ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" +
406
                                                 ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" +
407
                                                 ";}"
408
        );
409
    }
×
410

411
    /**
412
     * Checks if a nanopublication is of a specific class.
413
     *
414
     * @param np       the nanopublication to check
415
     * @param classIri the IRI of the class to check against
416
     * @return true if the nanopublication is of the specified class, false otherwise
417
     */
418
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
419
        return NanopubUtils.getTypes(np).contains(classIri);
5✔
420
    }
421

422
    /**
423
     * Checks if a nanopublication uses a specific predicate in its assertion.
424
     *
425
     * @param np           the nanopublication to check
426
     * @param predicateIri the IRI of the predicate to look for
427
     * @return true if the predicate is used in the assertion, false otherwise
428
     */
429
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
430
        for (Statement st : np.getAssertion()) {
11✔
431
            if (predicateIri.equals(st.getPredicate())) {
5✔
432
                return true;
2✔
433
            }
434
        }
1✔
435
        return false;
2✔
436
    }
437

438
    /**
439
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
440
     *
441
     * @param np the nanopublication from which to extract FOAF names
442
     * @return a map where keys are subjects and values are FOAF names
443
     */
444
    public static Map<String, String> getFoafNameMap(Nanopub np) {
445
        Map<String, String> foafNameMap = new HashMap<>();
4✔
446
        for (Statement st : np.getPubinfo()) {
11✔
447
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
14✔
448
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
8✔
449
            }
450
        }
1✔
451
        return foafNameMap;
2✔
452
    }
453

454
    /**
455
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
456
     *
457
     * @param obj the object to hash
458
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
459
     */
460
    public static String createSha256HexHash(Object obj) {
461
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
7✔
462
    }
463

464
    /**
465
     * Gets the types of a nanopublication.
466
     *
467
     * @param np the nanopublication from which to extract types
468
     * @return a list of IRI types associated with the nanopublication
469
     */
470
    public static List<IRI> getTypes(Nanopub np) {
471
        List<IRI> l = new ArrayList<>();
4✔
472
        for (IRI t : NanopubUtils.getTypes(np)) {
11✔
473
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) continue;
5✔
474
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED))
4✔
475
                continue;
1✔
476
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) continue;
4!
477
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED))
4!
478
                continue;
×
479
            l.add(t);
4✔
480
        }
1✔
481
        return l;
2✔
482
    }
483

484
    /**
485
     * Gets a label for a type IRI.
486
     *
487
     * @param typeIri the IRI of the type
488
     * @return a label for the type, potentially truncated
489
     */
490
    public static String getTypeLabel(IRI typeIri) {
491
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) return "FER";
6✔
492
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) return "FSR";
6✔
493
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) return "FIP";
6✔
494
        if (typeIri.equals(NPX.DECLARED_BY)) return "user intro";
6✔
495
        String l = typeIri.stringValue();
3✔
496
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
5✔
497
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
5✔
498
        if (l.length() > 25) l = l.substring(0, 20) + "...";
10✔
499
        return l;
2✔
500
    }
501

502
    /**
503
     * Gets a label for a URI.
504
     *
505
     * @param uri the URI to get the label from
506
     * @return a label for the URI, potentially truncated
507
     */
508
    public static String getUriLabel(String uri) {
509
        if (uri == null) return "";
4✔
510
        String uriLabel = uri;
2✔
511
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
4✔
512
            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");
5✔
513
            if (newUriLabel.length() <= 70) return newUriLabel;
6!
514
        }
515
        if (uriLabel.length() > 70) return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
16✔
516
        return uriLabel;
2✔
517
    }
518

519
    /**
520
     * Gets an ExternalLink with a URI label.
521
     *
522
     * @param markupId the markup ID for the link
523
     * @param uri      the URI to link to
524
     * @return an ExternalLink with the URI label
525
     */
526
    public static ExternalLink getUriLink(String markupId, String uri) {
527
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
13✔
528
    }
529

530
    /**
531
     * Gets an ExternalLink with a model for the URI label.
532
     *
533
     * @param markupId the markup ID for the link
534
     * @param model    the model containing the URI
535
     * @return an ExternalLink with the URI label
536
     */
537
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
538
        return new ExternalLink(markupId, model, new UriLabelModel(model));
×
539
    }
540

541
    private static class UriLabelModel implements IModel<String> {
542

543
        private IModel<String> uriModel;
544

545
        public UriLabelModel(IModel<String> uriModel) {
×
546
            this.uriModel = uriModel;
×
547
        }
×
548

549
        @Override
550
        public String getObject() {
551
            return getUriLabel(uriModel.getObject());
×
552
        }
553

554
    }
555

556
    /**
557
     * Creates a sublist from a list based on the specified indices.
558
     *
559
     * @param list      the list from which to create the sublist
560
     * @param fromIndex the starting index (inclusive) for the sublist
561
     * @param toIndex   the ending index (exclusive) for the sublist
562
     * @param <E>       the type of elements in the list
563
     * @return an ArrayList containing the elements from the specified range
564
     */
565
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
566
        // So the resulting list is serializable:
567
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
×
568
    }
569

570
    /**
571
     * Creates a sublist from an array based on the specified indices.
572
     *
573
     * @param array     the array from which to create the sublist
574
     * @param fromIndex the starting index (inclusive) for the sublist
575
     * @param toIndex   the ending index (exclusive) for the sublist
576
     * @param <E>       the type of elements in the array
577
     * @return an ArrayList containing the elements from the specified range
578
     */
579
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
580
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
581
    }
582

583
    /**
584
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
585
     */
586
    // TODO Move this to ApiResponseEntry class?
587
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
588

589
        private String field;
590
        private boolean descending;
591

592
        /**
593
         * Constructor for ApiResponseEntrySorter.
594
         *
595
         * @param field      the field to sort by
596
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
597
         */
598
        public ApiResponseEntrySorter(String field, boolean descending) {
×
599
            this.field = field;
×
600
            this.descending = descending;
×
601
        }
×
602

603
        /**
604
         * Compares two ApiResponseEntry objects based on the specified field.
605
         *
606
         * @param o1 the first object to be compared.
607
         * @param o2 the second object to be compared.
608
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
609
         */
610
        @Override
611
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
612
            if (descending) {
×
613
                return o2.get(field).compareTo(o1.get(field));
×
614
            } else {
615
                return o1.get(field).compareTo(o2.get(field));
×
616
            }
617
        }
618

619
    }
620

621
    /**
622
     * MIME type for TriG RDF format.
623
     */
624
    public static final String TYPE_TRIG = "application/trig";
625

626
    /**
627
     * MIME type for Jelly RDF format.
628
     */
629
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
630

631
    /**
632
     * MIME type for JSON-LD format.
633
     */
634
    public static final String TYPE_JSONLD = "application/ld+json";
635

636
    /**
637
     * MIME type for N-Quads format.
638
     */
639
    public static final String TYPE_NQUADS = "application/n-quads";
640

641
    /**
642
     * MIME type for Trix format.
643
     */
644
    public static final String TYPE_TRIX = "application/trix";
645

646
    /**
647
     * MIME type for HTML format.
648
     */
649
    public static final String TYPE_HTML = "text/html";
650

651
    /**
652
     * Comma-separated list of supported MIME types for nanopublications.
653
     */
654
    public static final String SUPPORTED_TYPES =
655
            TYPE_TRIG + "," +
656
            TYPE_JELLY + "," +
657
            TYPE_JSONLD + "," +
658
            TYPE_NQUADS + "," +
659
            TYPE_TRIX + "," +
660
            TYPE_HTML;
661

662
    /**
663
     * List of supported MIME types for nanopublications.
664
     */
665
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
6✔
666

667
    // TODO Move these to nanopub-java library:
668

669
    /**
670
     * Retrieves a set of introduced IRI IDs from the nanopublication.
671
     *
672
     * @param np the nanopublication from which to extract introduced IRI IDs
673
     * @return a set of introduced IRI IDs
674
     */
675
    public static Set<String> getIntroducedIriIds(Nanopub np) {
676
        Set<String> introducedIriIds = new HashSet<>();
4✔
677
        for (Statement st : np.getPubinfo()) {
11✔
678
            if (!st.getSubject().equals(np.getUri())) continue;
7✔
679
            if (!st.getPredicate().equals(NPX.INTRODUCES)) continue;
6✔
680
            if (st.getObject() instanceof IRI obj) introducedIriIds.add(obj.stringValue());
14✔
681
        }
1✔
682
        return introducedIriIds;
2✔
683
    }
684

685
    /**
686
     * Retrieves a set of embedded IRI IDs from the nanopublication.
687
     *
688
     * @param np the nanopublication from which to extract embedded IRI IDs
689
     * @return a set of embedded IRI IDs
690
     */
691
    public static Set<String> getEmbeddedIriIds(Nanopub np) {
692
        Set<String> embeddedIriIds = new HashSet<>();
4✔
693
        for (Statement st : np.getPubinfo()) {
11✔
694
            if (!st.getSubject().equals(np.getUri())) continue;
7✔
695
            if (!st.getPredicate().equals(NPX.EMBEDS)) continue;
6✔
696
            if (st.getObject() instanceof IRI obj) embeddedIriIds.add(obj.stringValue());
14✔
697
        }
1✔
698
        return embeddedIriIds;
2✔
699
    }
700

701
    /**
702
     * Returns the URL of the default Nanopub Registry as configured by the given instance.
703
     *
704
     * @return Nanopub Registry URL
705
     */
706
    public static String getMainRegistryUrl() {
707
        try {
708
            return EnvironmentUtils.getProcEnvironment().getOrDefault("NANODASH_MAIN_REGISTRY", "https://registry.knowledgepixels.com/");
6✔
709
        } catch (IOException ex) {
×
710
            logger.error("Could not get NANODASH_MAIN_REGISTRY environment variable, using default.", ex);
×
711
            return "https://registry.knowledgepixels.com/";
×
712
        }
713
    }
714

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

719
    /**
720
     * Checks whether string is valid literal serialization.
721
     *
722
     * @param literalString the literal string
723
     * @return true if valid
724
     */
725
    public static boolean isValidLiteralSerialization(String literalString) {
726
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
4✔
727
            return true;
2✔
728
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
4✔
729
            return true;
2✔
730
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
4✔
731
            return true;
2✔
732
        }
733
        return false;
2✔
734
    }
735

736
    /**
737
     * Returns a serialized version of the literal.
738
     *
739
     * @param literal the literal
740
     * @return the String serialization of the literal
741
     */
742
    public static String getSerializedLiteral(Literal literal) {
743
        if (literal.getLanguage().isPresent()) {
4✔
744
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
10✔
745
        } else if (literal.getDatatype().equals(XSD.STRING)) {
5✔
746
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
5✔
747
        } else {
748
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
8✔
749
        }
750
    }
751

752
    /**
753
     * Parses a serialized literal into a Literal object.
754
     *
755
     * @param serializedLiteral The serialized String of the literal
756
     * @return The parse Literal object
757
     */
758
    public static Literal getParsedLiteral(String serializedLiteral) {
759
        if (serializedLiteral.matches(PLAIN_LITERAL_PATTERN)) {
4✔
760
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(PLAIN_LITERAL_PATTERN, "$1")));
8✔
761
        } else if (serializedLiteral.matches(LANGTAG_LITERAL_PATTERN)) {
4✔
762
            String langtag = serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$3");
5✔
763
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$1")), langtag);
9✔
764
        } else if (serializedLiteral.matches(DATATYPE_LITERAL_PATTERN)) {
4✔
765
            IRI datatype = vf.createIRI(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$3"));
7✔
766
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$1")), datatype);
9✔
767
        }
768
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
6✔
769
    }
770

771
    /**
772
     * Escapes quotes (") and slashes (/) of a literal string.
773
     *
774
     * @param unescapedString un-escaped string
775
     * @return escaped string
776
     */
777
    public static String getEscapedLiteralString(String unescapedString) {
778
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
8✔
779
    }
780

781
    /**
782
     * Un-escapes quotes (") and slashes (/) of a literal string.
783
     *
784
     * @param escapedString escaped string
785
     * @return un-escaped string
786
     */
787
    public static String getUnescapedLiteralString(String escapedString) {
788
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
5✔
789
    }
790

791
    /**
792
     * Checks if a given IRI is a local URI.
793
     *
794
     * @param uri the IRI to check
795
     * @return true if the IRI is a local URI, false otherwise
796
     */
797
    public static boolean isLocalURI(IRI uri) {
798
        return uri != null && isLocalURI(uri.stringValue());
10✔
799
    }
800

801
    /**
802
     * Checks if a given string is a local URI.
803
     *
804
     * @param uriAsString the string to check
805
     * @return true if the string is a local URI, false otherwise
806
     */
807
    public static boolean isLocalURI(String uriAsString) {
808
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
11✔
809
    }
810

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