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

knowledgepixels / nanodash / 23799954373

31 Mar 2026 01:30PM UTC coverage: 16.286% (-0.01%) from 16.297%
23799954373

push

github

web-flow
Merge pull request #424 from knowledgepixels/fix/423-error-after-publishing

fix: prevent error page after publishing

756 of 5705 branches covered (13.25%)

Branch coverage included in aggregate %.

1902 of 10616 relevant lines covered (17.92%)

2.46 hits per line

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

68.28
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
    /**
153
     * URL-decodes the string representation of the given object using UTF-8 encoding.
154
     *
155
     * @param o the object to be URL-decoded
156
     * @return the URL-decoded string
157
     */
158
    public static String urlDecode(Object o) {
159
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
160
    }
161

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

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

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

219
    /**
220
     * Retrieves the name of the public key location based on the public key.
221
     *
222
     * @param pubkeyhash the public key string
223
     * @return the name of the public key location
224
     */
225
    public static String getPubkeyLocationName(String pubkeyhash) {
226
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
227
    }
228

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

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

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

278
    /**
279
     * Retrieves the short ORCID ID from an IRI object.
280
     *
281
     * @param orcidIri the IRI object representing the ORCID ID
282
     * @return the short ORCID ID as a string
283
     */
284
    public static String getShortOrcidId(IRI orcidIri) {
285
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
18✔
286
    }
287

288
    /**
289
     * Retrieves the URI postfix from a given URI object.
290
     *
291
     * @param uri the URI object from which to extract the postfix
292
     * @return the URI postfix as a string
293
     */
294
    public static String getUriPostfix(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
     * Retrieves the URI prefix from a given URI object.
302
     *
303
     * @param uri the URI object from which to extract the prefix
304
     * @return the URI prefix as a string
305
     */
306
    public static String getUriPrefix(Object uri) {
307
        String s = uri.toString();
9✔
308
        if (s.contains("#")) return s.replaceFirst("^(.*#).*$", "$1");
27✔
309
        return s.replaceFirst("^(.*/).*$", "$1");
15✔
310
    }
311

312
    /**
313
     * Checks if a given string is a valid URI postfix.
314
     * A valid URI postfix does not contain a colon (":").
315
     *
316
     * @param s the string to check
317
     * @return true if the string is a valid URI postfix, false otherwise
318
     */
319
    public static boolean isUriPostfix(String s) {
320
        return !s.contains(":");
24✔
321
    }
322

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

339
    /**
340
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
341
     *
342
     * @param inp the IntroNanopub from which to extract the signature element
343
     * @return the NanopubSignatureElement associated with the nanopublication
344
     */
345
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
346
        try {
347
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
348
        } catch (MalformedCryptoElementException ex) {
×
349
            throw new RuntimeException(ex);
×
350
        }
351
    }
352

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

371
    private static final PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder()
9✔
372
            .allowCommonBlockElements()
3✔
373
            .allowCommonInlineFormattingElements()
45✔
374
            .allowUrlProtocols("https", "http", "mailto")
21✔
375
            .allowElements("a")
21✔
376
            .allowAttributes("href").onElements("a")
42✔
377
            .allowElements("img")
21✔
378
            .allowAttributes("src").onElements("img")
42✔
379
            .allowElements("pre")
3✔
380
            .requireRelNofollowOnLinks()
3✔
381
            .toFactory();
6✔
382

383
    /**
384
     * Sanitizes raw HTML input to ensure safe rendering.
385
     *
386
     * @param rawHtml the raw HTML input to sanitize
387
     * @return sanitized HTML string
388
     */
389
    public static String sanitizeHtml(String rawHtml) {
390
        return htmlSanitizePolicy.sanitize(rawHtml);
12✔
391
    }
392

393
    /**
394
     * Checks if a given string is likely to be HTML content.
395
     *
396
     * @param value the string to check
397
     * @return true if the given string is HTML content, false otherwise
398
     */
399
    public static boolean looksLikeHtml(String value) {
400
        return LEADING_TAG.matcher(value).find();
×
401
    }
402

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

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

435
    /**
436
     * Checks if a nanopublication is of a specific class.
437
     *
438
     * @param np       the nanopublication to check
439
     * @param classIri the IRI of the class to check against
440
     * @return true if the nanopublication is of the specified class, false otherwise
441
     */
442
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
443
        return NanopubUtils.getTypes(np).contains(classIri);
15✔
444
    }
445

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

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

478
    /**
479
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
480
     *
481
     * @param obj the object to hash
482
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
483
     */
484
    public static String createSha256HexHash(Object obj) {
485
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21✔
486
    }
487

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

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

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

543
    /**
544
     * Gets an ExternalLink with a URI label.
545
     *
546
     * @param markupId the markup ID for the link
547
     * @param uri      the URI to link to
548
     * @return an ExternalLink with the URI label
549
     */
550
    public static ExternalLink getUriLink(String markupId, String uri) {
551
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39✔
552
    }
553

554
    /**
555
     * Gets an ExternalLink with a model for the URI label.
556
     *
557
     * @param markupId the markup ID for the link
558
     * @param model    the model containing the URI
559
     * @return an ExternalLink with the URI label
560
     */
561
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
562
        return new ExternalLink(markupId, model, new UriLabelModel(model));
×
563
    }
564

565
    private static class UriLabelModel implements IModel<String> {
566

567
        private IModel<String> uriModel;
568

569
        public UriLabelModel(IModel<String> uriModel) {
×
570
            this.uriModel = uriModel;
×
571
        }
×
572

573
        @Override
574
        public String getObject() {
575
            return getUriLabel(uriModel.getObject());
×
576
        }
577

578
    }
579

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

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

607
    /**
608
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
609
     */
610
    // TODO Move this to ApiResponseEntry class?
611
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
612

613
        private String field;
614
        private boolean descending;
615

616
        /**
617
         * Constructor for ApiResponseEntrySorter.
618
         *
619
         * @param field      the field to sort by
620
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
621
         */
622
        public ApiResponseEntrySorter(String field, boolean descending) {
×
623
            this.field = field;
×
624
            this.descending = descending;
×
625
        }
×
626

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

643
    }
644

645
    /**
646
     * MIME type for TriG RDF format.
647
     */
648
    public static final String TYPE_TRIG = "application/trig";
649

650
    /**
651
     * MIME type for Jelly RDF format.
652
     */
653
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
654

655
    /**
656
     * MIME type for JSON-LD format.
657
     */
658
    public static final String TYPE_JSONLD = "application/ld+json";
659

660
    /**
661
     * MIME type for N-Quads format.
662
     */
663
    public static final String TYPE_NQUADS = "application/n-quads";
664

665
    /**
666
     * MIME type for Trix format.
667
     */
668
    public static final String TYPE_TRIX = "application/trix";
669

670
    /**
671
     * MIME type for HTML format.
672
     */
673
    public static final String TYPE_HTML = "text/html";
674

675
    /**
676
     * Comma-separated list of supported MIME types for nanopublications.
677
     */
678
    public static final String SUPPORTED_TYPES =
679
            TYPE_TRIG + "," +
680
            TYPE_JELLY + "," +
681
            TYPE_JSONLD + "," +
682
            TYPE_NQUADS + "," +
683
            TYPE_TRIX + "," +
684
            TYPE_HTML;
685

686
    /**
687
     * List of supported MIME types for nanopublications.
688
     */
689
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
18✔
690

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

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

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

727
    /**
728
     * Checks whether string is valid literal serialization.
729
     *
730
     * @param literalString the literal string
731
     * @return true if valid
732
     */
733
    public static boolean isValidLiteralSerialization(String literalString) {
734
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
12✔
735
            return true;
6✔
736
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
737
            return true;
6✔
738
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
739
            return true;
6✔
740
        }
741
        return false;
6✔
742
    }
743

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

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

779
    /**
780
     * Escapes quotes (") and slashes (/) of a literal string.
781
     *
782
     * @param unescapedString un-escaped string
783
     * @return escaped string
784
     */
785
    public static String getEscapedLiteralString(String unescapedString) {
786
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
24✔
787
    }
788

789
    /**
790
     * Un-escapes quotes (") and slashes (/) of a literal string.
791
     *
792
     * @param escapedString escaped string
793
     * @return un-escaped string
794
     */
795
    public static String getUnescapedLiteralString(String escapedString) {
796
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
15✔
797
    }
798

799
    /**
800
     * Checks if a given IRI is a local URI.
801
     *
802
     * @param uri the IRI to check
803
     * @return true if the IRI is a local URI, false otherwise
804
     */
805
    public static boolean isLocalURI(IRI uri) {
806
        return uri != null && isLocalURI(uri.stringValue());
30✔
807
    }
808

809
    /**
810
     * Checks if a given string is a local URI.
811
     *
812
     * @param uriAsString the string to check
813
     * @return true if the string is a local URI, false otherwise
814
     */
815
    public static boolean isLocalURI(String uriAsString) {
816
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33✔
817
    }
818

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

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