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

knowledgepixels / nanodash / 19034335305

03 Nov 2025 12:14PM UTC coverage: 14.966% (+0.6%) from 14.338%
19034335305

push

github

ashleycaselli
refactor: remove Utils artifact code extraction and replace with existing GetNanopub utility

540 of 4518 branches covered (11.95%)

Branch coverage included in aggregate %.

1392 of 8391 relevant lines covered (16.59%)

0.75 hits per line

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

71.23
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
import static java.nio.charset.StandardCharsets.UTF_8;
47

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

53
    private Utils() {
54
    }  // no instances allowed
55

56
    /**
57
     * ValueFactory instance for creating RDF model objects.
58
     */
59
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
2✔
60
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
3✔
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 uri the URI string
76
     * @return a short representation of the URI
77
     */
78
    public static String getShortNameFromURI(String uri) {
79
        if (uri.startsWith("https://doi.org/") || uri.startsWith("http://dx.doi.org/")) {
8✔
80
            return uri.replaceFirst("^https?://(dx\\.)?doi.org/", "doi:");
5✔
81
        }
82
        uri = uri.replaceFirst("\\?.*$", "");
5✔
83
        uri = uri.replaceFirst("[/#]$", "");
5✔
84
        uri = uri.replaceFirst("^.*[/#]([^/#]*)[/#]([0-9]+)$", "$1/$2");
5✔
85
        if (uri.contains("#")) {
4✔
86
            uri = uri.replaceFirst("^.*#(.*[^0-9].*)$", "$1");
6✔
87
        } else {
88
            uri = uri.replaceFirst("^.*/([^/]*[^0-9/][^/]*)$", "$1");
5✔
89
        }
90
        uri = uri.replaceFirst("((^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{8})[A-Za-z0-9\\-_]{35}$", "$1");
5✔
91
        uri = uri.replaceFirst("(^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{43}[^A-Za-z0-9\\-_](.+)$", "$2");
5✔
92
        uri = URLDecoder.decode(uri, UTF_8);
4✔
93
        return uri;
2✔
94
    }
95

96
    /**
97
     * Generates a short nanopublication ID from a given nanopublication ID or URI.
98
     *
99
     * @param npId the nanopublication ID or URI
100
     * @return the first 10 characters of the artifact code
101
     */
102
    public static String getShortNanopubId(Object npId) {
103
        return TrustyUriUtils.getArtifactCode(npId.toString()).substring(0, 10);
7✔
104
    }
105

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

539
    private static class UriLabelModel implements IModel<String> {
540

541
        private IModel<String> uriModel;
542

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

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

552
    }
553

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

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

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

587
        private String field;
588
        private boolean descending;
589

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

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

617
    }
618

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

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

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

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

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

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

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

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

665
    // TODO Move these to nanopub-java library:
666

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

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

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

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

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

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

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

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

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

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

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

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