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

knowledgepixels / nanopub-query / 17767759901

16 Sep 2025 01:40PM UTC coverage: 71.59% (-0.2%) from 71.741%
17767759901

push

github

Ziroli Plutschow
Replacing newest System.err with slf4j logging

- Note: Also upgraded mockito, since it's transient dependency byte-buddy could not handle a jvm > 21

233 of 350 branches covered (66.57%)

Branch coverage included in aggregate %.

591 of 801 relevant lines covered (73.78%)

3.72 hits per line

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

81.56
src/main/java/com/knowledgepixels/query/NanopubLoader.java
1
package com.knowledgepixels.query;
2

3
import net.trustyuri.TrustyUriUtils;
4
import org.apache.http.client.HttpClient;
5
import org.apache.http.impl.client.HttpClientBuilder;
6
import org.eclipse.rdf4j.common.exception.RDF4JException;
7
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
8
import org.eclipse.rdf4j.model.*;
9
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
10
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
11
import org.eclipse.rdf4j.model.vocabulary.RDFS;
12
import org.eclipse.rdf4j.query.BindingSet;
13
import org.eclipse.rdf4j.query.QueryLanguage;
14
import org.eclipse.rdf4j.query.TupleQuery;
15
import org.eclipse.rdf4j.query.TupleQueryResult;
16
import org.eclipse.rdf4j.repository.RepositoryConnection;
17
import org.nanopub.Nanopub;
18
import org.nanopub.NanopubUtils;
19
import org.nanopub.SimpleCreatorPattern;
20
import org.nanopub.SimpleTimestampPattern;
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.setting.IntroNanopub;
27
import org.nanopub.vocabulary.NP;
28
import org.nanopub.vocabulary.NPA;
29
import org.nanopub.vocabulary.NPX;
30
import org.nanopub.vocabulary.PAV;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

34
import java.security.GeneralSecurityException;
35
import java.util.*;
36
import java.util.concurrent.ExecutionException;
37
import java.util.concurrent.Executors;
38
import java.util.concurrent.Future;
39
import java.util.concurrent.ThreadPoolExecutor;
40
import java.util.function.Consumer;
41

42
/**
43
 * Utility class for loading nanopublications into the database.
44
 */
45
public class NanopubLoader {
46

47
    private static HttpClient httpClient;
48
    private static final ThreadPoolExecutor loadingPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
4✔
49
    private Nanopub np;
50
    private NanopubSignatureElement el = null;
3✔
51
    private List<Statement> metaStatements = new ArrayList<>();
5✔
52
    private List<Statement> nanopubStatements = new ArrayList<>();
5✔
53
    private List<Statement> literalStatements = new ArrayList<>();
5✔
54
    private List<Statement> invalidateStatements = new ArrayList<>();
5✔
55
    private List<Statement> textStatements, allStatements;
56
    private Calendar timestamp = null;
3✔
57
    private Statement pubkeyStatement, pubkeyStatementX;
58
    private List<String> notes = new ArrayList<>();
5✔
59
    private boolean aborted = false;
3✔
60
    private static final Logger log = LoggerFactory.getLogger(NanopubLoader.class);
3✔
61

62

63
    NanopubLoader(Nanopub np, long counter) {
2✔
64
        this.np = np;
3✔
65
        if (counter >= 0) {
4✔
66
            log.info("Loading {}: {}", counter, np.getUri());
8✔
67
        } else {
68
            log.info("Loading: {}", np.getUri());
5✔
69
        }
70

71
        // TODO Ensure proper synchronization and DB rollbacks
72

73
        // TODO Check for null characters ("\0"), which can cause problems in Virtuoso.
74

75
        String ac = TrustyUriUtils.getArtifactCode(np.getUri().toString());
5✔
76
        if (!np.getHeadUri().toString().contains(ac) || !np.getAssertionUri().toString().contains(ac) || !np.getProvenanceUri().toString().contains(ac) || !np.getPubinfoUri().toString().contains(ac)) {
24!
77
            notes.add("could not load nanopub as not all graphs contained the artifact code");
×
78
            aborted = true;
×
79
            return;
×
80
        }
81

82
        try {
83
            el = SignatureUtils.getSignatureElement(np);
4✔
84
        } catch (MalformedCryptoElementException ex) {
×
85
            notes.add("Signature error");
×
86
        }
1✔
87
        if (!hasValidSignature(el)) {
4✔
88
            aborted = true;
3✔
89
            return;
1✔
90
        }
91

92
        pubkeyStatement = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, vf.createLiteral(el.getPublicKeyString()), NPA.GRAPH);
13✔
93
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKey, FULL_PUBKEY, npa:graph, meta, full pubkey if signature is valid
94
        metaStatements.add(pubkeyStatement);
6✔
95
        pubkeyStatementX = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, vf.createLiteral(Utils.createHash(el.getPublicKeyString())), NPA.GRAPH);
14✔
96
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKeyHash, PUBKEY_HASH, npa:graph, meta, hex-encoded SHA256 hash if signature is valid
97
        metaStatements.add(pubkeyStatementX);
6✔
98

99
        if (el.getSigners().size() == 1) {  // > 1 is deprecated
6!
100
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SIGNED_BY, el.getSigners().iterator().next(), NPA.GRAPH));
16✔
101
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:signedBy, SIGNER, npa:graph, meta, ID of signer
102
        }
103

104
        Set<IRI> subIris = new HashSet<>();
4✔
105
        Set<IRI> otherNps = new HashSet<>();
4✔
106
        Set<IRI> invalidated = new HashSet<>();
4✔
107
        Set<IRI> retracted = new HashSet<>();
4✔
108
        Set<IRI> superseded = new HashSet<>();
4✔
109
        String combinedLiterals = "";
2✔
110
        for (Statement st : NanopubUtils.getStatements(np)) {
11✔
111
            nanopubStatements.add(st);
5✔
112

113
            if (st.getPredicate().toString().contains(ac)) {
6!
114
                subIris.add(st.getPredicate());
×
115
            } else {
116
                IRI b = getBaseTrustyUri(st.getPredicate());
4✔
117
                if (b != null) otherNps.add(b);
2!
118
            }
119
            if (st.getPredicate().equals(NPX.RETRACTS) && st.getObject() instanceof IRI) {
5!
120
                retracted.add((IRI) st.getObject());
×
121
            }
122
            if (st.getPredicate().equals(NPX.INVALIDATES) && st.getObject() instanceof IRI) {
5!
123
                invalidated.add((IRI) st.getObject());
×
124
            }
125
            if (st.getSubject().equals(np.getUri()) && st.getObject() instanceof IRI) {
10✔
126
                if (st.getPredicate().equals(NPX.SUPERSEDES)) {
5✔
127
                    superseded.add((IRI) st.getObject());
6✔
128
                }
129
                if (st.getObject().toString().matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}")) {
6✔
130
                    metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.NETWORK_GRAPH));
13✔
131
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB1, RELATION, NANOPUB2, npa:networkGraph, meta, any inter-nanopub relation found in NANOPUB1
132
                }
133
                if (st.getContext().equals(np.getPubinfoUri())) {
6✔
134
                    if (st.getPredicate().equals(NPX.INTRODUCES) || st.getPredicate().equals(NPX.DESCRIBES) || st.getPredicate().equals(NPX.EMBEDS)) {
15!
135
                        metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.GRAPH));
13✔
136
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:introduces, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
137
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:describes, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
138
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:embeds, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
139
                    }
140
                }
141
            }
142
            if (st.getSubject().toString().contains(ac)) {
6✔
143
                subIris.add((IRI) st.getSubject());
7✔
144
            } else {
145
                IRI b = getBaseTrustyUri(st.getSubject());
4✔
146
                if (b != null) otherNps.add(b);
2!
147
            }
148
            if (st.getObject() instanceof IRI) {
4✔
149
                if (st.getObject().toString().contains(ac)) {
6✔
150
                    subIris.add((IRI) st.getObject());
7✔
151
                } else {
152
                    IRI b = getBaseTrustyUri(st.getObject());
4✔
153
                    if (b != null) otherNps.add(b);
6✔
154
                }
1✔
155
            } else {
156
                combinedLiterals += st.getObject().stringValue().replaceAll("\\s+", " ") + "\n";
9✔
157
//                                if (st.getSubject().equals(np.getUri()) && !st.getSubject().equals(HAS_FILTER_LITERAL)) {
158
//                                        literalStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), LITERAL_GRAPH));
159
//                                } else {
160
//                                        literalStatements.add(vf.createStatement(np.getUri(), HAS_LITERAL, st.getObject(), LITERAL_GRAPH));
161
//                                }
162
            }
163
        }
1✔
164
        subIris.remove(np.getUri());
5✔
165
        subIris.remove(np.getAssertionUri());
5✔
166
        subIris.remove(np.getProvenanceUri());
5✔
167
        subIris.remove(np.getPubinfoUri());
5✔
168
        for (IRI i : subIris) {
10✔
169
            metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_SUB_IRI, i, NPA.GRAPH));
11✔
170
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasSubIri, SUB_IRI, npa:graph, meta, for any IRI minted in the namespace of the NANOPUB
171
        }
1✔
172
        for (IRI i : otherNps) {
10✔
173
            metaStatements.add(vf.createStatement(np.getUri(), NPA.REFERS_TO_NANOPUB, i, NPA.NETWORK_GRAPH));
11✔
174
            // @ADMIN-TRIPLE-TABLE@ NANOPUB1, npa:refersToNanopub, NANOPUB2, npa:networkGraph, meta, generic inter-nanopub relation
175
        }
1✔
176
        for (IRI i : invalidated) {
6!
177
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
178
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:invalidates, INVALIDATED_NANOPUB, npa:graph, meta, if the NANOPUB retracts or supersedes another nanopub
179
        }
×
180
        for (IRI i : retracted) {
6!
181
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
182
            metaStatements.add(vf.createStatement(np.getUri(), NPX.RETRACTS, i, NPA.GRAPH));
×
183
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:retracts, RETRACTED_NANOPUB, npa:graph, meta, if the NANOPUB retracts another nanopub
184
        }
×
185
        for (IRI i : superseded) {
10✔
186
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
11✔
187
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SUPERSEDES, i, NPA.GRAPH));
11✔
188
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:supersedes, SUPERSEDED_NANOPUB, npa:graph, meta, if the NANOPUB supersedes another nanopub
189
        }
1✔
190

191
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_HEAD_GRAPH, np.getHeadUri(), NPA.GRAPH));
12✔
192
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasHeadGraph, HEAD_GRAPH, npa:graph, meta, direct link to the head graph of the NANOPUB
193
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getHeadUri(), NPA.GRAPH));
12✔
194
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasGraph, GRAPH, npa:graph, meta, generic link to all four graphs of the given NANOPUB
195
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_ASSERTION, np.getAssertionUri(), NPA.GRAPH));
12✔
196
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasAssertion, ASSERTION_GRAPH, npa:graph, meta, direct link to the assertion graph of the NANOPUB
197
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getAssertionUri(), NPA.GRAPH));
12✔
198
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PROVENANCE, np.getProvenanceUri(), NPA.GRAPH));
12✔
199
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasProvenance, PROVENANCE_GRAPH, npa:graph, meta, direct link to the provenance graph of the NANOPUB
200
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getProvenanceUri(), NPA.GRAPH));
12✔
201
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PUBINFO, np.getPubinfoUri(), NPA.GRAPH));
12✔
202
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasPublicationInfo, PUBINFO_GRAPH, npa:graph, meta, direct link to the pubinfo graph of the NANOPUB
203
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getPubinfoUri(), NPA.GRAPH));
12✔
204

205
        String artifactCode = TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
5✔
206
        metaStatements.add(vf.createStatement(np.getUri(), NPA.ARTIFACT_CODE, vf.createLiteral(artifactCode), NPA.GRAPH));
13✔
207
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:artifactCode, ARTIFACT_CODE, npa:graph, meta, artifact code starting with 'RA...'
208

209
        if (isIntroNanopub(np)) {
3✔
210
            IntroNanopub introNp = new IntroNanopub(np);
5✔
211
            metaStatements.add(vf.createStatement(np.getUri(), NPA.IS_INTRODUCTION_OF, introNp.getUser(), NPA.GRAPH));
12✔
212
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:isIntroductionOf, AGENT, npa:graph, meta, linking intro nanopub to the agent it is introducing
213
            for (KeyDeclaration kc : introNp.getKeyDeclarations()) {
11✔
214
                metaStatements.add(vf.createStatement(np.getUri(), NPA.DECLARES_PUBKEY, vf.createLiteral(kc.getPublicKeyString()), NPA.GRAPH));
14✔
215
                // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:declaresPubkey, FULL_PUBKEY, npa:graph, meta, full pubkey declared by the given intro NANOPUB
216
            }
1✔
217
        }
218

219
        try {
220
            timestamp = SimpleTimestampPattern.getCreationTime(np);
4✔
221
        } catch (IllegalArgumentException ex) {
×
222
            notes.add("Illegal date/time");
×
223
        }
1✔
224
        if (timestamp != null) {
3!
225
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATED, vf.createLiteral(timestamp.getTime()), NPA.GRAPH));
15✔
226
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:created, CREATION_DATE, npa:graph, meta, normalized creation timestamp
227
        }
228

229
        String literalFilter = "_pubkey_" + Utils.createHash(el.getPublicKeyString());
6✔
230
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
11✔
231
            metaStatements.add(vf.createStatement(np.getUri(), NPX.HAS_NANOPUB_TYPE, typeIri, NPA.GRAPH));
11✔
232
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:hasNanopubType, NANOPUB_TYPE, npa:graph, meta, type of NANOPUB
233
            literalFilter += " _type_" + Utils.createHash(typeIri);
5✔
234
        }
1✔
235
        String label = NanopubUtils.getLabel(np);
3✔
236
        if (label != null) {
2!
237
            metaStatements.add(vf.createStatement(np.getUri(), RDFS.LABEL, vf.createLiteral(label), NPA.GRAPH));
13✔
238
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, rdfs:label, LABEL, npa:graph, meta, label of NANOPUB
239
        }
240
        String description = NanopubUtils.getDescription(np);
3✔
241
        if (description != null) {
2✔
242
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.DESCRIPTION, vf.createLiteral(description), NPA.GRAPH));
13✔
243
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:description, LABEL, npa:graph, meta, description of NANOPUB
244
        }
245
        for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
11✔
246
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATOR, creatorIri, NPA.GRAPH));
11✔
247
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:creator, CREATOR, npa:graph, meta, creator of NANOPUB (can be several)
248
        }
1✔
249
        for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
7!
250
            metaStatements.add(vf.createStatement(np.getUri(), PAV.AUTHORED_BY, authorIri, NPA.GRAPH));
×
251
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, pav:authoredBy, AUTHOR, npa:graph, meta, author of NANOPUB (can be several)
252
        }
×
253

254
        if (!combinedLiterals.isEmpty()) {
3!
255
            literalStatements.add(vf.createStatement(np.getUri(), NPA.HAS_FILTER_LITERAL, vf.createLiteral(literalFilter + "\n" + combinedLiterals), NPA.GRAPH));
15✔
256
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasFilterLiteral, FILTER_LITERAL, npa:graph, literal, auxiliary literal for filtering by type and pubkey in text repo
257
        }
258

259
        // Any statements that express that the currently processed nanopub is already invalidated:
260
        List<Statement> invalidatingStatements = getInvalidatingStatements(np.getUri());
4✔
261

262
        metaStatements.addAll(invalidateStatements);
6✔
263

264
        allStatements = new ArrayList<>(nanopubStatements);
7✔
265
        allStatements.addAll(metaStatements);
6✔
266
        allStatements.addAll(invalidatingStatements);
5✔
267

268
        textStatements = new ArrayList<>(literalStatements);
7✔
269
        textStatements.addAll(metaStatements);
6✔
270
        textStatements.addAll(invalidatingStatements);
5✔
271
    }
1✔
272

273
    /**
274
     * Get the HTTP client used for fetching nanopublications.
275
     *
276
     * @return the HTTP client
277
     */
278
    static HttpClient getHttpClient() {
279
        if (httpClient == null) {
2✔
280
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(Utils.getHttpRequestConfig()).build();
5✔
281
        }
282
        return httpClient;
2✔
283
    }
284

285
    /**
286
     * Load the given nanopublication into the database.
287
     *
288
     * @param nanopubUri Nanopublication identifier (URI)
289
     */
290
    public static void load(String nanopubUri) {
291
        if (isNanopubLoaded(nanopubUri)) {
3!
292
            log.info("Already loaded: {}", nanopubUri);
×
293
        } else {
294
            Nanopub np = GetNanopub.get(nanopubUri, getHttpClient());
4✔
295
            load(np, -1);
3✔
296
        }
297
    }
1✔
298

299
    /**
300
     * Load a nanopub into the database.
301
     *
302
     * @param np      the nanopub to load
303
     * @param counter the load counter, only used for logging (or -1 if not known)
304
     * @throws RDF4JException if the loading fails
305
     */
306
    public static void load(Nanopub np, long counter) throws RDF4JException {
307
        NanopubLoader loader = new NanopubLoader(np, counter);
6✔
308
        loader.executeLoading();
2✔
309
    }
1✔
310

311
    @GeneratedFlagForDependentElements
312
    private void executeLoading() {
313
        var runningTasks = new ArrayList<Future<?>>();
314
        Consumer<Runnable> runTask = t -> runningTasks.add(loadingPool.submit(t));
×
315

316
        for (String note : notes) {
317
            loadNoteToRepo(np.getUri(), note);
318
        }
319

320
        if (!aborted) {
321
            if (timestamp != null) {
322
                if (new Date().getTime() - timestamp.getTimeInMillis() < THIRTY_DAYS) {
323
                    runTask.accept(() -> loadNanopubToLatest(allStatements));
×
324
                }
325
            }
326

327
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), textStatements, "text"));
×
328
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "full"));
×
329
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), metaStatements, "meta"));
×
330

331
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "pubkey_" + Utils.createHash(el.getPublicKeyString())));
×
332
            //                loadNanopubToRepo(np.getUri(), textStatements, "text-pubkey_" + Utils.createHash(el.getPublicKeyString()));
333
            for (IRI typeIri : NanopubUtils.getTypes(np)) {
334
                // Exclude locally minted IRIs:
335
                if (typeIri.stringValue().startsWith(np.getUri().stringValue())) continue;
336
                if (!typeIri.stringValue().matches("https?://.*")) continue;
337
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "type_" + Utils.createHash(typeIri)));
×
338
                //                        loadNanopubToRepo(np.getUri(), textStatements, "text-type_" + Utils.createHash(typeIri));
339
            }
340
            //                for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
341
            //                        // Exclude locally minted IRIs:
342
            //                        if (creatorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
343
            //                        if (!creatorIri.stringValue().matches("https?://.*")) continue;
344
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(creatorIri));
345
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(creatorIri));
346
            //                }
347
            //                for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
348
            //                        // Exclude locally minted IRIs:
349
            //                        if (authorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
350
            //                        if (!authorIri.stringValue().matches("https?://.*")) continue;
351
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(authorIri));
352
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(authorIri));
353
            //                }
354

355
            for (Statement st : invalidateStatements) {
356
                runTask.accept(() -> loadInvalidateStatements(np, el.getPublicKeyString(), st, pubkeyStatement, pubkeyStatementX));
×
357
            }
358
        }
359

360
        // Wait for all loading tasks to complete before returning
361
        for (var task : runningTasks) {
362
            try {
363
                task.get();
364
            } catch (ExecutionException | InterruptedException ex) {
365
                throw new RuntimeException("Error in nanopub loading thread", ex.getCause());
366
            }
367
        }
368
    }
369

370
    private static Long lastUpdateOfLatestRepo = null;
2✔
371
    private static long THIRTY_DAYS = 1000L * 60 * 60 * 24 * 30;
2✔
372
    private static long ONE_HOUR = 1000L * 60 * 60;
2✔
373

374
    @GeneratedFlagForDependentElements
375
    private static void loadNanopubToLatest(List<Statement> statements) {
376
        boolean success = false;
377
        while (!success) {
378
            RepositoryConnection conn = TripleStore.get().getRepoConnection("last30d");
379
            try (conn) {
380
                // Read committed, because deleting old nanopubs is idempotent. Inserts do not collide
381
                // with deletes, because we are not inserting old nanopubs.
382
                conn.begin(IsolationLevels.READ_COMMITTED);
383
                conn.add(statements);
384
                if (lastUpdateOfLatestRepo == null || new Date().getTime() - lastUpdateOfLatestRepo > ONE_HOUR) {
385
                    log.trace("Remove old nanopubs...");
386
                    Literal thirtyDaysAgo = vf.createLiteral(new Date(new Date().getTime() - THIRTY_DAYS));
387
                    TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + DCTERMS.CREATED + "> ?date . " + "filter ( ?date < ?thirtydaysago ) " + "} }");
388
                    q.setBinding("thirtydaysago", thirtyDaysAgo);
389
                    try (TupleQueryResult r = q.evaluate()) {
390
                        while (r.hasNext()) {
391
                            BindingSet b = r.next();
392
                            IRI oldNpId = (IRI) b.getBinding("np").getValue();
393
                            log.trace("Remove old nanopub: {}", oldNpId);
394
                            for (Value v : Utils.getObjectsForPattern(conn, NPA.GRAPH, oldNpId, NPA.HAS_GRAPH)) {
395
                                // Remove all four nanopub graphs:
396
                                conn.remove((Resource) null, (IRI) null, (Value) null, (IRI) v);
397
                            }
398
                            // Remove nanopubs in admin graphs:
399
                            conn.remove(oldNpId, null, null, NPA.GRAPH);
400
                            conn.remove(oldNpId, null, null, NPA.NETWORK_GRAPH);
401
                        }
402
                    }
403
                    lastUpdateOfLatestRepo = new Date().getTime();
404
                }
405
                conn.commit();
406
                success = true;
407
            } catch (Exception ex) {
408
                log.info("Could not get environment variable", ex);
409
                if (conn.isActive()) conn.rollback();
410
            }
411
            if (!success) {
412
                log.info("Retrying in 10 second...");
413
                try {
414
                    Thread.sleep(10000);
415
                } catch (InterruptedException x) {
416
                }
417
            }
418
        }
419
    }
420

421
    @GeneratedFlagForDependentElements
422
    private static void loadNanopubToRepo(IRI npId, List<Statement> statements, String repoName) {
423
        boolean success = false;
424
        while (!success) {
425
            RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
426
            try (conn) {
427
                // Serializable, because write skew would cause the chain of hashes to be broken.
428
                // The inserts must be done serially.
429
                conn.begin(IsolationLevels.SERIALIZABLE);
430
                var repoStatus = fetchRepoStatus(conn, npId);
431
                if (repoStatus.isLoaded) {
432
                    log.info("Already loaded: ", npId);
433
                } else {
434
                    String newChecksum = NanopubUtils.updateXorChecksum(npId, repoStatus.checksum);
435
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, null, NPA.GRAPH);
436
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, null, NPA.GRAPH);
437
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, vf.createLiteral(repoStatus.count + 1), NPA.GRAPH);
438
                    // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubCount, NANOPUB_COUNT, npa:graph, admin, number of nanopubs loaded
439
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
440
                    // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubChecksum, NANOPUB_CHECKSUM, npa:graph, admin, checksum of all loaded nanopubs (order-independent XOR checksum on trusty URIs in Base64 notation)
441
                    conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(repoStatus.count), NPA.GRAPH);
442
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadNumber, LOAD_NUMBER, npa:graph, admin, the sequential number at which this NANOPUB was loaded
443
                    conn.add(npId, NPA.HAS_LOAD_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
444
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadChecksum, LOAD_CHECKSUM, npa:graph, admin, the checksum of all loaded nanopubs after loading the given NANOPUB
445
                    conn.add(npId, NPA.HAS_LOAD_TIMESTAMP, vf.createLiteral(new Date()), NPA.GRAPH);
446
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadTimestamp, LOAD_TIMESTAMP, npa:graph, admin, the time point at which this NANOPUB was loaded
447
                    conn.add(statements);
448
                }
449
                conn.commit();
450
                success = true;
451
            } catch (Exception ex) {
452
                log.info("Could no load nanopub to repo. ", ex);
453
                if (conn.isActive()) conn.rollback();
454
            }
455
            if (!success) {
456
                log.info("Retrying in 10 second...");
457
                try {
458
                    Thread.sleep(10000);
459
                } catch (InterruptedException x) {
460
                }
461
            }
462
        }
463
    }
464

465
    private record RepoStatus(boolean isLoaded, long count, String checksum) {
×
466
    }
467

468
    /**
469
     * To execute before loading a nanopub: check if the nanopub is already loaded and what is the
470
     * current load counter and checksum. This effectively batches three queries into one.
471
     * This method must be called from within a transaction.
472
     *
473
     * @param conn repo connection
474
     * @param npId nanopub ID
475
     * @return the current status
476
     */
477
    @GeneratedFlagForDependentElements
478
    private static RepoStatus fetchRepoStatus(RepositoryConnection conn, IRI npId) {
479
        var result = conn.prepareTupleQuery(QueryLanguage.SPARQL, REPO_STATUS_QUERY_TEMPLATE.formatted(npId)).evaluate();
480
        try (result) {
481
            if (!result.hasNext()) {
482
                // This may happen if the repo was created, but is completely empty.
483
                return new RepoStatus(false, 0, NanopubUtils.INIT_CHECKSUM);
484
            }
485
            var row = result.next();
486
            return new RepoStatus(row.hasBinding("loadNumber"), Long.parseLong(row.getBinding("count").getValue().stringValue()), row.getBinding("checksum").getValue().stringValue());
487
        }
488
    }
489

490
    @GeneratedFlagForDependentElements
491
    private static void loadInvalidateStatements(Nanopub thisNp, String thisPubkey, Statement invalidateStatement, Statement pubkeyStatement, Statement pubkeyStatementX) {
492
        boolean success = false;
493
        while (!success) {
494
            List<RepositoryConnection> connections = new ArrayList<>();
495
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
496
            try {
497
                IRI invalidatedNpId = (IRI) invalidateStatement.getObject();
498
                // Basic isolation because here we only read append-only data.
499
                metaConn.begin(IsolationLevels.READ_COMMITTED);
500

501
                Value pubkeyValue = Utils.getObjectForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY);
502
                if (pubkeyValue != null) {
503
                    String pubkey = pubkeyValue.stringValue();
504

505
                    if (!pubkey.equals(thisPubkey)) {
506
                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for pubkey " + pubkey);
507
                        connections.add(loadStatements("pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement, pubkeyStatementX));
508
//                                                connections.add(loadStatements("text-pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement));
509
                    }
510

511
                    for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPX.HAS_NANOPUB_TYPE)) {
512
                        IRI typeIri = (IRI) v;
513
                        // TODO Avoid calling getTypes and getCreators multiple times:
514
                        if (!NanopubUtils.getTypes(thisNp).contains(typeIri)) {
515
                            //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for type " + typeIri);
516
                            connections.add(loadStatements("type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement, pubkeyStatementX));
517
//                                                        connections.add(loadStatements("text-type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement));
518
                        }
519
                    }
520

521
//                                        for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, DCTERMS.CREATOR)) {
522
//                                                IRI creatorIri = (IRI) v;
523
//                                                if (!SimpleCreatorPattern.getCreators(thisNp).contains(creatorIri)) {
524
//                                                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for user " + creatorIri);
525
//                                                        connections.add(loadStatements("user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
526
//                                                        connections.add(loadStatements("text-user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
527
//                                                }
528
//                                        }
529
                }
530

531
                metaConn.commit();
532
                // TODO handle case that some commits succeed and some fail
533
                for (RepositoryConnection c : connections) c.commit();
534
                success = true;
535
            } catch (Exception ex) {
536
                log.info("Could no load invalidate statements. ", ex);
537
                if (metaConn.isActive()) metaConn.rollback();
538
                for (RepositoryConnection c : connections) {
539
                    if (c.isActive()) c.rollback();
540
                }
541
            } finally {
542
                metaConn.close();
543
                for (RepositoryConnection c : connections) c.close();
544
            }
545
            if (!success) {
546
                log.info("Retrying in 10 second...");
547
                try {
548
                    Thread.sleep(10000);
549
                } catch (InterruptedException x) {
550
                }
551
            }
552
        }
553
    }
554

555
    @GeneratedFlagForDependentElements
556
    private static RepositoryConnection loadStatements(String repoName, Statement... statements) {
557
        RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
558
        // Basic isolation: we only append new statements
559
        conn.begin(IsolationLevels.READ_COMMITTED);
560
        for (Statement st : statements) {
561
            conn.add(st);
562
        }
563
        return conn;
564
    }
565

566
    @GeneratedFlagForDependentElements
567
    static List<Statement> getInvalidatingStatements(IRI npId) {
568
        List<Statement> invalidatingStatements = new ArrayList<>();
569
        boolean success = false;
570
        while (!success) {
571
            RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
572
            try (conn) {
573
                // Basic isolation because here we only read append-only data.
574
                conn.begin(IsolationLevels.READ_COMMITTED);
575

576
                TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + NPX.INVALIDATES + "> <" + npId + "> ; <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY + "> ?pubkey . " + "} }").evaluate();
577
                try (r) {
578
                    while (r.hasNext()) {
579
                        BindingSet b = r.next();
580
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPX.INVALIDATES, npId, NPA.GRAPH));
581
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, b.getBinding("pubkey").getValue(), NPA.GRAPH));
582
                    }
583
                }
584
                conn.commit();
585
                success = true;
586
            } catch (Exception ex) {
587
                log.info("Could no load invalidating statements. ", ex);
588
                if (conn.isActive()) conn.rollback();
589
            }
590
            if (!success) {
591
                log.info("Retrying in 10 second...");
592
                try {
593
                    Thread.sleep(10000);
594
                } catch (InterruptedException x) {
595
                }
596
            }
597
        }
598
        return invalidatingStatements;
599
    }
600

601
    @GeneratedFlagForDependentElements
602
    private static void loadNoteToRepo(Resource subj, String note) {
603
        boolean success = false;
604
        while (!success) {
605
            RepositoryConnection conn = TripleStore.get().getAdminRepoConnection();
606
            try (conn) {
607
                List<Statement> statements = new ArrayList<>();
608
                statements.add(vf.createStatement(subj, NPA.NOTE, vf.createLiteral(note), NPA.GRAPH));
609
                conn.add(statements);
610
                success = true;
611
            } catch (Exception ex) {
612
                log.info("Could no load note to repo. ", ex);
613
            }
614
            if (!success) {
615
                log.info("Retrying in 10 second...");
616
                try {
617
                    Thread.sleep(10000);
618
                } catch (InterruptedException x) {
619
                }
620
            }
621
        }
622
    }
623

624
    static boolean hasValidSignature(NanopubSignatureElement el) {
625
        try {
626
            if (el != null && SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
8!
627
                return true;
2✔
628
            }
629
        } catch (GeneralSecurityException ex) {
1✔
630
            log.info("Error for signature element {}", el.getUri());
5✔
631
            log.info("Error", ex);
4✔
632
        }
1✔
633
        return false;
2✔
634
    }
635

636
    private static IRI getBaseTrustyUri(Value v) {
637
        if (!(v instanceof IRI)) return null;
3!
638
        String s = v.stringValue();
3✔
639
        if (!s.matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}([^A-Za-z0-9\\\\-_].{0,43})?")) {
4✔
640
            return null;
2✔
641
        }
642
        return vf.createIRI(s.replaceFirst("^(.*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43})([^A-Za-z0-9\\\\-_].{0,43})?$", "$1"));
7✔
643
    }
644

645
    // TODO: Move this to nanopub library:
646
    private static boolean isIntroNanopub(Nanopub np) {
647
        for (Statement st : np.getAssertion()) {
11✔
648
            if (st.getPredicate().equals(NPX.DECLARED_BY)) return true;
7✔
649
        }
1✔
650
        return false;
2✔
651
    }
652

653
    /**
654
     * Check if a nanopub is already loaded in the admin graph.
655
     *
656
     * @param npId the nanopub ID
657
     * @return true if the nanopub is loaded, false otherwise
658
     */
659
    @GeneratedFlagForDependentElements
660
    static boolean isNanopubLoaded(String npId) {
661
        boolean loaded = false;
662
        RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
663
        try (conn) {
664
            if (Utils.getObjectForPattern(conn, NPA.GRAPH, vf.createIRI(npId), NPA.HAS_LOAD_NUMBER) != null) {
665
                loaded = true;
666
            }
667
        } catch (Exception ex) {
668
            log.info("Could no load nanopub. ",ex);
669
        }
670
        return loaded;
671
    }
672

673
    private static ValueFactory vf = SimpleValueFactory.getInstance();
2✔
674

675
    // TODO remove the constants and use the ones from the nanopub library instead
676

677
    /**
678
     * Template for the query that fetches the status of a repository.
679
     */
680
    // Template for .fetchRepoStatus
681
    private static final String REPO_STATUS_QUERY_TEMPLATE = """
28✔
682
            SELECT * { graph <%s> {
683
              OPTIONAL { <%s> <%s> ?loadNumber . }
684
              <%s> <%s> ?count ;
685
                   <%s> ?checksum .
686
            } }
687
            """.formatted(NPA.GRAPH, "%s", NPA.HAS_LOAD_NUMBER, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, NPA.HAS_NANOPUB_CHECKSUM);
2✔
688
}
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