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

knowledgepixels / nanodash / 24382503285

14 Apr 2026 05:24AM UTC coverage: 15.886% (-0.2%) from 16.094%
24382503285

push

github

web-flow
Merge pull request #438 from knowledgepixels/feature/item-list-view-435

feat: implement ItemListView and fix async view rendering

789 of 6130 branches covered (12.87%)

Branch coverage included in aggregate %.

1978 of 11288 relevant lines covered (17.52%)

2.4 hits per line

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

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

3
import com.google.common.hash.Hashing;
4
import com.knowledgepixels.nanodash.domain.User;
5
import net.trustyuri.TrustyUriUtils;
6
import org.apache.commons.codec.Charsets;
7
import org.apache.commons.lang.StringUtils;
8
import org.apache.http.client.utils.URIBuilder;
9
import org.apache.wicket.markup.html.link.ExternalLink;
10
import org.apache.wicket.model.IModel;
11
import org.apache.wicket.request.mapper.parameter.PageParameters;
12
import org.apache.wicket.util.string.StringValue;
13
import org.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.Serializable;
39
import java.net.URISyntaxException;
40
import java.net.URLDecoder;
41
import java.net.URLEncoder;
42
import java.nio.charset.StandardCharsets;
43
import java.util.*;
44
import java.util.regex.Pattern;
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();
6✔
60
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
9✔
61
    private static final Pattern LEADING_TAG = Pattern.compile("^\\s*<(p|div|span|img|pre)(\\s|>|/).*", Pattern.CASE_INSENSITIVE);
12✔
62
    private static final String DEFAULT_MAIN_QUERY_URL = "https://query.knowledgepixels.com/";
63
    private static final String DEFAULT_MAIN_REGISTRY_URL = "https://registry.knowledgepixels.com/";
64

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

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

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

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

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

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

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

152
    public static String truncateLabel(String label) {
153
        if (label != null && label.length() > 120) {
×
154
            return label.substring(0, 100) + "...";
×
155
        }
156
        return label;
×
157
    }
158

159
    /**
160
     * URL-decodes the string representation of the given object using UTF-8 encoding.
161
     *
162
     * @param o the object to be URL-decoded
163
     * @return the URL-decoded string
164
     */
165
    public static String urlDecode(Object o) {
166
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
167
    }
168

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

410
    /**
411
     * Converts PageParameters to a URL-encoded string representation.
412
     *
413
     * @param params the PageParameters to convert
414
     * @return a string representation of the parameters in URL-encoded format
415
     */
416
    public static String getPageParametersAsString(PageParameters params) {
417
        String s = "";
6✔
418
        for (String n : params.getNamedKeys()) {
33✔
419
            if (!s.isEmpty()) s += "&";
18✔
420
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
30✔
421
        }
3✔
422
        return s;
6✔
423
    }
424

425
    /**
426
     * Sets a minimal escape markup function for a Select2Choice component.
427
     * This function replaces certain characters and formats the display of choices.
428
     *
429
     * @param selectItem the Select2Choice component to set the escape markup for
430
     */
431
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
432
        selectItem.getSettings().setEscapeMarkup("function(markup) {" +
×
433
                                                 "return markup" +
434
                                                 ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" +
435
                                                 ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" +
436
                                                 ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" +
437
                                                 ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" +
438
                                                 ";}"
439
        );
440
    }
×
441

442
    /**
443
     * Checks if a nanopublication is of a specific class.
444
     *
445
     * @param np       the nanopublication to check
446
     * @param classIri the IRI of the class to check against
447
     * @return true if the nanopublication is of the specified class, false otherwise
448
     */
449
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
450
        return NanopubUtils.getTypes(np).contains(classIri);
15✔
451
    }
452

453
    /**
454
     * Checks if a nanopublication uses a specific predicate in its assertion.
455
     *
456
     * @param np           the nanopublication to check
457
     * @param predicateIri the IRI of the predicate to look for
458
     * @return true if the predicate is used in the assertion, false otherwise
459
     */
460
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
461
        for (Statement st : np.getAssertion()) {
33✔
462
            if (predicateIri.equals(st.getPredicate())) {
15✔
463
                return true;
6✔
464
            }
465
        }
3✔
466
        return false;
6✔
467
    }
468

469
    /**
470
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
471
     *
472
     * @param np the nanopublication from which to extract FOAF names
473
     * @return a map where keys are subjects and values are FOAF names
474
     */
475
    public static Map<String, String> getFoafNameMap(Nanopub np) {
476
        Map<String, String> foafNameMap = new HashMap<>();
12✔
477
        for (Statement st : np.getPubinfo()) {
33✔
478
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
42✔
479
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
24✔
480
            }
481
        }
3✔
482
        return foafNameMap;
6✔
483
    }
484

485
    /**
486
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
487
     *
488
     * @param obj the object to hash
489
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
490
     */
491
    public static String createSha256HexHash(Object obj) {
492
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21✔
493
    }
494

495
    /**
496
     * Gets the types of a nanopublication.
497
     *
498
     * @param np the nanopublication from which to extract types
499
     * @return a list of IRI types associated with the nanopublication
500
     */
501
    public static List<IRI> getTypes(Nanopub np) {
502
        List<IRI> l = new ArrayList<>();
12✔
503
        for (IRI t : NanopubUtils.getTypes(np)) {
33✔
504
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) continue;
15✔
505
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED))
12✔
506
                continue;
3✔
507
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) continue;
12!
508
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED))
12!
509
                continue;
×
510
            l.add(t);
12✔
511
        }
3✔
512
        return l;
6✔
513
    }
514

515
    /**
516
     * Gets a label for a type IRI.
517
     *
518
     * @param typeIri the IRI of the type
519
     * @return a label for the type, potentially truncated
520
     */
521
    public static String getTypeLabel(IRI typeIri) {
522
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) return "FER";
18✔
523
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) return "FSR";
18✔
524
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) return "FIP";
18✔
525
        if (typeIri.equals(NPX.DECLARED_BY)) return "user intro";
18✔
526
        String l = typeIri.stringValue();
9✔
527
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
15✔
528
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
15✔
529
        if (l.length() > 25) l = l.substring(0, 20) + "...";
30✔
530
        return l;
6✔
531
    }
532

533
    /**
534
     * Gets a label for a URI.
535
     *
536
     * @param uri the URI to get the label from
537
     * @return a label for the URI, potentially truncated
538
     */
539
    public static String getUriLabel(String uri) {
540
        if (uri == null) return "";
12✔
541
        String uriLabel = uri;
6✔
542
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
12✔
543
            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✔
544
            if (newUriLabel.length() <= 70) return newUriLabel;
18!
545
        }
546
        if (uriLabel.length() > 70) return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
48✔
547
        return uriLabel;
6✔
548
    }
549

550
    /**
551
     * Gets an ExternalLink with a URI label.
552
     *
553
     * @param markupId the markup ID for the link
554
     * @param uri      the URI to link to
555
     * @return an ExternalLink with the URI label
556
     */
557
    public static ExternalLink getUriLink(String markupId, String uri) {
558
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39✔
559
    }
560

561
    /**
562
     * Gets an ExternalLink with a model for the URI label.
563
     *
564
     * @param markupId the markup ID for the link
565
     * @param model    the model containing the URI
566
     * @return an ExternalLink with the URI label
567
     */
568
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
569
        return new ExternalLink(markupId, model, new UriLabelModel(model));
×
570
    }
571

572
    private static class UriLabelModel implements IModel<String> {
573

574
        private IModel<String> uriModel;
575

576
        public UriLabelModel(IModel<String> uriModel) {
×
577
            this.uriModel = uriModel;
×
578
        }
×
579

580
        @Override
581
        public String getObject() {
582
            return getUriLabel(uriModel.getObject());
×
583
        }
584

585
    }
586

587
    /**
588
     * Creates a sublist from a list based on the specified indices.
589
     *
590
     * @param list      the list from which to create the sublist
591
     * @param fromIndex the starting index (inclusive) for the sublist
592
     * @param toIndex   the ending index (exclusive) for the sublist
593
     * @param <E>       the type of elements in the list
594
     * @return an ArrayList containing the elements from the specified range
595
     */
596
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
597
        // So the resulting list is serializable:
598
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
×
599
    }
600

601
    /**
602
     * Creates a sublist from an array based on the specified indices.
603
     *
604
     * @param array     the array from which to create the sublist
605
     * @param fromIndex the starting index (inclusive) for the sublist
606
     * @param toIndex   the ending index (exclusive) for the sublist
607
     * @param <E>       the type of elements in the array
608
     * @return an ArrayList containing the elements from the specified range
609
     */
610
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
611
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
612
    }
613

614
    /**
615
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
616
     */
617
    // TODO Move this to ApiResponseEntry class?
618
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
619

620
        private String field;
621
        private boolean descending;
622

623
        /**
624
         * Constructor for ApiResponseEntrySorter.
625
         *
626
         * @param field      the field to sort by
627
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
628
         */
629
        public ApiResponseEntrySorter(String field, boolean descending) {
×
630
            this.field = field;
×
631
            this.descending = descending;
×
632
        }
×
633

634
        /**
635
         * Compares two ApiResponseEntry objects based on the specified field.
636
         *
637
         * @param o1 the first object to be compared.
638
         * @param o2 the second object to be compared.
639
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
640
         */
641
        @Override
642
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
643
            if (descending) {
×
644
                return o2.get(field).compareTo(o1.get(field));
×
645
            } else {
646
                return o1.get(field).compareTo(o2.get(field));
×
647
            }
648
        }
649

650
    }
651

652
    /**
653
     * MIME type for TriG RDF format.
654
     */
655
    public static final String TYPE_TRIG = "application/trig";
656

657
    /**
658
     * MIME type for Jelly RDF format.
659
     */
660
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
661

662
    /**
663
     * MIME type for JSON-LD format.
664
     */
665
    public static final String TYPE_JSONLD = "application/ld+json";
666

667
    /**
668
     * MIME type for N-Quads format.
669
     */
670
    public static final String TYPE_NQUADS = "application/n-quads";
671

672
    /**
673
     * MIME type for Trix format.
674
     */
675
    public static final String TYPE_TRIX = "application/trix";
676

677
    /**
678
     * MIME type for HTML format.
679
     */
680
    public static final String TYPE_HTML = "text/html";
681

682
    /**
683
     * Comma-separated list of supported MIME types for nanopublications.
684
     */
685
    public static final String SUPPORTED_TYPES =
686
            TYPE_TRIG + "," +
687
            TYPE_JELLY + "," +
688
            TYPE_JSONLD + "," +
689
            TYPE_NQUADS + "," +
690
            TYPE_TRIX + "," +
691
            TYPE_HTML;
692

693
    /**
694
     * List of supported MIME types for nanopublications.
695
     */
696
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
18✔
697

698
    /**
699
     * Returns the URL of the default Nanopub Registry as configured by the given instance.
700
     *
701
     * @return Nanopub Registry URL
702
     */
703
    public static String getMainRegistryUrl() {
704
        String envValue = System.getenv("NANODASH_MAIN_REGISTRY");
9✔
705
        if (envValue != null) {
6!
706
            logger.info("Found environment variable NANODASH_MAIN_REGISTRY with value: {}", envValue);
×
707
            return envValue;
×
708
        } else {
709
            logger.info("Environment variable NANODASH_MAIN_REGISTRY not set, using default: {}", DEFAULT_MAIN_REGISTRY_URL);
12✔
710
            return DEFAULT_MAIN_REGISTRY_URL;
6✔
711
        }
712
    }
713

714
    /**
715
     * Returns the URL of the default Nanopub Query as configured by the given instance.
716
     *
717
     * @return Nanopub Query URL
718
     */
719
    public static String getMainQueryUrl() {
720
        String envValue = System.getenv("NANODASH_MAIN_QUERY");
×
721
        if (envValue != null) {
×
722
            logger.info("Found environment variable NANODASH_MAIN_QUERY with value: {}", envValue);
×
723
            return envValue;
×
724
        } else {
725
            logger.info("Environment variable NANODASH_MAIN_QUERY not set, using default: {}", DEFAULT_MAIN_QUERY_URL);
×
726
            return DEFAULT_MAIN_QUERY_URL;
×
727
        }
728
    }
729

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

734
    /**
735
     * Checks whether string is valid literal serialization.
736
     *
737
     * @param literalString the literal string
738
     * @return true if valid
739
     */
740
    public static boolean isValidLiteralSerialization(String literalString) {
741
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
12✔
742
            return true;
6✔
743
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
744
            return true;
6✔
745
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
746
            return true;
6✔
747
        }
748
        return false;
6✔
749
    }
750

751
    /**
752
     * Returns a serialized version of the literal.
753
     *
754
     * @param literal the literal
755
     * @return the String serialization of the literal
756
     */
757
    public static String getSerializedLiteral(Literal literal) {
758
        if (literal.getLanguage().isPresent()) {
12✔
759
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
30✔
760
        } else if (literal.getDatatype().equals(XSD.STRING)) {
15✔
761
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
15✔
762
        } else {
763
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
24✔
764
        }
765
    }
766

767
    /**
768
     * Parses a serialized literal into a Literal object.
769
     *
770
     * @param serializedLiteral The serialized String of the literal
771
     * @return The parse Literal object
772
     */
773
    public static Literal getParsedLiteral(String serializedLiteral) {
774
        if (serializedLiteral.matches(PLAIN_LITERAL_PATTERN)) {
12✔
775
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(PLAIN_LITERAL_PATTERN, "$1")));
24✔
776
        } else if (serializedLiteral.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
777
            String langtag = serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$3");
15✔
778
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$1")), langtag);
27✔
779
        } else if (serializedLiteral.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
780
            IRI datatype = vf.createIRI(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$3"));
21✔
781
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$1")), datatype);
27✔
782
        }
783
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
18✔
784
    }
785

786
    /**
787
     * Escapes quotes (") and slashes (/) of a literal string.
788
     *
789
     * @param unescapedString un-escaped string
790
     * @return escaped string
791
     */
792
    public static String getEscapedLiteralString(String unescapedString) {
793
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
24✔
794
    }
795

796
    /**
797
     * Un-escapes quotes (") and slashes (/) of a literal string.
798
     *
799
     * @param escapedString escaped string
800
     * @return un-escaped string
801
     */
802
    public static String getUnescapedLiteralString(String escapedString) {
803
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
15✔
804
    }
805

806
    /**
807
     * Checks if a given IRI is a local URI.
808
     *
809
     * @param uri the IRI to check
810
     * @return true if the IRI is a local URI, false otherwise
811
     */
812
    public static boolean isLocalURI(IRI uri) {
813
        return uri != null && isLocalURI(uri.stringValue());
30✔
814
    }
815

816
    /**
817
     * Checks if a given string is a local URI.
818
     *
819
     * @param uriAsString the string to check
820
     * @return true if the string is a local URI, false otherwise
821
     */
822
    public static boolean isLocalURI(String uriAsString) {
823
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33✔
824
    }
825

826
    public static String unescapeMultiValue(String s) {
827
        StringBuilder sb = new StringBuilder();
12✔
828
        for (int i = 0; i < s.length(); i++) {
24✔
829
            if (s.charAt(i) == '\\' && i + 1 < s.length()) {
33✔
830
                char next = s.charAt(i + 1);
18✔
831
                if (next == 'n') {
9✔
832
                    sb.append('\n');
15✔
833
                } else if (next == '\\') {
9!
834
                    sb.append('\\');
15✔
835
                } else {
836
                    sb.append(next);
×
837
                }
838
                i++;
3✔
839
            } else {
3✔
840
                sb.append(s.charAt(i));
18✔
841
            }
842
        }
843
        return sb.toString();
9✔
844
    }
845

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