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

knowledgepixels / nanodash / 25719148003

12 May 2026 07:07AM UTC coverage: 20.478% (-0.03%) from 20.512%
25719148003

Pull #457

github

web-flow
Merge f6fde0f9b into d3781a3bf
Pull Request #457: fix: restore F5 form-state preservation via singleton LDMs (#456)

1013 of 6240 branches covered (16.23%)

Branch coverage included in aggregate %.

2591 of 11359 relevant lines covered (22.81%)

3.28 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.NPX;
36
import org.nanopub.vocabulary.NTEMPLATE;
37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39

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

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

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

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

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

65
    private Nanopub publishedNanopub = null;
×
66

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

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

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

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

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

115
        initPage();
×
116
    }
×
117

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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