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

knowledgepixels / nanodash / 17153434891

22 Aug 2025 10:57AM UTC coverage: 12.446% (+0.004%) from 12.442%
17153434891

push

github

tkuhn
Add environment variable for main Nanopub Registry instance

330 of 3766 branches covered (8.76%)

Branch coverage included in aggregate %.

978 of 6743 relevant lines covered (14.5%)

0.64 hits per line

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

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

3
import com.google.common.hash.Hashing;
4
import net.trustyuri.TrustyUriUtils;
5
import org.apache.commons.codec.Charsets;
6
import org.apache.commons.exec.environment.EnvironmentUtils;
7
import org.apache.commons.lang.StringUtils;
8
import org.apache.http.client.utils.URIBuilder;
9
import org.apache.wicket.markup.html.link.ExternalLink;
10
import org.apache.wicket.model.IModel;
11
import org.apache.wicket.request.mapper.parameter.PageParameters;
12
import org.apache.wicket.util.string.StringValue;
13
import org.eclipse.rdf4j.model.IRI;
14
import org.eclipse.rdf4j.model.Literal;
15
import org.eclipse.rdf4j.model.Statement;
16
import org.eclipse.rdf4j.model.ValueFactory;
17
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
18
import org.eclipse.rdf4j.model.vocabulary.FOAF;
19
import org.nanopub.Nanopub;
20
import org.nanopub.NanopubUtils;
21
import org.nanopub.extra.security.KeyDeclaration;
22
import org.nanopub.extra.security.MalformedCryptoElementException;
23
import org.nanopub.extra.security.NanopubSignatureElement;
24
import org.nanopub.extra.security.SignatureUtils;
25
import org.nanopub.extra.server.GetNanopub;
26
import org.nanopub.extra.services.ApiResponseEntry;
27
import org.nanopub.extra.setting.IntroNanopub;
28
import org.owasp.html.HtmlPolicyBuilder;
29
import org.owasp.html.PolicyFactory;
30
import org.wicketstuff.select2.Select2Choice;
31

32
import java.io.IOException;
33
import java.io.Serializable;
34
import java.net.URISyntaxException;
35
import java.net.URLDecoder;
36
import java.net.URLEncoder;
37
import java.nio.charset.StandardCharsets;
38
import java.util.*;
39

40
/**
41
 * Utility class providing various helper methods for handling nanopublications, URIs, and other related functionalities.
42
 */
43
public class Utils {
44

45
    private Utils() {
46
    }  // no instances allowed
47

48
    public static final ValueFactory vf = SimpleValueFactory.getInstance();
2✔
49

50
    // TODO Merge with IriItem.getShortNameFromURI
51
    public static String getShortNameFromURI(IRI uri) {
52
        return getShortNameFromURI(uri.stringValue());
4✔
53
    }
54

55
    public static String getShortNameFromURI(String u) {
56
        u = u.replaceFirst("\\?.*$", "");
5✔
57
        u = u.replaceFirst("[/#]$", "");
5✔
58
        u = u.replaceFirst("^.*[/#]([^/#]*)[/#]([0-9]+)$", "$1/$2");
5✔
59
        u = u.replaceFirst("^.*[/#]([^/#]*[^0-9][^/#]*)$", "$1");
5✔
60
        u = u.replaceFirst("((^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{8})[A-Za-z0-9\\-_]{35}$", "$1");
5✔
61
        u = u.replaceFirst("(^|[^A-Za-z0-9\\-_])RA[A-Za-z0-9\\-_]{43}[^A-Za-z0-9\\-_](.+)$", "$2");
5✔
62
        return u;
2✔
63
    }
64

65
    public static String getShortNanopubId(Object npId) {
66
        return TrustyUriUtils.getArtifactCode(npId.toString()).substring(0, 10);
7✔
67
    }
68

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

71
    public static Nanopub getNanopub(String uriOrArtifactCode) {
72
        String artifactCode = getArtifactCode(uriOrArtifactCode);
3✔
73
        if (!nanopubs.containsKey(artifactCode)) {
4✔
74
            for (int i = 0; i < 3; i++) {  // Try 3 times to get nanopub
5!
75
                Nanopub np = GetNanopub.get(artifactCode);
3✔
76
                if (np != null) {
2!
77
                    nanopubs.put(artifactCode, np);
5✔
78
                    break;
1✔
79
                }
80
            }
81
        }
82
        return nanopubs.get(artifactCode);
5✔
83
    }
84

85
    public static String getArtifactCode(String uriOrArtifactCode) {
86
        return uriOrArtifactCode.replaceFirst("^.*(RA[0-9a-zA-Z\\-_]{43})(\\?.*)?$", "$1");
5✔
87
    }
88

89
    public static String urlEncode(Object o) {
90
        return URLEncoder.encode((o == null ? "" : o.toString()), Charsets.UTF_8);
9✔
91
    }
92

93
    public static String urlDecode(Object o) {
94
        return URLDecoder.decode((o == null ? "" : o.toString()), Charsets.UTF_8);
9✔
95
    }
96

97
    public static String getUrlWithParameters(String base, PageParameters parameters) {
98
        try {
99
            URIBuilder u = new URIBuilder(base);
5✔
100
            for (String key : parameters.getNamedKeys()) {
11✔
101
                for (StringValue value : parameters.getValues(key)) {
12✔
102
                    if (!value.isNull()) u.addParameter(key, value.toString());
9!
103
                }
1✔
104
            }
1✔
105
            return u.build().toString();
4✔
106
        } catch (URISyntaxException ex) {
1✔
107
            ex.printStackTrace();
2✔
108
            return "/";
2✔
109
        }
110
    }
111

112
    public static String getShortPubkeyName(String pubkeyOrPubkeyhash) {
113
        if (pubkeyOrPubkeyhash.length() == 64) {
4!
114
            return pubkeyOrPubkeyhash.replaceFirst("^(.{8}).*$", "$1");
×
115
        } else {
116
            return pubkeyOrPubkeyhash.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
5✔
117
        }
118
    }
119

120
    public static String getShortPubkeyhashLabel(String pubkeyOrPubkeyhash, IRI user) {
121
        String s = getShortPubkeyName(pubkeyOrPubkeyhash);
×
122
        NanodashSession session = NanodashSession.get();
×
123
        List<String> l = new ArrayList<>();
×
124
        if (pubkeyOrPubkeyhash.equals(session.getPubkeyString()) || pubkeyOrPubkeyhash.equals(session.getPubkeyhash()))
×
125
            l.add("local");
×
126
        // TODO: Make this more efficient:
127
        String hashed = Utils.createSha256HexHash(pubkeyOrPubkeyhash);
×
128
        if (User.getPubkeyhashes(user, true).contains(pubkeyOrPubkeyhash) || User.getPubkeyhashes(user, true).contains(hashed))
×
129
            l.add("approved");
×
130
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
131
        return s;
×
132
    }
133

134
    /**
135
     * Retrieves the name of the public key location based on the public key.
136
     *
137
     * @param pubkeyhash the public key string
138
     * @return the name of the public key location
139
     */
140
    public static String getPubkeyLocationName(String pubkeyhash) {
141
        return getPubkeyLocationName(pubkeyhash, getShortPubkeyName(pubkeyhash));
×
142
    }
143

144
    /**
145
     * Retrieves the name of the public key location, or returns a fallback name if not found.
146
     * If the key location is localhost, it returns "localhost".
147
     *
148
     * @param pubkeyhash the public key string
149
     * @param fallback   the fallback name to return if the key location is not found
150
     * @return the name of the public key location or the fallback name
151
     */
152
    public static String getPubkeyLocationName(String pubkeyhash, String fallback) {
153
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyhash(pubkeyhash);
×
154
        if (keyLocation == null) return fallback;
×
155
        if (keyLocation.stringValue().equals("http://localhost:37373/")) return "localhost";
×
156
        return keyLocation.stringValue().replaceFirst("https?://(nanobench\\.)?(nanodash\\.)?(.*[^/])/?$", "$3");
×
157
    }
158

159
    /**
160
     * Generates a short label for a public key location, including its status (local or approved).
161
     *
162
     * @param pubkeyhash the public key string
163
     * @param user       the IRI of the user associated with the public key
164
     * @return a short label indicating the public key location and its status
165
     */
166
    public static String getShortPubkeyLocationLabel(String pubkeyhash, IRI user) {
167
        String s = getPubkeyLocationName(pubkeyhash);
×
168
        NanodashSession session = NanodashSession.get();
×
169
        List<String> l = new ArrayList<>();
×
170
        if (pubkeyhash.equals(session.getPubkeyhash())) l.add("local");
×
171
        // TODO: Make this more efficient:
172
        if (User.getPubkeyhashes(user, true).contains(pubkeyhash)) l.add("approved");
×
173
        if (!l.isEmpty()) s += " (" + String.join("/", l) + ")";
×
174
        return s;
×
175
    }
176

177
    /**
178
     * Checks if a given public key has a Nanodash location.
179
     * A Nanodash location is identified by specific keywords in the key location.
180
     *
181
     * @param pubkeyhash the public key to check
182
     * @return true if the public key has a Nanodash location, false otherwise
183
     */
184
    public static boolean hasNanodashLocation(String pubkeyhash) {
185
        IRI keyLocation = User.getUserData().getKeyLocationForPubkeyhash(pubkeyhash);
×
186
        if (keyLocation == null) return true; // potentially a Nanodash location
×
187
        if (keyLocation.stringValue().contains("nanodash")) return true;
×
188
        if (keyLocation.stringValue().contains("nanobench")) return true;
×
189
        if (keyLocation.stringValue().contains(":37373")) return true;
×
190
        return false;
×
191
    }
192

193
    /**
194
     * Retrieves the short ORCID ID from an IRI object.
195
     *
196
     * @param orcidIri the IRI object representing the ORCID ID
197
     * @return the short ORCID ID as a string
198
     */
199
    public static String getShortOrcidId(IRI orcidIri) {
200
        return orcidIri.stringValue().replaceFirst("^https://orcid.org/", "");
6✔
201
    }
202

203
    /**
204
     * Retrieves the URI postfix from a given URI object.
205
     *
206
     * @param uri the URI object from which to extract the postfix
207
     * @return the URI postfix as a string
208
     */
209
    public static String getUriPostfix(Object uri) {
210
        String s = uri.toString();
3✔
211
        if (s.contains("#")) return s.replaceFirst("^.*#(.*)$", "$1");
4!
212
        return s.replaceFirst("^.*/(.*)$", "$1");
5✔
213
    }
214

215
    /**
216
     * Retrieves the URI prefix from a given URI object.
217
     *
218
     * @param uri the URI object from which to extract the prefix
219
     * @return the URI prefix as a string
220
     */
221
    public static String getUriPrefix(Object uri) {
222
        String s = uri.toString();
3✔
223
        if (s.contains("#")) return s.replaceFirst("^(.*#).*$", "$1");
4!
224
        return s.replaceFirst("^(.*/).*$", "$1");
5✔
225
    }
226

227
    /**
228
     * Checks if a given string is a valid URI postfix.
229
     * A valid URI postfix does not contain a colon (":").
230
     *
231
     * @param s the string to check
232
     * @return true if the string is a valid URI postfix, false otherwise
233
     */
234
    public static boolean isUriPostfix(String s) {
235
        return !s.contains(":");
8✔
236
    }
237

238
    /**
239
     * Retrieves the location of a given IntroNanopub.
240
     *
241
     * @param inp the IntroNanopub from which to extract the location
242
     * @return the IRI location of the nanopublication, or null if not found
243
     */
244
    public static IRI getLocation(IntroNanopub inp) {
245
        NanopubSignatureElement el = getNanopubSignatureElement(inp);
×
246
        for (KeyDeclaration kd : inp.getKeyDeclarations()) {
×
247
            if (el.getPublicKeyString().equals(kd.getPublicKeyString())) {
×
248
                return kd.getKeyLocation();
×
249
            }
250
        }
×
251
        return null;
×
252
    }
253

254
    /**
255
     * Retrieves the NanopubSignatureElement from a given IntroNanopub.
256
     *
257
     * @param inp the IntroNanopub from which to extract the signature element
258
     * @return the NanopubSignatureElement associated with the nanopublication
259
     */
260
    public static NanopubSignatureElement getNanopubSignatureElement(IntroNanopub inp) {
261
        try {
262
            return SignatureUtils.getSignatureElement(inp.getNanopub());
×
263
        } catch (MalformedCryptoElementException ex) {
×
264
            throw new RuntimeException(ex);
×
265
        }
266
    }
267

268
    /**
269
     * Retrieves a Nanopub object from a given URI if it is a potential Trusty URI.
270
     *
271
     * @param uri the URI to check and retrieve the Nanopub from
272
     * @return the Nanopub object if found, or null if not a known nanopublication
273
     */
274
    public static Nanopub getAsNanopub(String uri) {
275
        if (TrustyUriUtils.isPotentialTrustyUri(uri)) {
×
276
            try {
277
                return Utils.getNanopub(uri);
×
278
            } catch (Exception ex) {
×
279
                // wasn't a known nanopublication
280
            }
281
        }
282
        return null;
×
283
    }
284

285
    private static PolicyFactory htmlSanitizePolicy = new HtmlPolicyBuilder()
3✔
286
            .allowCommonBlockElements()
1✔
287
            .allowCommonInlineFormattingElements()
15✔
288
            .allowUrlProtocols("https", "http", "mailto")
7✔
289
            .allowElements("a")
7✔
290
            .allowAttributes("href").onElements("a")
14✔
291
            .allowElements("img")
7✔
292
            .allowAttributes("src").onElements("img")
8✔
293
            .requireRelNofollowOnLinks()
1✔
294
            .toFactory();
2✔
295

296
    /**
297
     * Sanitizes raw HTML input to ensure safe rendering.
298
     *
299
     * @param rawHtml the raw HTML input to sanitize
300
     * @return sanitized HTML string
301
     */
302
    public static String sanitizeHtml(String rawHtml) {
303
        return htmlSanitizePolicy.sanitize(rawHtml);
4✔
304
    }
305

306
    /**
307
     * Converts PageParameters to a URL-encoded string representation.
308
     *
309
     * @param params the PageParameters to convert
310
     * @return a string representation of the parameters in URL-encoded format
311
     */
312
    public static String getPageParametersAsString(PageParameters params) {
313
        String s = "";
2✔
314
        for (String n : params.getNamedKeys()) {
11✔
315
            if (!s.isEmpty()) s += "&";
6✔
316
            s += n + "=" + URLEncoder.encode(params.get(n).toString(), Charsets.UTF_8);
10✔
317
        }
1✔
318
        return s;
2✔
319
    }
320

321
    /**
322
     * Sets a minimal escape markup function for a Select2Choice component.
323
     * This function replaces certain characters and formats the display of choices.
324
     *
325
     * @param selectItem the Select2Choice component to set the escape markup for
326
     */
327
    public static void setSelect2ChoiceMinimalEscapeMarkup(Select2Choice<?> selectItem) {
328
        selectItem.getSettings().setEscapeMarkup("function(markup) {" +
×
329
                                                 "return markup" +
330
                                                 ".replaceAll('<','&lt;').replaceAll('>', '&gt;')" +
331
                                                 ".replace(/^(.*?) - /, '<span class=\"term\">$1</span><br>')" +
332
                                                 ".replace(/\\((https?:[\\S]+)\\)$/, '<br><code>$1</code>')" +
333
                                                 ".replace(/^([^<].*)$/, '<span class=\"term\">$1</span>')" +
334
                                                 ";}"
335
        );
336
    }
×
337

338
    /**
339
     * Checks if a nanopublication is of a specific class.
340
     *
341
     * @param np       the nanopublication to check
342
     * @param classIri the IRI of the class to check against
343
     * @return true if the nanopublication is of the specified class, false otherwise
344
     */
345
    public static boolean isNanopubOfClass(Nanopub np, IRI classIri) {
346
        return NanopubUtils.getTypes(np).contains(classIri);
5✔
347
    }
348

349
    /**
350
     * Checks if a nanopublication uses a specific predicate in its assertion.
351
     *
352
     * @param np           the nanopublication to check
353
     * @param predicateIri the IRI of the predicate to look for
354
     * @return true if the predicate is used in the assertion, false otherwise
355
     */
356
    public static boolean usesPredicateInAssertion(Nanopub np, IRI predicateIri) {
357
        for (Statement st : np.getAssertion()) {
11✔
358
            if (predicateIri.equals(st.getPredicate())) {
5✔
359
                return true;
2✔
360
            }
361
        }
1✔
362
        return false;
2✔
363
    }
364

365
    /**
366
     * Retrieves a map of FOAF names from the nanopublication's pubinfo.
367
     *
368
     * @param np the nanopublication from which to extract FOAF names
369
     * @return a map where keys are subjects and values are FOAF names
370
     */
371
    public static Map<String, String> getFoafNameMap(Nanopub np) {
372
        Map<String, String> foafNameMap = new HashMap<>();
4✔
373
        for (Statement st : np.getPubinfo()) {
11✔
374
            if (st.getPredicate().equals(FOAF.NAME) && st.getObject() instanceof Literal objL) {
14✔
375
                foafNameMap.put(st.getSubject().stringValue(), objL.stringValue());
8✔
376
            }
377
        }
1✔
378
        return foafNameMap;
2✔
379
    }
380

381
    /**
382
     * Creates a SHA-256 hash of the string representation of an object and returns it as a hexadecimal string.
383
     *
384
     * @param obj the object to hash
385
     * @return the SHA-256 hash of the object's string representation in hexadecimal format
386
     */
387
    public static String createSha256HexHash(Object obj) {
388
        return Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
7✔
389
    }
390

391
    /**
392
     * Gets the types of a nanopublication.
393
     *
394
     * @param np the nanopublication from which to extract types
395
     * @return a list of IRI types associated with the nanopublication
396
     */
397
    public static List<IRI> getTypes(Nanopub np) {
398
        List<IRI> l = new ArrayList<IRI>();
4✔
399
        for (IRI t : NanopubUtils.getTypes(np)) {
11✔
400
            if (t.stringValue().equals("https://w3id.org/fair/fip/terms/Available-FAIR-Enabling-Resource")) continue;
6✔
401
            if (t.stringValue().equals("https://w3id.org/fair/fip/terms/FAIR-Enabling-Resource-to-be-Developed"))
5✔
402
                continue;
1✔
403
            if (t.stringValue().equals("https://w3id.org/fair/fip/terms/Available-FAIR-Supporting-Resource")) continue;
5!
404
            if (t.stringValue().equals("https://w3id.org/fair/fip/terms/FAIR-Supporting-Resource-to-be-Developed"))
5!
405
                continue;
×
406
            l.add(t);
4✔
407
        }
1✔
408
        return l;
2✔
409
    }
410

411
    /**
412
     * Gets a label for a type IRI.
413
     *
414
     * @param typeIri the IRI of the type
415
     * @return a label for the type, potentially truncated
416
     */
417
    public static String getTypeLabel(IRI typeIri) {
418
        String l = typeIri.stringValue();
3✔
419
        if (l.equals("https://w3id.org/fair/fip/terms/FAIR-Enabling-Resource")) return "FER";
6✔
420
        if (l.equals("https://w3id.org/fair/fip/terms/FAIR-Supporting-Resource")) return "FSR";
6✔
421
        if (l.equals("https://w3id.org/fair/fip/terms/FAIR-Implementation-Profile")) return "FIP";
6✔
422
        if (l.equals("http://purl.org/nanopub/x/declaredBy")) return "user intro";
6✔
423
        l = l.replaceFirst("^.*[/#]([^/#]+)[/#]?$", "$1");
5✔
424
        l = l.replaceFirst("^(.+)Nanopub$", "$1");
5✔
425
        if (l.length() > 25) l = l.substring(0, 20) + "...";
10✔
426
        return l;
2✔
427
    }
428

429
    /**
430
     * Gets a label for a URI.
431
     *
432
     * @param uri the URI to get the label from
433
     * @return a label for the URI, potentially truncated
434
     */
435
    public static String getUriLabel(String uri) {
436
        if (uri == null) return "";
4✔
437
        String uriLabel = uri;
2✔
438
        if (uriLabel.matches(".*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{43}([^A-Za-z0-9-_].*)?")) {
4✔
439
            String newUriLabel = uriLabel.replaceFirst("(.*[^A-Za-z0-9-_]RA[A-Za-z0-9-_]{8})[A-Za-z0-9-_]{35}([^A-Za-z0-9-_].*)?", "$1...$2");
5✔
440
            if (newUriLabel.length() <= 70) return newUriLabel;
6!
441
        }
442
        if (uriLabel.length() > 70) return uri.substring(0, 30) + "..." + uri.substring(uri.length() - 30);
16✔
443
        return uriLabel;
2✔
444
    }
445

446
    /**
447
     * Gets an ExternalLink with a URI label.
448
     *
449
     * @param markupId the markup ID for the link
450
     * @param uri      the URI to link to
451
     * @return an ExternalLink with the URI label
452
     */
453
    public static ExternalLink getUriLink(String markupId, String uri) {
454
        return new ExternalLink(markupId, (uri.startsWith("local:") ? "" : uri), getUriLabel(uri));
12!
455
    }
456

457
    /**
458
     * Gets an ExternalLink with a model for the URI label.
459
     *
460
     * @param markupId the markup ID for the link
461
     * @param model    the model containing the URI
462
     * @return an ExternalLink with the URI label
463
     */
464
    public static ExternalLink getUriLink(String markupId, IModel<String> model) {
465
        return new ExternalLink(markupId, model, new UriLabelModel(model));
×
466
    }
467

468
    private static class UriLabelModel implements IModel<String> {
469

470
        private static final long serialVersionUID = 1L;
471

472
        private IModel<String> uriModel;
473

474
        public UriLabelModel(IModel<String> uriModel) {
×
475
            this.uriModel = uriModel;
×
476
        }
×
477

478
        @Override
479
        public String getObject() {
480
            return getUriLabel(uriModel.getObject());
×
481
        }
482

483
    }
484

485
    /**
486
     * Creates a sublist from a list based on the specified indices.
487
     *
488
     * @param list      the list from which to create the sublist
489
     * @param fromIndex the starting index (inclusive) for the sublist
490
     * @param toIndex   the ending index (exclusive) for the sublist
491
     * @param <E>       the type of elements in the list
492
     * @return an ArrayList containing the elements from the specified range
493
     */
494
    public static <E> ArrayList<E> subList(List<E> list, long fromIndex, long toIndex) {
495
        // So the resulting list is serializable:
496
        return new ArrayList<E>(list.subList((int) fromIndex, (int) toIndex));
×
497
    }
498

499
    /**
500
     * Creates a sublist from an array based on the specified indices.
501
     *
502
     * @param array     the array from which to create the sublist
503
     * @param fromIndex the starting index (inclusive) for the sublist
504
     * @param toIndex   the ending index (exclusive) for the sublist
505
     * @param <E>       the type of elements in the array
506
     * @return an ArrayList containing the elements from the specified range
507
     */
508
    public static <E> ArrayList<E> subList(E[] array, long fromIndex, long toIndex) {
509
        return subList(Arrays.asList(array), fromIndex, toIndex);
×
510
    }
511

512
    /**
513
     * Comparator for sorting ApiResponseEntry objects based on a specified field.
514
     */
515
    // TODO Move this to ApiResponseEntry class?
516
    public static class ApiResponseEntrySorter implements Comparator<ApiResponseEntry>, Serializable {
517

518
        private static final long serialVersionUID = 1L;
519

520
        private String field;
521
        private boolean descending;
522

523
        /**
524
         * Constructor for ApiResponseEntrySorter.
525
         *
526
         * @param field      the field to sort by
527
         * @param descending if true, sorts in descending order; if false, sorts in ascending order
528
         */
529
        public ApiResponseEntrySorter(String field, boolean descending) {
×
530
            this.field = field;
×
531
            this.descending = descending;
×
532
        }
×
533

534
        /**
535
         * Compares two ApiResponseEntry objects based on the specified field.
536
         *
537
         * @param o1 the first object to be compared.
538
         * @param o2 the second object to be compared.
539
         * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
540
         */
541
        @Override
542
        public int compare(ApiResponseEntry o1, ApiResponseEntry o2) {
543
            if (descending) {
×
544
                return o2.get(field).compareTo(o1.get(field));
×
545
            } else {
546
                return o1.get(field).compareTo(o2.get(field));
×
547
            }
548
        }
549

550
    }
551

552
    /**
553
     * MIME type for TriG RDF format.
554
     */
555
    public static final String TYPE_TRIG = "application/trig";
556

557
    /**
558
     * MIME type for Jelly RDF format.
559
     */
560
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
561

562
    /**
563
     * MIME type for JSON-LD format.
564
     */
565
    public static final String TYPE_JSONLD = "application/ld+json";
566

567
    /**
568
     * MIME type for N-Quads format.
569
     */
570
    public static final String TYPE_NQUADS = "application/n-quads";
571

572
    /**
573
     * MIME type for Trix format.
574
     */
575
    public static final String TYPE_TRIX = "application/trix";
576

577
    /**
578
     * MIME type for HTML format.
579
     */
580
    public static final String TYPE_HTML = "text/html";
581

582
    public static final String SUPPORTED_TYPES =
583
            TYPE_TRIG + "," +
584
            TYPE_JELLY + "," +
585
            TYPE_JSONLD + "," +
586
            TYPE_NQUADS + "," +
587
            TYPE_TRIX + "," +
588
            TYPE_HTML;
589

590
    /**
591
     * List of supported MIME types for nanopublications.
592
     */
593
    public static final List<String> SUPPORTED_TYPES_LIST = Arrays.asList(StringUtils.split(SUPPORTED_TYPES, ','));
6✔
594

595
    // TODO Move these to nanopub-java library:
596

597
    /**
598
     * Retrieves a set of introduced IRI IDs from the nanopublication.
599
     *
600
     * @param np the nanopublication from which to extract introduced IRI IDs
601
     * @return a set of introduced IRI IDs
602
     */
603
    public static Set<String> getIntroducedIriIds(Nanopub np) {
604
        Set<String> introducedIriIds = new HashSet<>();
4✔
605
        for (Statement st : np.getPubinfo()) {
11✔
606
            if (!st.getSubject().equals(np.getUri())) continue;
7✔
607
            if (!st.getPredicate().equals(NanopubUtils.INTRODUCES)) continue;
6✔
608
            if (st.getObject() instanceof IRI obj) introducedIriIds.add(obj.stringValue());
14✔
609
        }
1✔
610
        return introducedIriIds;
2✔
611
    }
612

613
    /**
614
     * Retrieves a set of embedded IRI IDs from the nanopublication.
615
     *
616
     * @param np the nanopublication from which to extract embedded IRI IDs
617
     * @return a set of embedded IRI IDs
618
     */
619
    public static Set<String> getEmbeddedIriIds(Nanopub np) {
620
        Set<String> embeddedIriIds = new HashSet<>();
×
621
        for (Statement st : np.getPubinfo()) {
×
622
            if (!st.getSubject().equals(np.getUri())) continue;
×
623
            if (!st.getPredicate().equals(NanopubUtils.EMBEDS)) continue;
×
624
            if (st.getObject() instanceof IRI obj) embeddedIriIds.add(obj.stringValue());
×
625
        }
×
626
        return embeddedIriIds;
×
627
    }
628

629
    /**
630
     * Returns the URL of the default Nanopub Registry as configured by the given instance.
631
     *
632
     * @return Nanopub Registry URL
633
     */
634
    public static String getMainRegistryUrl() {
635
            try {
636
                        return EnvironmentUtils.getProcEnvironment().getOrDefault("NANODASH_MAIN_REGISTRY", "https://registry.knowledgepixels.com/");
6✔
637
                } catch (IOException ex) {
×
638
                        ex.printStackTrace();
×
639
                        return "https://registry.knowledgepixels.com/";
×
640
                }
641
    }
642

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