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

knowledgepixels / nanodash / 17581574457

09 Sep 2025 11:47AM UTC coverage: 13.561% (-0.04%) from 13.601%
17581574457

push

github

tkuhn
Add QueryRef convenience class

406 of 3856 branches covered (10.53%)

Branch coverage included in aggregate %.

1070 of 7028 relevant lines covered (15.22%)

0.68 hits per line

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

0.0
src/main/java/com/knowledgepixels/nanodash/ApiCache.java
1
package com.knowledgepixels.nanodash;
2

3
import org.nanopub.extra.services.APINotReachableException;
4
import org.nanopub.extra.services.ApiResponse;
5
import org.nanopub.extra.services.ApiResponseEntry;
6
import org.nanopub.extra.services.FailedApiCallException;
7
import org.nanopub.extra.services.NotEnoughAPIInstancesException;
8
import org.slf4j.Logger;
9
import org.slf4j.LoggerFactory;
10

11
import java.util.*;
12
import java.util.concurrent.ConcurrentHashMap;
13
import java.util.concurrent.ConcurrentMap;
14

15
/**
16
 * A utility class for caching API responses and maps to reduce redundant API calls.
17
 * This class is thread-safe and ensures that cached data is refreshed periodically.
18
 */
19
public class ApiCache {
20

21
    private ApiCache() {
22
    } // no instances allowed
23

24
    private transient static ConcurrentMap<String, ApiResponse> cachedResponses = new ConcurrentHashMap<>();
×
25
    private transient static ConcurrentMap<String, Map<String, String>> cachedMaps = new ConcurrentHashMap<>();
×
26
    private transient static ConcurrentMap<String, Long> lastRefresh = new ConcurrentHashMap<>();
×
27
    private transient static ConcurrentMap<String, Long> refreshStart = new ConcurrentHashMap<>();
×
28
    private static final Logger logger = LoggerFactory.getLogger(ApiCache.class);
×
29

30
    /**
31
     * Checks if a cache refresh is currently running for the given cache ID.
32
     *
33
     * @param cacheId The unique identifier for the cache.
34
     * @return True if a refresh is running, false otherwise.
35
     */
36
    private static boolean isRunning(String cacheId) {
37
        if (!refreshStart.containsKey(cacheId)) return false;
×
38
        return System.currentTimeMillis() - refreshStart.get(cacheId) < 60 * 1000;
×
39
    }
40

41
    /**
42
     * Checks if a cache refresh is running for a specific query and parameters.
43
     *
44
     * @param queryName The name of the query.
45
     * @param params    The parameters for the query.
46
     * @return True if a refresh is running, false otherwise.
47
     */
48
    public static boolean isRunning(String queryName, Map<String, String> params) {
49
        return isRunning(getCacheId(queryName, params));
×
50
    }
51

52
    /**
53
     * Checks if a cache refresh is running for a specific query and a single parameter.
54
     *
55
     * @param queryName  The name of the query.
56
     * @param paramName  The name of the parameter.
57
     * @param paramValue The value of the parameter.
58
     * @return True if a refresh is running, false otherwise.
59
     */
60
    public static boolean isRunning(String queryName, String paramName, String paramValue) {
61
        Map<String, String> params = new HashMap<>();
×
62
        params.put(paramName, paramValue);
×
63
        return isRunning(getCacheId(queryName, params));
×
64
    }
65

66
    /**
67
     * Updates the cached API response for a specific query and parameters.
68
     *
69
     * @param queryName The name of the query.
70
     * @param params    The parameters for the query.
71
     * @throws FailedApiCallException If the API call fails.
72
     */
73
    private static void updateResponse(String queryName, Map<String, String> params) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
74
        Map<String, String> nanopubParams = new HashMap<>();
×
75
        for (String k : params.keySet()) nanopubParams.put(k, params.get(k));
×
76
        ApiResponse response = QueryApiAccess.get(queryName, nanopubParams);
×
77
        String cacheId = getCacheId(queryName, params);
×
78
        cachedResponses.put(cacheId, response);
×
79
        lastRefresh.put(cacheId, System.currentTimeMillis());
×
80
    }
×
81

82
    /**
83
     * Retrieves a cached API response for a specific query and a single parameter.
84
     *
85
     * @param queryName  The name of the query.
86
     * @param paramName  The name of the parameter.
87
     * @param paramValue The value of the parameter.
88
     * @return The cached API response, or null if not cached.
89
     */
90
    public static ApiResponse retrieveResponse(String queryName, String paramName, String paramValue) {
91
        Map<String, String> params = new HashMap<>();
×
92
        params.put(paramName, paramValue);
×
93
        return retrieveResponse(queryName, params);
×
94
    }
95

96
    public static ApiResponse retrieveResponse(QueryRef queryRef) {
97
        return retrieveResponse(queryRef.getName(), queryRef.getParams());
×
98
    }
99

100
    /**
101
     * Retrieves a cached API response for a specific query and parameters.
102
     * If the cache is stale, it triggers a background refresh.
103
     *
104
     * @param queryName The name of the query.
105
     * @param params    The parameters for the query.
106
     * @return The cached API response, or null if not cached.
107
     */
108
    public static synchronized ApiResponse retrieveResponse(final String queryName, final Map<String, String> params) {
109
        long timeNow = System.currentTimeMillis();
×
110
        String cacheId = getCacheId(queryName, params);
×
111
        boolean isCached = false;
×
112
        boolean needsRefresh = true;
×
113
        if (cachedResponses.containsKey(cacheId) && cachedResponses.get(cacheId) != null) {
×
114
            long cacheAge = timeNow - lastRefresh.get(cacheId);
×
115
            isCached = cacheAge < 24 * 60 * 60 * 1000;
×
116
            needsRefresh = cacheAge > 60 * 1000;
×
117
        }
118
        if (needsRefresh && !isRunning(cacheId)) {
×
119
            refreshStart.put(cacheId, timeNow);
×
120
            new Thread(() -> {
×
121
                try {
122
                    Thread.sleep(100 + new Random().nextLong(400));
×
123
                } catch (InterruptedException ex) {
×
124
                    logger.error("Interrupted while waiting to refresh cache: {}", ex.getMessage());
×
125
                }
×
126
                try {
127
                    ApiCache.updateResponse(queryName, params);
×
128
                } catch (Exception ex) {
×
129
                    logger.error("Failed to update cache for {}: {}", cacheId, ex.getMessage());
×
130
                    cachedResponses.put(cacheId, null);
×
131
                    lastRefresh.put(cacheId, System.currentTimeMillis());
×
132
                } finally {
133
                    refreshStart.remove(cacheId);
×
134
                }
135
            }).start();
×
136
        }
137
        if (isCached) {
×
138
            if (cachedResponses.get(cacheId) == null) {
×
139
                cachedResponses.remove(cacheId);
×
140
                throw new RuntimeException("Query failed: " + cacheId);
×
141
            }
142
            return cachedResponses.get(cacheId);
×
143
        } else {
144
            return null;
×
145
        }
146
    }
147

148
    /**
149
     * Updates the cached map for a specific query and parameters.
150
     *
151
     * @param queryName The name of the query.
152
     * @param params    The parameters for the query.
153
     * @throws FailedApiCallException If the API call fails.
154
     */
155
    private static void updateMap(String queryName, Map<String, String> params) throws FailedApiCallException, APINotReachableException, NotEnoughAPIInstancesException {
156
        Map<String, String> map = new HashMap<>();
×
157
        Map<String, String> nanopubParams = new HashMap<>();
×
158
        for (String k : params.keySet()) nanopubParams.put(k, params.get(k));
×
159
        List<ApiResponseEntry> respList = QueryApiAccess.get(queryName, nanopubParams).getData();
×
160
        while (respList != null && !respList.isEmpty()) {
×
161
            ApiResponseEntry resultEntry = respList.remove(0);
×
162
            map.put(resultEntry.get("key"), resultEntry.get("value"));
×
163
        }
×
164
        String cacheId = getCacheId(queryName, params);
×
165
        cachedMaps.put(cacheId, map);
×
166
        lastRefresh.put(cacheId, System.currentTimeMillis());
×
167
    }
×
168

169
    /**
170
     * Retrieves a cached map for a specific query and parameters.
171
     * If the cache is stale, it triggers a background refresh.
172
     *
173
     * @param queryName The name of the query.
174
     * @param params    The parameters for the query.
175
     * @return The cached map, or null if not cached.
176
     */
177
    public static synchronized Map<String, String> retrieveMap(String queryName, Map<String, String> params) {
178
        long timeNow = System.currentTimeMillis();
×
179
        String cacheId = getCacheId(queryName, params);
×
180
        boolean isCached = false;
×
181
        boolean needsRefresh = true;
×
182
        if (cachedMaps.containsKey(cacheId)) {
×
183
            long cacheAge = timeNow - lastRefresh.get(cacheId);
×
184
            isCached = cacheAge < 24 * 60 * 60 * 1000;
×
185
            needsRefresh = cacheAge > 60 * 1000;
×
186
        }
187
        if (needsRefresh && !isRunning(cacheId)) {
×
188
            refreshStart.put(cacheId, timeNow);
×
189
            new Thread(() -> {
×
190
                try {
191
                    Thread.sleep(100 + new Random().nextLong(400));
×
192
                } catch (InterruptedException ex) {
×
193
                    logger.error("Interrupted while waiting to refresh cache: {}", ex.getMessage());
×
194
                }
×
195
                try {
196
                    ApiCache.updateMap(queryName, params);
×
197
                } catch (Exception ex) {
×
198
                    logger.error("Failed to update cache for {}: {}", cacheId, ex.getMessage());
×
199
                    cachedResponses.put(cacheId, null);
×
200
                    lastRefresh.put(cacheId, System.currentTimeMillis());
×
201
                } finally {
202
                    refreshStart.remove(cacheId);
×
203
                }
204
            }).start();
×
205
        }
206
        if (isCached) {
×
207
            if (cachedResponses.get(cacheId) == null) {
×
208
                cachedResponses.remove(cacheId);
×
209
                throw new RuntimeException("Query failed: " + cacheId);
×
210
            }
211
            return cachedMaps.get(cacheId);
×
212
        } else {
213
            return null;
×
214
        }
215
    }
216

217
    /**
218
     * Converts a map of parameters to a sorted string representation.
219
     *
220
     * @param params The map of parameters.
221
     * @return A string representation of the parameters.
222
     */
223
    private static String paramsToString(Map<String, String> params) {
224
        List<String> keys = new ArrayList<>(params.keySet());
×
225
        Collections.sort(keys);
×
226
        String s = "";
×
227
        for (String k : keys) s += " " + k + "=" + params.get(k);
×
228
        return s;
×
229
    }
230

231
    /**
232
     * Generates a unique cache ID for a specific query and parameters.
233
     *
234
     * @param queryName The name of the query.
235
     * @param params    The parameters for the query.
236
     * @return The unique cache ID.
237
     */
238
    public static String getCacheId(String queryName, Map<String, String> params) {
239
        return queryName + " " + paramsToString(params);
×
240
    }
241
}
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