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

knowledgepixels / nanopub-query / 17760712547

16 Sep 2025 09:07AM UTC coverage: 73.984% (-2.0%) from 75.992%
17760712547

push

github

tkuhn
feat: Add /apix/ handling to bypass grlc service (some issues remain)

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
 * Main verticle that coordinates the incoming HTTP requests.
45
 */
46
@GeneratedFlagForDependentElements
47
public class MainVerticle extends AbstractVerticle {
48

49
    private static String css = null;
50

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

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

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

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

89
        rdf4jProxy.addInterceptor(new ProxyInterceptor() {
×
90

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

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

119
        });
120
        // ----------
121

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

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

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

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

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

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

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

366
        });
367

368
        HttpProxy grlcxProxy = HttpProxy.reverseProxy(httpClient);
369
        grlcxProxy.origin(proxyPort, proxy);
370

371
        grlcxProxy.addInterceptor(new ProxyInterceptor() {
×
372

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

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

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

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

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

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

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

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

420

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

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

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

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

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

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