source: vlo/branches/vlo-2.13-param/vlo_webapp/src/main/java/eu/clarin/cmdi/vlo/pages/ShowResultPage.java @ 2627

Last change on this file since 2627 was 2627, checked in by keeloo, 11 years ago

Fixed a few tests, moved the SearchResultsDao? method to the init
method of the WebApplication? class. Tested the web application.

From now on, it is possible to override an optional external
configuration file in the context segment by a context definition of
the solrUrl parameter.

Removed parameters from application properties, removed application
properties files themselves, removed unused configuration files and
context segments, and finally: removed Spring dependencies.

File size: 14.2 KB
Line 
1package eu.clarin.cmdi.vlo.pages;
2
3import java.io.InputStreamReader;
4import java.io.StringWriter;
5import java.io.UnsupportedEncodingException;
6import java.net.MalformedURLException;
7import java.net.URL;
8import java.net.URLEncoder;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.HashMap;
12import java.util.List;
13import java.util.regex.Pattern;
14
15import javax.xml.transform.stream.StreamSource;
16
17import net.sf.saxon.s9api.Processor;
18import net.sf.saxon.s9api.Serializer;
19import net.sf.saxon.s9api.XdmNode;
20import net.sf.saxon.s9api.XsltCompiler;
21import net.sf.saxon.s9api.XsltExecutable;
22import net.sf.saxon.s9api.XsltTransformer;
23
24import org.apache.solr.common.SolrDocument;
25import org.apache.wicket.Component;
26import org.apache.wicket.PageParameters;
27import org.apache.wicket.RequestCycle;
28import org.apache.wicket.behavior.AbstractBehavior;
29import org.apache.wicket.behavior.SimpleAttributeModifier;
30import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;
31import org.apache.wicket.extensions.markup.html.basic.SmartLinkMultiLineLabel;
32import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
33import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
34import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
35import org.apache.wicket.extensions.markup.html.repeater.data.table.HeadersToolbar;
36import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
37import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
38import org.apache.wicket.markup.ComponentTag;
39import org.apache.wicket.markup.MarkupStream;
40import org.apache.wicket.markup.html.IHeaderResponse;
41import org.apache.wicket.markup.html.WebMarkupContainer;
42import org.apache.wicket.markup.html.basic.Label;
43import org.apache.wicket.markup.html.image.Image;
44import org.apache.wicket.markup.html.link.BookmarkablePageLink;
45import org.apache.wicket.markup.html.link.ExternalLink;
46import org.apache.wicket.markup.repeater.Item;
47import org.apache.wicket.markup.repeater.RepeatingView;
48import org.apache.wicket.model.IModel;
49import org.apache.wicket.model.ResourceModel;
50import org.apache.wicket.protocol.http.RequestUtils;
51import org.apache.wicket.protocol.http.WicketURLDecoder;
52import org.apache.wicket.protocol.http.WicketURLEncoder;
53import org.apache.wicket.resource.ContextRelativeResource;
54import org.slf4j.Logger;
55import org.slf4j.LoggerFactory;
56
57import eu.clarin.cmdi.vlo.FacetConstants;
58import eu.clarin.cmdi.vlo.Resources;
59import eu.clarin.cmdi.vlo.StringUtils;
60import eu.clarin.cmdi.vlo.config.VloConfig;
61import eu.clarin.cmdi.vlo.dao.DaoLocator;
62
63public class ShowResultPage extends BasePage {
64
65    private final static Logger LOG = LoggerFactory.getLogger(ShowResultPage.class);
66    public static final String PARAM_DOC_ID = "docId";
67    public static final String feedbackfromURL = "http://www.clarin.eu/node/3502?url=";
68   
69    private final static ImageResource FEEDBACK_IMAGE = new ImageResource(new ContextRelativeResource("Images/feedback.png"), "Report an Error");
70    private final URL xslFile = getClass().getResource("/cmdi2xhtml.xsl");
71
72    @SuppressWarnings("serial")
73    public ShowResultPage(final PageParameters parameters) {
74        super(parameters);
75        final String docId = WicketURLDecoder.QUERY_INSTANCE.decode(getPageParameters().getString(PARAM_DOC_ID, null));
76        SolrDocument solrDocument = DaoLocator.getSearchResultsDao().getSolrDocument(docId);
77        if (solrDocument != null) {
78            final SearchPageQuery query = new SearchPageQuery(parameters);
79            BookmarkablePageLink<String> backLink = new BookmarkablePageLink<String>("backLink", FacetedSearchPage.class, query.getPageParameters());
80            add(backLink);
81            String href = getHref(docId);
82            if (href != null) {
83                add(new ExternalLink("openBrowserLink", href, new ResourceModel(Resources.OPEN_IN_ORIGINAL_CONTEXT).getObject()));
84            } else {
85                add(new Label("openBrowserLink", new ResourceModel(Resources.ORIGINAL_CONTEXT_NOT_AVAILABLE).getObject()));
86            }
87            addAttributesTable(solrDocument);
88            addResourceLinks(solrDocument);
89            addSearchServiceForm(solrDocument);
90            addCompleteCmdiView(solrDocument);
91           
92            add(new AjaxLazyLoadPanel("prevNextHeader") {
93
94                @Override
95                public Component getLazyLoadComponent(String markupId) {
96                    return new PrevNextHeaderPanel(markupId, docId, query);
97                }
98
99                @Override
100                public Component getLoadingComponent(String markupId) {
101                    return new PrevNextHeaderPanel(markupId);
102                }
103            });
104        } else {
105            setResponsePage(new ResultNotFoundPage(parameters));
106        }
107
108        // add feedback link
109        addFeedbackLink(parameters);
110    }
111
112    private String getHref(String linkToOriginalContext) {
113        String result = linkToOriginalContext;
114        if (linkToOriginalContext != null) {
115            if (linkToOriginalContext.startsWith(FacetConstants.TEST_HANDLE_MPI_PREFIX)) {
116                linkToOriginalContext = linkToOriginalContext.replace(FacetConstants.TEST_HANDLE_MPI_PREFIX, FacetConstants.HANDLE_MPI_PREFIX);
117            }
118            if (linkToOriginalContext.startsWith(FacetConstants.HANDLE_MPI_PREFIX)) {
119                result = VloConfig.get().getIMDIBrowserUrl(linkToOriginalContext);
120            } else {
121                try {
122                    new URL(linkToOriginalContext);
123                } catch (MalformedURLException e) {
124                    LOG.debug("Link to original context is incorrect:", e);
125                    result = null;
126                }
127            }
128        }
129        return result;
130    }
131
132        private void addAttributesTable(final SolrDocument solrDocument) {
133                solrDocument.remove(FacetConstants.FIELD_LANGUAGE);     // ignore language entry, because of FIELD_LANGUAGE_LINK
134        DocumentAttributesDataProvider attributeProvider = new DocumentAttributesDataProvider(solrDocument);
135        @SuppressWarnings("unchecked")
136                DataTable table = new DataTable("attributesTable", createAttributesColumns(), attributeProvider, 250);
137        table.setTableBodyCss("attributesTbody");
138        table.addTopToolbar(new HeadersToolbar(table, null));
139        add(table);
140    }
141
142    @SuppressWarnings({ "serial" })
143    private IColumn[] createAttributesColumns() {
144        IColumn[] columns = new IColumn[2];
145
146        columns[0] = new PropertyColumn<Object>(new ResourceModel(Resources.FIELD), "field") {
147
148            @Override
149            public String getCssClass() {
150                return "attribute";
151            }
152        };
153
154        columns[1] = new AbstractColumn<DocumentAttribute>(new ResourceModel(Resources.VALUE)) {
155            @Override
156            public void populateItem(Item<ICellPopulator<DocumentAttribute>> cellItem, String componentId, IModel<DocumentAttribute> rowModel) {
157                DocumentAttribute attribute = rowModel.getObject();
158
159                if (attribute.getField().equals(FacetConstants.FIELD_LANGUAGE)) {
160                    cellItem.add(new SmartLinkMultiLineLabel(componentId, attribute.getValue()) {
161
162                        @Override
163                        protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
164                            CharSequence body = StringUtils.toMultiLineHtml(getDefaultModelObjectAsString());
165                            replaceComponentTagBody(markupStream, openTag, getSmartLink(body));
166                        }
167                    });
168                } else if(attribute.getField().equals(FacetConstants.FIELD_LANGUAGES)) {
169                    cellItem.add(new SmartLinkMultiLineLabel(componentId, attribute.getValue()) {
170
171                        @Override
172                        protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
173                                setEscapeModelStrings(false);
174                            CharSequence body = getDefaultModelObjectAsString();
175                            replaceComponentTagBody(markupStream, openTag, body);
176                        }
177                    });
178                } else {
179                    cellItem.add(new SmartLinkMultiLineLabel(componentId, attribute.getValue()) {
180
181                        @Override
182                        protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
183                            CharSequence body = StringUtils.toMultiLineHtml(getDefaultModelObjectAsString());
184                            replaceComponentTagBody(markupStream, openTag, getSmartLink(body));
185                        }
186                    });
187                }
188            }
189
190            @Override
191            public String getCssClass() {
192                return "attributeValue";
193            }
194        };
195
196        return columns;
197    }
198
199    @SuppressWarnings("serial")
200    private void addResourceLinks(SolrDocument solrDocument) {
201        RepeatingView repeatingView = new RepeatingView("resourceList");
202        add(repeatingView);
203        if (solrDocument.containsKey(FacetConstants.FIELD_RESOURCE)) {
204            Collection<Object> resources = solrDocument.getFieldValues(FacetConstants.FIELD_RESOURCE);
205            for (Object resource : resources) {
206                String[] split = resource.toString().split(Pattern.quote(FacetConstants.FIELD_RESOURCE_SPLIT_CHAR), 2);
207                final String mimeType = split[0];
208                final String resourceLink = split[1];
209                repeatingView.add(new AjaxLazyLoadPanel(repeatingView.newChildId()) {
210
211                    @Override
212                    public Component getLazyLoadComponent(String markupId) {
213                        return new ResourceLinkPanel(markupId, mimeType, resourceLink);
214                    }
215                });
216            }
217        } else {
218            repeatingView.add(new Label(repeatingView.newChildId(), new ResourceModel(Resources.NO_RESOURCE_FOUND)));
219        }
220    }
221   
222    private void addFeedbackLink(final PageParameters parameters) {
223        String thisURL = RequestUtils.toAbsolutePath(RequestCycle.get().urlFor(ShowResultPage.class, parameters).toString());
224        try {
225            thisURL = URLEncoder.encode(thisURL,"UTF-8");
226        } catch (UnsupportedEncodingException e) {
227            LOG.error(e.toString());
228        }
229       
230        Image resourceImg = new Image("feedbackImage", FEEDBACK_IMAGE.getResource());
231        String title = "Report an error";
232        resourceImg.add(new SimpleAttributeModifier("title", title));
233        resourceImg.add(new SimpleAttributeModifier("alt", title));
234        String href = getHref(feedbackfromURL+thisURL);
235        String name = feedbackfromURL+thisURL;
236        ExternalLink link = new ExternalLink("feedbackLink", href);
237        link.add(resourceImg);
238        add(new Label("feedbackLabel", "Found an error?"));
239        add(link);
240    }
241
242    public static BookmarkablePageLink<ShowResultPage> createBookMarkableLink(String linkId, SearchPageQuery query, String docId) {
243        PageParameters pageParameters = query.getPageParameters();
244        pageParameters.put(ShowResultPage.PARAM_DOC_ID, WicketURLEncoder.QUERY_INSTANCE.encode(docId));
245        BookmarkablePageLink<ShowResultPage> docLink = new BookmarkablePageLink<ShowResultPage>(linkId, ShowResultPage.class,
246                pageParameters);
247        return docLink;
248    }
249   
250        /**
251         * Add contentSearch form (FCS)
252         * @param solrDocument
253         */
254        private void addSearchServiceForm(final SolrDocument solrDocument) {
255                final WebMarkupContainer contentSearchContainer = new WebMarkupContainer("contentSearch");
256                add(contentSearchContainer);
257               
258                if (solrDocument.containsKey(FacetConstants.FIELD_SEARCH_SERVICE)) {
259                        try {
260                                // building map (CQL endpoint -> List with resource ID)
261                                HashMap<String, List<String>> aggregrationContextMap = new HashMap<String, List<String>>();
262                                List<String> idList = new ArrayList<String>();
263                                idList.add(solrDocument.getFirstValue(FacetConstants.FIELD_ID).toString());
264                                aggregrationContextMap.put(solrDocument.getFirstValue(FacetConstants.FIELD_SEARCH_SERVICE).toString(), idList);
265                                Label contentSearchLabel = new Label("contentSearchForm", HtmlFormCreator.getContentSearchForm(aggregrationContextMap));
266                                contentSearchLabel.setEscapeModelStrings(false);                               
267                                contentSearchContainer.add(contentSearchLabel);
268                        } catch (UnsupportedEncodingException uee) {
269                                contentSearchContainer.setVisible(false);
270                        }
271                } else {
272                        contentSearchContainer.setVisible(false);
273                }
274        }
275       
276        /**
277         * Add complete CMDI view
278         * @param solrDocument
279         */
280        private void addCompleteCmdiView(final SolrDocument solrDocument) {
281                StringWriter strWriter = new StringWriter();
282
283        final Processor proc = new Processor(false);
284        final XsltCompiler comp = proc.newXsltCompiler();
285
286        try {
287                final XsltExecutable exp = comp.compile(new StreamSource(xslFile.getFile()));
288                final XdmNode source = proc.newDocumentBuilder().build(
289                                new StreamSource(new InputStreamReader(new URL(solrDocument.getFirstValue(FacetConstants.FIELD_COMPLETE_METADATA).toString()).openStream())));
290                final Serializer out = new Serializer();
291                out.setOutputProperty(Serializer.Property.METHOD, "html");
292                out.setOutputProperty(Serializer.Property.INDENT, "yes");
293                out.setOutputWriter(strWriter);
294                final XsltTransformer trans = exp.load();
295
296                trans.setInitialContextNode(source);
297                trans.setDestination(out);
298                trans.transform();
299        } catch (Exception e) {
300                LOG.error("Couldn't create CMDI metadata: "+e.getMessage());
301                strWriter = new StringWriter().append("<b>Could not load complete CMDI metadata</b>");
302        }               
303               
304        Label completeCmdiLabel = new Label("completeCmdi", strWriter.toString());
305                completeCmdiLabel.setEscapeModelStrings(false);
306                add(completeCmdiLabel);
307               
308                // remove complete CMDI view on page load
309                add(new AbstractBehavior() {
310                        private static final long serialVersionUID = 1865219352602175954L;
311
312                        @Override
313                        public void renderHead(IHeaderResponse response) {
314                                super.renderHead(response);
315                                response.renderOnLoadJavascript("toogleDiv('completeCmdi', 'toogleLink')");
316                        }
317                });
318        }
319}
Note: See TracBrowser for help on using the repository browser.