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

knowledgepixels / nanodash / 20299457275

17 Dec 2025 10:20AM UTC coverage: 14.401% (-0.9%) from 15.279%
20299457275

push

github

tkuhn
fix: Use API result cache for all requests

546 of 5004 branches covered (10.91%)

Branch coverage included in aggregate %.

1496 of 9176 relevant lines covered (16.3%)

2.13 hits per line

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

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

3
import com.google.common.collect.ArrayListMultimap;
4
import com.google.common.collect.Multimap;
5
import com.knowledgepixels.nanodash.*;
6
import com.knowledgepixels.nanodash.component.*;
7
import jakarta.servlet.http.HttpServletRequest;
8
import net.trustyuri.TrustyUriUtils;
9
import org.apache.wicket.RestartResponseException;
10
import org.apache.wicket.markup.html.WebMarkupContainer;
11
import org.apache.wicket.markup.html.basic.Label;
12
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
13
import org.apache.wicket.markup.html.link.ExternalLink;
14
import org.apache.wicket.model.Model;
15
import org.apache.wicket.request.flow.RedirectToUrlException;
16
import org.apache.wicket.request.mapper.parameter.INamedParameters.NamedPair;
17
import org.apache.wicket.request.mapper.parameter.PageParameters;
18
import org.commonjava.mimeparse.MIMEParse;
19
import org.eclipse.rdf4j.model.IRI;
20
import org.eclipse.rdf4j.model.Statement;
21
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
22
import org.eclipse.rdf4j.model.vocabulary.RDF;
23
import org.eclipse.rdf4j.model.vocabulary.SKOS;
24
import org.nanopub.Nanopub;
25
import org.nanopub.NanopubUtils;
26
import org.nanopub.extra.security.SignatureUtils;
27
import org.nanopub.extra.services.ApiResponse;
28
import org.nanopub.extra.services.QueryRef;
29
import org.nanopub.vocabulary.NPX;
30
import org.nanopub.vocabulary.NTEMPLATE;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

34
import java.util.HashMap;
35
import java.util.HashSet;
36
import java.util.Map;
37
import java.util.Set;
38

39
/**
40
 * ExplorePage is a page that allows users to explore a specific Nanopublication or Thing.
41
 */
42
public class ExplorePage extends NanodashPage {
43

44
    private static final Logger logger = LoggerFactory.getLogger(ExplorePage.class);
×
45

46
    /**
47
     * The mount path for this page.
48
     */
49
    public static final String MOUNT_PATH = "/explore";
50

51
    /**
52
     * {@inheritDoc}
53
     */
54
    @Override
55
    public String getMountPath() {
56
        return MOUNT_PATH;
×
57
    }
58

59
    private Nanopub publishedNanopub = null;
×
60

61
    /**
62
     * Constructor for ExplorePage.
63
     *
64
     * @param parameters Page parameters containing the ID of the Nanopublication or Thing to explore.
65
     */
66
    public ExplorePage(final PageParameters parameters) {
67
        super(parameters);
×
68
        add(new Label("publish-confirm-panel").setVisible(false));
×
69
        initPage();
×
70
    }
×
71

72
    public ExplorePage(final Nanopub publishedNanopub, final PageParameters parameters) {
73
        super(parameters.set("id", publishedNanopub.getUri()));
×
74
        this.publishedNanopub = publishedNanopub;
×
75

76
        WebMarkupContainer publishConfirmPanel = new WebMarkupContainer("publish-confirm-panel");
×
77
        final NanodashSession session = NanodashSession.get();
×
78
        boolean hasKnownOwnLocalIntro = session.getLocalIntroCount() > 0;
×
79
        boolean someIntroJustNowPublished = Utils.usesPredicateInAssertion(publishedNanopub, NPX.DECLARED_BY);
×
80
        if (someIntroJustNowPublished) NanodashSession.get().setIntroPublishedNow();
×
81
        boolean lastIntroPublishedMoreThanFiveMinsAgo = session.getTimeSinceLastIntroPublished() > 5 * 60 * 1000;
×
82
        if (!hasKnownOwnLocalIntro && session.hasIntroPublished()) User.refreshUsers();
×
83
        publishConfirmPanel.add(new WebMarkupContainer("missing-intro-warning").setVisible(!hasKnownOwnLocalIntro && lastIntroPublishedMoreThanFiveMinsAgo));
×
84

85
        PageParameters plainLinkParams = new PageParameters();
×
86
        plainLinkParams.set("template", parameters.get("template"));
×
87
        if (!parameters.get("template-version").isEmpty()) {
×
88
            plainLinkParams.set("template-version", parameters.get("template-version"));
×
89
        }
90
        publishConfirmPanel.add(new BookmarkablePageLink<Void>("publish-another-link", PublishPage.class, plainLinkParams));
×
91

92
        PageParameters linkParams = new PageParameters(parameters);
×
93
        linkParams.remove("supersede");
×
94
        linkParams.remove("supersede-a");
×
95
        boolean publishAnotherFilledLinkVisible = false;
×
96
        for (NamedPair n : linkParams.getAllNamed()) {
×
97
            if (n.getKey().matches("(param|prparam|piparam[1-9][0-9]*)_.*")) {
×
98
                publishAnotherFilledLinkVisible = true;
×
99
                break;
×
100
            }
101
        }
×
102
        if (publishAnotherFilledLinkVisible) {
×
103
            publishConfirmPanel.add(new BookmarkablePageLink<Void>("publish-another-filled-link", PublishPage.class, linkParams));
×
104
        } else {
105
            publishConfirmPanel.add(new Label("publish-another-filled-link", "").setVisible(false));
×
106
        }
107
        add(publishConfirmPanel);
×
108

109
        initPage();
×
110
    }
×
111

112
    private void initPage() {
113
        PageParameters parameters = getPageParameters();
×
114

115
        add(new TitleBar("titlebar", this, null));
×
116

117
        String tempRef = parameters.get("id").toString();
×
118
        // Sometimes these Wicket session IDs end up here and they can mess up the query cache:
119
        tempRef = tempRef.replaceFirst(";jsessionid.*$", "");
×
120

121
        String contextId = parameters.get("context").toString("");
×
122
        if (Space.get(contextId) != null) {
×
123
            add(new BookmarkablePageLink<Void>("back-to-context-link", SpacePage.class, new PageParameters().set("id", contextId)).setBody(Model.of("back to " + Space.get(contextId).getLabel())));
×
124
        } else if (MaintainedResource.get(contextId) != null) {
×
125
            add(new BookmarkablePageLink<Void>("back-to-context-link", MaintainedResourcePage.class, new PageParameters().set("id", contextId)).setBody(Model.of("back to " + MaintainedResource.get(contextId).getLabel())));
×
126
        } else if (User.isUser(contextId)) {
×
127
            add(new BookmarkablePageLink<Void>("back-to-context-link", UserPage.class, new PageParameters().set("id", contextId)).setBody(Model.of("back to " + User.getShortDisplayName(Utils.vf.createIRI(contextId)))));
×
128
        } else {
129
            add(new Label("back-to-context-link").setVisible(false));
×
130
        }
131

132
        if (User.getUserData().isUser(tempRef)) {
×
133
            add(new BookmarkablePageLink<Void>("to-specific-page-link", UserPage.class, parameters).setBody(Model.of("go to user page")));
×
134
        } else if (Space.get(tempRef) != null) {
×
135
            add(new BookmarkablePageLink<Void>("to-specific-page-link", SpacePage.class, parameters).setBody(Model.of("go to Space page")));
×
136
        } else {
137
            add(new Label("to-specific-page-link").setVisible(false));
×
138
        }
139

140
        WebMarkupContainer raw = new WebMarkupContainer("raw");
×
141
        add(raw);
×
142

143
        Map<String, String> nanopubParams = new HashMap<>();
×
144
        nanopubParams.put("ref", tempRef);
×
145
        Nanopub np = Utils.getAsNanopub(tempRef);
×
146
        boolean isNanopubId = (np != null);
×
147
        if (isNanopubId) {
×
148
            tempRef = np.getUri().stringValue();
×
149
        }
150
        if (!isNanopubId && tempRef.matches("^(.*[^A-Za-z0-9-_])?RA[A-Za-z0-9-_]{43}[^A-Za-z0-9-_].*$")) {
×
151
            np = Utils.getAsNanopub(tempRef.replaceFirst("^(.*[^A-Za-z0-9-_])?(RA[A-Za-z0-9-_]{43})[^A-Za-z0-9-_].*$", "$2"));
×
152
            if (np != null) {
×
153
                String npId = np.getUri().stringValue();
×
154
                tempRef = npId + tempRef.replaceFirst("^(.*[^A-Za-z0-9-_])?(RA[A-Za-z0-9-_]{43})([^A-Za-z0-9-_].*)$", "$3");
×
155
                Multimap<String, String> params = ArrayListMultimap.create();
×
156
                params.put("thing", tempRef);
×
157
                params.put("np", npId);
×
158
                ApiResponse resp = ApiCache.retrieveResponseSync(new QueryRef("get-latest-thing-nanopub", params), false);
×
159
                if (!resp.getData().isEmpty()) {
×
160
                    // TODO We take the most recent in case more than one latest version exists. Make other latest versions visible too.
161
                    npId = resp.getData().get(0).get("latestVersion");
×
162
                }
163
                np = Utils.getAsNanopub(npId);
×
164
            }
165
        }
166

167
        if (parameters.get("forward-to-part").toString("").equals("true") && !contextId.isEmpty()) {
×
168
            parameters.remove("forward-to-part");
×
169
            Set<IRI> classes = new HashSet<>();
×
170
            if (np != null) {
×
171
                Set<String> introducedIds = NanopubUtils.getIntroducedIriIds(np);
×
172
                if (introducedIds.size() == 1 && introducedIds.iterator().next().equals(tempRef)) {
×
173
                    for (Statement st : np.getAssertion()) {
×
174
                        if (!st.getSubject().stringValue().equals(tempRef)) continue;
×
175
                        if (st.getPredicate().equals(DCTERMS.IS_PART_OF) || st.getPredicate().equals(SKOS.IN_SCHEME)) {
×
176
                            String resourceId = st.getObject().stringValue();
×
177
                            if (MaintainedResource.get(resourceId) == null) continue;
×
178
                            throw new RestartResponseException(ResourcePartPage.class, parameters);
×
179
                        } else if (st.getPredicate().equals(RDF.TYPE) && st.getObject() instanceof IRI objIri) {
×
180
                            classes.add(objIri);
×
181
                        }
182
                    }
×
183
                }
184
            }
185
            // TODO Improve this so we have just one check:
186
            if (Space.get(contextId) != null && Space.get(contextId).appliesTo(tempRef, classes)) {
×
187
                throw new RestartResponseException(ResourcePartPage.class, parameters);
×
188
            } else if (MaintainedResource.get(contextId) != null && MaintainedResource.get(contextId).appliesTo(tempRef, classes)) {
×
189
                throw new RestartResponseException(ResourcePartPage.class, parameters);
×
190
            }
191
            
192
        }
193

194
        if (np == null) {
×
195
            raw.setVisible(false);
×
196
            add(new Label("nanopub-header", ""));
×
197
            add(new Label("nanopub", ""));
×
198
            add(new WebMarkupContainer("use-template").setVisible(false));
×
199
            add(new WebMarkupContainer("run-query").setVisible(false));
×
200
        } else {
201

202
            // Check whether we should redirect to Nanopub Registry for machine-friendly formats:
203
            String mimeType = Utils.TYPE_HTML;
×
204
            try {
205
                HttpServletRequest httpRequest = (HttpServletRequest) getRequest().getContainerRequest();
×
206
                mimeType = MIMEParse.bestMatch(Utils.SUPPORTED_TYPES_LIST, httpRequest.getHeader("Accept"));
×
207
            } catch (Exception ex) {
×
208
                logger.error("Error determining MIME type from Accept header.", ex);
×
209
            }
×
210
            if (!mimeType.equals(Utils.TYPE_HTML)) {
×
211
                logger.info("Non-HTML content type: {}", mimeType);
×
212
                // TODO Make this registry URL configurable/dynamic:
213
                String redirectUrl = Utils.getMainRegistryUrl() + "np/" + TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
×
214
                logger.info("Redirecting to: {}", redirectUrl);
×
215
                throw new RedirectToUrlException(redirectUrl, 302);
×
216
            }
217

218
            String nanopubHeaderLabel = "<h4>%s</h4>";
×
219
            if (isNanopubId) {
×
220
                nanopubHeaderLabel = String.format(nanopubHeaderLabel, "Nanopublication");
×
221
            } else {
222
                nanopubHeaderLabel = String.format(nanopubHeaderLabel, "Minted in Nanopublication");
×
223
            }
224
            add(new Label("nanopub-header", nanopubHeaderLabel).setEscapeModelStrings(false));
×
225
            add(new NanopubItem("nanopub", NanopubElement.get(np)));
×
226
            String url = Utils.getMainRegistryUrl() + "np/" + TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
×
227
            raw.add(new ExternalLink("trig-txt", url + ".trig.txt"));
×
228
            raw.add(new ExternalLink("jsonld-txt", url + ".jsonld.txt"));
×
229
            raw.add(new ExternalLink("nq-txt", url + ".nq.txt"));
×
230
            raw.add(new ExternalLink("xml-txt", url + ".xml.txt"));
×
231
            raw.add(new ExternalLink("trig", url + ".trig"));
×
232
            raw.add(new ExternalLink("jsonld", url + ".jsonld"));
×
233
            raw.add(new ExternalLink("nq", url + ".nq"));
×
234
            raw.add(new ExternalLink("xml", url + ".xml"));
×
235
            if (Utils.isNanopubOfClass(np, NTEMPLATE.ASSERTION_TEMPLATE)) {
×
236
                add(new WebMarkupContainer("use-template").add(new BookmarkablePageLink<Void>("template-link", PublishPage.class, new PageParameters().set("template", np.getUri()))));
×
237
            } else {
238
                add(new WebMarkupContainer("use-template").setVisible(false));
×
239
            }
240
            if (Utils.isNanopubOfClass(np, GrlcQuery.GRLC_QUERY_CLASS)) {
×
241
                add(new WebMarkupContainer("run-query").add(new BookmarkablePageLink<Void>("query-link", QueryPage.class, new PageParameters().set("id", np.getUri()))));
×
242
            } else {
243
                add(new WebMarkupContainer("run-query").setVisible(false));
×
244
            }
245
        }
246

247
        final String ref = tempRef;
×
248
        final String shortName;
249
        if (publishedNanopub != null) {
×
250
            shortName = NanopubUtils.getLabel(np);
×
251
        } else if (parameters.get("label").isEmpty()) {
×
252
            shortName = Utils.getShortNameFromURI(ref);
×
253
        } else {
254
            shortName = parameters.get("label").toString();
×
255
        }
256
        add(new Label("pagetitle", shortName + " (explore) | nanodash"));
×
257
        add(new Label("termname", shortName));
×
258
        add(new ExternalLink("urilink", ref, ref));
×
259
        if (publishedNanopub != null) {
×
260
            add(new Label("statusline", "<h4>Status</h4><p>Successfully published.</p>").setEscapeModelStrings(false));
×
261
        } else if (isNanopubId && SignatureUtils.seemsToHaveSignature(np)) {
×
262
            add(StatusLine.createComponent("statusline", ref));
×
263
        } else {
264
            add(new Label("statusline").setVisible(false));
×
265
        }
266
        if (publishedNanopub != null) {
×
267
            add(new Label("classes-panel").setVisible(false));
×
268
        } else {
269
            add(ThingListPanel.createComponent("classes-panel", ThingListPanel.Mode.CLASSES, ref, "<em>Searching for classes...</em>"));
×
270
        }
271
        if (isNanopubId) {
×
272
            add(new Label("definitions-panel").setVisible(false));
×
273
            add(new Label("instances-panel").setVisible(false));
×
274
            add(new Label("parts-panel").setVisible(false));
×
275
            add(new Label("templates-panel").setVisible(false));
×
276
        } else {
277
            add(ThingListPanel.createComponent("definitions-panel", ThingListPanel.Mode.DESCRIPTIONS, ref, "<em>Searching for term descriptions...</em>"));
×
278
            add(ThingListPanel.createComponent("instances-panel", ThingListPanel.Mode.INSTANCES, ref, "<em>Searching for instances...</em>"));
×
279
            add(ThingListPanel.createComponent("parts-panel", ThingListPanel.Mode.PARTS, ref, "<em>Searching for parts...</em>"));
×
280
            add(ThingListPanel.createComponent("templates-panel", ThingListPanel.Mode.TEMPLATES, ref, "<em>Searching for templates...</em>"));
×
281
        }
282
        add(ExploreDataTable.createComponent("reftable", ref));
×
283
    }
×
284

285
    @Override
286
    protected void onBeforeRender() {
287
        if (publishedNanopub != null && !getPageParameters().get("postpub-redirect-url").isNull()) {
×
288
            String forwardUrl = getPageParameters().get("postpub-redirect-url").toString();
×
289
            if (forwardUrl.contains("?")) {
×
290
                // TODO: Add here URI of created nanopublication too?
291
                throw new RedirectToUrlException(forwardUrl);
×
292
            } else {
293
                String paramString = Utils.getPageParametersAsString(new PageParameters().set("id", publishedNanopub.getUri()));
×
294
                throw new RedirectToUrlException(forwardUrl + "?" + paramString);
×
295
            }
296
        }
297
        super.onBeforeRender();
×
298
    }
×
299

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