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

Nanopublication / nanopub-java / 17376844338

01 Sep 2025 11:54AM UTC coverage: 45.468% (-0.03%) from 45.497%
17376844338

push

github

ashleycaselli
refactor: update code to use NanopubAlreadyFinalizedException

825 of 2878 branches covered (28.67%)

Branch coverage included in aggregate %.

4608 of 9071 relevant lines covered (50.8%)

2.43 hits per line

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

0.0
src/main/java/org/nanopub/op/Build.java
1
package org.nanopub.op;
2

3
import com.beust.jcommander.ParameterException;
4
import net.trustyuri.TrustyUriException;
5
import org.apache.commons.lang3.tuple.Pair;
6
import org.eclipse.rdf4j.model.IRI;
7
import org.eclipse.rdf4j.model.Resource;
8
import org.eclipse.rdf4j.model.Statement;
9
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
10
import org.eclipse.rdf4j.model.vocabulary.PROV;
11
import org.eclipse.rdf4j.rio.*;
12
import org.nanopub.*;
13
import org.nanopub.trusty.TempUriReplacer;
14

15
import java.io.*;
16
import java.util.ArrayList;
17
import java.util.List;
18
import java.util.Random;
19
import java.util.zip.GZIPInputStream;
20
import java.util.zip.GZIPOutputStream;
21

22
/**
23
 * Command-line utility to build nanopublications from RDF files.
24
 */
25
public class Build extends CliRunner {
×
26

27
    @com.beust.jcommander.Parameter(description = "input-rdf-files", required = true)
×
28
    private List<File> inputRdfdFiles = new ArrayList<>();
29

30
    @com.beust.jcommander.Parameter(names = "-d", description = "Point to the URI of the resource the created nanopublications are derived from")
31
    private String derivedFrom;
32

33
    @com.beust.jcommander.Parameter(names = "-c", description = "Creator of nanopublication")
×
34
    private List<String> creators = new ArrayList<>();
35

36
    @com.beust.jcommander.Parameter(names = "-o", description = "Output file")
37
    private File outputFile;
38

39
    @com.beust.jcommander.Parameter(names = "--in-format", description = "Format of the input RDF files: ttl, jsonld, nt, ttl.gz, ...")
40
    private String inFormat;
41

42
    @com.beust.jcommander.Parameter(names = "--out-format", description = "Format of the output nanopubs: trig, nq, trix, trig.gz, ...")
43
    private String outFormat;
44

45
    /**
46
     * Main method to run the Build command-line utility.
47
     *
48
     * @param args Command-line arguments
49
     */
50
    public static void main(String[] args) {
51
        try {
52
            Build obj = CliRunner.initJc(new Build(), args);
×
53
            obj.run();
×
54
        } catch (ParameterException ex) {
×
55
            System.exit(1);
×
56
        } catch (Exception ex) {
×
57
            ex.printStackTrace();
×
58
            System.exit(1);
×
59
        }
×
60
    }
×
61

62
    private RDFFormat rdfInFormat, rdfOutFormat;
63
    private OutputStream outputStream = System.out;
×
64
    private Random random = new Random();
×
65
    private NanopubCreator npCreator;
66
    private IRI nanopubIri, assertionIri;
67
    private Resource previousSubj;
68
    private IRI derivedFromUri;
69
    private List<Pair<String, String>> namespaces = new ArrayList<>();
×
70

71
    private void run() throws IOException, RDFParseException, RDFHandlerException,
72
            MalformedNanopubException, TrustyUriException, NanopubAlreadyFinalizedException {
73

74
        if (outputFile == null) {
×
75
            if (outFormat == null) {
×
76
                outFormat = "trig";
×
77
            }
78
            rdfOutFormat = Rio.getParserFormatForFileName("file." + outFormat).orElse(null);
×
79
        } else {
80
            rdfOutFormat = Rio.getParserFormatForFileName(outputFile.getName()).orElse(null);
×
81
            if (outputFile.getName().endsWith(".gz")) {
×
82
                outputStream = new GZIPOutputStream(new FileOutputStream(outputFile));
×
83
            } else {
84
                outputStream = new FileOutputStream(outputFile);
×
85
            }
86
        }
87
        if (derivedFrom != null) {
×
88
            derivedFromUri = vf.createIRI(derivedFrom);
×
89
        }
90

91
        for (File inputFile : inputRdfdFiles) {
×
92
            String dummyFileName;
93
            if (inFormat != null) {
×
94
                dummyFileName = "file." + inFormat;
×
95
            } else {
96
                dummyFileName = inputFile.toString();
×
97
            }
98
            rdfInFormat = Rio.getParserFormatForFileName(dummyFileName).orElse(null);
×
99
            InputStream inputStream;
100
            if (dummyFileName.matches(".*\\.(gz|gzip)")) {
×
101
                inputStream = new GZIPInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
×
102
            } else {
103
                inputStream = new BufferedInputStream(new FileInputStream(inputFile));
×
104
            }
105

106
            RDFParser parser = Rio.createParser(rdfInFormat);
×
107
            parser.setRDFHandler(new RDFHandler() {
×
108

109
                @Override
110
                public void startRDF() throws RDFHandlerException {
111
                }
×
112

113
                @Override
114
                public void handleStatement(Statement st) throws RDFHandlerException {
115
                    try {
116
                        processStatement(st);
×
117
                    } catch (NanopubAlreadyFinalizedException e) {
×
118
                        throw new RuntimeException(e);
×
119
                    }
×
120
                }
×
121

122
                @Override
123
                public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
124
                    try {
125
                        processNamespace(prefix, uri);
×
126
                    } catch (NanopubAlreadyFinalizedException e) {
×
127
                        throw new RuntimeException(e);
×
128
                    }
×
129
                }
×
130

131
                @Override
132
                public void handleComment(String comment) throws RDFHandlerException {
133
                }
×
134

135
                @Override
136
                public void endRDF() throws RDFHandlerException {
137
                }
×
138

139
            });
140
            parser.parse(inputStream, "http://example.com/baseuri");
×
141

142
            inputStream.close();
×
143
        }
×
144

145
        if (previousSubj != null) finalizeNanopub();
×
146

147
        outputStream.flush();
×
148
        if (outputStream != System.out) {
×
149
            outputStream.close();
×
150
        }
151
    }
×
152

153
    private void processStatement(Statement st) throws NanopubAlreadyFinalizedException {
154
        prepareCreator(st.getSubject());
×
155
        npCreator.addAssertionStatements(st);
×
156
    }
×
157

158
    private void processNamespace(String prefix, String uri) throws NanopubAlreadyFinalizedException {
159
        prepareCreator(null);
×
160
        namespaces.add(Pair.of(prefix, uri));
×
161
        npCreator.addNamespace(prefix, uri);
×
162
    }
×
163

164
    private void prepareCreator(Resource subj) throws NanopubAlreadyFinalizedException {
165
        if (previousSubj != null && subj != null && !subj.equals(previousSubj)) {
×
166
            finalizeNanopub();
×
167
        }
168
        if (npCreator == null) {
×
169
            initNanopub();
×
170
        }
171
        previousSubj = subj;
×
172
    }
×
173

174
    private void initNanopub() throws NanopubAlreadyFinalizedException {
175
        String npUriString = TempUriReplacer.tempUri + Math.abs(random.nextInt()) + "/";
×
176
        nanopubIri = vf.createIRI(npUriString);
×
177
        assertionIri = vf.createIRI(npUriString + "assertion");
×
178
        if (creators.isEmpty()) creators.add(npUriString + "creator");
×
179
        npCreator = new NanopubCreator(nanopubIri);
×
180
        npCreator.setAssertionUri(assertionIri);
×
181
        npCreator.addDefaultNamespaces();
×
182
        for (Pair<String, String> p : namespaces) {
×
183
            npCreator.addNamespace(p.getLeft(), p.getRight());
×
184
        }
×
185
        if (derivedFromUri != null) {
×
186
            npCreator.addProvenanceStatement(PROV.WAS_DERIVED_FROM, derivedFromUri);
×
187
        } else {
188
            for (String c : creators) {
×
189
                npCreator.addProvenanceStatement(PROV.HAD_PRIMARY_SOURCE, vf.createIRI(c));
×
190
            }
×
191
        }
192
        for (String c : creators) {
×
193
            npCreator.addCreator(vf.createIRI(c));
×
194
        }
×
195
    }
×
196

197
    private void finalizeNanopub() throws NanopubAlreadyFinalizedException {
198
        npCreator.addTimestampNow();
×
199
        npCreator.setRemoveUnusedPrefixesEnabled(true);
×
200
        try {
201
            Nanopub np = npCreator.finalizeNanopub();
×
202
            NanopubUtils.writeToStream(np, outputStream, rdfOutFormat);
×
203
        } catch (MalformedNanopubException ex) {
×
204
            throw new RuntimeException(ex);
×
205
        }
×
206
        npCreator = null;
×
207
    }
×
208

209
    private static SimpleValueFactory vf = SimpleValueFactory.getInstance();
×
210

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