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

knowledgepixels / nanodash / 17735616195

15 Sep 2025 01:58PM UTC coverage: 13.74% (-0.03%) from 13.767%
17735616195

push

github

tkuhn
feat: Show 100 (instead of 10) latest nanopublications on home page

435 of 3992 branches covered (10.9%)

Branch coverage included in aggregate %.

1113 of 7274 relevant lines covered (15.3%)

0.68 hits per line

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

80.53
src/main/java/com/knowledgepixels/nanodash/QueryApiAccess.java
1
package com.knowledgepixels.nanodash;
2

3
import org.apache.commons.lang3.tuple.Pair;
4
import org.eclipse.rdf4j.model.IRI;
5
import org.nanopub.extra.services.APINotReachableException;
6
import org.nanopub.extra.services.ApiResponse;
7
import org.nanopub.extra.services.FailedApiCallException;
8
import org.nanopub.extra.services.NotEnoughAPIInstancesException;
9
import org.nanopub.extra.services.QueryAccess;
10
import org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
12

13
import java.util.HashMap;
14
import java.util.Map;
15
import java.util.concurrent.ConcurrentHashMap;
16
import java.util.concurrent.ConcurrentMap;
17

18
/**
19
 * Utility class for accessing and managing API queries.
20
 * Provides methods to retrieve query results, manage query IDs, and fetch the latest versions of nanopublications.
21
 */
22
public class QueryApiAccess {
23

24
    private QueryApiAccess() {
25
    }  // no instances allowed
26

27
    private static ConcurrentMap<String, String> queryIds = new ConcurrentHashMap<>();
4✔
28
    private static final Logger logger = LoggerFactory.getLogger(QueryApiAccess.class);
3✔
29

30
    private static ConcurrentMap<String, Pair<Long, String>> latestVersionMap = new ConcurrentHashMap<>();
4✔
31

32
    private static final String queryIriPattern = "^(.*[^A-Za-z0-9-_])(RA[A-Za-z0-9-_]{43})[/#]([^/#]+)$";
33

34
    static {
35
        // TODO Load this dynamically somehow at some point:
36
        load("RAe-oA5eSmkCXCALZ99-0k4imnlI74KPqURfhHOmnzo6A/get-latest-nanopubs-from-pubkeys");
2✔
37
        load("RAuy4N1h4vZ1wgBUMvTiWw2y_Y0_5oFYRTwdq-xj2qqNM/get-latest-nanopubs-from-userid");
2✔
38
        load("RAZbyFSenuKSRMLGlRfrbeu6vQ6g2IEECYZ2zSGcIBIhQ/get-accepted-nanopubs-by-author");
2✔
39
        load("RAiCBvPL2hRGzI8g5L68O-C9yEXryC_vG35GdEm5jtH_s/get-user-stats-from-pubkeys");  // Deactivated for now...
2✔
40
        load("RA3U23LL3xbNwsu92fAqsKb0kagOud4f9TlRQq3evNJck/get-user-stats-from-userid");  // Deactivated for now...
2✔
41
        load("RAcNvmEiUNUb2a7O4fwRvy2x2BCN640AC880fTzFworr8/get-top-creators-last30d");
2✔
42
        load("RAr27GmRUKQmvPbfmB34N9l9lX-xYK7nQhvOMbQCk3byI/get-latest-users");
2✔
43
        //load("RAmhy4KQe6I80bA2Da4JziYyKBoXuXIzqo57GDSVgLfDg/get-top-authors");
44
        load("RAYNg6rfvXIVvJY2u8oS0EEjxnVvimLLVZG1rOar_nWIY/get-most-recent-nanopubs");
2✔
45
        load("RA52cg2OzJucmpCb7KSKTgfPV5HKIjsFcmww_rxb7v5zU/get-latest-accepted");
2✔
46
        load("RAPGhXDRzeGu-Qk0AkjleEtxMxqAvJ-dZn7985gzAbyhs/get-publisher-version");
2✔
47
        load("RAvL7pe2ppsfq4mVWTdJjssYGsjrmliNd_sZO2ytLvg1Y/get-most-used-templates-last30d");
2✔
48
        load("RANn4Mu8r8bqJA9KJMGXTQAEGAEvtNKGFsuhRIC6BRIOo/get-latest-nanopubs-by-type");
2✔
49
        load("RAiRsB2YywxjsBMkVRTREJBooXhf2ZOHoUs5lxciEl37I/get-latest-version-of-np");
2✔
50
        load("RA0aZxyh_I0rCJyBepXOWC2tGdI5YYHORFCC-qBR8xHZA/get-all-user-intros");
2✔
51
        load("RA-tlMmQA7iT2wR2aS3PlONrepX7vdXbkzeWluea7AECg/get-suggested-templates-to-get-started");
2✔
52
        load("RActSoHqt-TlpCOldqLb9skfMioVxHzCZUYaNEM06FTsY/get-type-overview-last-12-months");
2✔
53
        load("RAn3agwsH2yk-8132RJApGYxdPSHHCXDAIYiCaSBBo6tg/get-approved-nanopubs");
2✔
54
        load("RAz1ogtMxSTKSOYwHAfD5M3Y-vd1vd46OZta_vvbqh8kY/find-uri-references");
2✔
55
        load("RAE35dYJQlpnqim7VeKuu07E9I1LQUZpkdYQR4RvU3KMU/get-nanopubs-by-type");
2✔
56
        load("RALZXWg5lZoJoQ0VHL5mpDgNxYpqU6FoDLWGp4rs8A6b8/get-introducing-nanopub");
2✔
57
        load("RAWruhiSmyzgZhVRs8QY8YQPAgHzTfl7anxII1de-yaCs/fulltext-search-on-labels");
2✔
58
        load("RAyMrQ89RECTi9gZK5q7gjL1wKTiP8StkLy0NIkkCiyew/find-things");
2✔
59
        load("RAjt1H9rCSr6A9VGzlhye00zPdH69JdGc3kd_2VjDmzVg/get-instances");
2✔
60
        load("RAH06iUwnvj_pRARY15ayJAY5tuJau3rCvHhPPhe49fVI/get-classes-for-thing");
2✔
61
        load("RAJStXEm1wZcg34ZLPqe00VPSzIVCwC2rrxdj_JR8v5DY/find-referencing-nanopubs");  // not yet used...
2✔
62
        load("RAtftxAXJubB4rlm9fOvvHNVIkXvWQLC6Ag_MiV7HL0ow/get-labels-for-thing");  // not yet used...
2✔
63
        load("RARtWHRzNY5hh31X2VB5eOCJAdp9Cjv4CakA0Idqz69MI/get-templates-with-uri");
2✔
64
        load("RAIn9NTsWE0qrpKiK3nOmZRXVzwv0qnfbm7dR_CUnp4aA/get-newer-versions-of-np");
2✔
65
        load("RAQqjXQYlxYQeI4Y3UQy9OrD5Jx1E3PJ8KwKKQlWbiYSw/get-queries");
2✔
66
        load("RAzXDzCHoZmJITgYYquLwDDkSyNf3eKKQz9NfQPYB1cyE/get-latest-thing-nanopub");
2✔
67
        load("RAnpimW7SPwaum2fefdS6_jpzYxcTRGjE-pmgNTL_BBJU/get-projects");
2✔
68
        load("RAlPzIqHJsPt33WuPNBIyPDr8KC7htHO9UYvSuYOfTjwo/get-spaces");
2✔
69
        load("RAJmZoM0xCGE8OL6EgmQBOd1M58ggNkwZ0IUqHOAPRfvE/get-parts");
2✔
70
        load("RA6bgrU3Ezfg5VAiLru0BFYHaSj6vZU6jJTscxNl8Wqvc/get-assertion-templates");
2✔
71
        load("RA4bt3MQRnEPC2nSsdbCJc74wT-e1w68dSCpYVyvG0274/get-provenance-templates");
2✔
72
        load("RAMcdiJpvvk8424AJIH1jsDUQVcPYOLRw0DNnZt_ND_LQ/get-pubinfo-templates");
2✔
73
        load("RApiw7Z0NeP3RaLiqX6Q7Ml5CfEWbt-PysUbMNljuiLJw/get-owners");
2✔
74
        load("RAYI6_CkA7nY58hCGx3nbBncBWXle1azhVqBnNPCpw_R8/get-admins");
2✔
75
        load("RASyFJyADTtG-l_Qe3a5PE_e2yUJR-PydXfkZjjrBuV7U/get-members");
2✔
76
        load("RAbq1a1FwRFAZPDde3Sy4GqNUQ2TmaKOWLydJPOyCKc0w/get-filtered-nanopub-list");
2✔
77
        load("RAa2949qM3veXzp6rWoW-KNLSEbKOenMR9z3w9qQ48VsM/get-pinned-templates");
2✔
78
        load("RAdyYeWRfQl8TecahiU77iVStCcESf90HR_9pr2EJP4FE/get-pinned-queries");
2✔
79
    }
1✔
80

81
    /**
82
     * Loads a query ID into the queryIds map.
83
     *
84
     * @param queryId The query ID to load.
85
     */
86
    static void load(String queryId) {
87
        queryIds.put(queryId.substring(46), queryId);
7✔
88
    }
1✔
89

90
    /**
91
     * Forces the retrieval of an API response for a given query name and parameters.
92
     * Retries until a valid response is received.
93
     *
94
     * @param queryName The name of the query.
95
     * @return The API response.
96
     */
97
    public static ApiResponse forcedGet(String queryName) {
98
        return forcedGet(queryName, new HashMap<>());
6✔
99
    }
100

101
    /**
102
     * Forces the retrieval of an API response for a given query name and a single parameter.
103
     * Retries until a valid response is received.
104
     *
105
     * @param queryName  The name of the query.
106
     * @param paramKey   The key of the parameter.
107
     * @param paramValue The value of the parameter.
108
     * @return The API response.
109
     */
110
    public static ApiResponse forcedGet(String queryName, String paramKey, String paramValue) {
111
        Map<String, String> params = new HashMap<>();
×
112
        params.put(paramKey, paramValue);
×
113
        return forcedGet(queryName, params);
×
114
    }
115

116
    /**
117
     * Forces the retrieval of an API response for a given query name and parameters.
118
     * Retries until a valid response is received.
119
     *
120
     * @param queryName The name of the query.
121
     * @param params    The parameters for the query.
122
     * @return The API response.
123
     */
124
    public static ApiResponse forcedGet(String queryName, Map<String, String> params) {
125
        while (true) {
126
            ApiResponse resp = null;
2✔
127
            try {
128
                resp = QueryApiAccess.get(queryName, params);
4✔
129
            } catch (Exception ex) {
×
130
                // TODO We should be more specific about which exceptions we catch here
131
                //      and generally improve this, as this could hang forever.
132
                logger.error("Error while forcing API get for query '{}' with params {}", queryName, params, ex);
×
133
            }
1✔
134
            if (resp != null) return resp;
4✔
135
            try {
136
                Thread.sleep(100);
2✔
137
            } catch (InterruptedException ex) {
×
138
                logger.error("Interrupted while forcing API get for query '{}' with params {}", queryName, params, ex);
×
139
            }
1✔
140
        }
1✔
141
    }
142

143
    /**
144
     * Retrieves an API response for a given query name.
145
     *
146
     * @param queryName The name of the query.
147
     * @return The API response.
148
     * @throws org.nanopub.extra.services.FailedApiCallException If the API call fails.
149
     */
150
    public static ApiResponse get(String queryName) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
151
        return get(queryName, new HashMap<>());
6✔
152
    }
153

154
    /**
155
     * Retrieves an API response for a given query name and a single parameter.
156
     *
157
     * @param queryName  The name of the query.
158
     * @param paramKey   The key of the parameter.
159
     * @param paramValue The value of the parameter.
160
     * @return The API response.
161
     * @throws org.nanopub.extra.services.FailedApiCallException If the API call fails.
162
     */
163
    public static ApiResponse get(String queryName, String paramKey, String paramValue) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
164
        Map<String, String> params = new HashMap<>();
×
165
        params.put(paramKey, paramValue);
×
166
        return get(queryName, params);
×
167
    }
168

169
    /**
170
     * Retrieves an API response for a given query name and parameters.
171
     *
172
     * @param queryName The name of the query.
173
     * @param params    The parameters for the query.
174
     * @return The API response.
175
     * @throws org.nanopub.extra.services.FailedApiCallException If the API call fails.
176
     */
177
    public static ApiResponse get(String queryName, Map<String, String> params) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
178
        String queryId;
179
        if (queryName.matches("^RA[A-Za-z0-9-_]{43}/.*$")) {
4✔
180
            queryId = queryName;
3✔
181
        } else if (queryIds.containsKey(queryName)) {
4✔
182
            queryId = queryIds.get(queryName);
6✔
183
        } else {
184
            throw new IllegalArgumentException("Query name not known: " + queryName);
6✔
185
        }
186
        return QueryAccess.get(queryId, params);
4✔
187
    }
188

189
    /**
190
     * Retrieves the latest version ID of a given nanopublication.
191
     *
192
     * @param nanopubId The ID of the nanopublication.
193
     * @return The latest version ID.
194
     */
195
    public static String getLatestVersionId(String nanopubId) {
196
        long currentTime = System.currentTimeMillis();
2✔
197
        if (!latestVersionMap.containsKey(nanopubId) || currentTime - latestVersionMap.get(nanopubId).getLeft() > 1000 * 60) {
16!
198
            // Re-fetch if existing value is older than 1 minute
199
            Map<String, String> params = new HashMap<>();
4✔
200
            params.put("np", nanopubId);
5✔
201
            try {
202
                ApiResponse r = get("get-latest-version-of-np", params);
4✔
203
                if (r.getData().size() != 1) return nanopubId;
5!
204
                String l = r.getData().get(0).get("latest");
8✔
205
                latestVersionMap.put(nanopubId, Pair.of(currentTime, l));
8✔
206
            } catch (Exception ex) {
×
207
                logger.error("Error while getting latest version of nanopub '{}'", nanopubId, ex);
×
208
                return nanopubId;
×
209
            }
1✔
210
        }
211
        return latestVersionMap.get(nanopubId).getRight();
7✔
212
    }
213

214
    /**
215
     * Extracts the query ID from a given query IRI.
216
     *
217
     * @param queryIri The query IRI.
218
     * @return The query ID, or null if the IRI is invalid.
219
     */
220
    public static String getQueryId(IRI queryIri) {
221
        if (queryIri == null) return null;
×
222
        if (!queryIri.stringValue().matches(queryIriPattern)) return null;
×
223
        return queryIri.stringValue().replaceFirst(queryIriPattern, "$2/$3");
×
224
    }
225

226
    /**
227
     * Retrieves the query ID for a given query name.
228
     *
229
     * @param queryName The name of the query.
230
     * @return The query ID, or null if the query name is unknown.
231
     */
232
    public static String getQueryId(String queryName) {
233
        return queryIds.get(queryName);
5✔
234
    }
235

236
    /**
237
     * Extracts the query name from a given query IRI.
238
     *
239
     * @param queryIri The query IRI.
240
     * @return The query name, or null if the IRI is invalid.
241
     */
242
    public static String getQueryName(IRI queryIri) {
243
        if (queryIri == null) return null;
4✔
244
        if (!queryIri.stringValue().matches(queryIriPattern)) return null;
7✔
245
        return queryIri.stringValue().replaceFirst(queryIriPattern, "$3");
6✔
246
    }
247

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