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

knowledgepixels / nanodash / 17424747928

03 Sep 2025 06:13AM UTC coverage: 12.048% (-0.02%) from 12.066%
17424747928

push

github

tkuhn
Update dependencies and adapt to new exceptions in nanopub-java

331 of 3866 branches covered (8.56%)

Branch coverage included in aggregate %.

967 of 6908 relevant lines covered (14.0%)

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

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

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

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

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