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

knowledgepixels / nanodash / 20268226543

16 Dec 2025 12:39PM UTC coverage: 14.107% (-1.3%) from 15.358%
20268226543

push

github

ashleycaselli
refactor: replace VocabUtils with the ones defined in the nanopub-java library

526 of 4946 branches covered (10.63%)

Branch coverage included in aggregate %.

1452 of 9075 relevant lines covered (16.0%)

2.11 hits per line

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

68.47
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
import java.util.regex.Pattern;
46

47
import static java.nio.charset.StandardCharsets.UTF_8;
48

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

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

57
    /**
58
     * ValueFactory instance for creating RDF model objects.
59
     */
60
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
61
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
9✔
62
    private static final Pattern LEADING_TAG = Pattern.compile("^\\s*<(p|div|span|img)(\\s|>|/).*", Pattern.CASE_INSENSITIVE);
12✔
63

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

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

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

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

110
    /**
111
     * Retrieves a Nanopub object based on the given URI or artifact code.
112
     *
113
     * @param uriOrArtifactCode the URI or artifact code of the nanopublication
114
     * @return the Nanopub object, or null if not found
115
     */
116
    public static Nanopub getNanopub(String uriOrArtifactCode) {
117
        String artifactCode = GetNanopub.getArtifactCode(uriOrArtifactCode);
9✔
118
        if (!nanopubs.containsKey(artifactCode)) {
12✔
119
            for (int i = 0; i < 3; i++) {  // Try 3 times to get nanopub
15!
120
                Nanopub np = GetNanopub.get(artifactCode);
9✔
121
                if (np != null) {
6!
122
                    nanopubs.put(artifactCode, np);
15✔
123
                    break;
3✔
124
                }
125
            }
126
        }
127
        return nanopubs.get(artifactCode);
15✔
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);
27✔
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);
27✔
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);
15✔
160
            for (String key : parameters.getNamedKeys()) {
33✔
161
                for (StringValue value : parameters.getValues(key)) {
36✔
162
                    if (!value.isNull()) u.addParameter(key, value.toString());
27!
163
                }
3✔
164
            }
3✔
165
            return u.build().toString();
12✔
166
        } catch (URISyntaxException ex) {
3✔
167
            logger.error("Could not build URL with parameters: {} {}", base, parameters, ex);
51✔
168
            return "/";
6✔
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) {
12!
180
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
181
        } else {
182
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
15✔
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/", "");
18✔
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();
9✔
284
        if (s.contains("#")) return s.replaceFirst("^.*#(.*)$", "$1");
27✔
285
        return s.replaceFirst("^.*/(.*)$", "$1");
15✔
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();
9✔
296
        if (s.contains("#")) return s.replaceFirst("^(.*#).*$", "$1");
27✔
297
        return s.replaceFirst("^(.*/).*$", "$1");
15✔
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(":");
24✔
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 (uri == null) return null;
6!
349
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
9!
350
            try {
351
                return Utils.getNanopub(uri);
9✔
352
            } catch (Exception ex) {
×
353
                logger.error("The given URI is not a known nanopublication: {}", uri, ex);
×
354
            }
355
        }
356
        return null;
×
357
    }
358

359
    private static final PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder()
9✔
360
            .allowCommonBlockElements()
3✔
361
            .allowCommonInlineFormattingElements()
45✔
362
            .allowUrlProtocols("https", "http", "mailto")
21✔
363
            .allowElements("a")
21✔
364
            .allowAttributes("href").onElements("a")
42✔
365
            .allowElements("img")
21✔
366
            .allowAttributes("src").onElements("img")
24✔
367
            .requireRelNofollowOnLinks()
3✔
368
            .toFactory();
6✔
369

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

380
    /**
381
     * Checks if a given string is likely to be HTML content.
382
     *
383
     * @param value the string to check
384
     * @return true if the given string is HTML content, false otherwise
385
     */
386
    public static boolean looksLikeHtml(String value) {
387
        return LEADING_TAG.matcher(value).find();
×
388
    }
389

390
    /**
391
     * Converts PageParameters to a URL-encoded string representation.
392
     *
393
     * @param params the PageParameters to convert
394
     * @return a string representation of the parameters in URL-encoded format
395
     */
396
    public static String getPageParametersAsString(PageParameters params) {
397
        String s = "";
6✔
398
        for (String n : params.getNamedKeys()) {
33✔
399
            if (!s.isEmpty()) s += "&";
18✔
400
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
30✔
401
        }
3✔
402
        return s;
6✔
403
    }
404

405
    /**
406
     * Sets a minimal escape markup function for a Select2Choice component.
407
     * This function replaces certain characters and formats the display of choices.
408
     *
409
     * @param selectItem the Select2Choice component to set the escape markup for
410
     */
411
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
412
        selectItem.getSettings().setEscapeMarkup("function(markup) {" +
×
413
                                                 "return markup" +
414
                                                 ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" +
415
                                                 ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" +
416
                                                 ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" +
417
                                                 ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" +
418
                                                 ";}"
419
        );
420
    }
×
421

422
    /**
423
     * Checks if a nanopublication is of a specific class.
424
     *
425
     * @param np       the nanopublication to check
426
     * @param classIri the IRI of the class to check against
427
     * @return true if the nanopublication is of the specified class, false otherwise
428
     */
429
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
430
        return NanopubUtils.getTypes(np).contains(classIri);
15✔
431
    }
432

433
    /**
434
     * Checks if a nanopublication uses a specific predicate in its assertion.
435
     *
436
     * @param np           the nanopublication to check
437
     * @param predicateIri the IRI of the predicate to look for
438
     * @return true if the predicate is used in the assertion, false otherwise
439
     */
440
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
441
        for (Statement st : np.getAssertion()) {
33✔
442
            if (predicateIri.equals(st.getPredicate())) {
15✔
443
                return true;
6✔
444
            }
445
        }
3✔
446
        return false;
6✔
447
    }
448

449
    /**
450
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
451
     *
452
     * @param np the nanopublication from which to extract FOAF names
453
     * @return a map where keys are subjects and values are FOAF names
454
     */
455
    public static Map<String, String> getFoafNameMap(Nanopub np) {
456
        Map<String, String> foafNameMap = new HashMap<>();
12✔
457
        for (Statement st : np.getPubinfo()) {
33✔
458
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
42✔
459
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
24✔
460
            }
461
        }
3✔
462
        return foafNameMap;
6✔
463
    }
464

465
    /**
466
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
467
     *
468
     * @param obj the object to hash
469
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
470
     */
471
    public static String createSha256HexHash(Object obj) {
472
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21✔
473
    }
474

475
    /**
476
     * Gets the types of a nanopublication.
477
     *
478
     * @param np the nanopublication from which to extract types
479
     * @return a list of IRI types associated with the nanopublication
480
     */
481
    public static List<IRI> getTypes(Nanopub np) {
482
        List<IRI> l = new ArrayList<>();
12✔
483
        for (IRI t : NanopubUtils.getTypes(np)) {
33✔
484
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) continue;
15✔
485
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED))
12✔
486
                continue;
3✔
487
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) continue;
12!
488
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED))
12!
489
                continue;
×
490
            l.add(t);
12✔
491
        }
3✔
492
        return l;
6✔
493
    }
494

495
    /**
496
     * Gets a label for a type IRI.
497
     *
498
     * @param typeIri the IRI of the type
499
     * @return a label for the type, potentially truncated
500
     */
501
    public static String getTypeLabel(IRI typeIri) {
502
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) return "FER";
18✔
503
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) return "FSR";
18✔
504
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) return "FIP";
18✔
505
        if (typeIri.equals(NPX.DECLARED_BY)) return "user intro";
18✔
506
        String l = typeIri.stringValue();
9✔
507
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
15✔
508
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
15✔
509
        if (l.length() > 25) l = l.substring(0, 20) + "...";
30✔
510
        return l;
6✔
511
    }
512

513
    /**
514
     * Gets a label for a URI.
515
     *
516
     * @param uri the URI to get the label from
517
     * @return a label for the URI, potentially truncated
518
     */
519
    public static String getUriLabel(String uri) {
520
        if (uri == null) return "";
12✔
521
        String uriLabel = uri;
6✔
522
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
12✔
523
            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✔
524
            if (newUriLabel.length() <= 70) return newUriLabel;
18!
525
        }
526
        if (uriLabel.length() > 70) return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
48✔
527
        return uriLabel;
6✔
528
    }
529

530
    /**
531
     * Gets an ExternalLink with a URI label.
532
     *
533
     * @param markupId the markup ID for the link
534
     * @param uri      the URI to link to
535
     * @return an ExternalLink with the URI label
536
     */
537
    public static ExternalLink getUriLink(String markupId, String uri) {
538
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39✔
539
    }
540

541
    /**
542
     * Gets an ExternalLink with a model for the URI label.
543
     *
544
     * @param markupId the markup ID for the link
545
     * @param model    the model containing the URI
546
     * @return an ExternalLink with the URI label
547
     */
548
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
549
        return new ExternalLink(markupId, model, new UriLabelModel(model));
×
550
    }
551

552
    private static class UriLabelModel implements IModel<String> {
553

554
        private IModel<String> uriModel;
555

556
        public UriLabelModel(IModel<String> uriModel) {
×
557
            this.uriModel = uriModel;
×
558
        }
×
559

560
        @Override
561
        public String getObject() {
562
            return getUriLabel(uriModel.getObject());
×
563
        }
564

565
    }
566

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

581
    /**
582
     * Creates a sublist from an array based on the specified indices.
583
     *
584
     * @param array     the array from which to create the sublist
585
     * @param fromIndex the starting index (inclusive) for the sublist
586
     * @param toIndex   the ending index (exclusive) for the sublist
587
     * @param <E>       the type of elements in the array
588
     * @return an ArrayList containing the elements from the specified range
589
     */
590
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
591
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
592
    }
593

594
    /**
595
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
596
     */
597
    // TODO Move this to ApiResponseEntry class?
598
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
599

600
        private String field;
601
        private boolean descending;
602

603
        /**
604
         * Constructor for ApiResponseEntrySorter.
605
         *
606
         * @param field      the field to sort by
607
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
608
         */
609
        public ApiResponseEntrySorter(String field, boolean descending) {
×
610
            this.field = field;
×
611
            this.descending = descending;
×
612
        }
×
613

614
        /**
615
         * Compares two ApiResponseEntry objects based on the specified field.
616
         *
617
         * @param o1 the first object to be compared.
618
         * @param o2 the second object to be compared.
619
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
620
         */
621
        @Override
622
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
623
            if (descending) {
×
624
                return o2.get(field).compareTo(o1.get(field));
×
625
            } else {
626
                return o1.get(field).compareTo(o2.get(field));
×
627
            }
628
        }
629

630
    }
631

632
    /**
633
     * MIME type for TriG RDF format.
634
     */
635
    public static final String TYPE_TRIG = "application/trig";
636

637
    /**
638
     * MIME type for Jelly RDF format.
639
     */
640
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
641

642
    /**
643
     * MIME type for JSON-LD format.
644
     */
645
    public static final String TYPE_JSONLD = "application/ld+json";
646

647
    /**
648
     * MIME type for N-Quads format.
649
     */
650
    public static final String TYPE_NQUADS = "application/n-quads";
651

652
    /**
653
     * MIME type for Trix format.
654
     */
655
    public static final String TYPE_TRIX = "application/trix";
656

657
    /**
658
     * MIME type for HTML format.
659
     */
660
    public static final String TYPE_HTML = "text/html";
661

662
    /**
663
     * Comma-separated list of supported MIME types for nanopublications.
664
     */
665
    public static final String SUPPORTED_TYPES =
666
            TYPE_TRIG + "," +
667
            TYPE_JELLY + "," +
668
            TYPE_JSONLD + "," +
669
            TYPE_NQUADS + "," +
670
            TYPE_TRIX + "," +
671
            TYPE_HTML;
672

673
    /**
674
     * List of supported MIME types for nanopublications.
675
     */
676
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
18✔
677

678
    /**
679
     * Returns the URL of the default Nanopub Registry as configured by the given instance.
680
     *
681
     * @return Nanopub Registry URL
682
     */
683
    public static String getMainRegistryUrl() {
684
        try {
685
            return EnvironmentUtils.getProcEnvironment().getOrDefault("NANODASH_MAIN_REGISTRY", "https://registry.knowledgepixels.com/");
18✔
686
        } catch (IOException ex) {
×
687
            logger.error("Could not get NANODASH_MAIN_REGISTRY environment variable, using default.", ex);
×
688
            return "https://registry.knowledgepixels.com/";
×
689
        }
690
    }
691

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

696
    /**
697
     * Checks whether string is valid literal serialization.
698
     *
699
     * @param literalString the literal string
700
     * @return true if valid
701
     */
702
    public static boolean isValidLiteralSerialization(String literalString) {
703
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
12✔
704
            return true;
6✔
705
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
706
            return true;
6✔
707
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
708
            return true;
6✔
709
        }
710
        return false;
6✔
711
    }
712

713
    /**
714
     * Returns a serialized version of the literal.
715
     *
716
     * @param literal the literal
717
     * @return the String serialization of the literal
718
     */
719
    public static String getSerializedLiteral(Literal literal) {
720
        if (literal.getLanguage().isPresent()) {
12✔
721
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
30✔
722
        } else if (literal.getDatatype().equals(XSD.STRING)) {
15✔
723
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
15✔
724
        } else {
725
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
24✔
726
        }
727
    }
728

729
    /**
730
     * Parses a serialized literal into a Literal object.
731
     *
732
     * @param serializedLiteral The serialized String of the literal
733
     * @return The parse Literal object
734
     */
735
    public static Literal getParsedLiteral(String serializedLiteral) {
736
        if (serializedLiteral.matches(PLAIN_LITERAL_PATTERN)) {
12✔
737
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(PLAIN_LITERAL_PATTERN, "$1")));
24✔
738
        } else if (serializedLiteral.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
739
            String langtag = serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$3");
15✔
740
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$1")), langtag);
27✔
741
        } else if (serializedLiteral.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
742
            IRI datatype = vf.createIRI(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$3"));
21✔
743
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$1")), datatype);
27✔
744
        }
745
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
18✔
746
    }
747

748
    /**
749
     * Escapes quotes (") and slashes (/) of a literal string.
750
     *
751
     * @param unescapedString un-escaped string
752
     * @return escaped string
753
     */
754
    public static String getEscapedLiteralString(String unescapedString) {
755
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
24✔
756
    }
757

758
    /**
759
     * Un-escapes quotes (") and slashes (/) of a literal string.
760
     *
761
     * @param escapedString escaped string
762
     * @return un-escaped string
763
     */
764
    public static String getUnescapedLiteralString(String escapedString) {
765
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
15✔
766
    }
767

768
    /**
769
     * Checks if a given IRI is a local URI.
770
     *
771
     * @param uri the IRI to check
772
     * @return true if the IRI is a local URI, false otherwise
773
     */
774
    public static boolean isLocalURI(IRI uri) {
775
        return uri != null && isLocalURI(uri.stringValue());
30✔
776
    }
777

778
    /**
779
     * Checks if a given string is a local URI.
780
     *
781
     * @param uriAsString the string to check
782
     * @return true if the string is a local URI, false otherwise
783
     */
784
    public static boolean isLocalURI(String uriAsString) {
785
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33✔
786
    }
787

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