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

knowledgepixels / nanopub-query / 16986825439

15 Aug 2025 09:05AM UTC coverage: 25.779% (+3.1%) from 22.72%
16986825439

push

github

ashleycaselli
ci: update config to use maven wrapper

122 of 494 branches covered (24.7%)

Branch coverage included in aggregate %.

333 of 1271 relevant lines covered (26.2%)

1.28 hits per line

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

81.08
src/main/java/com/knowledgepixels/query/Utils.java
1
package com.knowledgepixels.query;
2

3
import com.google.common.hash.Hashing;
4
import org.apache.commons.exec.environment.EnvironmentUtils;
5
import org.apache.commons.lang3.StringUtils;
6
import org.eclipse.rdf4j.model.IRI;
7
import org.eclipse.rdf4j.model.Value;
8
import org.eclipse.rdf4j.model.ValueFactory;
9
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
10
import org.eclipse.rdf4j.query.BindingSet;
11
import org.eclipse.rdf4j.query.QueryLanguage;
12
import org.eclipse.rdf4j.query.TupleQuery;
13
import org.eclipse.rdf4j.query.TupleQueryResult;
14
import org.eclipse.rdf4j.repository.RepositoryConnection;
15

16
import java.nio.charset.StandardCharsets;
17
import java.util.ArrayList;
18
import java.util.HashMap;
19
import java.util.List;
20
import java.util.Map;
21

22
/**
23
 * Utils class for Nanopub Registry.
24
 */
25
public class Utils {
26

27
    private Utils() {
28
    }  // no instances allowed
29

30
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
2✔
31

32
    /**
33
     * IRI for the predicate that indicates that a hash value is associated with an object.
34
     */
35
    public static final IRI IS_HASH_OF = vf.createIRI("http://purl.org/nanopub/admin/isHashOf");
4✔
36

37
    /**
38
     * Prefix for the hash values stored in the admin graph.
39
     */
40
    public static final IRI HASH_PREFIX = vf.createIRI("http://purl.org/nanopub/admin/hash/");
5✔
41

42
    private static Map<String, Value> hashToObjMap;
43

44
    /**
45
     * Returns reverse hashing map.
46
     *
47
     * @return Map from hashes to their original objects
48
     */
49
    static Map<String, Value> getHashToObjectMap() {
50
        if (hashToObjMap == null) {
2✔
51
            hashToObjMap = new HashMap<>();
4✔
52
            try (RepositoryConnection conn = TripleStore.get().getAdminRepoConnection()) {
×
53
                TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph ?g { ?s ?p ?o } }");
×
54
                query.setBinding("g", NanopubLoader.ADMIN_GRAPH);
×
55
                query.setBinding("p", IS_HASH_OF);
×
56
                try (TupleQueryResult r = query.evaluate()) {
×
57
                    while (r.hasNext()) {
×
58
                        BindingSet b = r.next();
×
59
                        String hash = b.getBinding("s").getValue().stringValue();
×
60
                        hash = StringUtils.replace(hash, HASH_PREFIX.toString(), "");
×
61
                        hashToObjMap.put(hash, b.getBinding("o").getValue());
×
62
                    }
×
63
                }
64
            }
65
        }
66
        return hashToObjMap;
2✔
67
    }
68

69
    /**
70
     * Returns the original object for the given hash value.
71
     *
72
     * @param hash The hash value
73
     * @return The original object
74
     */
75
    public static Value getObjectForHash(String hash) {
76
        return getHashToObjectMap().get(hash);
5✔
77
    }
78

79
    /**
80
     * Creates a hash value for the object and remembers it.
81
     *
82
     * @param obj Object to be hashed
83
     * @return hash value
84
     */
85
    public static String createHash(Object obj) {
86
        String hash = Hashing.sha256().hashString(obj.toString(), StandardCharsets.UTF_8).toString();
7✔
87

88
        if (!getHashToObjectMap().containsKey(hash)) {
4✔
89
            Value objV = getValue(obj);
3✔
90
            try (RepositoryConnection conn = TripleStore.get().getAdminRepoConnection()) {
3✔
91
                conn.add(vf.createStatement(vf.createIRI(HASH_PREFIX + hash), IS_HASH_OF, objV, NanopubLoader.ADMIN_GRAPH));
15✔
92
            }
93
            getHashToObjectMap().put(hash, objV);
5✔
94
        }
95
        return hash;
2✔
96
    }
97

98
    /**
99
     * Returns the object as a Value object.
100
     *
101
     * @param obj Input object
102
     * @return A Value object with the string content of the input object
103
     */
104
    static Value getValue(Object obj) {
105
        if (obj instanceof Value) {
3✔
106
            return (Value) obj;
3✔
107
        } else {
108
            return vf.createLiteral(obj.toString());
5✔
109
        }
110
    }
111

112
    /**
113
     * Returns a short "name" for the given public key
114
     *
115
     * @param pubkey Public key string
116
     * @return Short "name"
117
     */
118
    public static String getShortPubkeyName(String pubkey) {
119
        return pubkey.replaceFirst("^(.).{39}(.{5}).*$", "$1..$2..");
5✔
120
    }
121

122
    /**
123
     * Executes a query on the given connection to return the first objects matching the input.
124
     *
125
     * @param conn  The repository connection
126
     * @param graph Graph (=context) IRI
127
     * @param subj  Subject IRI
128
     * @param pred  Predicate IRI
129
     * @return the first object to match the pattern
130
     */
131
    public static Value getObjectForPattern(RepositoryConnection conn, IRI graph, IRI subj, IRI pred) {
132
        TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + graph.stringValue() + "> { <" + subj.stringValue() + "> <" + pred.stringValue() + "> ?o } }").evaluate();
12✔
133
        try (r) {
2✔
134
            if (!r.hasNext()) return null;
7✔
135
            return r.next().getBinding("o").getValue();
9✔
136
        }
4!
137
    }
138

139
    /**
140
     * Executes a query on the given connection to return all objects matching the input.
141
     *
142
     * @param conn  The repository connection
143
     * @param graph Graph (=context) IRI
144
     * @param subj  Subject IRI
145
     * @param pred  Predicate IRI
146
     * @return a list of all objects matching the pattern
147
     */
148
    public static List<Value> getObjectsForPattern(RepositoryConnection conn, IRI graph, IRI subj, IRI pred) {
149
        List<Value> values = new ArrayList<>();
4✔
150
        TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + graph.stringValue() + "> { <" + subj.stringValue() + "> <" + pred.stringValue() + "> ?o } }").evaluate();
12✔
151
        try (r) {
2✔
152
            while (r.hasNext()) {
3✔
153
                values.add(r.next().getBinding("o").getValue());
10✔
154
            }
155
            return values;
4✔
156
        }
157
    }
158

159
    /**
160
     * Returns the system environment variable content for the given environment variable name.
161
     *
162
     * @param envVarName   environment variable name
163
     * @param defaultValue default value if not found
164
     * @return environment variable value
165
     */
166
    public static String getEnvString(String envVarName, String defaultValue) {
167
        try {
168
            String s = EnvironmentUtils.getProcEnvironment().get(envVarName);
5✔
169
            if (s != null && !s.isEmpty()) {
5✔
170
                return s;
2✔
171
            }
172
        } catch (Exception ex) {
1✔
173
            ex.printStackTrace();
2✔
174
        }
1✔
175
        return defaultValue;
2✔
176
    }
177

178
    /**
179
     * Returns the system environment variable content as an integer for the given environment variable name.
180
     *
181
     * @param envVarName   environment variable name
182
     * @param defaultValue default value if not found
183
     * @return environment variable value interpreted as an integer
184
     */
185
    public static int getEnvInt(String envVarName, int defaultValue) {
186
        try {
187
            String s = getEnvString(envVarName, null);
4✔
188
            if (s != null) {
2✔
189
                return Integer.parseInt(s);
3✔
190
            }
191
        } catch (Exception ex) {
1✔
192
            ex.printStackTrace();
2✔
193
        }
1✔
194
        return defaultValue;
2✔
195
    }
196

197
    /**
198
     * Default query to be shown in YASGUI client.
199
     */
200
    public static final String defaultQuery = """
201
            prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
202
            prefix dct: <http://purl.org/dc/terms/>
203
            prefix np: <http://www.nanopub.org/nschema#>
204
            prefix npa: <http://purl.org/nanopub/admin/>
205
            prefix npx: <http://purl.org/nanopub/x/>
206
            
207
            select * where {
208
            ## Info about this repo:
209
              npa:thisRepo ?pred ?obj .
210
            ## Search for nanopublications:
211
            # graph npa:graph {
212
            #   ?np npa:hasValidSignatureForPublicKey ?pubkey .
213
            #   filter not exists { ?npx npx:invalidates ?np ; npa:hasValidSignatureForPublicKey ?pubkey . }
214
            #   ?np dct:created ?date .
215
            #   ?np np:hasAssertion ?a .
216
            #   optional { ?np rdfs:label ?label }
217
            # }
218
            } limit 10""";
219

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