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

knowledgepixels / nanodash / 23265765136

18 Mar 2026 08:34PM UTC coverage: 16.251% (-0.02%) from 16.273%
23265765136

Pull #406

github

web-flow
Merge 50e7060f4 into 399d749bf
Pull Request #406: Redesign Explore page layout and extract References page

728 of 5521 branches covered (13.19%)

Branch coverage included in aggregate %.

1850 of 10343 relevant lines covered (17.89%)

2.44 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.Model;
20
import org.apache.wicket.request.flow.RedirectToUrlException;
21
import org.apache.wicket.request.mapper.parameter.INamedParameters.NamedPair;
22
import org.apache.wicket.request.mapper.parameter.PageParameters;
23
import org.commonjava.mimeparse.MIMEParse;
24
import org.eclipse.rdf4j.model.IRI;
25
import org.eclipse.rdf4j.model.Statement;
26
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
27
import org.eclipse.rdf4j.model.vocabulary.RDF;
28
import org.eclipse.rdf4j.model.vocabulary.SKOS;
29
import org.nanopub.Nanopub;
30
import org.nanopub.NanopubUtils;
31
import org.nanopub.extra.security.SignatureUtils;
32
import org.nanopub.extra.services.ApiResponse;
33
import org.nanopub.extra.services.QueryRef;
34
import org.nanopub.vocabulary.NPX;
35
import org.nanopub.vocabulary.NTEMPLATE;
36
import org.slf4j.Logger;
37
import org.slf4j.LoggerFactory;
38

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

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

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

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

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

64
    private Nanopub publishedNanopub = null;
×
65

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

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

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

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

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

114
        initPage();
×
115
    }
×
116

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

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

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

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

128
        if (SpaceRepository.get().findById(contextId) != null) {
×
129
            add(new BookmarkablePageLink<Void>("back-to-context-link", SpacePage.class, new PageParameters().set("id", contextId)).setBody(Model.of("back to " + SpaceRepository.get().findById(contextId).getLabel())));
×
130
        } else if (MaintainedResourceRepository.get().findById(contextId) != null) {
×
131
            add(new BookmarkablePageLink<Void>("back-to-context-link", MaintainedResourcePage.class, new PageParameters().set("id", contextId)).setBody(Model.of("back to " + MaintainedResourceRepository.get().findById(contextId).getLabel())));
×
132
        } else if (IndividualAgent.isUser(contextId)) {
×
133
            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)))));
×
134
        } else {
135
            add(new Label("back-to-context-link").setVisible(false));
×
136
        }
137

138
        if (User.getUserData().isUser(tempRef)) {
×
139
            add(new BookmarkablePageLink<Void>("to-specific-page-link", UserPage.class, parameters).setBody(Model.of("go to user page")));
×
140
        } else if (SpaceRepository.get().findById(tempRef) != null) {
×
141
            add(new BookmarkablePageLink<Void>("to-specific-page-link", SpacePage.class, parameters).setBody(Model.of("go to Space page")));
×
142
        } else {
143
            add(new Label("to-specific-page-link").setVisible(false));
×
144
        }
145

146
        WebMarkupContainer raw = new WebMarkupContainer("raw");
×
147
        add(raw);
×
148

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

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

200
        WebMarkupContainer nanopubSection = new WebMarkupContainer("nanopub-section");
×
201

202
        if (np == null) {
×
203
            nanopubSection.setVisible(false);
×
204
            nanopubSection.add(new Label("nanopub-header", ""));
×
205
            nanopubSection.add(new Label("nanopub", ""));
×
206
            raw.setVisible(false);
×
207
            nanopubSection.add(raw);
×
208
            nanopubSection.add(new WebMarkupContainer("use-template").setVisible(false));
×
209
            nanopubSection.add(new WebMarkupContainer("run-query").setVisible(false));
×
210
        } else {
211

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

228
            String nanopubHeaderLabel = "<h4>%s</h4>";
×
229
            if (isNanopubId) {
×
230
                nanopubHeaderLabel = String.format(nanopubHeaderLabel, "📌 Nanopublication");
×
231
            } else {
232
                nanopubHeaderLabel = String.format(nanopubHeaderLabel, "🚩 Minted in Nanopublication");
×
233
            }
234
            nanopubSection.add(new Label("nanopub-header", nanopubHeaderLabel).setEscapeModelStrings(false));
×
235
            nanopubSection.add(new NanopubItem("nanopub", NanopubElement.get(np)));
×
236
            String url = Utils.getMainRegistryUrl() + "np/" + TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
×
237
            raw.add(new ExternalLink("trig-txt", url + ".trig.txt"));
×
238
            raw.add(new ExternalLink("jsonld-txt", url + ".jsonld.txt"));
×
239
            raw.add(new ExternalLink("nq-txt", url + ".nq.txt"));
×
240
            raw.add(new ExternalLink("xml-txt", url + ".xml.txt"));
×
241
            raw.add(new ExternalLink("trig", url + ".trig"));
×
242
            raw.add(new ExternalLink("jsonld", url + ".jsonld"));
×
243
            raw.add(new ExternalLink("nq", url + ".nq"));
×
244
            raw.add(new ExternalLink("xml", url + ".xml"));
×
245
            nanopubSection.add(raw);
×
246
            if (Utils.isNanopubOfClass(np, NTEMPLATE.ASSERTION_TEMPLATE)) {
×
247
                nanopubSection.add(new WebMarkupContainer("use-template").add(new BookmarkablePageLink<Void>("template-link", PublishPage.class, new PageParameters().set("template", np.getUri()))));
×
248
            } else {
249
                nanopubSection.add(new WebMarkupContainer("use-template").setVisible(false));
×
250
            }
251
            if (Utils.isNanopubOfClass(np, GrlcQuery.GRLC_QUERY_CLASS)) {
×
252
                nanopubSection.add(new WebMarkupContainer("run-query").add(new BookmarkablePageLink<Void>("query-link", QueryPage.class, new PageParameters().set("id", np.getUri()))));
×
253
            } else {
254
                nanopubSection.add(new WebMarkupContainer("run-query").setVisible(false));
×
255
            }
256
        }
257
        add(nanopubSection);
×
258

259
        final String ref = tempRef;
×
260
        final String shortName;
261
        if (publishedNanopub != null) {
×
262
            shortName = NanopubUtils.getLabel(np);
×
263
        } else if (parameters.get("label").isEmpty()) {
×
264
            shortName = Utils.getShortNameFromURI(ref);
×
265
        } else {
266
            shortName = parameters.get("label").toString();
×
267
        }
268
        add(new Label("pagetitle", shortName + " (explore) | nanodash"));
×
269
        add(new Label("termname", shortName));
×
270

271
        //add(new ExternalLink("urilink", ref, ref));
272
        add(new ExternalLinkWithActionsPanel("urilink", Model.of(ref)));
×
273

274
        add(new BookmarkablePageLink<Void>("references-link", ReferencesPage.class, new PageParameters().set("id", ref)));
×
275
        if (publishedNanopub != null) {
×
276
            add(new Label("statusLine").setVisible(false));
×
277
        } else if (np != null && SignatureUtils.seemsToHaveSignature(np)) {
×
278
            add(StatusLine.createComponent("statusLine", np.getUri().stringValue()));
×
279
        } else {
280
            add(new Label("statusLine").setVisible(false));
×
281
        }
282
        WebMarkupContainer infoSection = new WebMarkupContainer("info-section");
×
283
        if (publishedNanopub != null) {
×
284
            infoSection.add(new Label("classes-panel").setVisible(false));
×
285
        } else {
286
            infoSection.add(ThingListPanel.createComponent("classes-panel", ThingListPanel.Mode.CLASSES, ref, "<em>Searching for classes...</em>"));
×
287
        }
288
        if (isNanopubId) {
×
289
            infoSection.add(new Label("definitions-panel").setVisible(false));
×
290
            infoSection.add(new Label("instances-panel").setVisible(false));
×
291
            infoSection.add(new Label("parts-panel").setVisible(false));
×
292
            infoSection.add(new Label("templates-panel").setVisible(false));
×
293
        } else {
294
            infoSection.add(ThingListPanel.createComponent("definitions-panel", ThingListPanel.Mode.DESCRIPTIONS, ref, "<em>Searching for term descriptions...</em>"));
×
295
            infoSection.add(ThingListPanel.createComponent("instances-panel", ThingListPanel.Mode.INSTANCES, ref, "<em>Searching for instances...</em>"));
×
296
            infoSection.add(ThingListPanel.createComponent("parts-panel", ThingListPanel.Mode.PARTS, ref, "<em>Searching for parts...</em>"));
×
297
            infoSection.add(ThingListPanel.createComponent("templates-panel", ThingListPanel.Mode.TEMPLATES, ref, "<em>Searching for templates...</em>"));
×
298
        }
299
        add(infoSection);
×
300
    }
×
301

302
    @Override
303
    protected void onBeforeRender() {
304
        if (publishedNanopub != null && !getPageParameters().get("postpub-redirect-url").isNull()) {
×
305
            String forwardUrl = getPageParameters().get("postpub-redirect-url").toString();
×
306
            if (forwardUrl.contains("?")) {
×
307
                // TODO: Add here URI of created nanopublication too?
308
                throw new RedirectToUrlException(forwardUrl);
×
309
            } else {
310
                String paramString = Utils.getPageParametersAsString(new PageParameters().set("id", publishedNanopub.getUri()));
×
311
                throw new RedirectToUrlException(forwardUrl + "?" + paramString);
×
312
            }
313
        }
314
        super.onBeforeRender();
×
315
    }
×
316

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