001/*
002 * (C) Copyright 2008 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 * $Id$
020 */
021package org.nuxeo.ecm.platform.ui.web.restAPI;
022
023import java.io.IOException;
024import java.net.URLEncoder;
025
026import org.dom4j.Element;
027import org.dom4j.Namespace;
028import org.dom4j.QName;
029import org.dom4j.dom.DOMDocument;
030import org.dom4j.dom.DOMDocumentFactory;
031import org.nuxeo.ecm.core.api.CloseableCoreSession;
032import org.nuxeo.ecm.core.api.CoreInstance;
033import org.nuxeo.ecm.core.api.CoreSession;
034import org.nuxeo.ecm.core.api.DocumentModel;
035import org.nuxeo.ecm.core.api.DocumentModelList;
036import org.nuxeo.ecm.core.api.NuxeoException;
037import org.nuxeo.ecm.platform.ui.web.tag.fn.DocumentModelFunctions;
038import org.nuxeo.ecm.platform.ui.web.util.BaseURL;
039import org.restlet.data.CharacterSet;
040import org.restlet.data.MediaType;
041import org.restlet.data.Request;
042import org.restlet.data.Response;
043import org.restlet.resource.Representation;
044import org.restlet.resource.StringRepresentation;
045
046/**
047 * Basic OpenSearch REST fulltext search implementation using the RSS 2.0 results format.
048 * <p>
049 * TODO: make it possible to change the page size and navigate to next results pages using additional query parameters.
050 * See http://opensearch.org for official specifications.
051 * <p>
052 * TODO: use a OPENSEARCH stateless query model to be able to override the currently hardcoded request pattern.
053 * <p>
054 * TODO: add OpenSearch XML description snippet in the default theme so that Firefox can autodetect the service URL.
055 *
056 * @author Olivier Grisel
057 */
058public class OpenSearchRestlet extends BaseNuxeoRestlet {
059
060    public static final String RSS_TAG = "rss";
061
062    public static final String CHANNEL_TAG = "channel";
063
064    public static final String TITLE_TAG = "title";
065
066    public static final String DESCRIPTION_TAG = "description";
067
068    public static final String LINK_TAG = "link";
069
070    public static final String ITEM_TAG = "item";
071
072    public static final String QUERY = "SELECT * FROM Document WHERE ecm:fulltext LIKE '%s' ORDER BY dc:modified DESC";
073
074    public static final int MAX = 10;
075
076    public static final Namespace OPENSEARCH_NS = new Namespace("opensearch", "http://a9.com/-/spec/opensearch/1.1/");
077
078    public static final Namespace ATOM_NS = new Namespace("atom", "http://www.w3.org/2005/Atom");
079
080    @Override
081    public void handle(Request req, Response res) {
082        try (CloseableCoreSession session = CoreInstance.openCoreSession(null, getUserPrincipal(req))) {
083            // read the search term passed as the 'q' request parameter
084            String keywords = getQueryParamValue(req, "q", " ");
085
086            // perform the search on the fulltext index and wrap the results as
087            // a DocumentModelList with the 10 first matching results ordered by
088            // modification time
089            String query = String.format(QUERY, keywords);
090            DocumentModelList documents = session.query(query, null, MAX, 0, true);
091
092            // build the RSS 2.0 response document holding the results
093            DOMDocumentFactory domFactory = new DOMDocumentFactory();
094            DOMDocument resultDocument = (DOMDocument) domFactory.createDocument();
095
096            // rss root tag
097            Element rssElement = resultDocument.addElement(RSS_TAG);
098            rssElement.addAttribute("version", "2.0");
099            rssElement.addNamespace(OPENSEARCH_NS.getPrefix(), OPENSEARCH_NS.getURI());
100            rssElement.addNamespace(ATOM_NS.getPrefix(), ATOM_NS.getURI());
101
102            // channel with OpenSearch metadata
103            Element channelElement = rssElement.addElement(CHANNEL_TAG);
104
105            channelElement.addElement(TITLE_TAG).setText("Nuxeo EP OpenSearch channel for " + keywords);
106            channelElement.addElement("link").setText(
107                    BaseURL.getBaseURL(getHttpRequest(req)) + "restAPI/opensearch?q="
108                            + URLEncoder.encode(keywords, "UTF-8"));
109            channelElement.addElement(new QName("totalResults", OPENSEARCH_NS)).setText(
110                    Long.toString(documents.totalSize()));
111            channelElement.addElement(new QName("startIndex", OPENSEARCH_NS)).setText("0");
112            channelElement.addElement(new QName("itemsPerPage", OPENSEARCH_NS)).setText(
113                    Integer.toString(documents.size()));
114
115            Element queryElement = channelElement.addElement(new QName("Query", OPENSEARCH_NS));
116            queryElement.addAttribute("role", "request");
117            queryElement.addAttribute("searchTerms", keywords);
118            queryElement.addAttribute("startPage", Integer.toString(1));
119
120            // document items
121            String baseUrl = BaseURL.getBaseURL(getHttpRequest(req));
122
123            for (DocumentModel doc : documents) {
124                Element itemElement = channelElement.addElement(ITEM_TAG);
125                Element titleElement = itemElement.addElement(TITLE_TAG);
126                String title = doc.getTitle();
127                if (title != null) {
128                    titleElement.setText(title);
129                }
130                Element descriptionElement = itemElement.addElement(DESCRIPTION_TAG);
131                String description = doc.getProperty("dublincore:description").getValue(String.class);
132                if (description != null) {
133                    descriptionElement.setText(description);
134                }
135                Element linkElement = itemElement.addElement("link");
136                linkElement.setText(baseUrl + DocumentModelFunctions.documentUrl(doc));
137            }
138
139            Representation rep = new StringRepresentation(resultDocument.asXML(), MediaType.APPLICATION_XML);
140            rep.setCharacterSet(CharacterSet.UTF_8);
141            res.setEntity(rep);
142
143        } catch (NuxeoException | IOException e) {
144            handleError(res, e);
145        }
146    }
147
148}