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

knowledgepixels / nanodash / 26455055595

26 May 2026 02:38PM UTC coverage: 20.427% (-0.3%) from 20.748%
26455055595

Pull #468

github

web-flow
Merge 0354b3eb9 into 65b0c8452
Pull Request #468: Source space data from nanopub-query spaces repo

1005 of 6260 branches covered (16.05%)

Branch coverage included in aggregate %.

2600 of 11388 relevant lines covered (22.83%)

3.27 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 com.knowledgepixels.nanodash.domain.AbstractResourceWithProfile;
8
import com.knowledgepixels.nanodash.domain.IndividualAgent;
9
import com.knowledgepixels.nanodash.domain.User;
10
import com.knowledgepixels.nanodash.repository.MaintainedResourceRepository;
11
import com.knowledgepixels.nanodash.repository.SpaceRepository;
12
import jakarta.servlet.http.HttpServletRequest;
13
import net.trustyuri.TrustyUriUtils;
14
import org.apache.wicket.RestartResponseException;
15
import org.apache.wicket.markup.html.WebMarkupContainer;
16
import org.apache.wicket.markup.html.basic.Label;
17
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
18
import org.apache.wicket.markup.html.link.ExternalLink;
19
import org.apache.wicket.model.LoadableDetachableModel;
20
import org.apache.wicket.model.Model;
21
import org.apache.wicket.request.flow.RedirectToUrlException;
22
import org.apache.wicket.request.mapper.parameter.INamedParameters.NamedPair;
23
import org.apache.wicket.request.mapper.parameter.PageParameters;
24
import org.commonjava.mimeparse.MIMEParse;
25
import org.eclipse.rdf4j.model.IRI;
26
import org.eclipse.rdf4j.model.Statement;
27
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
28
import org.eclipse.rdf4j.model.vocabulary.RDF;
29
import org.eclipse.rdf4j.model.vocabulary.SKOS;
30
import org.nanopub.Nanopub;
31
import org.nanopub.NanopubUtils;
32
import org.nanopub.extra.security.SignatureUtils;
33
import org.nanopub.extra.services.ApiResponse;
34
import org.nanopub.extra.services.QueryRef;
35
import org.nanopub.vocabulary.KPXL_GRLC;
36
import org.nanopub.vocabulary.NPX;
37
import org.nanopub.vocabulary.NTEMPLATE;
38
import org.slf4j.Logger;
39
import org.slf4j.LoggerFactory;
40

41
import java.util.HashMap;
42
import java.util.HashSet;
43
import java.util.Map;
44
import java.util.Set;
45

46
/**
47
 * ExplorePage is a page that allows users to explore a specific Nanopublication or Thing.
48
 */
49
public class ExplorePage extends NanodashPage {
50

51
    private static final Logger logger = LoggerFactory.getLogger(ExplorePage.class);
×
52

53
    /**
54
     * The mount path for this page.
55
     */
56
    public static final String MOUNT_PATH = "/explore";
57

58
    /**
59
     * {@inheritDoc}
60
     */
61
    @Override
62
    public String getMountPath() {
63
        return MOUNT_PATH;
×
64
    }
65

66
    private Nanopub publishedNanopub = null;
×
67

68
    /**
69
     * Constructor for ExplorePage.
70
     *
71
     * @param parameters Page parameters containing the ID of the Nanopublication or Thing to explore.
72
     */
73
    public ExplorePage(final PageParameters parameters) {
74
        super(parameters);
×
75
        add(new Label("publish-confirm-panel").setVisible(false));
×
76
        initPage();
×
77
    }
×
78

79
    public ExplorePage(final Nanopub publishedNanopub, final PageParameters parameters) {
80
        super(parameters.set("id", publishedNanopub.getUri()));
×
81
        this.publishedNanopub = publishedNanopub;
×
82

83
        WebMarkupContainer publishConfirmPanel = new WebMarkupContainer("publish-confirm-panel");
×
84
        final NanodashSession session = NanodashSession.get();
×
85
        boolean hasKnownOwnLocalIntro = session.getLocalIntroCount() > 0;
×
86
        boolean someIntroJustNowPublished = Utils.usesPredicateInAssertion(publishedNanopub, NPX.DECLARED_BY);
×
87
        if (someIntroJustNowPublished) NanodashSession.get().setIntroPublishedNow();
×
88
        boolean lastIntroPublishedMoreThanFiveMinsAgo = session.getTimeSinceLastIntroPublished() > 5 * 60 * 1000;
×
89
        if (!hasKnownOwnLocalIntro && session.hasIntroPublished()) User.refreshUsers();
×
90
        publishConfirmPanel.add(new WebMarkupContainer("missing-intro-warning").setVisible(!hasKnownOwnLocalIntro && lastIntroPublishedMoreThanFiveMinsAgo));
×
91

92
        PageParameters plainLinkParams = new PageParameters();
×
93
        plainLinkParams.set("template", parameters.get("template"));
×
94
        if (!parameters.get("template-version").isEmpty()) {
×
95
            plainLinkParams.set("template-version", parameters.get("template-version"));
×
96
        }
97
        publishConfirmPanel.add(new BookmarkablePageLink<Void>("publish-another-link", PublishPage.class, plainLinkParams));
×
98

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

116
        initPage();
×
117
    }
×
118

119
    private void initPage() {
120
        PageParameters parameters = getPageParameters();
×
121

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

126
        String contextId = parameters.get("context").toString("");
×
127

128
        add(new TitleBar("titlebar", this, null));
×
129

130
        if (SpaceRepository.get().findById(contextId) != null) {
×
131
            add(new BookmarkablePageLink<Void>("back-to-context-link", SpacePage.class, new PageParameters().set("id", contextId)).setBody(LoadableDetachableModel.of(() -> {
×
132
                var space = SpaceRepository.get().findById(contextId);
×
133
                return "back to " + (space == null ? contextId : space.getLabel());
×
134
            })));
135
        } else if (MaintainedResourceRepository.get().findById(contextId) != null) {
×
136
            add(new BookmarkablePageLink<Void>("back-to-context-link", MaintainedResourcePage.class, new PageParameters().set("id", contextId)).setBody(LoadableDetachableModel.of(() -> {
×
137
                var resource = MaintainedResourceRepository.get().findById(contextId);
×
138
                return "back to " + (resource == null ? contextId : resource.getLabel());
×
139
            })));
140
        } else if (IndividualAgent.isUser(contextId)) {
×
141
            add(new BookmarkablePageLink<Void>("back-to-context-link", UserPage.class, new PageParameters().set("id", contextId)).setBody(LoadableDetachableModel.of(() -> "back to " + User.getShortDisplayName(Utils.vf.createIRI(contextId)))));
×
142
        } else {
143
            add(new Label("back-to-context-link").setVisible(false));
×
144
        }
145

146
        if (User.getUserData().isUser(tempRef)) {
×
147
            add(new BookmarkablePageLink<Void>("to-specific-page-link", UserPage.class, parameters).setBody(Model.of("go to user page")));
×
148
        } else if (SpaceRepository.get().findById(tempRef) != null) {
×
149
            add(new BookmarkablePageLink<Void>("to-specific-page-link", SpacePage.class, parameters).setBody(Model.of("go to Space page")));
×
150
        } else {
151
            add(new Label("to-specific-page-link").setVisible(false));
×
152
        }
153

154
        WebMarkupContainer raw = new WebMarkupContainer("raw");
×
155
        add(raw);
×
156

157
        Map<String, String> nanopubParams = new HashMap<>();
×
158
        nanopubParams.put("ref", tempRef);
×
159
        Nanopub np = Utils.getAsNanopub(tempRef);
×
160
        boolean isNanopubId = (np != null);
×
161
        if (isNanopubId) {
×
162
            tempRef = np.getUri().stringValue();
×
163
        }
164
        if (!isNanopubId && tempRef.matches("^(.*[^A-Za-z0-9-_])?RA[A-Za-z0-9-_]{43}[^A-Za-z0-9-_].*$")) {
×
165
            np = Utils.getAsNanopub(tempRef.replaceFirst("^(.*[^A-Za-z0-9-_])?(RA[A-Za-z0-9-_]{43})[^A-Za-z0-9-_].*$", "$2"));
×
166
            if (np != null) {
×
167
                String npId = np.getUri().stringValue();
×
168
                tempRef = npId + tempRef.replaceFirst("^(.*[^A-Za-z0-9-_])?(RA[A-Za-z0-9-_]{43})([^A-Za-z0-9-_].*)$", "$3");
×
169
                Multimap<String, String> params = ArrayListMultimap.create();
×
170
                params.put("thing", tempRef);
×
171
                params.put("np", npId);
×
172
                ApiResponse resp = ApiCache.retrieveResponseSync(new QueryRef(QueryApiAccess.GET_LATEST_THING_NANOPUB, params), false);
×
173
                if (!resp.getData().isEmpty()) {
×
174
                    // TODO We take the most recent in case more than one latest version exists. Make other latest versions visible too.
175
                    npId = resp.getData().getFirst().get("latestVersion");
×
176
                }
177
                np = Utils.getAsNanopub(npId);
×
178
            }
179
        }
180

181
        if (parameters.get("forward-to-part").toString("").equals("true") && !contextId.isEmpty() && publishedNanopub == null) {
×
182
            parameters.remove("forward-to-part");
×
183
            Set<IRI> classes = new HashSet<>();
×
184
            if (np != null) {
×
185
                Set<String> introducedIds = NanopubUtils.getIntroducedIriIds(np);
×
186
                if (introducedIds.size() == 1 && introducedIds.iterator().next().equals(tempRef)) {
×
187
                    for (Statement st : np.getAssertion()) {
×
188
                        if (!st.getSubject().stringValue().equals(tempRef)) continue;
×
189
                        if (st.getPredicate().equals(DCTERMS.IS_PART_OF) || st.getPredicate().equals(SKOS.IN_SCHEME)) {
×
190
                            String resourceId = st.getObject().stringValue();
×
191
                            if (MaintainedResourceRepository.get().findById(resourceId) == null) continue;
×
192
                            throw new RestartResponseException(ResourcePartPage.class, parameters);
×
193
                        } else if (st.getPredicate().equals(RDF.TYPE) && st.getObject() instanceof IRI objIri) {
×
194
                            classes.add(objIri);
×
195
                        }
196
                    }
×
197
                }
198
            }
199
            AbstractResourceWithProfile contextResource = AbstractResourceWithProfile.get(contextId);
×
200
            if (contextResource instanceof IndividualAgent && !IndividualAgent.isUser(contextId)) {
×
201
                contextResource = null;
×
202
            }
203
            if (contextResource != null && contextResource.appliesTo(tempRef, classes)) {
×
204
                throw new RestartResponseException(ResourcePartPage.class, parameters);
×
205
            }
206
        }
207

208
        WebMarkupContainer nanopubSection = new WebMarkupContainer("nanopub-section");
×
209

210
        if (np == null) {
×
211
            nanopubSection.setVisible(false);
×
212
            nanopubSection.add(new Label("nanopub-header", ""));
×
213
            nanopubSection.add(new Label("nanopub", ""));
×
214
            raw.setVisible(false);
×
215
            nanopubSection.add(raw);
×
216
            nanopubSection.add(new WebMarkupContainer("use-template").setVisible(false));
×
217
            nanopubSection.add(new WebMarkupContainer("run-query").setVisible(false));
×
218
        } else {
219

220
            // Check whether we should redirect to Nanopub Registry for machine-friendly formats:
221
            String mimeType = Utils.TYPE_HTML;
×
222
            try {
223
                HttpServletRequest httpRequest = (HttpServletRequest) getRequest().getContainerRequest();
×
224
                mimeType = MIMEParse.bestMatch(Utils.SUPPORTED_TYPES_LIST, httpRequest.getHeader("Accept"));
×
225
            } catch (Exception ex) {
×
226
                logger.error("Error determining MIME type from Accept header.", ex);
×
227
            }
×
228
            if (!mimeType.equals(Utils.TYPE_HTML)) {
×
229
                logger.info("Non-HTML content type: {}", mimeType);
×
230
                // TODO Make this registry URL configurable/dynamic:
231
                String redirectUrl = Utils.getMainRegistryUrl() + "np/" + TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
×
232
                logger.info("Redirecting to: {}", redirectUrl);
×
233
                throw new RedirectToUrlException(redirectUrl, 302);
×
234
            }
235

236
            String nanopubHeaderLabel = "<h4>%s</h4>";
×
237
            if (isNanopubId) {
×
238
                nanopubHeaderLabel = String.format(nanopubHeaderLabel, "📌 Nanopublication");
×
239
            } else {
240
                nanopubHeaderLabel = String.format(nanopubHeaderLabel, "🚩 Minted in Nanopublication");
×
241
            }
242
            nanopubSection.add(new Label("nanopub-header", nanopubHeaderLabel).setEscapeModelStrings(false));
×
243
            nanopubSection.add(new NanopubItem("nanopub", NanopubElement.get(np)));
×
244
            String url = Utils.getMainRegistryUrl() + "np/" + TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
×
245
            raw.add(new ExternalLink("trig-txt", url + ".trig.txt"));
×
246
            raw.add(new ExternalLink("jsonld-txt", url + ".jsonld.txt"));
×
247
            raw.add(new ExternalLink("nq-txt", url + ".nq.txt"));
×
248
            raw.add(new ExternalLink("xml-txt", url + ".xml.txt"));
×
249
            raw.add(new ExternalLink("trig", url + ".trig"));
×
250
            raw.add(new ExternalLink("jsonld", url + ".jsonld"));
×
251
            raw.add(new ExternalLink("nq", url + ".nq"));
×
252
            raw.add(new ExternalLink("xml", url + ".xml"));
×
253
            String npUri = np.getUri().stringValue();
×
254
            raw.add(createAssertionLink("a-turtle", npUri, "turtle", false));
×
255
            raw.add(createAssertionLink("a-turtle-txt", npUri, "turtle", true));
×
256
            raw.add(createAssertionLink("a-jsonld", npUri, "jsonld", false));
×
257
            raw.add(createAssertionLink("a-jsonld-txt", npUri, "jsonld", true));
×
258
            raw.add(createAssertionLink("a-nt", npUri, "nt", false));
×
259
            raw.add(createAssertionLink("a-nt-txt", npUri, "nt", true));
×
260
            raw.add(createAssertionLink("a-rdfxml", npUri, "rdfxml", false));
×
261
            raw.add(createAssertionLink("a-rdfxml-txt", npUri, "rdfxml", true));
×
262
            nanopubSection.add(raw);
×
263
            if (Utils.isNanopubOfClass(np, NTEMPLATE.ASSERTION_TEMPLATE)) {
×
264
                nanopubSection.add(new WebMarkupContainer("use-template").add(new BookmarkablePageLink<Void>("template-link", PublishPage.class, new PageParameters().set("template", np.getUri()))));
×
265
            } else {
266
                nanopubSection.add(new WebMarkupContainer("use-template").setVisible(false));
×
267
            }
268
            if (Utils.isNanopubOfClass(np, KPXL_GRLC.GRLC_QUERY)) {
×
269
                nanopubSection.add(new WebMarkupContainer("run-query").add(new BookmarkablePageLink<Void>("query-link", QueryPage.class, new PageParameters().set("id", np.getUri()))));
×
270
            } else {
271
                nanopubSection.add(new WebMarkupContainer("run-query").setVisible(false));
×
272
            }
273
        }
274
        add(nanopubSection);
×
275

276
        final String ref = tempRef;
×
277
        final String shortName;
278
        if (publishedNanopub != null) {
×
279
            shortName = NanopubUtils.getLabel(np);
×
280
        } else if (parameters.get("label").isEmpty()) {
×
281
            shortName = Utils.getShortNameFromURI(ref);
×
282
        } else {
283
            shortName = parameters.get("label").toString();
×
284
        }
285
        add(new Label("pagetitle", shortName + " (explore) | nanodash"));
×
286
        add(new Label("termname", shortName));
×
287

288
        //add(new ExternalLink("urilink", ref, ref));
289
        add(new ExternalLinkWithActionsPanel("urilink", Model.of(ref)));
×
290

291
        add(new BookmarkablePageLink<Void>("references-link", ReferencesPage.class, new PageParameters().set("id", ref)));
×
292
        if (publishedNanopub != null) {
×
293
            add(new Label("statusLine").setVisible(false));
×
294
        } else if (np != null && SignatureUtils.seemsToHaveSignature(np)) {
×
295
            add(StatusLine.createComponent("statusLine", np.getUri().stringValue()));
×
296
        } else {
297
            add(new Label("statusLine").setVisible(false));
×
298
        }
299
        WebMarkupContainer infoSection = new WebMarkupContainer("info-section");
×
300
        if (publishedNanopub != null) {
×
301
            infoSection.add(new Label("classes-panel").setVisible(false));
×
302
        } else {
303
            infoSection.add(ThingListPanel.createComponent("classes-panel", ThingListPanel.Mode.CLASSES, ref, "<em>Searching for classes...</em>"));
×
304
        }
305
        if (isNanopubId) {
×
306
            infoSection.add(new Label("definitions-panel").setVisible(false));
×
307
            infoSection.add(new Label("instances-panel").setVisible(false));
×
308
            infoSection.add(new Label("parts-panel").setVisible(false));
×
309
            infoSection.add(new Label("templates-panel").setVisible(false));
×
310
        } else {
311
            infoSection.add(ThingListPanel.createComponent("definitions-panel", ThingListPanel.Mode.DESCRIPTIONS, ref, "<em>Searching for term descriptions...</em>"));
×
312
            infoSection.add(ThingListPanel.createComponent("instances-panel", ThingListPanel.Mode.INSTANCES, ref, "<em>Searching for instances...</em>"));
×
313
            infoSection.add(ThingListPanel.createComponent("parts-panel", ThingListPanel.Mode.PARTS, ref, "<em>Searching for parts...</em>"));
×
314
            infoSection.add(ThingListPanel.createComponent("templates-panel", ThingListPanel.Mode.TEMPLATES, ref, "<em>Searching for templates...</em>"));
×
315
        }
316
        add(infoSection);
×
317
    }
×
318

319
    @Override
320
    protected void onBeforeRender() {
321
        if (publishedNanopub != null && !getPageParameters().get("postpub-redirect-url").isNull()) {
×
322
            String forwardUrl = getPageParameters().get("postpub-redirect-url").toString();
×
323
            if (forwardUrl.contains("?")) {
×
324
                // TODO: Add here URI of created nanopublication too?
325
                throw new RedirectToUrlException(forwardUrl);
×
326
            } else {
327
                Set<String> introducedIds = NanopubUtils.getIntroducedIriIds(publishedNanopub);
×
328
                String redirectId = introducedIds.size() == 1 ? introducedIds.iterator().next() : publishedNanopub.getUri().stringValue();
×
329
                String paramString = Utils.getPageParametersAsString(new PageParameters().set("id", redirectId));
×
330
                throw new RedirectToUrlException(forwardUrl + "?" + paramString);
×
331
            }
332
        }
333
        super.onBeforeRender();
×
334
    }
×
335

336
    private BookmarkablePageLink<Void> createAssertionLink(String wicketId, String npUri, String format, boolean txt) {
337
        PageParameters params = new PageParameters()
×
338
                .set("type", "np")
×
339
                .set("id", npUri)
×
340
                .set("format", format)
×
341
                .set("assertions", "");
×
342
        if (txt) {
×
343
            params.set("txt", "");
×
344
        }
345
        return new BookmarkablePageLink<>(wicketId, DownloadRdfPage.class, params);
×
346
    }
347

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