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

knowledgepixels / nanopub-query / 17760762297

16 Sep 2025 09:09AM UTC coverage: 73.984%. Remained the same
17760762297

push

github

tkuhn
chore: Add TODO item

234 of 334 branches covered (70.06%)

Branch coverage included in aggregate %.

585 of 773 relevant lines covered (75.68%)

3.82 hits per line

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

0.0
src/main/java/com/knowledgepixels/query/MainVerticle.java
1
package com.knowledgepixels.query;
2

3
import java.io.InputStream;
4
import java.net.URLEncoder;
5
import java.util.ArrayList;
6
import java.util.Collections;
7
import java.util.List;
8
import java.util.Map.Entry;
9
import java.util.Scanner;
10
import java.util.concurrent.Executors;
11
import java.util.concurrent.TimeUnit;
12

13
import org.eclipse.rdf4j.model.Value;
14

15
import com.github.jsonldjava.shaded.com.google.common.base.Charsets;
16

17
import io.micrometer.prometheus.PrometheusMeterRegistry;
18
import io.vertx.core.AbstractVerticle;
19
import io.vertx.core.Future;
20
import io.vertx.core.MultiMap;
21
import io.vertx.core.Promise;
22
import io.vertx.core.buffer.Buffer;
23
import io.vertx.core.http.HttpClient;
24
import io.vertx.core.http.HttpClientOptions;
25
import io.vertx.core.http.HttpMethod;
26
import io.vertx.core.http.HttpServer;
27
import io.vertx.core.http.HttpServerResponse;
28
import io.vertx.core.http.PoolOptions;
29
import io.vertx.ext.web.Router;
30
import io.vertx.ext.web.RoutingContext;
31
import io.vertx.ext.web.handler.CorsHandler;
32
import io.vertx.ext.web.handler.StaticHandler;
33
import io.vertx.ext.web.proxy.handler.ProxyHandler;
34
import io.vertx.httpproxy.Body;
35
import io.vertx.httpproxy.HttpProxy;
36
import io.vertx.httpproxy.ProxyContext;
37
import io.vertx.httpproxy.ProxyInterceptor;
38
import io.vertx.httpproxy.ProxyRequest;
39
import io.vertx.httpproxy.ProxyResponse;
40
import io.vertx.micrometer.PrometheusScrapingHandler;
41
import io.vertx.micrometer.backends.BackendRegistries;
42

43

44
// TODO merge this class with GrlcQuery of Nanodash and move to a library like nanopub-java
45
/**
46
 * Main verticle that coordinates the incoming HTTP requests.
47
 */
48
@GeneratedFlagForDependentElements
49
public class MainVerticle extends AbstractVerticle {
50

51
    private static String css = null;
52

53
    /**
54
     * Start the main verticle.
55
     *
56
     * @param startPromise the promise to complete when the verticle is started
57
     * @throws Exception if an error occurs during startup
58
     */
59
    @Override
60
    public void start(Promise<Void> startPromise) throws Exception {
61
        HttpClient httpClient = vertx.createHttpClient(
62
                new HttpClientOptions()
63
                        .setConnectTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_CONNECT_TIMEOUT", 1000))
64
                        .setIdleTimeoutUnit(TimeUnit.SECONDS)
65
                        .setIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
66
                        .setReadIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60))
67
                        .setWriteIdleTimeout(Utils.getEnvInt("NANOPUB_QUERY_VERTX_IDLE_TIMEOUT", 60)),
68
                new PoolOptions().setHttp1MaxSize(200).setHttp2MaxSize(200)
69
        );
70

71
        HttpServer proxyServer = vertx.createHttpServer();
72
        Router proxyRouter = Router.router(vertx);
73
        proxyRouter.route().handler(CorsHandler.create().addRelativeOrigin(".*"));
74

75
        // Metrics
76
        final var metricsHttpServer = vertx.createHttpServer();
77
        final var metricsRouter = Router.router(vertx);
78
        metricsHttpServer.requestHandler(metricsRouter).listen(9394);
79

80
        final var metricsRegistry = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
81
        final var collector = new MetricsCollector(metricsRegistry);
82
        metricsRouter.route("/metrics").handler(PrometheusScrapingHandler.create(metricsRegistry));
83
        // ----------
84
        // This part is only used if the redirection is not done through Nginx.
85
        // See nginx.conf and this bug report: https://github.com/eclipse-rdf4j/rdf4j/discussions/5120
86
        HttpProxy rdf4jProxy = HttpProxy.reverseProxy(httpClient);
87
        String proxy = Utils.getEnvString("RDF4J_PROXY_HOST", "rdf4j");
88
        int proxyPort = Utils.getEnvInt("RDF4J_PROXY_PORT", 8080);
89
        rdf4jProxy.origin(proxyPort, proxy);
90

91
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
92

93
            @Override
94
            @GeneratedFlagForDependentElements
95
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
96
                ProxyRequest request = context.request();
97
                request.setURI(request.getURI().replaceAll("/", "_").replaceFirst("^_repo_", "/rdf4j-server/repositories/"));
98
                // For later to try to get HTML tables out:
99
//                                if (request.headers().get("Accept") == null) {
100
//                                        request.putHeader("Accept", "text/html");
101
//                                }
102
//                                request.putHeader("Accept", "application/json");
103
                return ProxyInterceptor.super.handleProxyRequest(context);
104
            }
105

106
            @Override
107
            @GeneratedFlagForDependentElements
108
            public Future<Void> handleProxyResponse(ProxyContext context) {
109
                ProxyResponse resp = context.response();
110
                resp.putHeader("Access-Control-Allow-Origin", "*");
111
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
112
                // For later to try to get HTML tables out:
113
//                                String acceptHeader = context.request().headers().get("Accept");
114
//                                if (acceptHeader != null && acceptHeader.contains("text/html")) {
115
//                                        resp.putHeader("Content-Type", "text/html");
116
//                                        resp.setBody(Body.body(Buffer.buffer("<html><body><strong>test</strong></body></html>")));
117
//                                }
118
                return ProxyInterceptor.super.handleProxyResponse(context);
119
            }
120

121
        });
122
        // ----------
123

124
        proxyRouter.route(HttpMethod.GET, "/repo").handler(req -> handleRedirect(req, "/repo"));
125
        proxyRouter.route(HttpMethod.GET, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
126
        proxyRouter.route(HttpMethod.POST, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
127
        proxyRouter.route(HttpMethod.HEAD, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
128
        proxyRouter.route(HttpMethod.OPTIONS, "/repo/*").handler(ProxyHandler.create(rdf4jProxy));
129
        proxyRouter.route(HttpMethod.GET, "/tools/*").handler(req -> {
130
            final String yasguiPattern = "^/tools/([a-zA-Z0-9-_]+)(/([a-zA-Z0-9-_]+))?/yasgui\\.html$";
131
            if (req.normalizedPath().matches(yasguiPattern)) {
132
                String repo = req.normalizedPath().replaceFirst(yasguiPattern, "$1$2");
133
                req.response()
134
                        .putHeader("content-type", "text/html")
135
                        .end("<!DOCTYPE html>\n"
136
                                + "<html lang=\"en\">\n"
137
                                + "<head>\n"
138
                                + "<meta charset=\"utf-8\">\n"
139
                                + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
140
                                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
141
                                + "<title>Nanopub Query SPARQL Editor for repository: " + repo + "</title>\n"
142
                                + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
143
                                + "<link href='https://cdn.jsdelivr.net/yasgui/2.6.1/yasgui.min.css' rel='stylesheet' type='text/css'/>\n"
144
                                + "<style>.yasgui .endpointText {display:none !important;}</style>\n"
145
                                + "<script type=\"text/javascript\">localStorage.clear();</script>\n"
146
                                + "</head>\n"
147
                                + "<body>\n"
148
                                + "<h3>Nanopub Query SPARQL Editor for repository: " + repo + "</h3>\n"
149
                                + "<div id='yasgui'></div>\n"
150
                                + "<script src='https://cdn.jsdelivr.net/yasgui/2.6.1/yasgui.min.js'></script>\n"
151
                                + "<script type=\"text/javascript\">\n"
152
                                + "var yasgui = YASGUI(document.getElementById(\"yasgui\"), {\n"
153
                                + "  yasqe:{sparql:{endpoint:'/repo/" + repo + "'},value:'" + Utils.defaultQuery.replaceAll("\n", "\\\\n") + "'}\n"
154
                                + "});\n"
155
                                + "</script>\n"
156
                                + "</body>\n"
157
                                + "</html>");
158
            } else {
159
                req.response()
160
                        .putHeader("content-type", "text/plain")
161
                        .setStatusCode(404)
162
                        .end("not found");
163
            }
164
        });
165
        proxyRouter.route(HttpMethod.GET, "/page").handler(req -> handleRedirect(req, "/page"));
166
        proxyRouter.route(HttpMethod.GET, "/page/*").handler(req -> {
167
            final String pagePattern = "^/page/([a-zA-Z0-9-_]+)(/([a-zA-Z0-9-_]+))?$";
168
            if (req.normalizedPath().matches(pagePattern)) {
169
                String repo = req.normalizedPath().replaceFirst(pagePattern, "$1$2");
170
                req.response()
171
                        .putHeader("content-type", "text/html")
172
                        .end("<!DOCTYPE html>\n"
173
                                + "<html lang=\"en\">\n"
174
                                + "<head>\n"
175
                                + "<meta charset=\"utf-8\">\n"
176
                                + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"
177
                                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
178
                                + "<title>Nanopub Query repo: " + repo + "</title>\n"
179
                                + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
180
                                + "</head>\n"
181
                                + "<body>\n"
182
                                + "<h3>Nanopub Query repo: " + repo + "</h3>\n"
183
                                + "<p>Endpoint: <a href=\"/repo/" + repo + "\">/repo/" + repo + "</a></p>"
184
                                + "<p>YASGUI: <a href=\"/tools/" + repo + "/yasgui.html\">/tools/" + repo + "/yasgui.hml</a></p>"
185
                                + "</body>\n"
186
                                + "</html>");
187
            } else {
188
                req.response()
189
                        .putHeader("content-type", "text/plain")
190
                        .setStatusCode(404)
191
                        .end("not found");
192
            }
193
        });
194
        proxyRouter.route(HttpMethod.GET, "/").handler(req -> {
195
            String repos = "";
196
            List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
197
            Collections.sort(repoList);
198
            for (String s : repoList) {
199
                if (s.startsWith("pubkey_") || s.startsWith("type_")) continue;
200
                repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a></code></li>";
201
            }
202
            String pinnedApisValue = Utils.getEnvString("NANOPUB_QUERY_PINNED_APIS", "");
203
            String[] pinnedApis = pinnedApisValue.split(" ");
204
            String pinnedApiLinks = "";
205
            if (!pinnedApisValue.isEmpty()) {
206
                for (String s : pinnedApis) {
207
                    pinnedApiLinks = pinnedApiLinks + "<li><a href=\"openapi/?url=spec/" + s + "%3Fapi-version=latest\">" + s.replaceFirst("^.*/", "") + "</a></li>";
208
                }
209
                pinnedApiLinks = "<p>Pinned APIs:</p>\n" +
210
                        "<ul>\n" +
211
                        pinnedApiLinks +
212
                        "</ul>\n";
213
            }
214
            req.response()
215
                    .putHeader("content-type", "text/html")
216
                    .end("<!DOCTYPE html>\n"
217
                            + "<html lang='en'>\n"
218
                            + "<head>\n"
219
                            + "<title>Nanopub Query</title>\n"
220
                            + "<meta charset='utf-8'>\n"
221
                            + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
222
                            + "</head>\n"
223
                            + "<body>\n"
224
                            + "<h1>Nanopub Query</h1>"
225
                            + "<p>General repos:</p>"
226
                            + "<ul>" + repos + "</ul>"
227
                            + "<p>Specific repos:</p>"
228
                            + "<ul>"
229
                            + "<li><a href=\"/pubkeys\">Pubkey Repos</a></li>"
230
                            + "<li><a href=\"/types\">Type Repos</a></li>"
231
                            + "</ul>"
232
                            + pinnedApiLinks
233
                            + "</body>\n"
234
                            + "</html>");
235
        });
236
        proxyRouter.route(HttpMethod.GET, "/pubkeys").handler(req -> {
237
            String repos = "";
238
            List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
239
            Collections.sort(repoList);
240
            for (String s : repoList) {
241
                if (!s.startsWith("pubkey_")) continue;
242
                String hash = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$2");
243
                Value hashObj = Utils.getObjectForHash(hash);
244
                String label;
245
                if (hashObj == null) {
246
                    label = "";
247
                } else {
248
                    label = " (" + Utils.getShortPubkeyName(hashObj.stringValue()) + ")";
249
                }
250
                s = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$1/$2");
251
                repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a>" + label + "</code></li>";
252
            }
253
            req.response()
254
                    .putHeader("content-type", "text/html")
255
                    .end("<!DOCTYPE html>\n"
256
                            + "<html lang='en'>\n"
257
                            + "<head>\n"
258
                            + "<title>Nanopub Query: Pubkey Repos</title>\n"
259
                            + "<meta charset='utf-8'>\n"
260
                            + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
261
                            + "</head>\n"
262
                            + "<body>\n"
263
                            + "<h3>Pubkey Repos</h3>"
264
                            + "<p>Repos:</p>"
265
                            + "<ul>" + repos + "</ul>"
266
                            + "</body>\n"
267
                            + "</html>");
268
        });
269
        proxyRouter.route(HttpMethod.GET, "/types").handler(req -> {
270
            String repos = "";
271
            List<String> repoList = new ArrayList<>(TripleStore.get().getRepositoryNames());
272
            Collections.sort(repoList);
273
            for (String s : repoList) {
274
                if (!s.startsWith("type_")) continue;
275
                String hash = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$2");
276
                Value hashObj = Utils.getObjectForHash(hash);
277
                String label;
278
                if (hashObj == null) {
279
                    label = "";
280
                } else {
281
                    label = " (" + hashObj.stringValue() + ")";
282
                }
283
                s = s.replaceFirst("^([a-zA-Z0-9-]+)_([a-zA-Z0-9-_]+)$", "$1/$2");
284
                repos += "<li><code><a href=\"/page/" + s + "\">" + s + "</a>" + label + "</code></li>";
285
            }
286
            req.response()
287
                    .putHeader("content-type", "text/html")
288
                    .end("<!DOCTYPE html>\n"
289
                            + "<html lang='en'>\n"
290
                            + "<head>\n"
291
                            + "<title>Nanopub Query: Type Repos</title>\n"
292
                            + "<meta charset='utf-8'>\n"
293
                            + "<link rel=\"stylesheet\" href=\"/style.css\">\n"
294
                            + "</head>\n"
295
                            + "<body>\n"
296
                            + "<h3>Type Repos</h3>"
297
                            + "<p>Repos:</p>"
298
                            + "<ul>" + repos + "</ul>"
299
                            + "</body>\n"
300
                            + "</html>");
301
        });
302
        proxyRouter.route(HttpMethod.GET, "/style.css").handler(req -> {
303
            if (css == null) {
304
                css = getResourceAsString("style.css");
305
            }
306
            req.response().end(css);
307
        });
308

309
        proxyRouter.route(HttpMethod.GET, "/grlc-spec/*").handler(req -> {
310
            GrlcSpec gsp = new GrlcSpec(req.normalizedPath(), req.queryParams());
311
            String spec = gsp.getSpec();
312
            if (spec == null) {
313
                req.response().setStatusCode(404).end("query definition not found / not valid");
314
            } else {
315
                req.response().putHeader("content-type", "text/yaml").end(spec);
316
            }
317
        });
318

319
        proxyRouter.route(HttpMethod.GET, "/openapi/spec/*").handler(req -> {
320
            OpenApiSpecPage osp = new OpenApiSpecPage(req.normalizedPath(), req.queryParams());
321
            String spec = osp.getSpec();
322
            if (spec == null) {
323
                req.response().setStatusCode(404).end("query definition not found / not valid");
324
            } else {
325
                req.response().putHeader("content-type", "text/yaml").end(spec);
326
            }
327
        });
328

329
        proxyRouter.route("/openapi/*").handler(StaticHandler.create("com/knowledgepixels/query/swagger"));
330

331
        HttpProxy grlcProxy = HttpProxy.reverseProxy(httpClient);
332
        grlcProxy.origin(80, "grlc");
333
        grlcProxy.addInterceptor(new ProxyInterceptor() {
×
334

335
            @Override
336
            @GeneratedFlagForDependentElements
337
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
338
                final String apiPattern = "^/api/(RA[a-zA-Z0-9-_]{43})/([a-zA-Z0-9-_]+)([?].*)?$";
339
                if (context.request().getURI().matches(apiPattern)) {
340
                    String artifactCode = context.request().getURI().replaceFirst(apiPattern, "$1");
341
                    String queryName = context.request().getURI().replaceFirst(apiPattern, "$2");
342
                    String grlcUrlParams = "";
343
                    String grlcSpecUrlParams = "";
344
                    MultiMap pm = context.request().proxiedRequest().params();
345
                    for (Entry<String, String> e : pm) {
346
                        if (e.getKey().equals("api-version")) {
347
                            grlcSpecUrlParams += "&" + e.getKey() + "=" + URLEncoder.encode(e.getValue(), Charsets.UTF_8);
348
                        } else {
349
                            grlcUrlParams += "&" + e.getKey() + "=" + URLEncoder.encode(e.getValue(), Charsets.UTF_8);
350
                        }
351
                    }
352
                    String url = "/api-url/" + queryName +
353
                            "?specUrl=" + URLEncoder.encode(GrlcSpec.nanopubQueryUrl + "grlc-spec/" + artifactCode + "/?" +
354
                            grlcSpecUrlParams, Charsets.UTF_8) + grlcUrlParams;
355
                    context.request().setURI(url);
356
                }
357
                return context.sendRequest();
358
            }
359

360
            @Override
361
            @GeneratedFlagForDependentElements
362
            public Future<Void> handleProxyResponse(ProxyContext context) {
363
                // To avoid double entries:
364
                context.response().headers().remove("Access-Control-Allow-Origin");
365
                return context.sendResponse();
366
            }
367

368
        });
369

370
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
371
        grlcxProxy.origin(proxyPort, proxy);
372

373
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
374

375
            @Override
376
            @GeneratedFlagForDependentElements
377
            public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
378
                final ProxyRequest req = context.request();
379
                final String apiPattern = "^/apix/(RA[a-zA-Z0-9-_]{43})/([a-zA-Z0-9-_]+)([?].*)?$";
380
                if (req.getURI().matches(apiPattern)) {
381
                    GrlcSpec grlcSpec = new GrlcSpec(req.getURI(), req.proxiedRequest().params());
382
                    req.setMethod(HttpMethod.POST);
383

384
                    // Variant 1:
385
                    req.putHeader("Content-Type", "application/sparql-query");
386
                    req.setBody(Body.body(Buffer.buffer(grlcSpec.getExpandedQueryContent())));
387
                    // Variant 2:
388
                    //req.putHeader("Content-Type", "application/x-www-form-urlencoded");
389
                    //req.setBody(Body.body(Buffer.buffer("query=" + URLEncoder.encode(grlcSpec.getExpandedQueryContent(), Charsets.UTF_8))));
390

391
                    req.setURI("/rdf4j-server/repositories/" + grlcSpec.getRepoName());
392
                    System.err.println("Forwarding apix request to /rdf4j-server/repositories/" + grlcSpec.getRepoName());
393
                }
394
                return ProxyInterceptor.super.handleProxyRequest(context);
395
            }
396

397
            @Override
398
            @GeneratedFlagForDependentElements
399
            public Future<Void> handleProxyResponse(ProxyContext context) {
400
                System.err.println("Receiving apix response");
401
                ProxyResponse resp = context.response();
402
                resp.putHeader("Access-Control-Allow-Origin", "*");
403
                resp.putHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
404
                return ProxyInterceptor.super.handleProxyResponse(context);
405
            }
406

407
        });
408
        proxyRouter.route(HttpMethod.GET, "/apix/*").handler(ProxyHandler.create(grlcxProxy));
409

410
        proxyServer.requestHandler(req -> {
411
            applyGlobalHeaders(req.response());
412
            proxyRouter.handle(req);
413
        });
414
        proxyServer.listen(9393);
415

416
        proxyRouter.route("/api/*").handler(ProxyHandler.create(grlcProxy));
417
        proxyRouter.route("/static/*").handler(ProxyHandler.create(grlcProxy));
418

419
        // Periodic metrics update
420
        vertx.setPeriodic(1000, id -> collector.updateMetrics());
421

422

423
        new Thread(() -> {
424
            try {
425
                var status = StatusController.get().initialize();
426
                System.err.println("Current state: " + status.state + ", last committed counter: " + status.loadCounter);
427
                if (status.state == StatusController.State.LAUNCHING || status.state == StatusController.State.LOADING_INITIAL) {
428
                    // Do the initial nanopublication loading
429
                    StatusController.get().setLoadingInitial(status.loadCounter);
430
                    // Fall back to local nanopub loading if the local files are present
431
                    if (!LocalNanopubLoader.init()) {
432
                        JellyNanopubLoader.loadInitial(status.loadCounter);
433
                    } else {
434
                        System.err.println("Local nanopublication loading finished");
435
                    }
436
                    StatusController.get().setReady();
437
                } else {
438
                    System.err.println("Initial load is already done");
439
                    StatusController.get().setReady();
440
                }
441
            } catch (Exception ex) {
442
                ex.printStackTrace();
443
                System.err.println("Initial load failed, terminating...");
444
                Runtime.getRuntime().exit(1);
445
            }
446

447
            // Start periodic nanopub loading
448
            System.err.println("Starting periodic nanopub loading...");
449
            var executor = Executors.newSingleThreadScheduledExecutor();
450
            executor.scheduleWithFixedDelay(
451
                    JellyNanopubLoader::loadUpdates,
452
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
453
                    JellyNanopubLoader.UPDATES_POLL_INTERVAL,
454
                    TimeUnit.MILLISECONDS
455
            );
456
        }).start();
457

458
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
459
            try {
460
                System.err.println("Gracefully shutting down...");
461
                TripleStore.get().shutdownRepositories();
462
                vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
463
                System.err.println("Graceful shutdown completed");
464
            } catch (Exception ex) {
465
                System.err.println("Graceful shutdown failed");
466
                ex.printStackTrace();
467
            }
468
        }));
469
    }
470

471
    private String getResourceAsString(String file) {
472
        InputStream is = getClass().getClassLoader().getResourceAsStream("com/knowledgepixels/query/" + file);
473
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
474
            String fileContent = s.hasNext() ? s.next() : "";
475
            return fileContent;
476
        }
477
    }
478

479
    private static void handleRedirect(RoutingContext req, String path) {
480
        String queryString = "";
481
        if (!req.queryParam("query").isEmpty())
482
            queryString = "?query=" + URLEncoder.encode(req.queryParam("query").get(0), Charsets.UTF_8);
483
        if (req.queryParam("for-type").size() == 1) {
484
            String type = req.queryParam("for-type").get(0);
485
            req.response().putHeader("location", path + "/type/" + Utils.createHash(type) + queryString);
486
            req.response().setStatusCode(301).end();
487
        } else if (req.queryParam("for-pubkey").size() == 1) {
488
            String type = req.queryParam("for-pubkey").get(0);
489
            req.response().putHeader("location", path + "/pubkey/" + Utils.createHash(type) + queryString);
490
            req.response().setStatusCode(301).end();
491
        } else if (req.queryParam("for-user").size() == 1) {
492
            String type = req.queryParam("for-user").get(0);
493
            req.response().putHeader("location", path + "/user/" + Utils.createHash(type) + queryString);
494
            req.response().setStatusCode(301).end();
495
        }
496
    }
497

498
    /**
499
     * Apply headers to the response that should be present for all requests.
500
     *
501
     * @param response The response to which the headers should be applied.
502
     */
503
    private static void applyGlobalHeaders(HttpServerResponse response) {
504
        response.putHeader("Nanopub-Query-Status", StatusController.get().getState().state.toString());
505
    }
506
}
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