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

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

created branch for parameterized vlo

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