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

knowledgepixels / nanodash / 30430442207

29 Jul 2026 07:06AM UTC coverage: 33.91% (+0.5%) from 33.442%
30430442207

push

github

web-flow
Merge pull request #568 from knowledgepixels/440-add-calendar-event

feat: add to calendar and subscribe to event calendars

2412 of 7855 branches covered (30.71%)

Branch coverage included in aggregate %.

4701 of 13121 relevant lines covered (35.83%)

5.53 hits per line

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

62.71
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.Url;
12
import org.apache.wicket.request.cycle.RequestCycle;
13
import org.apache.wicket.request.mapper.parameter.PageParameters;
14
import org.apache.wicket.util.string.StringValue;
15
import org.apache.wicket.util.string.Strings;
16
import org.eclipse.rdf4j.model.IRI;
17
import org.eclipse.rdf4j.model.Literal;
18
import org.eclipse.rdf4j.model.Statement;
19
import org.eclipse.rdf4j.model.ValueFactory;
20
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
21
import org.eclipse.rdf4j.model.util.Literals;
22
import org.eclipse.rdf4j.model.vocabulary.FOAF;
23
import org.eclipse.rdf4j.model.vocabulary.XSD;
24
import org.nanopub.Nanopub;
25
import org.nanopub.NanopubUtils;
26
import org.nanopub.extra.security.KeyDeclaration;
27
import org.nanopub.extra.security.MalformedCryptoElementException;
28
import org.nanopub.extra.security.NanopubSignatureElement;
29
import org.nanopub.extra.security.SignatureUtils;
30
import org.nanopub.extra.server.GetNanopub;
31
import org.nanopub.extra.server.NanopubServerUtils;
32
import org.nanopub.extra.services.ApiResponseEntry;
33
import org.nanopub.extra.services.NotEnoughAPIInstancesException;
34
import org.nanopub.extra.services.QueryCall;
35
import org.nanopub.extra.setting.IntroNanopub;
36
import org.nanopub.vocabulary.FIP;
37
import org.nanopub.vocabulary.NPX;
38
import org.owasp.html.HtmlPolicyBuilder;
39
import org.owasp.html.PolicyFactory;
40
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42
import org.wicketstuff.select2.Select2Choice;
43

44
import java.io.Serializable;
45
import java.net.URISyntaxException;
46
import java.net.URLDecoder;
47
import java.net.URLEncoder;
48
import java.nio.charset.StandardCharsets;
49
import java.time.LocalDateTime;
50
import java.time.OffsetDateTime;
51
import java.time.format.DateTimeFormatter;
52
import java.time.format.DateTimeParseException;
53
import java.util.*;
54
import java.util.regex.Pattern;
55

56
import static java.nio.charset.StandardCharsets.UTF_8;
57

58
/**
59
 * Utility class providing various helper methods for handling nanopublications, URIs, and other related functionalities.
60
 */
61
public class Utils {
62

63
    private Utils() {
64
    }  // no instances allowed
65

66
    /**
67
     * ValueFactory instance for creating RDF model objects.
68
     */
69
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
70
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
9✔
71
    private static final Pattern LEADING_TAG = Pattern.compile("^\\s*<(p|div|span|img|pre)(\\s|>|/).*", Pattern.CASE_INSENSITIVE);
12✔
72
    private static final String DEFAULT_MAIN_QUERY_URL = "https://query.knowledgepixels.com/";
73
    private static final String DEFAULT_MAIN_REGISTRY_URL = "https://registry.knowledgepixels.com/";
74

75
    /**
76
     * Generates a short name from a given IRI object.
77
     *
78
     * @param uri the IRI object
79
     * @return a short representation of the URI
80
     */
81
    public static String getShortNameFromURI(IRI uri) {
82
        return getShortNameFromURI(uri.stringValue());
12✔
83
    }
84

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

109
    /**
110
     * Generates a short nanopublication ID from a given nanopublication ID or URI.
111
     *
112
     * @param npId the nanopublication ID or URI
113
     * @return the first 10 characters of the artifact code
114
     */
115
    public static String getShortNanopubId(Object npId) {
116
        return TrustyUriUtils.getArtifactCode(npId.toString()).substring(0, 10);
21✔
117
    }
118

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

121
    /**
122
     * Adds a nanopublication to the local cache so it can be retrieved immediately
123
     * without needing to fetch it from the registry.
124
     *
125
     * @param np the nanopublication to cache
126
     */
127
    public static void cacheNanopub(Nanopub np) {
128
        String artifactCode = GetNanopub.getArtifactCode(np.getUri().stringValue()).toString();
×
129
        nanopubs.put(artifactCode, np);
×
130
    }
×
131

132
    /**
133
     * Retrieves a Nanopub object based on the given URI or artifact code.
134
     *
135
     * @param uriOrArtifactCode the URI or artifact code of the nanopublication
136
     * @return the Nanopub object, or null if not found
137
     */
138
    public static Nanopub getNanopub(String uriOrArtifactCode) {
139
        String artifactCode = GetNanopub.getArtifactCode(uriOrArtifactCode).toString();
12✔
140
        if (!nanopubs.containsKey(artifactCode)) {
12✔
141
            for (int i = 0; i < 3; i++) {  // Try 3 times to get nanopub
15!
142
                Nanopub np = GetNanopub.get(artifactCode);
9✔
143
                if (np != null) {
6!
144
                    nanopubs.put(artifactCode, np);
15✔
145
                    break;
3✔
146
                }
147
            }
148
        }
149
        return nanopubs.get(artifactCode);
15✔
150
    }
151

152
    /**
153
     * Strips a sub-IRI of a nanopublication (e.g. an embedded resource IRI like
154
     * {@code <np-uri>/template}) down to the nanopublication ID itself, i.e. up to
155
     * and including the trusty artifact code. An ID without a sub-path is returned
156
     * unchanged.
157
     *
158
     * @param id the ID to strip
159
     * @return the nanopublication ID
160
     */
161
    public static String stripToNanopubId(String id) {
162
        return id.replaceFirst("^(.*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43})[^A-Za-z0-9-_].*$", "$1");
15✔
163
    }
164

165
    // Wicket URL-encodes the session into a path parameter when the client has not (yet)
166
    // returned a cookie. Harmless for a link the browser follows, poisonous for a URL that
167
    // outlives the request — see absolutePageUrl.
168
    private static final Pattern JSESSIONID_PATTERN = Pattern.compile(";jsessionid=[^?/;]*", Pattern.CASE_INSENSITIVE);
12✔
169

170
    /**
171
     * The absolute URL of a mounted page, for handing to something outside this request:
172
     * embedding in a downloaded file, giving to a third-party service to fetch, or showing
173
     * the user to copy.
174
     *
175
     * <p>Any {@code ;jsessionid=} Wicket added is stripped. Such a URL is not merely ugly —
176
     * it is bound to one visitor's session, so a calendar feed URL carrying one would break
177
     * once the session expired, and would hand out a live session identifier to anyone the
178
     * user shared it with.</p>
179
     *
180
     * @param pageClass the mounted page
181
     * @param params    the page parameters
182
     * @return the full URL, including scheme and host
183
     */
184
    public static String absolutePageUrl(Class<? extends org.apache.wicket.Page> pageClass, PageParameters params) {
185
        RequestCycle cycle = RequestCycle.get();
×
186
        String url = cycle.urlFor(pageClass, params).toString();
×
187
        return stripSessionId(cycle.getUrlRenderer().renderFullUrl(Url.parse(url)));
×
188
    }
189

190
    /**
191
     * Removes a {@code ;jsessionid=...} path parameter from a URL. See
192
     * {@link #absolutePageUrl} for why this must happen before a URL leaves the request.
193
     *
194
     * @param url the URL, possibly session-decorated
195
     * @return the URL without its session id
196
     */
197
    static String stripSessionId(String url) {
198
        return JSESSIONID_PATTERN.matcher(url).replaceAll("");
18✔
199
    }
200

201
    /**
202
     * URL-encodes the string representation of the given object using UTF-8 encoding.
203
     *
204
     * @param o the object to be URL-encoded
205
     * @return the URL-encoded string
206
     */
207
    public static String urlEncode(Object o) {
208
        return URLEncoder.encode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
209
    }
210

211
    public static String truncateLabel(String label) {
212
        if (label != null && label.length() > 120) {
×
213
            return label.substring(0, 100) + "...";
×
214
        }
215
        return label;
×
216
    }
217

218
    /**
219
     * Truncates an over-long entity label for display in a link or breadcrumb:
220
     * labels longer than 60 characters are cut to 47 characters with an ellipsis
221
     * ("...") appended, so a single long label (e.g. a full IRI tail) never blows
222
     * up the surrounding UI. Shorter labels are returned unchanged. The full label
223
     * stays available on the entity's own page, which shows it as the title.
224
     *
225
     * @param label the label to truncate, or null
226
     * @return the truncated label, or the original if 60 characters or shorter
227
     */
228
    public static String truncateLinkLabel(String label) {
229
        if (label == null || label.length() <= 60) {
18!
230
            return label;
6✔
231
        }
232
        return label.substring(0, 47).stripTrailing() + "...";
×
233
    }
234

235
    /**
236
     * Builds the HTML body for a menu entry whose label may begin with a leading
237
     * symbol/emoji used as the entry's icon. If {@code label} starts with a token
238
     * of symbol/emoji characters (no letters or digits) followed by whitespace,
239
     * that token is wrapped in the {@code .actionmenu-icon} slot and the remaining
240
     * text follows it (both escaped). Returns {@code null} when there is no such
241
     * leading icon, so callers can fall back to the plain (escaped) label.
242
     *
243
     * @param label the menu entry label
244
     * @return the icon+text HTML body to render with escaping disabled, or null
245
     */
246
    public static String menuEntryIconBodyHtml(String label) {
247
        if (label == null) {
×
248
            return null;
×
249
        }
250
        int sp = -1;
×
251
        for (int i = 0; i < label.length(); i++) {
×
252
            if (Character.isWhitespace(label.charAt(i))) {
×
253
                sp = i;
×
254
                break;
×
255
            }
256
        }
257
        if (sp <= 0) {
×
258
            return null;
×
259
        }
260
        String icon = label.substring(0, sp);
×
261
        String rest = label.substring(sp).replaceFirst("^\\s+", "");
×
262
        if (rest.isEmpty()) {
×
263
            return null;
×
264
        }
265
        // Only a pure symbol/emoji token (no letters or digits) counts as an icon.
266
        if (icon.codePoints().anyMatch(Character::isLetterOrDigit)) {
×
267
            return null;
×
268
        }
269
        return "<span class=\"actionmenu-icon\">" + Strings.escapeMarkup(icon) + "</span>" + Strings.escapeMarkup(rest);
×
270
    }
271

272
    /**
273
     * URL-decodes the string representation of the given object using UTF-8 encoding.
274
     *
275
     * @param o the object to be URL-decoded
276
     * @return the URL-decoded string
277
     */
278
    public static String urlDecode(Object o) {
279
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
27✔
280
    }
281

282
    /**
283
     * Generates a URL with the given base and appends the provided PageParameters as query parameters.
284
     *
285
     * @param base       the base URL
286
     * @param parameters the PageParameters to append
287
     * @return the complete URL with parameters
288
     */
289
    public static String getUrlWithParameters(String base, PageParameters parameters) {
290
        try {
291
            URIBuilder u = new URIBuilder(base);
15✔
292
            for (String key : parameters.getNamedKeys()) {
33✔
293
                for (StringValue value : parameters.getValues(key)) {
36✔
294
                    if (!value.isNull()) {
9!
295
                        u.addParameter(key, value.toString());
18✔
296
                    }
297
                }
3✔
298
            }
3✔
299
            return u.build().toString();
12✔
300
        } catch (URISyntaxException ex) {
3✔
301
            logger.error("Could not build URL with parameters: {} {}", base, parameters, ex);
51✔
302
            return "/";
6✔
303
        }
304
    }
305

306
    /**
307
     * Generates a short name for a public key or public key hash.
308
     *
309
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
310
     * @return a short representation of the public key or public key hash
311
     */
312
    public static String getShortPubkeyName(String pubkeyOrPubkeyhash) {
313
        if (pubkeyOrPubkeyhash.length() == 64) {
12!
314
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
315
        } else {
316
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
15✔
317
        }
318
    }
319

320
    /**
321
     * Generates a short label for a public key or public key hash, including its status (local or approved).
322
     *
323
     * @param pubkeyOrPubkeyhash the public key (64 characters) or public key hash (40 characters)
324
     * @param user               the IRI of the user associated with the public key
325
     * @return a short label indicating the public key and its status
326
     */
327
    public static String getShortPubkeyhashLabel(String pubkeyOrPubkeyhash, IRI user) {
328
        String s = getShortPubkeyName(pubkeyOrPubkeyhash);
×
329
        NanodashSession session = NanodashSession.get();
×
330
        List<String> l = new ArrayList<>();
×
331
        if (pubkeyOrPubkeyhash.equals(session.getPubkeyString()) || pubkeyOrPubkeyhash.equals(session.getPubkeyhash())) {
×
332
            l.add("local");
×
333
        }
334
        // TODO: Make this more efficient:
335
        String hashed = Utils.createSha256HexHash(pubkeyOrPubkeyhash);
×
336
        if (User.getPubkeyhashes(user, true).contains(pubkeyOrPubkeyhash) || User.getPubkeyhashes(user, true).contains(hashed)) {
×
337
            l.add("approved");
×
338
        }
339
        if (!l.isEmpty()) {
×
340
            s += " (" + String.join("/", l) + ")";
×
341
        }
342
        return s;
×
343
    }
344

345
    /**
346
     * Retrieves the name of the public key location based on the public key.
347
     *
348
     * @param pubkeyhash the public key string
349
     * @return the name of the public key location
350
     */
351
    public static String getPubkeyLocationName(String pubkeyhash) {
352
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
353
    }
354

355
    /**
356
     * Retrieves the name of the public key location, or returns a fallback name if not found.
357
     * If the key location is localhost, it returns "localhost".
358
     *
359
     * @param pubkeyhash the public key string
360
     * @param fallback   the fallback name to return if the key location is not found
361
     * @return the name of the public key location or the fallback name
362
     */
363
    public static String getPubkeyLocationName(String pubkeyhash, String fallback) {
364
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
365
        if (keyLocation == null) {
×
366
            return fallback;
×
367
        }
368
        if (keyLocation.stringValue().equals("http://localhost:37373/")) {
×
369
            return "localhost";
×
370
        }
371
        return keyLocation.stringValue().replaceFirst("https?://(nanobench\\.)?(nanodash\\.(?=.*\\..))?(.*[^/])/?$", "$3");
×
372
    }
373

374
    /**
375
     * Generates a short label for a public key location, including its status (local or approved).
376
     *
377
     * @param pubkeyhash the public key string
378
     * @param user       the IRI of the user associated with the public key
379
     * @return a short label indicating the public key location and its status
380
     */
381
    public static String getShortPubkeyLocationLabel(String pubkeyhash, IRI user) {
382
        String s = getPubkeyLocationName(pubkeyhash);
×
383
        NanodashSession session = NanodashSession.get();
×
384
        List<String> l = new ArrayList<>();
×
385
        if (pubkeyhash.equals(session.getPubkeyhash())) {
×
386
            l.add("local");
×
387
        }
388
        // TODO: Make this more efficient:
389
        if (User.getPubkeyhashes(user, true).contains(pubkeyhash)) {
×
390
            l.add("approved");
×
391
        }
392
        if (!l.isEmpty()) {
×
393
            s += " (" + String.join("/", l) + ")";
×
394
        }
395
        return s;
×
396
    }
397

398
    /**
399
     * Checks if a given public key has a Nanodash location.
400
     * A Nanodash location is identified by specific keywords in the key location.
401
     *
402
     * @param pubkeyhash the public key to check
403
     * @return true if the public key has a Nanodash location, false otherwise
404
     */
405
    public static boolean hasNanodashLocation(String pubkeyhash) {
406
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyHash(pubkeyhash);
×
407
        if (keyLocation == null) {
×
408
            return true; // potentially a Nanodash location
×
409
        }
410
        if (keyLocation.stringValue().contains("nanodash")) {
×
411
            return true;
×
412
        }
413
        if (keyLocation.stringValue().contains("nanobench")) {
×
414
            return true;
×
415
        }
416
        if (keyLocation.stringValue().contains(":37373")) {
×
417
            return true;
×
418
        }
419
        return false;
×
420
    }
421

422
    /**
423
     * Retrieves the short ORCID ID from an IRI object.
424
     *
425
     * @param orcidIri the IRI object representing the ORCID ID
426
     * @return the short ORCID ID as a string
427
     */
428
    public static String getShortOrcidId(IRI orcidIri) {
429
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
18✔
430
    }
431

432
    /**
433
     * Retrieves the URI postfix from a given URI object.
434
     *
435
     * @param uri the URI object from which to extract the postfix
436
     * @return the URI postfix as a string
437
     */
438
    public static String getUriPostfix(Object uri) {
439
        String s = uri.toString();
9✔
440
        if (s.contains("#")) {
12✔
441
            return s.replaceFirst("^.*#(.*)$", "$1");
15✔
442
        }
443
        return s.replaceFirst("^.*/(.*)$", "$1");
15✔
444
    }
445

446
    /**
447
     * Retrieves the URI prefix from a given URI object.
448
     *
449
     * @param uri the URI object from which to extract the prefix
450
     * @return the URI prefix as a string
451
     */
452
    public static String getUriPrefix(Object uri) {
453
        String s = uri.toString();
9✔
454
        if (s.contains("#")) {
12✔
455
            return s.replaceFirst("^(.*#).*$", "$1");
15✔
456
        }
457
        return s.replaceFirst("^(.*/).*$", "$1");
15✔
458
    }
459

460
    /**
461
     * Checks if a given string is a valid URI postfix.
462
     * A valid URI postfix does not contain a colon (":").
463
     *
464
     * @param s the string to check
465
     * @return true if the string is a valid URI postfix, false otherwise
466
     */
467
    public static boolean isUriPostfix(String s) {
468
        return !s.contains(":");
24✔
469
    }
470

471
    /**
472
     * Retrieves the location of a given IntroNanopub.
473
     *
474
     * @param inp the IntroNanopub from which to extract the location
475
     * @return the IRI location of the nanopublication, or null if not found
476
     */
477
    public static IRI getLocation(IntroNanopub inp) {
478
        NanopubSignatureElement el = getNanopubSignatureElement(inp);
×
479
        for (KeyDeclaration kd : inp.getKeyDeclarations()) {
×
480
            if (el.getPublicKeyString().equals(kd.getPublicKeyString())) {
×
481
                return kd.getKeyLocation();
×
482
            }
483
        }
×
484
        return null;
×
485
    }
486

487
    /**
488
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
489
     *
490
     * @param inp the IntroNanopub from which to extract the signature element
491
     * @return the NanopubSignatureElement associated with the nanopublication
492
     */
493
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
494
        try {
495
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
496
        } catch (MalformedCryptoElementException ex) {
×
497
            throw new RuntimeException(ex);
×
498
        }
499
    }
500

501
    /**
502
     * Retrieves a Nanopub object from a given URI if it is a potential Trusty URI.
503
     *
504
     * @param uri the URI to check and retrieve the Nanopub from
505
     * @return the Nanopub object if found, or null if not a known nanopublication
506
     */
507
    public static Nanopub getAsNanopub(String uri) {
508
        if (uri == null) {
6!
509
            return null;
×
510
        }
511
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
9!
512
            try {
513
                return Utils.getNanopub(uri);
9✔
514
            } catch (Exception ex) {
×
515
                logger.error("The given URI is not a known nanopublication: {}", uri, ex);
×
516
            }
517
        }
518
        return null;
×
519
    }
520

521
    private static final PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder().allowCommonBlockElements().allowCommonInlineFormattingElements().allowUrlProtocols("https", "http", "mailto").allowElements("a").allowAttributes("href").onElements("a").allowElements("img").allowAttributes("src").onElements("img").allowElements("pre").requireRelNofollowOnLinks().toFactory();
216✔
522

523
    /**
524
     * Sanitizes raw HTML input to ensure safe rendering.
525
     *
526
     * @param rawHtml the raw HTML input to sanitize
527
     * @return sanitized HTML string
528
     */
529
    public static String sanitizeHtml(String rawHtml) {
530
        return htmlSanitizePolicy.sanitize(rawHtml);
12✔
531
    }
532

533
    /**
534
     * Checks if a given string is likely to be HTML content.
535
     *
536
     * @param value the string to check
537
     * @return true if the given string is HTML content, false otherwise
538
     */
539
    public static boolean looksLikeHtml(String value) {
540
        return LEADING_TAG.matcher(value).find();
15✔
541
    }
542

543
    public static boolean isDate(String value) {
544
        return isDateLiteral(value) || isDateTimeLiteral(value);
30✔
545
    }
546

547
    public static boolean isDateLiteral(String value) {
548
        if (value == null || value.isBlank() || value.contains("T")) {
27✔
549
            return false;
6✔
550
        }
551
        try {
552
            DateTimeFormatter.ISO_DATE.parse(value);
12✔
553
            return true;
6✔
554
        } catch (DateTimeParseException ex) {
3✔
555
            return false;
6✔
556
        }
557
    }
558

559
    /**
560
     * Checks whether a (raw query-result) string looks like an ISO-8601 date-time literal.
561
     *
562
     * @param value the string to check
563
     * @return true if the string parses as a xsd:dateTime-style value
564
     */
565
    public static boolean isDateTimeLiteral(String value) {
566
        if (value == null || value.isBlank()) {
15✔
567
            return false;
6✔
568
        }
569

570
        try {
571
            OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
12✔
572
            return true;
6✔
573
        } catch (DateTimeParseException ignored) {
3✔
574
        }
575

576
        try {
577
            LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
12✔
578
            return true;
6✔
579
        } catch (DateTimeParseException ignored) {
3✔
580
            return false;
6✔
581
        }
582
    }
583

584
    /**
585
     * Renders a {@code <time>} element for an ISO-8601 date-time value. The machine-readable
586
     * value goes in the {@code datetime} attribute; client-side script (nanodash.js) rewrites
587
     * the visible text to a relative form ("10 minutes ago") in the viewer's local timezone and
588
     * puts the absolute date-time in the tooltip. If script does not run, {@code fallbackText}
589
     * remains visible.
590
     *
591
     * @param isoValue     the ISO-8601 date-time string (machine-readable)
592
     * @param fallbackText the human-readable text shown when script is unavailable
593
     * @return an HTML {@code <time>} element string (caller must render with escaping disabled)
594
     */
595
    public static String friendlyDateHtml(String isoValue, String fallbackText) {
596
        return "<time class=\"friendly-date\" datetime=\"" + Strings.escapeMarkup(isoValue) + "\">" + Strings.escapeMarkup(fallbackText) + "</time>";
×
597
    }
598

599
    /**
600
     * Converts PageParameters to a URL-encoded string representation.
601
     *
602
     * @param params the PageParameters to convert
603
     * @return a string representation of the parameters in URL-encoded format
604
     */
605
    public static String getPageParametersAsString(PageParameters params) {
606
        String s = "";
6✔
607
        for (String n : params.getNamedKeys()) {
33✔
608
            if (!s.isEmpty()) {
9✔
609
                s += "&";
9✔
610
            }
611
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
30✔
612
        }
3✔
613
        return s;
6✔
614
    }
615

616
    /**
617
     * Sets a minimal escape markup function for a Select2Choice component.
618
     * This function replaces certain characters and formats the display of choices.
619
     *
620
     * @param selectItem the Select2Choice component to set the escape markup for
621
     */
622
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
623
        selectItem.getSettings().setEscapeMarkup("function(markup) {" + "return markup" + ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" + ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" + ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" + ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" + ";}");
15✔
624
    }
3✔
625

626
    /**
627
     * Checks if a nanopublication is of a specific class.
628
     *
629
     * @param np       the nanopublication to check
630
     * @param classIri the IRI of the class to check against
631
     * @return true if the nanopublication is of the specified class, false otherwise
632
     */
633
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
634
        return NanopubUtils.getTypes(np).contains(classIri);
15✔
635
    }
636

637
    /**
638
     * Checks if a nanopublication uses a specific predicate in its assertion.
639
     *
640
     * @param np           the nanopublication to check
641
     * @param predicateIri the IRI of the predicate to look for
642
     * @return true if the predicate is used in the assertion, false otherwise
643
     */
644
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
645
        for (Statement st : np.getAssertion()) {
33✔
646
            if (predicateIri.equals(st.getPredicate())) {
15✔
647
                return true;
6✔
648
            }
649
        }
3✔
650
        return false;
6✔
651
    }
652

653
    /**
654
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
655
     *
656
     * @param np the nanopublication from which to extract FOAF names
657
     * @return a map where keys are subjects and values are FOAF names
658
     */
659
    public static Map<String, String> getFoafNameMap(Nanopub np) {
660
        Map<String, String> foafNameMap = new HashMap<>();
12✔
661
        for (Statement st : np.getPubinfo()) {
33✔
662
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
42✔
663
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
24✔
664
            }
665
        }
3✔
666
        return foafNameMap;
6✔
667
    }
668

669
    /**
670
     * Creates an SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
671
     *
672
     * @param obj the object to hash
673
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
674
     */
675
    public static String createSha256HexHash(Object obj) {
676
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
21✔
677
    }
678

679
    /**
680
     * Gets the types of a nanopublication.
681
     *
682
     * @param np the nanopublication from which to extract types
683
     * @return a list of IRI types associated with the nanopublication
684
     */
685
    public static List<IRI> getTypes(Nanopub np) {
686
        List<IRI> l = new ArrayList<>();
12✔
687
        for (IRI t : NanopubUtils.getTypes(np)) {
33✔
688
            if (t.equals(FIP.AVAILABLE_FAIR_ENABLING_RESOURCE)) {
12✔
689
                continue;
3✔
690
            }
691
            if (t.equals(FIP.FAIR_ENABLING_RESOURCE_TO_BE_DEVELOPED)) {
12✔
692
                continue;
3✔
693
            }
694
            if (t.equals(FIP.AVAILABLE_FAIR_SUPPORTING_RESOURCE)) {
12!
695
                continue;
×
696
            }
697
            if (t.equals(FIP.FAIR_SUPPORTING_RESOURCE_TO_BE_DEVELOPED)) {
12!
698
                continue;
×
699
            }
700
            l.add(t);
12✔
701
        }
3✔
702
        return l;
6✔
703
    }
704

705
    /**
706
     * Gets a label for a type IRI.
707
     *
708
     * @param typeIri the IRI of the type
709
     * @return a label for the type, potentially truncated
710
     */
711
    public static String getTypeLabel(IRI typeIri) {
712
        if (typeIri.equals(FIP.FAIR_ENABLING_RESOURCE)) {
12✔
713
            return "FER";
6✔
714
        }
715
        if (typeIri.equals(FIP.FAIR_SUPPORTING_RESOURCE)) {
12✔
716
            return "FSR";
6✔
717
        }
718
        if (typeIri.equals(FIP.FAIR_IMPLEMENTATION_PROFILE)) {
12✔
719
            return "FIP";
6✔
720
        }
721
        if (typeIri.equals(NPX.DECLARED_BY)) {
12✔
722
            return "user intro";
6✔
723
        }
724
        String l = typeIri.stringValue();
9✔
725
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
15✔
726
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
15✔
727
        if (l.length() > 25) {
12✔
728
            l = l.substring(0, 20) + "...";
18✔
729
        }
730
        return l;
6✔
731
    }
732

733
    /**
734
     * Gets a label for a URI.
735
     *
736
     * @param uri the URI to get the label from
737
     * @return a label for the URI, potentially truncated
738
     */
739
    public static String getUriLabel(String uri) {
740
        if (uri == null) {
6✔
741
            return "";
6✔
742
        }
743
        String uriLabel = uri;
6✔
744
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
12✔
745
            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✔
746
            if (newUriLabel.length() <= 70) {
12!
747
                return newUriLabel;
6✔
748
            }
749
        }
750
        if (uriLabel.length() > 70) {
12✔
751
            return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
36✔
752
        }
753
        return uriLabel;
6✔
754
    }
755

756
    /**
757
     * Gets an ExternalLink with a URI label.
758
     *
759
     * @param markupId the markup ID for the link
760
     * @param uri      the URI to link to
761
     * @return an ExternalLink with the URI label
762
     */
763
    public static ExternalLink getUriLink(String markupId, String uri) {
764
        return new ExternalLink(markupId, (Utils.isLocalURI(uri) ? "" : uri), getUriLabel(uri));
39✔
765
    }
766

767
    /**
768
     * Gets an ExternalLink with a model for the URI label.
769
     *
770
     * @param markupId the markup ID for the link
771
     * @param model    the model containing the URI
772
     * @return an ExternalLink with the URI label
773
     */
774
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
775
        return new ExternalLink(markupId, model, new UriLabelModel(model));
30✔
776
    }
777

778
    private static class UriLabelModel implements IModel<String> {
779

780
        private IModel<String> uriModel;
781

782
        public UriLabelModel(IModel<String> uriModel) {
6✔
783
            this.uriModel = uriModel;
9✔
784
        }
3✔
785

786
        @Override
787
        public String getObject() {
788
            return getUriLabel(uriModel.getObject());
18✔
789
        }
790

791
    }
792

793
    /**
794
     * Creates a sublist from a list based on the specified indices.
795
     *
796
     * @param list      the list from which to create the sublist
797
     * @param fromIndex the starting index (inclusive) for the sublist
798
     * @param toIndex   the ending index (exclusive) for the sublist
799
     * @param <E>       the type of elements in the list
800
     * @return an ArrayList containing the elements from the specified range
801
     */
802
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
803
        // So the resulting list is serializable:
804
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
×
805
    }
806

807
    /**
808
     * Creates a sublist from an array based on the specified indices.
809
     *
810
     * @param array     the array from which to create the sublist
811
     * @param fromIndex the starting index (inclusive) for the sublist
812
     * @param toIndex   the ending index (exclusive) for the sublist
813
     * @param <E>       the type of elements in the array
814
     * @return an ArrayList containing the elements from the specified range
815
     */
816
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
817
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
818
    }
819

820
    /**
821
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
822
     */
823
    // TODO Move this to ApiResponseEntry class?
824
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
825

826
        private String field;
827
        private boolean descending;
828

829
        /**
830
         * Constructor for ApiResponseEntrySorter.
831
         *
832
         * @param field      the field to sort by
833
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
834
         */
835
        public ApiResponseEntrySorter(String field, boolean descending) {
×
836
            this.field = field;
×
837
            this.descending = descending;
×
838
        }
×
839

840
        /**
841
         * Compares two ApiResponseEntry objects based on the specified field.
842
         *
843
         * @param o1 the first object to be compared.
844
         * @param o2 the second object to be compared.
845
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
846
         */
847
        @Override
848
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
849
            if (descending) {
×
850
                return o2.get(field).compareTo(o1.get(field));
×
851
            } else {
852
                return o1.get(field).compareTo(o2.get(field));
×
853
            }
854
        }
855

856
    }
857

858
    /**
859
     * MIME type for TriG RDF format.
860
     */
861
    public static final String TYPE_TRIG = "application/trig";
862

863
    /**
864
     * MIME type for Jelly RDF format.
865
     */
866
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
867

868
    /**
869
     * MIME type for JSON-LD format.
870
     */
871
    public static final String TYPE_JSONLD = "application/ld+json";
872

873
    /**
874
     * MIME type for N-Quads format.
875
     */
876
    public static final String TYPE_NQUADS = "application/n-quads";
877

878
    /**
879
     * MIME type for Trix format.
880
     */
881
    public static final String TYPE_TRIX = "application/trix";
882

883
    /**
884
     * MIME type for HTML format.
885
     */
886
    public static final String TYPE_HTML = "text/html";
887

888
    /**
889
     * Comma-separated list of supported MIME types for nanopublications.
890
     */
891
    public static final String SUPPORTED_TYPES = TYPE_TRIG + "," + TYPE_JELLY + "," + TYPE_JSONLD + "," + TYPE_NQUADS + "," + TYPE_TRIX + "," + TYPE_HTML;
892

893
    /**
894
     * List of supported MIME types for nanopublications.
895
     */
896
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
18✔
897

898
    private static volatile String resolvedMainRegistryUrl;
899
    private static volatile String resolvedMainQueryUrl;
900

901
    /**
902
     * Eagerly resolves the main registry and query URLs. Call at application startup
903
     * so the (potentially slow) first-time discovery does not happen during a user request.
904
     */
905
    public static void initMainUrls() {
906
        getMainRegistryUrl();
6✔
907
        getMainQueryUrl();
6✔
908
    }
3✔
909

910
    /**
911
     * Returns the URL of the main Nanopub Registry for this nanodash instance.
912
     * <p>
913
     * If {@code NANODASH_MAIN_REGISTRY} is set and matches an entry in the library's
914
     * discovered registry instance list, that URL is used. Otherwise the first entry
915
     * of the library list is used. If the library list is empty, the env var value
916
     * (or built-in default) is used unvalidated. The result is cached for the JVM lifetime.
917
     *
918
     * @return Nanopub Registry URL (with trailing slash)
919
     */
920
    public static String getMainRegistryUrl() {
921
        if (resolvedMainRegistryUrl == null) {
6✔
922
            synchronized (Utils.class) {
12✔
923
                if (resolvedMainRegistryUrl == null) {
6!
924
                    resolvedMainRegistryUrl = resolveMainRegistryUrl();
6✔
925
                }
926
            }
9✔
927
        }
928
        return resolvedMainRegistryUrl;
6✔
929
    }
930

931
    /**
932
     * Returns the URL of the main Nanopub Query API for this nanodash instance.
933
     * <p>
934
     * If {@code NANODASH_MAIN_QUERY} is set and matches an entry in the library's
935
     * discovered query instance list, that URL is used. Otherwise the first entry
936
     * of the library list is used. If the library list is empty, the env var value
937
     * (or built-in default) is used unvalidated. The result is cached for the JVM lifetime.
938
     *
939
     * @return Nanopub Query URL (with trailing slash)
940
     */
941
    public static String getMainQueryUrl() {
942
        if (resolvedMainQueryUrl == null) {
6✔
943
            synchronized (Utils.class) {
12✔
944
                if (resolvedMainQueryUrl == null) {
6!
945
                    resolvedMainQueryUrl = resolveMainQueryUrl();
6✔
946
                }
947
            }
9✔
948
        }
949
        return resolvedMainQueryUrl;
6✔
950
    }
951

952
    private static String resolveMainRegistryUrl() {
953
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_REGISTRY"));
12✔
954
        List<String> instances;
955
        try {
956
            instances = NanopubServerUtils.getRegistryServerList();
6✔
957
        } catch (Exception ex) {
×
958
            logger.warn("Could not retrieve registry instance list from nanopub library: {}", ex.toString());
×
959
            instances = Collections.emptyList();
×
960
        }
3✔
961
        return resolveMainUrl("NANODASH_MAIN_REGISTRY", envValue, instances, DEFAULT_MAIN_REGISTRY_URL);
18✔
962
    }
963

964
    private static String resolveMainQueryUrl() {
965
        String envValue = trimToNull(System.getenv("NANODASH_MAIN_QUERY"));
12✔
966
        List<String> instances;
967
        try {
968
            instances = QueryCall.getApiInstances();
6✔
969
        } catch (NotEnoughAPIInstancesException ex) {
×
970
            logger.warn("Nanopub library reports not enough query API instances available: {}", ex.toString());
×
971
            instances = Collections.emptyList();
×
972
        } catch (Exception ex) {
×
973
            logger.warn("Could not retrieve query instance list from nanopub library: {}", ex.toString());
×
974
            instances = Collections.emptyList();
×
975
        }
3✔
976
        return resolveMainUrl("NANODASH_MAIN_QUERY", envValue, instances, DEFAULT_MAIN_QUERY_URL);
18✔
977
    }
978

979
    private static String resolveMainUrl(String envVarName, String envValue, List<String> instances, String builtInDefault) {
980
        if (envValue != null) {
6!
981
            if (containsNormalized(instances, envValue)) {
×
982
                logger.info("Using main URL from {} (validated against library instance list): {}", envVarName, envValue);
×
983
                return ensureTrailingSlash(envValue);
×
984
            }
985
            if (instances.isEmpty()) {
×
986
                logger.warn("Library instance list is empty; using {} unvalidated: {}", envVarName, envValue);
×
987
                return ensureTrailingSlash(envValue);
×
988
            }
989
            logger.warn("{}={} is not in the library instance list {}; falling back to first library instance", envVarName, envValue, instances);
×
990
            return ensureTrailingSlash(instances.get(0));
×
991
        }
992
        if (!instances.isEmpty()) {
9!
993
            String first = instances.get(0);
15✔
994
            logger.info("{} not set; using first library instance: {}", envVarName, first);
15✔
995
            return ensureTrailingSlash(first);
9✔
996
        }
997
        logger.warn("{} not set and library instance list is empty; using built-in default: {}", envVarName, builtInDefault);
×
998
        return builtInDefault;
×
999
    }
1000

1001
    private static boolean containsNormalized(List<String> urls, String target) {
1002
        String normTarget = normalizeUrl(target);
×
1003
        for (String url : urls) {
×
1004
            if (normalizeUrl(url).equals(normTarget)) {
×
1005
                return true;
×
1006
            }
1007
        }
×
1008
        return false;
×
1009
    }
1010

1011
    private static String normalizeUrl(String url) {
1012
        if (url == null) {
×
1013
            return "";
×
1014
        }
1015
        return url.trim().replaceFirst("/+$", "").toLowerCase(Locale.ROOT);
×
1016
    }
1017

1018
    private static String ensureTrailingSlash(String url) {
1019
        return url.endsWith("/") ? url : url + "/";
21!
1020
    }
1021

1022
    private static String trimToNull(String s) {
1023
        if (s == null) {
6!
1024
            return null;
6✔
1025
        }
1026
        s = s.trim();
×
1027
        return s.isEmpty() ? null : s;
×
1028
    }
1029

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

1034
    /**
1035
     * Checks whether string is valid literal serialization.
1036
     *
1037
     * @param literalString the literal string
1038
     * @return true if valid
1039
     */
1040
    public static boolean isValidLiteralSerialization(String literalString) {
1041
        if (literalString.matches(PLAIN_LITERAL_PATTERN)) {
12✔
1042
            return true;
6✔
1043
        } else if (literalString.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
1044
            return true;
6✔
1045
        } else if (literalString.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
1046
            return true;
6✔
1047
        }
1048
        return false;
6✔
1049
    }
1050

1051
    /**
1052
     * Returns a serialized version of the literal.
1053
     *
1054
     * @param literal the literal
1055
     * @return the String serialization of the literal
1056
     */
1057
    public static String getSerializedLiteral(Literal literal) {
1058
        if (literal.getLanguage().isPresent()) {
12✔
1059
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"@" + Literals.normalizeLanguageTag(literal.getLanguage().get());
30✔
1060
        } else if (literal.getDatatype().equals(XSD.STRING)) {
15✔
1061
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"";
15✔
1062
        } else {
1063
            return "\"" + getEscapedLiteralString(literal.stringValue()) + "\"^^<" + literal.getDatatype() + ">";
24✔
1064
        }
1065
    }
1066

1067
    /**
1068
     * Parses a serialized literal into a Literal object.
1069
     *
1070
     * @param serializedLiteral The serialized String of the literal
1071
     * @return The parse Literal object
1072
     */
1073
    public static Literal getParsedLiteral(String serializedLiteral) {
1074
        if (serializedLiteral.matches(PLAIN_LITERAL_PATTERN)) {
12✔
1075
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(PLAIN_LITERAL_PATTERN, "$1")));
24✔
1076
        } else if (serializedLiteral.matches(LANGTAG_LITERAL_PATTERN)) {
12✔
1077
            String langtag = serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$3");
15✔
1078
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(LANGTAG_LITERAL_PATTERN, "$1")), langtag);
27✔
1079
        } else if (serializedLiteral.matches(DATATYPE_LITERAL_PATTERN)) {
12✔
1080
            IRI datatype = vf.createIRI(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$3"));
21✔
1081
            return vf.createLiteral(getUnescapedLiteralString(serializedLiteral.replaceFirst(DATATYPE_LITERAL_PATTERN, "$1")), datatype);
27✔
1082
        }
1083
        throw new IllegalArgumentException("Not a valid literal serialization: " + serializedLiteral);
18✔
1084
    }
1085

1086
    /**
1087
     * Escapes quotes (") and slashes (/) of a literal string.
1088
     *
1089
     * @param unescapedString un-escaped string
1090
     * @return escaped string
1091
     */
1092
    public static String getEscapedLiteralString(String unescapedString) {
1093
        return unescapedString.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"");
24✔
1094
    }
1095

1096
    /**
1097
     * Un-escapes quotes (") and slashes (/) of a literal string.
1098
     *
1099
     * @param escapedString escaped string
1100
     * @return un-escaped string
1101
     */
1102
    public static String getUnescapedLiteralString(String escapedString) {
1103
        return escapedString.replaceAll("\\\\(\\\\|\\\")", "$1");
15✔
1104
    }
1105

1106
    /**
1107
     * Checks if a given IRI is a local URI.
1108
     *
1109
     * @param uri the IRI to check
1110
     * @return true if the IRI is a local URI, false otherwise
1111
     */
1112
    public static boolean isLocalURI(IRI uri) {
1113
        return uri != null && isLocalURI(uri.stringValue());
30✔
1114
    }
1115

1116
    /**
1117
     * Checks if a given string is a local URI.
1118
     *
1119
     * @param uriAsString the string to check
1120
     * @return true if the string is a local URI, false otherwise
1121
     */
1122
    public static boolean isLocalURI(String uriAsString) {
1123
        return !uriAsString.isBlank() && uriAsString.startsWith(LocalUri.PREFIX);
33✔
1124
    }
1125

1126
    public static String unescapeMultiValue(String s) {
1127
        StringBuilder sb = new StringBuilder();
12✔
1128
        for (int i = 0; i < s.length(); i++) {
24✔
1129
            if (s.charAt(i) == '\\' && i + 1 < s.length()) {
33✔
1130
                char next = s.charAt(i + 1);
18✔
1131
                if (next == 'n') {
9✔
1132
                    sb.append('\n');
15✔
1133
                } else if (next == '\\') {
9!
1134
                    sb.append('\\');
15✔
1135
                } else {
1136
                    sb.append(next);
×
1137
                }
1138
                i++;
3✔
1139
            } else {
3✔
1140
                sb.append(s.charAt(i));
18✔
1141
            }
1142
        }
1143
        return sb.toString();
9✔
1144
    }
1145

1146
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc