OpenSearch Impl

- addition of icons (for search engine, feed and feed entries)
- configurable items per page
- addition of feed entry relevance (score) (ATOM only)
- addition for generator & author feed elements (ATOM only)
- guest url argument support
- logging (log4j.logger.org.alfresco.web.api=DEBUG)
- addition of abstract web api plug-in (for building new url web services)

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@4668 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
David Caruana
2006-12-20 00:38:47 +00:00
parent d4df23ea30
commit 257568270d
11 changed files with 457 additions and 175 deletions

View File

@@ -8,9 +8,9 @@
<!-- --> <!-- -->
<!-- TODO: For now, experiment with HTTP Basic Authentication --> <!-- TODO: For now, experiment with HTTP Basic Authentication -->
<alias alias="web.api.Authentication" name="web.api.BasicAuthentication" /> <alias alias="web.api.Authenticator" name="web.api.BasicAuthenticator" />
<bean id="web.api.BasicAuthentication" class="org.alfresco.web.api.BasicAuthentication"> <bean id="web.api.BasicAuthenticator" class="org.alfresco.web.api.BasicAuthenticator">
<property name="authenticationService" ref="AuthenticationService" /> <property name="authenticationService" ref="AuthenticationService" />
</bean> </bean>
@@ -19,16 +19,19 @@
<!-- Web API Services --> <!-- Web API Services -->
<!-- --> <!-- -->
<bean id="web.api.TextSearchDescription" class="org.alfresco.web.api.services.TextSearchDescription"> <bean id="web.api.APIService" abstract="true">
<property name="httpUri" value="/search/textsearchdescription.xml" /> <property name="serviceRegistry" ref="ServiceRegistry" />
<property name="descriptorService" ref="DescriptorService" />
<property name="templateService" ref="TemplateService" /> <property name="templateService" ref="TemplateService" />
</bean> </bean>
<bean id="web.api.TextSearch" class="org.alfresco.web.api.services.TextSearch"> <bean id="web.api.TextSearchDescription" class="org.alfresco.web.api.services.TextSearchDescription" parent="web.api.APIService">
<property name="httpUri" value="/search/textsearchdescription.xml" />
</bean>
<bean id="web.api.TextSearch" class="org.alfresco.web.api.services.TextSearch" parent="web.api.APIService">
<property name="httpUri" value="/search/text" /> <property name="httpUri" value="/search/text" />
<property name="serviceRegistry" ref="ServiceRegistry" />
<property name="searchService" ref="SearchService" /> <property name="searchService" ref="SearchService" />
<property name="templateService" ref="TemplateService"/>
</bean> </bean>
</beans> </beans>

View File

@@ -19,6 +19,8 @@ package org.alfresco.web.api;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletRequestWrapper;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
/** /**
* API Service Request * API Service Request
@@ -47,13 +49,12 @@ public class APIRequest extends HttpServletRequestWrapper
User User
} }
/** /**
* Construct * Construct
* *
* @param req * @param req
*/ */
public APIRequest(HttpServletRequest req) /*package*/ APIRequest(HttpServletRequest req)
{ {
super(req); super(req);
} }
@@ -89,4 +90,24 @@ public class APIRequest extends HttpServletRequestWrapper
return getPath() + getServletPath(); return getPath() + getServletPath();
} }
/**
* Gets the currently authenticated username
*
* @return username
*/
public String getAuthenticatedUsername()
{
return AuthenticationUtil.getCurrentUserName();
}
/**
* Determine if Guest User?
*
* @return true => guest user
*/
public boolean isGuest()
{
return Boolean.valueOf(getParameter("guest"));
}
} }

View File

@@ -38,7 +38,7 @@ public class APIResponse extends HttpServletResponseWrapper
* *
* @param res * @param res
*/ */
public APIResponse(HttpServletResponse res) /*package*/ APIResponse(HttpServletResponse res)
{ {
super(res); super(res);
} }

View File

@@ -20,8 +20,11 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletContext;
import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.RegexpMethodPointcutAdvisor;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@@ -30,7 +33,7 @@ import org.springframework.context.ApplicationContext;
* *
* @author davidc * @author davidc
*/ */
public class APIServiceMap public class APIServiceRegistry
{ {
// TODO: Support different kinds of uri resolution (e.g. regex:/search/.*) // TODO: Support different kinds of uri resolution (e.g. regex:/search/.*)
@@ -44,17 +47,21 @@ public class APIServiceMap
* *
* @param context * @param context
*/ */
public APIServiceMap(ApplicationContext context) public APIServiceRegistry(ServletContext servletContext, ApplicationContext appContext)
{ {
// locate authentication interceptor // retrieve service authenticator
MethodInterceptor authInterceptor = (MethodInterceptor)context.getBean("web.api.Authentication"); MethodInterceptor authenticator = (MethodInterceptor)appContext.getBean("web.api.Authenticator");
// register all API Services // register all API Services
// NOTE: An API Service is one registered in Spring which supports the APIService interface // NOTE: An API Service is one registered in Spring which is of type APIServiceImpl
Map<String, APIService> apiServices = context.getBeansOfType(APIService.class, false, false); Map<String, APIService> apiServices = appContext.getBeansOfType(APIService.class, false, false);
for (Map.Entry<String, APIService> apiService : apiServices.entrySet()) for (Map.Entry<String, APIService> apiService : apiServices.entrySet())
{ {
// retrieve service
APIService service = apiService.getValue(); APIService service = apiService.getValue();
service.init(servletContext);
// retrieve http method
APIRequest.HttpMethod method = service.getHttpMethod(); APIRequest.HttpMethod method = service.getHttpMethod();
String httpUri = service.getHttpUri(); String httpUri = service.getHttpUri();
if (httpUri == null || httpUri.length() == 0) if (httpUri == null || httpUri.length() == 0)
@@ -62,14 +69,21 @@ public class APIServiceMap
throw new APIException("Web API Service " + apiService.getKey() + " does not specify a HTTP URI mapping"); throw new APIException("Web API Service " + apiService.getKey() + " does not specify a HTTP URI mapping");
} }
if (authInterceptor != null && service.getRequiredAuthentication() != APIRequest.RequiredAuthentication.None) // wrap API Service in appropriate interceptors (e.g. authentication)
if (service.getRequiredAuthentication() != APIRequest.RequiredAuthentication.None)
{ {
// wrap API Service in appropriate interceptors (e.g. authentication) if (authenticator == null)
ProxyFactory authFactory = new ProxyFactory(service); {
authFactory.addAdvice(authInterceptor); throw new APIException("Web API Authenticator not specified");
}
RegexpMethodPointcutAdvisor advisor = new RegexpMethodPointcutAdvisor(".*execute", authenticator);
ProxyFactory authFactory = new ProxyFactory((APIService)service);
authFactory.addAdvisor(advisor);
service = (APIService)authFactory.getProxy(); service = (APIService)authFactory.getProxy();
} }
// register service
methods.add(method); methods.add(method);
uris.add(httpUri); uris.add(httpUri);
services.add(service); services.add(service);

View File

@@ -23,6 +23,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.alfresco.web.app.servlet.BaseServlet; import org.alfresco.web.app.servlet.BaseServlet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.context.support.WebApplicationContextUtils;
@@ -35,9 +37,12 @@ import org.springframework.web.context.support.WebApplicationContextUtils;
public class APIServlet extends BaseServlet public class APIServlet extends BaseServlet
{ {
private static final long serialVersionUID = 4209892938069597860L; private static final long serialVersionUID = 4209892938069597860L;
// Logger
private static final Log logger = LogFactory.getLog(APIServlet.class);
// API Services // API Services
private APIServiceMap apiServiceMap; private APIServiceRegistry apiServiceRegistry;
@Override @Override
@@ -47,18 +52,12 @@ public class APIServlet extends BaseServlet
// Retrieve all web api services and index by http url & http method // Retrieve all web api services and index by http url & http method
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
apiServiceMap = new APIServiceMap(context); apiServiceRegistry = new APIServiceRegistry(getServletContext(), context);
} }
// TODO: // TODO:
// - authentication (as suggested in http://www.xml.com/pub/a/2003/12/17/dive.html) // - authentication (as suggested in http://www.xml.com/pub/a/2003/12/17/dive.html)
// - atom
// - generator
// - author (authenticated)
// - icon
// - html
// - icon
/* /*
@@ -80,16 +79,32 @@ public class APIServlet extends BaseServlet
APIRequest.HttpMethod method = request.getHttpMethod(); APIRequest.HttpMethod method = request.getHttpMethod();
String uri = request.getPathInfo(); String uri = request.getPathInfo();
APIService service = apiServiceMap.get(method, uri); if (logger.isDebugEnabled())
logger.debug("Processing request (" + request.getHttpMethod() + ") " + request.getRequestURL() + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
APIService service = apiServiceRegistry.get(method, uri);
if (service != null) if (service != null)
{ {
if (logger.isDebugEnabled())
logger.debug("Mapped to service " + service.getName());
long start = System.currentTimeMillis();
service.execute(request, response); service.execute(request, response);
long end = System.currentTimeMillis();
if (logger.isDebugEnabled())
logger.debug("Service " + service.getName() + " executed in " + (end - start) + "ms");
} }
else else
{ {
if (logger.isDebugEnabled())
logger.debug("Request does not map to service.");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
// TODO: add appropriate error detail // TODO: add appropriate error detail
} }
// TODO: exception handling
} }
} }

View File

@@ -22,6 +22,8 @@ import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.util.Base64; import org.alfresco.util.Base64;
import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/** /**
@@ -29,8 +31,11 @@ import org.aopalliance.intercept.MethodInvocation;
* *
* @author davidc * @author davidc
*/ */
public class BasicAuthentication implements MethodInterceptor public class BasicAuthenticator implements MethodInterceptor
{ {
// Logger
private static final Log logger = LogFactory.getLog(BasicAuthenticator.class);
// dependencies // dependencies
private AuthenticationService authenticationService; private AuthenticationService authenticationService;
@@ -60,9 +65,22 @@ public class BasicAuthentication implements MethodInterceptor
// validate credentials // validate credentials
// //
boolean isGuest = request.isGuest();
String authorization = request.getHeader("Authorization"); String authorization = request.getHeader("Authorization");
if ((authorization == null || authorization.length() == 0) && service.getRequiredAuthentication().equals(APIRequest.RequiredAuthentication.Guest))
if (logger.isDebugEnabled())
{ {
logger.debug("Service authentication required: " + service.getRequiredAuthentication());
logger.debug("Guest login: " + isGuest);
logger.debug("Authorization provided (overrides Guest login): " + (authorization != null && authorization.length() > 0));
}
if (((authorization == null || authorization.length() == 0) || isGuest)
&& service.getRequiredAuthentication().equals(APIRequest.RequiredAuthentication.Guest))
{
if (logger.isDebugEnabled())
logger.debug("Authenticating as Guest");
// authenticate as guest, if service allows // authenticate as guest, if service allows
authenticationService.authenticateAsGuest(); authenticationService.authenticateAsGuest();
authorized = true; authorized = true;
@@ -81,17 +99,26 @@ public class BasicAuthentication implements MethodInterceptor
if (parts.length == 1) if (parts.length == 1)
{ {
if (logger.isDebugEnabled())
logger.debug("Authenticating ticket " + parts[0]);
// assume a ticket has been passed // assume a ticket has been passed
authenticationService.validate(parts[0]); authenticationService.validate(parts[0]);
authorized = true; authorized = true;
} }
else else
{ {
if (logger.isDebugEnabled())
logger.debug("Authenticating user " + parts[0]);
// assume username and password passed // assume username and password passed
if (parts[0].equals(AuthenticationUtil.getGuestUserName())) if (parts[0].equals(AuthenticationUtil.getGuestUserName()))
{ {
authenticationService.authenticateAsGuest(); if (service.getRequiredAuthentication().equals(APIRequest.RequiredAuthentication.Guest))
authorized = true; {
authenticationService.authenticateAsGuest();
authorized = true;
}
} }
else else
{ {
@@ -110,6 +137,9 @@ public class BasicAuthentication implements MethodInterceptor
// execute API service or request authorization // execute API service or request authorization
// //
if (logger.isDebugEnabled())
logger.debug("Authenticated: " + authorized);
if (authorized) if (authorized)
{ {
retVal = invocation.proceed(); retVal = invocation.proceed();

View File

@@ -0,0 +1,192 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.web.api.services;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.TemplateService;
import org.alfresco.service.descriptor.DescriptorService;
import org.alfresco.web.api.APIRequest;
import org.alfresco.web.api.APIResponse;
import org.alfresco.web.api.APIService;
import org.springframework.beans.factory.BeanNameAware;
/**
* Skeleton implementation of an API Service
*
* @author davidc
*/
public abstract class APIServiceImpl implements BeanNameAware, APIService
{
private String name;
private String uri;
// dependencies
private ServletContext context;
private ServiceRegistry serviceRegistry;
private DescriptorService descriptorService;
private TemplateService templateService;
//
// Initialisation
//
/* (non-Javadoc)
* @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
*/
public void setBeanName(String name)
{
this.name = name;
}
/**
* @param serviceRegistry
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.serviceRegistry = serviceRegistry;
}
/**
* @param templateService
*/
public void setTemplateService(TemplateService templateService)
{
this.templateService = templateService;
}
/**
* @param descriptorService
*/
public void setDescriptorService(DescriptorService descriptorService)
{
this.descriptorService = descriptorService;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#init(javax.servlet.ServletContext)
*/
public void init(ServletContext context)
{
this.context = context;
}
/**
* Sets the Http URI
*
* @param uri
*/
public void setHttpUri(String uri)
{
this.uri = uri;
}
//
// Service Meta-Data
//
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getName()
*/
public String getName()
{
return this.name;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpUri()
*/
public String getHttpUri()
{
return this.uri;
}
//
// Service Implementation Helpers
//
/**
* @return descriptorService
*/
protected ServletContext getServletContext()
{
return context;
}
/**
* @return descriptorService
*/
protected DescriptorService getDescriptorService()
{
return descriptorService;
}
/**
* @return serviceRegistry
*/
protected ServiceRegistry getServiceRegistry()
{
return serviceRegistry;
}
/**
* @return templateService
*/
protected TemplateService getTemplateService()
{
return templateService;
}
/**
* Create a basic template model
*
* @param req api request
* @param res api response
* @return template model
*/
protected Map<String, Object> createTemplateModel(APIRequest req, APIResponse res)
{
Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);
model.put("date", new Date());
model.put("agent", descriptorService.getServerDescriptor());
model.put("request", req);
model.put("response", res);
return model;
}
/**
* Render a template to the API Response
*
* @param template
* @param model
* @param res
*/
protected void renderTemplate(String template, Map<String, Object> model, APIResponse res)
throws IOException
{
templateService.processTemplateString(null, template, model, res.getWriter());
}
}

View File

@@ -19,23 +19,30 @@ package org.alfresco.web.api.services;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.alfresco.service.ServiceRegistry; import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.repository.TemplateImageResolver;
import org.alfresco.service.cmr.repository.TemplateNode; import org.alfresco.service.cmr.repository.TemplateNode;
import org.alfresco.service.cmr.repository.TemplateService; import org.alfresco.service.cmr.repository.TemplateService;
import org.alfresco.service.cmr.search.ResultSet; import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.descriptor.DescriptorService;
import org.alfresco.util.ApplicationContextHelper; import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.GUID; import org.alfresco.util.GUID;
import org.alfresco.web.api.APIException; import org.alfresco.web.api.APIException;
import org.alfresco.web.api.APIRequest; import org.alfresco.web.api.APIRequest;
import org.alfresco.web.api.APIResponse; import org.alfresco.web.api.APIResponse;
import org.alfresco.web.api.APIService; import org.alfresco.web.api.APIServlet;
import org.alfresco.web.api.APIRequest.HttpMethod; import org.alfresco.web.api.APIRequest.HttpMethod;
import org.alfresco.web.api.APIRequest.RequiredAuthentication; import org.alfresco.web.api.APIRequest.RequiredAuthentication;
import org.alfresco.web.ui.common.Utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@@ -44,39 +51,27 @@ import org.springframework.context.ApplicationContext;
* *
* @author davidc * @author davidc
*/ */
public class TextSearch implements APIService public class TextSearch extends APIServiceImpl
{ {
// NOTE: startPage and startIndex are 1 offset. // Logger
private static final Log logger = LogFactory.getLog(APIServlet.class);
// search parameters // search parameters
// TODO: allow configuration of these // TODO: allow configuration of search store
private static final StoreRef searchStore = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"); protected static final StoreRef SEARCH_STORE = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
private static final int itemsPerPage = 10; protected static final int DEFAULT_ITEMS_PER_PAGE = 10;
// dependencies // dependencies
private String uri; protected SearchService searchService;
private ServiceRegistry serviceRegistry;
private SearchService searchService;
private TemplateService templateService;
// icon resolver
/** protected TemplateImageResolver iconResolver = new TemplateImageResolver()
* Sets the Http URI
*
* @param uri
*/
public void setHttpUri(String uri)
{ {
this.uri = uri; public String resolveImagePathForName(String filename, boolean small)
} {
return Utils.getFileTypeImage(getServletContext(), filename, small);
/** }
* @param serviceRegistry };
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.serviceRegistry = serviceRegistry;
}
/** /**
* @param searchService * @param searchService
@@ -86,14 +81,6 @@ public class TextSearch implements APIService
this.searchService = searchService; this.searchService = searchService;
} }
/**
* @param templateService
*/
public void setTemplateService(TemplateService templateService)
{
this.templateService = templateService;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getRequiredAuthentication() * @see org.alfresco.web.api.APIService#getRequiredAuthentication()
*/ */
@@ -110,14 +97,6 @@ public class TextSearch implements APIService
return APIRequest.HttpMethod.GET; return APIRequest.HttpMethod.GET;
} }
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpUri()
*/
public String getHttpUri()
{
return this.uri;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.alfresco.web.api.APIService#execute(org.alfresco.web.api.APIRequest, org.alfresco.web.api.APIResponse) * @see org.alfresco.web.api.APIService#execute(org.alfresco.web.api.APIRequest, org.alfresco.web.api.APIResponse)
*/ */
@@ -125,7 +104,7 @@ public class TextSearch implements APIService
throws IOException throws IOException
{ {
// //
// execute the search // process parameters
// //
String searchTerms = req.getParameter("q"); String searchTerms = req.getParameter("q");
@@ -139,8 +118,22 @@ public class TextSearch implements APIService
{ {
// NOTE: use default startPage // NOTE: use default startPage
} }
String itemsPerPageArg = req.getParameter("c");
int itemsPerPage = DEFAULT_ITEMS_PER_PAGE;
try
{
itemsPerPage = new Integer(itemsPerPageArg);
}
catch(NumberFormatException e)
{
// NOTE: use default itemsPerPage
}
SearchResult results = search(searchTerms, startPage); //
// execute the search
//
SearchResult results = search(searchTerms, startPage, itemsPerPage);
// //
// render the results // render the results
@@ -160,12 +153,10 @@ public class TextSearch implements APIService
} }
} }
// execute template Map<String, Object> model = createTemplateModel(req, res);
Map<String, Object> searchModel = new HashMap<String, Object>(7, 1.0f); model.put("search", results);
searchModel.put("request", req);
searchModel.put("search", results);
res.setContentType(contentType + ";charset=UTF-8"); res.setContentType(contentType + ";charset=UTF-8");
templateService.processTemplateString(null, template, searchModel, res.getWriter()); renderTemplate(template, model, res);
} }
/** /**
@@ -175,30 +166,38 @@ public class TextSearch implements APIService
* @param startPage * @param startPage
* @return * @return
*/ */
private SearchResult search(String searchTerms, int startPage) private SearchResult search(String searchTerms, int startPage, int itemsPerPage)
{ {
SearchResult searchResult = null; SearchResult searchResult = null;
ResultSet results = null; ResultSet results = null;
try try
{ {
// Construct search statement // construct search statement
String[] terms = searchTerms.split(" "); String[] terms = searchTerms.split(" ");
Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f); Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f);
statementModel.put("terms", terms); statementModel.put("terms", terms);
String query = templateService.processTemplateString(null, QUERY_STATEMENT, statementModel); String query = getTemplateService().processTemplateString(null, QUERY_STATEMENT, statementModel);
results = searchService.query(searchStore, SearchService.LANGUAGE_LUCENE, query);
// execute query
if (logger.isDebugEnabled())
logger.debug("Issuing lucene search: " + query);
results = searchService.query(SEARCH_STORE, SearchService.LANGUAGE_LUCENE, query);
int totalResults = results.length(); int totalResults = results.length();
int totalPages = (totalResults / itemsPerPage);
totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0; if (logger.isDebugEnabled())
logger.debug("Results: " + totalResults + " rows");
// are we out-of-range // are we out-of-range
int totalPages = (totalResults / itemsPerPage);
totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;
if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) if (totalPages != 0 && (startPage < 1 || startPage > totalPages))
{ {
throw new APIException("Start page " + startPage + " is outside boundary of " + totalPages + " pages"); throw new APIException("Start page " + startPage + " is outside boundary of " + totalPages + " pages");
} }
// construct search result
searchResult = new SearchResult(); searchResult = new SearchResult();
searchResult.setSearchTerms(searchTerms); searchResult.setSearchTerms(searchTerms);
searchResult.setItemsPerPage(itemsPerPage); searchResult.setItemsPerPage(itemsPerPage);
@@ -207,13 +206,14 @@ public class TextSearch implements APIService
searchResult.setTotalResults(totalResults); searchResult.setTotalResults(totalResults);
searchResult.setStartIndex(((startPage -1) * itemsPerPage) + 1); searchResult.setStartIndex(((startPage -1) * itemsPerPage) + 1);
searchResult.setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1)); searchResult.setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
TemplateNode[] nodes = new TemplateNode[searchResult.getTotalPageItems()]; SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
for (int i = 0; i < searchResult.getTotalPageItems(); i++) for (int i = 0; i < searchResult.getTotalPageItems(); i++)
{ {
nodes[i] = new TemplateNode(results.getNodeRef(i + searchResult.getStartIndex() - 1), serviceRegistry, null); NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
float score = results.getScore(i + searchResult.getStartIndex() - 1);
nodes[i] = new SearchTemplateNode(node, score);
} }
searchResult.setResults(nodes); searchResult.setResults(nodes);
return searchResult; return searchResult;
} }
finally finally
@@ -240,7 +240,7 @@ public class TextSearch implements APIService
private int totalPageItems; private int totalPageItems;
private int startPage; private int startPage;
private int startIndex; private int startIndex;
private TemplateNode[] results; private SearchTemplateNode[] results;
public int getItemsPerPage() public int getItemsPerPage()
@@ -258,7 +258,7 @@ public class TextSearch implements APIService
return results; return results;
} }
/*package*/ void setResults(TemplateNode[] results) /*package*/ void setResults(SearchTemplateNode[] results)
{ {
this.results = results; this.results = results;
} }
@@ -333,41 +333,79 @@ public class TextSearch implements APIService
} }
} }
/**
* Search result row template node
*/
public class SearchTemplateNode extends TemplateNode
{
private static final long serialVersionUID = -1791913270786140012L;
private float score;
/**
* Construct
*
* @param nodeRef
* @param score
*/
public SearchTemplateNode(NodeRef nodeRef, float score)
{
super(nodeRef, getServiceRegistry(), iconResolver);
this.score = score;
}
/**
* Gets the result row score
*
* @return score
*/
public float getScore()
{
return score;
}
}
// TODO: place into accessible file // TODO: place into accessible file
private final static String ATOM_TEMPLATE = private final static String ATOM_TEMPLATE =
"<#assign dateformat=\"yyyy-MM-dd\">" + "<#assign dateformat=\"yyyy-MM-dd\">" +
"<#assign timeformat=\"HH:mm:sszzz\">" + "<#assign timeformat=\"HH:mm:sszzz\">" +
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\">\n" + "<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:relevance=\"http://a9.com/-/opensearch/extensions/relevance/1.0/\">\n" +
" <generator version=\"${agent.version}\">Alfresco (${agent.edition})</generator>\n" +
" <title>Alfresco Search: ${search.searchTerms}</title>\n" + " <title>Alfresco Search: ${search.searchTerms}</title>\n" +
" <updated>2003-12-13T18:30:02Z</updated>\n" + // TODO: " <updated>${date?string(dateformat)}T${date?string(timeformat)}</updated>\n" +
" <icon>${request.path}/images/logo/AlfrescoLogo16.ico</icon>\n" +
" <author>\n" + " <author>\n" +
" <name>Alfresco</name>\n" + // TODO: Issuer of search? " <name><#if request.authenticatedUsername?exists>${request.authenticatedUsername}<#else>unknown</#if></name>\n" +
" </author>\n" + " </author>\n" +
" <id>urn:uuid:${search.id}</id>\n" + " <id>urn:uuid:${search.id}</id>\n" +
" <opensearch:totalResults>${search.totalResults}</opensearch:totalResults>\n" + " <opensearch:totalResults>${search.totalResults}</opensearch:totalResults>\n" +
" <opensearch:startIndex>${search.startIndex}</opensearch:startIndex>\n" + " <opensearch:startIndex>${search.startIndex}</opensearch:startIndex>\n" +
" <opensearch:itemsPerPage>${search.itemsPerPage}</opensearch:itemsPerPage>\n" + " <opensearch:itemsPerPage>${search.itemsPerPage}</opensearch:itemsPerPage>\n" +
" <opensearch:Query role=\"request\" searchTerms=\"${search.searchTerms}\" startPage=\"${search.startPage}\"/>\n" + " <opensearch:Query role=\"request\" searchTerms=\"${search.searchTerms}\" startPage=\"${search.startPage}\"/>\n" +
" <link rel=\"alternate\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage}&amp;format=html\" type=\"text/html\"/>\n" + " <link rel=\"alternate\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage}&amp;c=${search.itemsPerPage}&amp;guest=${request.guest?string(\"true\",\"\")}&amp;format=html\" type=\"text/html\"/>\n" +
" <link rel=\"self\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage}&amp;format=atom\" type=\"application/atom+xml\"/>\n" + " <link rel=\"self\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage}&amp;c=${search.itemsPerPage}&amp;guest=${request.guest?string(\"true\",\"\")}&amp;format=atom\" type=\"application/atom+xml\"/>\n" +
" <link rel=\"first\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=1&amp;format=atom\" type=\"application/atom+xml\"/>\n" + " <link rel=\"first\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=1&amp;c=${search.itemsPerPage}&amp;guest=${request.guest?string(\"true\",\"\")}&amp;format=atom\" type=\"application/atom+xml\"/>\n" +
"<#if search.startPage &gt; 1>" + "<#if search.startPage &gt; 1>" +
" <link rel=\"previous\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage - 1}&amp;format=atom\" type=\"application/atom+xml\"/>\n" + " <link rel=\"previous\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage - 1}&amp;c=${search.itemsPerPage}&amp;guest=${request.guest?string(\"true\",\"\")}&amp;format=atom\" type=\"application/atom+xml\"/>\n" +
"</#if>" + "</#if>" +
"<#if search.startPage &lt; search.totalPages>" + "<#if search.startPage &lt; search.totalPages>" +
" <link rel=\"next\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage + 1}&amp;format=atom\" type=\"application/atom+xml\"/>\n" + " <link rel=\"next\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.startPage + 1}&amp;c=${search.itemsPerPage}&amp;guest=${request.guest?string(\"true\",\"\")}&amp;format=atom\" type=\"application/atom+xml\"/>\n" +
"</#if>" + "</#if>" +
" <link rel=\"last\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.totalPages}&amp;format=atom\" type=\"application/atom+xml\"/>\n" + " <link rel=\"last\" href=\"${request.servicePath}/search/text?q=${search.searchTerms}&amp;p=${search.totalPages}&amp;c=${search.itemsPerPage}&amp;guest=${request.guest?string(\"true\",\"\")}&amp;format=atom\" type=\"application/atom+xml\"/>\n" +
" <link rel=\"search\" type=\"application/opensearchdescription+xml\" href=\"${request.servicePath}/search/text/textsearchdescription.xml\"/>\n" + " <link rel=\"search\" type=\"application/opensearchdescription+xml\" href=\"${request.servicePath}/search/text/textsearchdescription.xml\"/>\n" +
"<#list search.results as row>" + "<#list search.results as row>" +
" <entry>\n" + " <entry>\n" +
" <title>${row.name}</title>\n" + " <title>${row.name}</title>\n" +
" <link href=\"${request.path}/${row.url}\"/>\n" + " <link href=\"${request.path}${row.url}\"/>\n" +
" <icon>${request.path}${row.icon16}\"</icon>\n" + // TODO: Standard for entry icons?
" <id>urn:uuid:${row.id}</id>\n" + " <id>urn:uuid:${row.id}</id>\n" +
" <updated>${row.properties.modified?string(dateformat)}T${row.properties.modified?string(timeformat)}</updated>\n" + " <updated>${row.properties.modified?string(dateformat)}T${row.properties.modified?string(timeformat)}</updated>\n" +
" <summary>${row.properties.description}</summary>\n" + " <summary>${row.properties.description}</summary>\n" +
" <author>\n" +
" <name>${row.properties.creator}</name>\n" +
" </author>\n" +
" <relevance:score>${row.score}</relevance:score>\n" +
" </entry>\n" + " </entry>\n" +
"</#list>" + "</#list>" +
"</feed>"; "</feed>";
@@ -386,53 +424,53 @@ public class TextSearch implements APIService
" </head>\n" + " </head>\n" +
" <body>\n" + " <body>\n" +
" <h2>Alfresco Text Search</h2>\n" + " <h2>Alfresco Text Search</h2>\n" +
" Results <b>${search.startIndex}</b> - <b>${search.startIndex + search.totalPageItems - 1}</b> of <b>${search.totalResults}</b> for <b>${search.searchTerms}.</b>\n" + " Results <b>${search.startIndex}</b> - <b>${search.startIndex + search.totalPageItems - 1}</b> of <b>${search.totalResults}</b> for <b>${search.searchTerms}</b> " +
"visible to user <b><#if request.authenticatedUsername?exists>${request.authenticatedUsername}<#else>unknown</#if>.</b>\n" +
" <ul>\n" + " <ul>\n" +
"<#list search.results as row>" + "<#list search.results as row>" +
" <li>\n" + " <li>\n" +
" <a href=\"${request.path}/${row.url}\">\n" + " <img src=\"${request.path}${row.icon16}\"/>" +
" ${row.name}\n" + " <a href=\"${request.path}${row.url}\">${row.name}</a>\n" +
" </a>\n" +
" <div>\n" + " <div>\n" +
" ${row.properties.description}\n" + " ${row.properties.description}\n" +
" </div>\n" + " </div>\n" +
" </li>\n" + " </li>\n" +
"</#list>" + "</#list>" +
" </ul>\n" + " </ul>\n" +
" <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=1\">first</a>" + " <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=1&c=${search.itemsPerPage}&guest=${request.guest?string(\"true\",\"\")}\">first</a>" +
"<#if search.startPage &gt; 1>" + "<#if search.startPage &gt; 1>" +
" <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.startPage - 1}\">previous</a>" + " <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.startPage - 1}&c=${search.itemsPerPage}&guest=${request.guest?string(\"true\",\"\")}\">previous</a>" +
"</#if>" + "</#if>" +
" <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.startPage}\">${search.startPage}</a>" + " <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.startPage}&c=${search.itemsPerPage}&guest=${request.guest?string(\"true\",\"\")}\">${search.startPage}</a>" +
"<#if search.startPage &lt; search.totalPages>" + "<#if search.startPage &lt; search.totalPages>" +
" <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.startPage + 1}\">next</a>" + " <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.startPage + 1}&c=${search.itemsPerPage}&guest=${request.guest?string(\"true\",\"\")}\">next</a>" +
"</#if>" + "</#if>" +
" <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.totalPages}\">last</a>" + " <a href=\"${request.servicePath}/search/text?q=${search.searchTerms}&p=${search.totalPages}&c=${search.itemsPerPage}&guest=${request.guest?string(\"true\",\"\")}\">last</a>" +
" </body>\n" + " </body>\n" +
"</html>\n"; "</html>\n";
// TODO: place into accessible file // TODO: place into accessible file
private final static String QUERY_STATEMENT = private final static String QUERY_STATEMENT =
"( " + "(" +
" TYPE:\"{http://www.alfresco.org/model/content/1.0}content\" AND " + "TYPE:\"{http://www.alfresco.org/model/content/1.0}content\" AND " +
" (" + "(" +
" (" + "(" +
"<#list 1..terms?size as i>" + "<#list 1..terms?size as i>" +
" @\\{http\\://www.alfresco.org/model/content/1.0\\}name:${terms[i - 1]}" + "@\\{http\\://www.alfresco.org/model/content/1.0\\}name:${terms[i - 1]}" +
"<#if (i < terms?size)>" + "<#if (i < terms?size)>" +
" OR " + " OR " +
"</#if>" + "</#if>" +
"</#list>" + "</#list>" +
" ) " + ")" +
" ( " + "(" +
"<#list 1..terms?size as i>" + "<#list 1..terms?size as i>" +
" TEXT:${terms[i - 1]}" + "TEXT:${terms[i - 1]}" +
"<#if (i < terms?size)>" + "<#if (i < terms?size)>" +
" OR " + " OR " +
"</#if>" + "</#if>" +
"</#list>" + "</#list>" +
" )" + ")" +
" )" + ")" +
")"; ")";
@@ -453,6 +491,7 @@ public class TextSearch implements APIService
method.setServiceRegistry((ServiceRegistry)context.getBean(ServiceRegistry.SERVICE_REGISTRY)); method.setServiceRegistry((ServiceRegistry)context.getBean(ServiceRegistry.SERVICE_REGISTRY));
method.setTemplateService((TemplateService)context.getBean(ServiceRegistry.TEMPLATE_SERVICE.getLocalName())); method.setTemplateService((TemplateService)context.getBean(ServiceRegistry.TEMPLATE_SERVICE.getLocalName()));
method.setSearchService((SearchService)context.getBean(ServiceRegistry.SEARCH_SERVICE.getLocalName())); method.setSearchService((SearchService)context.getBean(ServiceRegistry.SEARCH_SERVICE.getLocalName()));
method.setDescriptorService((DescriptorService)context.getBean(ServiceRegistry.DESCRIPTOR_SERVICE.getLocalName()));
method.setHttpUri("/search/text"); method.setHttpUri("/search/text");
method.test(); method.test();
} }
@@ -464,18 +503,21 @@ public class TextSearch implements APIService
*/ */
private void test() private void test()
{ {
SearchResult result = search("alfresco tutorial", 1); SearchResult result = search("alfresco tutorial", 1, 5);
Map<String, Object> searchModel = new HashMap<String, Object>(7, 1.0f); Map<String, Object> searchModel = new HashMap<String, Object>(7, 1.0f);
Map<String, Object> request = new HashMap<String, Object>(); Map<String, Object> request = new HashMap<String, Object>();
request.put("servicePath", "http://localhost:8080/alfresco/service"); request.put("servicePath", "http://localhost:8080/alfresco/service");
request.put("path", "http://localhost:8080/alfresco"); request.put("path", "http://localhost:8080/alfresco");
request.put("guest", false);
searchModel.put("date", new Date());
searchModel.put("agent", getDescriptorService().getServerDescriptor());
searchModel.put("request", request); searchModel.put("request", request);
searchModel.put("search", result); searchModel.put("search", result);
StringWriter rendition = new StringWriter(); StringWriter rendition = new StringWriter();
PrintWriter writer = new PrintWriter(rendition); PrintWriter writer = new PrintWriter(rendition);
templateService.processTemplateString(null, HTML_TEMPLATE, searchModel, writer); getTemplateService().processTemplateString(null, ATOM_TEMPLATE, searchModel, writer);
System.out.println(rendition.toString()); System.out.println(rendition.toString());
} }

View File

@@ -17,13 +17,10 @@
package org.alfresco.web.api.services; package org.alfresco.web.api.services;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.alfresco.service.cmr.repository.TemplateService;
import org.alfresco.web.api.APIRequest; import org.alfresco.web.api.APIRequest;
import org.alfresco.web.api.APIResponse; import org.alfresco.web.api.APIResponse;
import org.alfresco.web.api.APIService;
import org.alfresco.web.api.APIRequest.HttpMethod; import org.alfresco.web.api.APIRequest.HttpMethod;
import org.alfresco.web.api.APIRequest.RequiredAuthentication; import org.alfresco.web.api.APIRequest.RequiredAuthentication;
@@ -33,30 +30,8 @@ import org.alfresco.web.api.APIRequest.RequiredAuthentication;
* *
* @author davidc * @author davidc
*/ */
public class TextSearchDescription implements APIService public class TextSearchDescription extends APIServiceImpl
{ {
// dependencies
private String uri;
private TemplateService templateService;
/**
* Sets the Http URI
*
* @param uri
*/
public void setHttpUri(String uri)
{
this.uri = uri;
}
/**
* @param templateService
*/
public void setTemplateService(TemplateService templateService)
{
this.templateService = templateService;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getRequiredAuthentication() * @see org.alfresco.web.api.APIService#getRequiredAuthentication()
@@ -74,37 +49,27 @@ public class TextSearchDescription implements APIService
return APIRequest.HttpMethod.GET; return APIRequest.HttpMethod.GET;
} }
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpUri()
*/
public String getHttpUri()
{
return this.uri;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.alfresco.web.api.APIService#execute(org.alfresco.web.api.APIRequest, org.alfresco.web.api.APIResponse) * @see org.alfresco.web.api.APIService#execute(org.alfresco.web.api.APIRequest, org.alfresco.web.api.APIResponse)
*/ */
public void execute(APIRequest req, APIResponse res) public void execute(APIRequest req, APIResponse res)
throws IOException throws IOException
{ {
// create model for open search template Map<String, Object> model = createTemplateModel(req, res);
Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);
model.put("request", req);
// execute template
res.setContentType(APIResponse.OPEN_SEARCH_DESCRIPTION_TYPE + ";charset=UTF-8"); res.setContentType(APIResponse.OPEN_SEARCH_DESCRIPTION_TYPE + ";charset=UTF-8");
templateService.processTemplateString(null, OPEN_SEARCH_DESCRIPTION, model, res.getWriter()); renderTemplate(OPEN_SEARCH_DESCRIPTION, model, res);
} }
// TODO: place into accessible file // TODO: place into accessible file
private final static String OPEN_SEARCH_DESCRIPTION = private final static String OPEN_SEARCH_DESCRIPTION =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\">\n" + "<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:alf=\"http://www.alfresco.org\">\n" +
" <ShortName>Alfresco Text Search</ShortName>\n" + " <ShortName>Alfresco Text Search</ShortName>\n" +
" <Description>Search all of Alfresco Company Home via text keywords</Description>\n" + " <LongName>Alfresco ${agent.edition} Text Search ${agent.version}</LongName>\n" +
" <Url type=\"application/atom+xml\" template=\"${request.servicePath}/search/text?q={searchTerms}&amp;p={startPage?}&amp;format=atom\"/>\n" + " <Description>Search Alfresco \"company home\" using text keywords</Description>\n" +
" <Url type=\"text/html\" template=\"${request.servicePath}/search/text?q={searchTerms}&amp;p={startPage?}\"/>\n" + " <Url type=\"application/atom+xml\" template=\"${request.servicePath}/search/text?q={searchTerms}&amp;p={startPage?}&amp;c={count?}&amp;guest={alf:guest?}&amp;format=atom\"/>\n" +
" <Url type=\"text/html\" template=\"${request.servicePath}/search/text?q={searchTerms}&amp;p={startPage?}&amp;c={count?}&amp;guest={alf:guest?}\"/>\n" +
" <Image height=\"16\" width=\"16\" type=\"image/x-icon\">${request.path}/images/logo/AlfrescoLogo16.ico</Image>\n" +
"</OpenSearchDescription>"; "</OpenSearchDescription>";
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 894 B