You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by su...@apache.org on 2012/11/27 10:42:50 UTC

svn commit: r1414039 - in /stanbol/trunk/contenthub: servicesapi/src/main/java/org/apache/stanbol/contenthub/servicesapi/ldpath/ web/src/main/java/org/apache/stanbol/contenthub/web/resources/

Author: suat
Date: Tue Nov 27 09:42:48 2012
New Revision: 1414039

URL: http://svn.apache.org/viewvc?rev=1414039&view=rev
Log:
STANBOL-781:
Currently, when a ContentItem is submitted to an index which was created using a custom LDPath, the LDPath is only executed on the recognized entities through the Entityhub. This aims to gather additional information regarding to the entities of the ContentItem.

However, we would need to execute custom LDPath programs on additional RDF parts of ContentItems. Otherwise, it is not possible benefit from the additional parts. With this commit, SemanticIndexManagerImpl will execute the LDPath program on the RDF parts of ContentItem through the ContentItemBackend.

Modified:
    stanbol/trunk/contenthub/servicesapi/src/main/java/org/apache/stanbol/contenthub/servicesapi/ldpath/SemanticIndexManager.java
    stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/FeaturedSearchResource.java
    stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/SemanticIndexManagerResource.java

Modified: stanbol/trunk/contenthub/servicesapi/src/main/java/org/apache/stanbol/contenthub/servicesapi/ldpath/SemanticIndexManager.java
URL: http://svn.apache.org/viewvc/stanbol/trunk/contenthub/servicesapi/src/main/java/org/apache/stanbol/contenthub/servicesapi/ldpath/SemanticIndexManager.java?rev=1414039&r1=1414038&r2=1414039&view=diff
==============================================================================
--- stanbol/trunk/contenthub/servicesapi/src/main/java/org/apache/stanbol/contenthub/servicesapi/ldpath/SemanticIndexManager.java (original)
+++ stanbol/trunk/contenthub/servicesapi/src/main/java/org/apache/stanbol/contenthub/servicesapi/ldpath/SemanticIndexManager.java Tue Nov 27 09:42:48 2012
@@ -21,115 +21,104 @@ import java.util.Collection;
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.stanbol.enhancer.servicesapi.ContentItem;
+
 import at.newmedialab.ldpath.model.programs.Program;
 
 /**
- * This interface provides create, retrieve, delete operations for LDPath
- * programs to be managed in the scope of Contenthub.
+ * This interface provides create, retrieve, delete operations for LDPath programs to be managed in the scope
+ * of Contenthub.
  * 
  * @author anil.sinaci
  * 
  */
 public interface SemanticIndexManager {
 
-	/**
-	 * Saves LDPath program to persistent storage with given name and
-	 * initializes a new Solr core with the same name
-	 * 
-	 * @param programName
-	 *            name of the submitted program, also will be name of
-	 *            corresponding Solr Core
-	 * @param ldPathProgram
-	 *            LDPath Program in the form of {@link String}
-	 * @throws LDPathException
-	 *             is thrown while parsing program and creating Solr Core
-	 */
-	public void submitProgram(String programName, String ldPathProgram)
-			throws LDPathException;
-
-	/**
-	 * Saves LDPath program to persistent storage with given name and
-	 * initializes a new Solr core with the same name
-	 * 
-	 * @param programName
-	 *            name of the submitted program, also will be name of
-	 *            corresponding Solr Core
-	 * @param ldPathProgram
-	 *            LDPath Program in the form of {@link java.io.Reader}
-	 * @throws LDPathException
-	 *             is thrown while parsing program and creating Solr Core
-	 */
-	public void submitProgram(String programName, Reader ldPathProgram)
-			throws LDPathException;
-
-	/**
-	 * Checks whether a program-core pair exists with given name or not
-	 * 
-	 * @param programName
-	 *            name of the program/core
-	 * @return {@link true} if a program with given name exists; {@link false}
-	 *         otherwise
-	 */
-	public boolean isManagedProgram(String programName);
-
-	/**
-	 * Retrieves the program managed by {@link ProgramManager} with given name
-	 * 
-	 * @param programName
-	 *            name of the program that will be retrieved
-	 * @return requested program as String, if such program does not exist,
-	 *         returns {@link false}
-	 */
-	public String getProgramByName(String programName);
-
-	 /**
-	 * Retrieves the program managed by {@link ProgramManager} with given
-	 name,
-	 * parses it, and returns the {@link Progra}
-	 *
-	 * @param programName
-	 * @return
-	 * @throws LDPathException
-	 */
-	 public Program<Object> getParsedProgramByName(String programName);
-
-	/**
-	 * Deletes both the program and the corresponding Solr Core
-	 * 
-	 * @param programName
-	 *            name of the program-core pair to be deleted
-	 */
-	public void deleteProgram(String programName);
-
-	/**
-	 * Used to retrieve names and programs of all currently managed program-core
-	 * pairs
-	 * 
-	 * @return All managed programs as {@link LDProgramCollection}
-	 */
-	public LDProgramCollection retrieveAllPrograms();
-
-	/**
-	 * This method first tries to obtain the program itself through the given
-	 * <code>programName</code> and if the program is obtained it is executed on
-	 * the given <code>graph</code>.
-	 * 
-	 * @param programName
-	 *            name of the program to be executed
-	 * @param contexts
-	 *            a {@link Set} of URIs (string representations) that are used
-	 *            as starting nodes to execute LDPath program specified by
-	 *            {@code programName} on the given {@code program}
-	 * @param graph
-	 *            a Clerezza graph on which the specified program will be
-	 *            executed
-	 * @return the {@link Map} containing the results obtained by executing the
-	 *         given program on the given graph. Keys of the map corresponds to
-	 *         fields in the program and values of the map corresponds to
-	 *         results obtained for the field specified in the key.
-	 * @throws LDPathException
-	 */
-	public Map<String, Collection<?>> executeProgram(String programName,
-			Set<String> contexts) throws LDPathException;
+    /**
+     * Saves LDPath program to persistent storage with given name and initializes a new Solr core with the
+     * same name
+     * 
+     * @param programName
+     *            name of the submitted program, also will be name of corresponding Solr Core
+     * @param ldPathProgram
+     *            LDPath Program in the form of {@link String}
+     * @throws LDPathException
+     *             is thrown while parsing program and creating Solr Core
+     */
+    public void submitProgram(String programName, String ldPathProgram) throws LDPathException;
+
+    /**
+     * Saves LDPath program to persistent storage with given name and initializes a new Solr core with the
+     * same name
+     * 
+     * @param programName
+     *            name of the submitted program, also will be name of corresponding Solr Core
+     * @param ldPathProgram
+     *            LDPath Program in the form of {@link java.io.Reader}
+     * @throws LDPathException
+     *             is thrown while parsing program and creating Solr Core
+     */
+    public void submitProgram(String programName, Reader ldPathProgram) throws LDPathException;
+
+    /**
+     * Checks whether a program-core pair exists with given name or not
+     * 
+     * @param programName
+     *            name of the program/core
+     * @return {@link true} if a program with given name exists; {@link false} otherwise
+     */
+    public boolean isManagedProgram(String programName);
+
+    /**
+     * Retrieves the program managed by {@link ProgramManager} with given name
+     * 
+     * @param programName
+     *            name of the program that will be retrieved
+     * @return requested program as String, if such program does not exist, returns {@link false}
+     */
+    public String getProgramByName(String programName);
+
+    /**
+     * Retrieves the program managed by {@link ProgramManager} with given name, parses it, and returns the
+     * {@link Progra}
+     * 
+     * @param programName
+     * @return
+     * @throws LDPathException
+     */
+    public Program<Object> getParsedProgramByName(String programName);
+
+    /**
+     * Deletes both the program and the corresponding Solr Core
+     * 
+     * @param programName
+     *            name of the program-core pair to be deleted
+     */
+    public void deleteProgram(String programName);
+
+    /**
+     * Used to retrieve names and programs of all currently managed program-core pairs
+     * 
+     * @return All managed programs as {@link LDProgramCollection}
+     */
+    public LDProgramCollection retrieveAllPrograms();
+
+    /**
+     * This method first tries to obtain the program itself through the given <code>programName</code> and if
+     * the program is obtained it is executed on the given <code>graph</code>.
+     * 
+     * @param programName
+     *            name of the program to be executed
+     * @param contexts
+     *            a {@link Set} of URIs (string representations) that are used as starting nodes to execute
+     *            LDPath program specified by {@code programName} on the given {@code program}
+     * @param ci
+     *            a {@link ContentItem} on which the specified program will be executed
+     * @return the {@link Map} containing the results obtained by executing the given program on the given
+     *         graph. Keys of the map corresponds to fields in the program and values of the map corresponds
+     *         to results obtained for the field specified in the key.
+     * @throws LDPathException
+     */
+    public Map<String,Collection<?>> executeProgram(String programName, Set<String> contexts, ContentItem ci) throws LDPathException;
 
 }

Modified: stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/FeaturedSearchResource.java
URL: http://svn.apache.org/viewvc/stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/FeaturedSearchResource.java?rev=1414039&r1=1414038&r2=1414039&view=diff
==============================================================================
--- stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/FeaturedSearchResource.java (original)
+++ stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/FeaturedSearchResource.java Tue Nov 27 09:42:48 2012
@@ -66,8 +66,8 @@ import org.slf4j.LoggerFactory;
 import org.apache.stanbol.commons.ldviewable.Viewable;
 
 /**
- * This class is the web resource which provides RESTful and HTTP interfaces for
- * {@link FeaturedSearch} services.
+ * This class is the web resource which provides RESTful and HTTP interfaces for {@link FeaturedSearch}
+ * services.
  * 
  * @author anil.sinaci
  * @author suat
@@ -76,302 +76,281 @@ import org.apache.stanbol.commons.ldview
 @Path("/contenthub/{index}/search/featured")
 public class FeaturedSearchResource extends BaseStanbolResource {
 
-	private final static Logger log = LoggerFactory
-			.getLogger(FeaturedSearchResource.class);
+    private final static Logger log = LoggerFactory.getLogger(FeaturedSearchResource.class);
 
-	private TcManager tcManager;
+    private TcManager tcManager;
 
-	private FeaturedSearch featuredSearch;
+    private FeaturedSearch featuredSearch;
 
-	private String indexName;
+    private String indexName;
 
-	/**
-	 * 
-	 * @param context
-	 * @param indexName
-	 *            Name of the LDPath program (name of the Solr core/index) to be
-	 *            used while storing this content item. LDPath programs can be
-	 *            managed through {@link SemanticIndexManagerResource} or
-	 *            {@link SemanticIndexManager}
-	 * @throws IOException
-	 * @throws InvalidSyntaxException
-	 */
-	public FeaturedSearchResource(@Context ServletContext context,
-			@PathParam(value = "index") String indexName) throws IOException,
-			InvalidSyntaxException {
-		this.indexName = indexName;
-		this.featuredSearch = ContextHelper.getServiceFromContext(
-				FeaturedSearch.class, context);
-		this.tcManager = ContextHelper.getServiceFromContext(TcManager.class,
-				context);
-	}
-
-	@OPTIONS
-	public Response handleCorsPreflight(@Context HttpHeaders headers) {
-		ResponseBuilder res = Response.ok();
-		enableCORS(servletContext, res, headers);
-		return res.build();
-	}
-
-	/**
-	 * HTTP GET method to make a featured search over Contenthub.
-	 * 
-	 * @param queryTerm
-	 *            A keyword a statement or a set of keywords which can be
-	 *            regarded as the query term.
-	 * @param solrQuery
-	 *            Solr query string. This is the string format which is accepted
-	 *            by a Solr server. For example, {@code q="john doe"&fl=score}
-	 *            is a valid value for this parameter. If this parameter exists,
-	 *            search is performed based on this solrQuery and any queryTerms
-	 *            are neglected.
-	 * @param jsonCons
-	 *            Constrainst in JSON format. These constraints are tranformed
-	 *            to corresponding Solr queries to enable faceted search. Each
-	 *            constraint is a facet field and values of the constraints maps
-	 *            to the values of the facet fields in Solr queries.
-	 * @param ontologyURI
-	 *            URI of the ontology in which related keywords will be searched
-	 *            by
-	 *            {@link RelatedKeywordSearchManager#getRelatedKeywordsFromOntology(String, String)}
-	 * @param offset
-	 *            The offset of the document from which the resultant documents
-	 *            will start as the search result. {@link offset} and
-	 *            {@link limit} parameters can be used to make a pagination
-	 *            mechanism for search results.
-	 * @param limit
-	 *            Maximum number of resultant documents to be returned as the
-	 *            search result. {@link offset} and {@link limit} parameters can
-	 *            be used to make a pagination mechanism for search results.
-	 * @param fromStore
-	 *            Special parameter for HTML view only.
-	 * @param headers
-	 *            HTTP headers
-	 * @return HTML view or JSON representation of the search results or HTTP
-	 *         BAD REQUEST(400)
-	 * @throws IllegalArgumentException
-	 * @throws SearchException
-	 * @throws InstantiationException
-	 * @throws IllegalAccessException
-	 * @throws SolrServerException
-	 * @throws IOException
-	 */
-	@GET
-	@Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON })
-	public final Response get(@QueryParam("queryTerm") String queryTerm,
-			@QueryParam("solrQuery") String solrQuery,
-			@QueryParam("constraints") String jsonCons,
-			@QueryParam("ontologyURI") String ontologyURI,
-			@QueryParam("offset") @DefaultValue("0") int offset,
-			@QueryParam("limit") @DefaultValue("10") int limit,
-			@QueryParam("fromStore") String fromStore,
-			@Context HttpHeaders headers) throws IllegalArgumentException,
-			SearchException, InstantiationException, IllegalAccessException,
-			SolrServerException, IOException {
-		MediaType acceptedHeader = RestUtil.getAcceptedMediaType(headers);
-
-		this.queryTerm = queryTerm = RestUtil.nullify(queryTerm);
-		solrQuery = RestUtil.nullify(solrQuery);
-		ontologyURI = RestUtil.nullify(ontologyURI);
-		jsonCons = RestUtil.nullify(jsonCons);
-		this.offset = offset;
-		this.pageSize = limit;
-
-		if (acceptedHeader.isCompatible(MediaType.TEXT_HTML_TYPE)) {
-			if (fromStore != null) {
-				return Response.ok(new Viewable("index", this),
-						MediaType.TEXT_HTML).build();
-			}
-			if (queryTerm == null && solrQuery == null) {
-				this.ontologies = new ArrayList<String>();
-				Set<UriRef> mGraphs = tcManager.listMGraphs();
-				Iterator<UriRef> it = mGraphs.iterator();
-				while (it.hasNext()) {
-					ontologyURI = it.next().getUnicodeString();
-					if (Constants.isGraphReserved(ontologyURI)) {
-						continue;
-					}
-					this.ontologies.add(ontologyURI);
-				}
-				return Response.ok(new Viewable("index", this),
-						MediaType.TEXT_HTML).build();
-			} else {
-				ResponseBuilder rb = performSearch(queryTerm, solrQuery,
-						jsonCons, ontologyURI, offset, limit,
-						MediaType.TEXT_HTML_TYPE);
-				addCORSOrigin(servletContext, rb, headers);
-				return rb.build();
-			}
-		} else {
-			if (queryTerm == null && solrQuery == null) {
-				return Response
-						.status(Status.BAD_REQUEST)
-						.entity("Either 'queryTerm' or 'solrQuery' should be specified")
-						.build();
-			} else {
-				ResponseBuilder rb = performSearch(queryTerm, solrQuery,
-						jsonCons, ontologyURI, offset, limit,
-						MediaType.APPLICATION_JSON_TYPE);
-				addCORSOrigin(servletContext, rb, headers);
-				return rb.build();
-			}
-		}
-	}
-
-	private ResponseBuilder performSearch(String queryTerm, String solrQuery,
-			String jsonCons, String ontologyURI, int offset, int limit,
-			MediaType acceptedMediaType) throws SearchException {
-
-		if (solrQuery != null) {
-			this.searchResults = featuredSearch.search(
-					new SolrQuery(solrQuery), ontologyURI, indexName);
-		} else if (queryTerm != null) {
-			Map<String, List<Object>> constraintsMap = JSONUtils
-					.convertToMap(jsonCons);
-			this.chosenFacets = JSONUtils.convertToString(constraintsMap);
-
-			SolrQuery sq;
-			if (this.chosenFacets != null) {
-				List<FacetResult> allAvailableFacets = featuredSearch
-						.getAllFacetResults(indexName);
-				sq = SolrQueryUtil.prepareSolrQuery(queryTerm,
-						allAvailableFacets, constraintsMap);
-			} else {
-				sq = SolrQueryUtil.prepareSolrQuery(queryTerm);
-			}
-			sq.setStart(offset);
-			sq.setRows(limit + 1);
-			this.searchResults = featuredSearch.search(sq, ontologyURI,
-					indexName);
-		} else {
-			log.error("Should never reach here!!!!");
-			throw new SearchException(
-					"Either 'queryTerm' or 'solrQuery' paramater should be set");
-		}
-
-		ResponseBuilder rb = null;
-		if (acceptedMediaType.isCompatible(MediaType.TEXT_HTML_TYPE)) {
-			// return HTML document
-			/*
-			 * For HTML view, sort facets according to their names
-			 */
-			this.searchResults.setFacets(sortFacetResults(this.searchResults
-					.getFacets()));
-			rb = Response.ok(new Viewable("result.ftl", this));
-			rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML
-					+ "; charset=utf-8");
-
-		} else {
-			// it is compatible with JSON (default) - return JSON
-			rb = Response.ok(this.searchResults);
-			rb.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON
-					+ "; charset=utf-8");
-		}
-		return rb;
-	}
-
-	private List<FacetResult> sortFacetResults(List<FacetResult> facetResults) {
-		List<FacetResult> orderedFacets = new ArrayList<FacetResult>();
-		int annotatedFacetNum = 0;
-		for (FacetResult fr : facetResults) {
-			String facetName = fr.getFacetField().getName();
-			if (fr.getFacetField().getValues() == null) {
-				continue;
-			} else if (SolrVocabulary.SolrFieldName
-					.isAnnotatedEntityFacet(facetName)) {
-				orderedFacets.add(annotatedFacetNum, fr);
-				annotatedFacetNum++;
-			} else {
-				boolean inserted = false;
-				for (int j = annotatedFacetNum; j < orderedFacets.size(); j++) {
-					if (facetName.compareTo(orderedFacets.get(j)
-							.getFacetField().getName()) < 0) {
-						orderedFacets.add(j, fr);
-						inserted = true;
-						break;
-					}
-				}
-				if (inserted == false) {
-					orderedFacets.add(fr);
-				}
-			}
-		}
-		return orderedFacets;
-	}
-
-	/*
-	 * Services to draw HTML view
-	 */
-
-	// Data holders for HTML view
-	private List<String> ontologies = null;
-	private String queryTerm = null;
-	// private String solrQuery = null;
-	// private String ldProgram = null;
-	// private String graphURI = null;
-	private SearchResult searchResults = null;
-	private String chosenFacets = null;
-	private int offset = 0;
-	private int pageSize = 10;
-
-	// ///////////////////////////
-
-	/*
-	 * Helper methods for HTML view
-	 */
-
-	public Object getMoreRecentItems() {
-		if (offset >= pageSize) {
-			return new Object();
-		} else {
-			return null;
-		}
-	}
-
-	public Object getOlderItems() {
-		if (searchResults.getDocuments().size() <= pageSize) {
-			return null;
-		} else {
-			return new Object();
-		}
-	}
-
-	public int getOffset() {
-		return this.offset;
-	}
-
-	public int getPageSize() {
-		return this.pageSize;
-	}
-
-	public Object getSearchResults() {
-		return this.searchResults;
-	}
-
-	public Object getDocuments() {
-		if (searchResults.getDocuments().size() > pageSize) {
-			return searchResults.getDocuments().subList(0, pageSize);
-		} else {
-			return searchResults.getDocuments();
-		}
-	}
-
-	public Object getOntologies() {
-		return this.ontologies;
-	}
-
-	public Object getQueryTerm() {
-		if (queryTerm != null) {
-			return queryTerm;
-		}
-		return "";
-	}
-
-	public String getChosenFacets() {
-		return this.chosenFacets;
-	}
-
-	public String getIndexName() {
-		return this.indexName;
-	}
+    /**
+     * 
+     * @param context
+     * @param indexName
+     *            Name of the LDPath program (name of the Solr core/index) to be used while storing this
+     *            content item. LDPath programs can be managed through {@link SemanticIndexManagerResource} or
+     *            {@link SemanticIndexManager}
+     * @throws IOException
+     * @throws InvalidSyntaxException
+     */
+    public FeaturedSearchResource(@Context ServletContext context,
+                                  @PathParam(value = "index") String indexName) throws IOException,
+                                                                               InvalidSyntaxException {
+        this.indexName = indexName;
+        this.featuredSearch = ContextHelper.getServiceFromContext(FeaturedSearch.class, context);
+        this.tcManager = ContextHelper.getServiceFromContext(TcManager.class, context);
+    }
+
+    @OPTIONS
+    public Response handleCorsPreflight(@Context HttpHeaders headers) {
+        ResponseBuilder res = Response.ok();
+        enableCORS(servletContext, res, headers);
+        return res.build();
+    }
+
+    /**
+     * HTTP GET method to make a featured search over Contenthub.
+     * 
+     * @param queryTerm
+     *            A keyword a statement or a set of keywords which can be regarded as the query term.
+     * @param solrQuery
+     *            Solr query string. This is the string format which is accepted by a Solr server. For
+     *            example, {@code q="john doe"&fl=score} is a valid value for this parameter. If this
+     *            parameter exists, search is performed based on this solrQuery and any queryTerms are
+     *            neglected.
+     * @param jsonCons
+     *            Constrainst in JSON format. These constraints are tranformed to corresponding Solr queries
+     *            to enable faceted search. Each constraint is a facet field and values of the constraints
+     *            maps to the values of the facet fields in Solr queries.
+     * @param ontologyURI
+     *            URI of the ontology in which related keywords will be searched by
+     *            {@link RelatedKeywordSearchManager#getRelatedKeywordsFromOntology(String, String)}
+     * @param offset
+     *            The offset of the document from which the resultant documents will start as the search
+     *            result. {@link offset} and {@link limit} parameters can be used to make a pagination
+     *            mechanism for search results.
+     * @param limit
+     *            Maximum number of resultant documents to be returned as the search result. {@link offset}
+     *            and {@link limit} parameters can be used to make a pagination mechanism for search results.
+     * @param fromStore
+     *            Special parameter for HTML view only.
+     * @param headers
+     *            HTTP headers
+     * @return HTML view or JSON representation of the search results or HTTP BAD REQUEST(400)
+     * @throws IllegalArgumentException
+     * @throws SearchException
+     * @throws InstantiationException
+     * @throws IllegalAccessException
+     * @throws SolrServerException
+     * @throws IOException
+     */
+    @GET
+    @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
+    public final Response get(@QueryParam("queryTerm") String queryTerm,
+                              @QueryParam("solrQuery") String solrQuery,
+                              @QueryParam("constraints") String jsonCons,
+                              @QueryParam("ontologyURI") String ontologyURI,
+                              @QueryParam("offset") @DefaultValue("0") int offset,
+                              @QueryParam("limit") @DefaultValue("10") int limit,
+                              @QueryParam("fromStore") String fromStore,
+                              @Context HttpHeaders headers) throws IllegalArgumentException,
+                                                           SearchException,
+                                                           InstantiationException,
+                                                           IllegalAccessException,
+                                                           SolrServerException,
+                                                           IOException {
+        MediaType acceptedHeader = RestUtil.getAcceptedMediaType(headers, MediaType.APPLICATION_JSON_TYPE);
+
+        this.queryTerm = queryTerm = RestUtil.nullify(queryTerm);
+        solrQuery = RestUtil.nullify(solrQuery);
+        ontologyURI = RestUtil.nullify(ontologyURI);
+        jsonCons = RestUtil.nullify(jsonCons);
+        this.offset = offset;
+        this.pageSize = limit;
+
+        if (acceptedHeader.isCompatible(MediaType.TEXT_HTML_TYPE)) {
+            if (fromStore != null) {
+                return Response.ok(new Viewable("index", this), MediaType.TEXT_HTML).build();
+            }
+            if (queryTerm == null && solrQuery == null) {
+                this.ontologies = new ArrayList<String>();
+                Set<UriRef> mGraphs = tcManager.listMGraphs();
+                Iterator<UriRef> it = mGraphs.iterator();
+                while (it.hasNext()) {
+                    ontologyURI = it.next().getUnicodeString();
+                    if (Constants.isGraphReserved(ontologyURI)) {
+                        continue;
+                    }
+                    this.ontologies.add(ontologyURI);
+                }
+                return Response.ok(new Viewable("index", this), MediaType.TEXT_HTML).build();
+            } else {
+                ResponseBuilder rb = performSearch(queryTerm, solrQuery, jsonCons, ontologyURI, offset,
+                    limit, MediaType.TEXT_HTML_TYPE);
+                addCORSOrigin(servletContext, rb, headers);
+                return rb.build();
+            }
+        } else {
+            if (queryTerm == null && solrQuery == null) {
+                return Response.status(Status.BAD_REQUEST)
+                        .entity("Either 'queryTerm' or 'solrQuery' should be specified").build();
+            } else {
+                ResponseBuilder rb = performSearch(queryTerm, solrQuery, jsonCons, ontologyURI, offset,
+                    limit, MediaType.APPLICATION_JSON_TYPE);
+                addCORSOrigin(servletContext, rb, headers);
+                return rb.build();
+            }
+        }
+    }
+
+    private ResponseBuilder performSearch(String queryTerm,
+                                          String solrQuery,
+                                          String jsonCons,
+                                          String ontologyURI,
+                                          int offset,
+                                          int limit,
+                                          MediaType acceptedMediaType) throws SearchException {
+
+        if (solrQuery != null) {
+            this.searchResults = featuredSearch.search(new SolrQuery(solrQuery), ontologyURI, indexName);
+        } else if (queryTerm != null) {
+            Map<String,List<Object>> constraintsMap = JSONUtils.convertToMap(jsonCons);
+            this.chosenFacets = JSONUtils.convertToString(constraintsMap);
+
+            SolrQuery sq;
+            if (this.chosenFacets != null) {
+                List<FacetResult> allAvailableFacets = featuredSearch.getAllFacetResults(indexName);
+                sq = SolrQueryUtil.prepareSolrQuery(queryTerm, allAvailableFacets, constraintsMap);
+            } else {
+                sq = SolrQueryUtil.prepareSolrQuery(queryTerm);
+            }
+            sq.setStart(offset);
+            sq.setRows(limit + 1);
+            this.searchResults = featuredSearch.search(sq, ontologyURI, indexName);
+        } else {
+            log.error("Should never reach here!!!!");
+            throw new SearchException("Either 'queryTerm' or 'solrQuery' paramater should be set");
+        }
+
+        ResponseBuilder rb = null;
+        if (acceptedMediaType.isCompatible(MediaType.TEXT_HTML_TYPE)) {
+            // return HTML document
+            /*
+             * For HTML view, sort facets according to their names
+             */
+            this.searchResults.setFacets(sortFacetResults(this.searchResults.getFacets()));
+            rb = Response.ok(new Viewable("result.ftl", this));
+            rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML + "; charset=utf-8");
+
+        } else {
+            // it is compatible with JSON (default) - return JSON
+            rb = Response.ok(this.searchResults);
+            rb.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=utf-8");
+        }
+        return rb;
+    }
+
+    private List<FacetResult> sortFacetResults(List<FacetResult> facetResults) {
+        List<FacetResult> orderedFacets = new ArrayList<FacetResult>();
+        int annotatedFacetNum = 0;
+        for (FacetResult fr : facetResults) {
+            String facetName = fr.getFacetField().getName();
+            if (fr.getFacetField().getValues() == null) {
+                continue;
+            } else if (SolrVocabulary.SolrFieldName.isAnnotatedEntityFacet(facetName)) {
+                orderedFacets.add(annotatedFacetNum, fr);
+                annotatedFacetNum++;
+            } else {
+                boolean inserted = false;
+                for (int j = annotatedFacetNum; j < orderedFacets.size(); j++) {
+                    if (facetName.compareTo(orderedFacets.get(j).getFacetField().getName()) < 0) {
+                        orderedFacets.add(j, fr);
+                        inserted = true;
+                        break;
+                    }
+                }
+                if (inserted == false) {
+                    orderedFacets.add(fr);
+                }
+            }
+        }
+        return orderedFacets;
+    }
+
+    /*
+     * Services to draw HTML view
+     */
+
+    // Data holders for HTML view
+    private List<String> ontologies = null;
+    private String queryTerm = null;
+    // private String solrQuery = null;
+    // private String ldProgram = null;
+    // private String graphURI = null;
+    private SearchResult searchResults = null;
+    private String chosenFacets = null;
+    private int offset = 0;
+    private int pageSize = 10;
+
+    // ///////////////////////////
+
+    /*
+     * Helper methods for HTML view
+     */
+
+    public Object getMoreRecentItems() {
+        if (offset >= pageSize) {
+            return new Object();
+        } else {
+            return null;
+        }
+    }
+
+    public Object getOlderItems() {
+        if (searchResults.getDocuments().size() <= pageSize) {
+            return null;
+        } else {
+            return new Object();
+        }
+    }
+
+    public int getOffset() {
+        return this.offset;
+    }
+
+    public int getPageSize() {
+        return this.pageSize;
+    }
+
+    public Object getSearchResults() {
+        return this.searchResults;
+    }
+
+    public Object getDocuments() {
+        if (searchResults.getDocuments().size() > pageSize) {
+            return searchResults.getDocuments().subList(0, pageSize);
+        } else {
+            return searchResults.getDocuments();
+        }
+    }
+
+    public Object getOntologies() {
+        return this.ontologies;
+    }
+
+    public Object getQueryTerm() {
+        if (queryTerm != null) {
+            return queryTerm;
+        }
+        return "";
+    }
+
+    public String getChosenFacets() {
+        return this.chosenFacets;
+    }
+
+    public String getIndexName() {
+        return this.indexName;
+    }
 }

Modified: stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/SemanticIndexManagerResource.java
URL: http://svn.apache.org/viewvc/stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/SemanticIndexManagerResource.java?rev=1414039&r1=1414038&r2=1414039&view=diff
==============================================================================
--- stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/SemanticIndexManagerResource.java (original)
+++ stanbol/trunk/contenthub/web/src/main/java/org/apache/stanbol/contenthub/web/resources/SemanticIndexManagerResource.java Tue Nov 27 09:42:48 2012
@@ -16,11 +16,11 @@
  */
 package org.apache.stanbol.contenthub.web.resources;
 
+import static javax.ws.rs.HttpMethod.DELETE;
+import static javax.ws.rs.HttpMethod.OPTIONS;
 import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
 import static org.apache.stanbol.commons.web.base.CorsHelper.addCORSOrigin;
 import static org.apache.stanbol.commons.web.base.CorsHelper.enableCORS;
-import static javax.ws.rs.HttpMethod.DELETE;
-import static javax.ws.rs.HttpMethod.OPTIONS;
 
 import java.util.List;
 
@@ -100,7 +100,7 @@ public class SemanticIndexManagerResourc
         enableCORS(servletContext, res, headers, DELETE, OPTIONS);
         return res.build();
     }
-    
+
     @OPTIONS
     @Path("/exists")
     public Response handleCorsPreflightExists(@Context HttpHeaders headers) {
@@ -121,14 +121,14 @@ public class SemanticIndexManagerResourc
     @GET
     @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
     public Response retrieveAllPrograms(@Context HttpHeaders headers) {
-        MediaType acceptedHeader = RestUtil.getAcceptedMediaType(headers);
+        MediaType acceptedHeader = RestUtil.getAcceptedMediaType(headers, MediaType.APPLICATION_JSON_TYPE);
         if (acceptedHeader.isCompatible(MediaType.TEXT_HTML_TYPE)) {
-        	return Response.ok(new Viewable("index", this), MediaType.TEXT_HTML).build();
-        } else{
-	        LDProgramCollection ldProgramCollection = programManager.retrieveAllPrograms();
-	        ResponseBuilder rb = Response.ok(ldProgramCollection, MediaType.APPLICATION_JSON);
-	        addCORSOrigin(servletContext, rb, headers);
-	        return rb.build();
+            return Response.ok(new Viewable("index", this), MediaType.TEXT_HTML).build();
+        } else {
+            LDProgramCollection ldProgramCollection = programManager.retrieveAllPrograms();
+            ResponseBuilder rb = Response.ok(ldProgramCollection, MediaType.APPLICATION_JSON);
+            addCORSOrigin(servletContext, rb, headers);
+            return rb.build();
         }
     }
 
@@ -151,12 +151,13 @@ public class SemanticIndexManagerResourc
                                   @FormParam("program") String program,
                                   @Context HttpHeaders headers) throws LDPathException {
 
-        try {
-            programManager.submitProgram(programName, program);
-        } catch (LDPathException e) {
-            logger.error("LDPath program cannot be submitted", e);
-            return Response.status(Status.BAD_REQUEST).entity(e).build();
+        programName = RestUtil.nullify(programName);
+        program = RestUtil.nullify(program);
+        if (programName == null || program == null) {
+            logger.error("LDPath program cannot be submitted");
+            return Response.status(Status.BAD_REQUEST).build();
         }
+        programManager.submitProgram(programName, program);
         ResponseBuilder rb = Response
                 .ok("LDPath program has been successfully saved and corresponding Solr Core has been successfully created.");
         addCORSOrigin(servletContext, rb, headers);
@@ -175,6 +176,7 @@ public class SemanticIndexManagerResourc
     @GET
     @Path("/program")
     public Response getProgramByName(@QueryParam("name") String programName, @Context HttpHeaders headers) {
+        programName = RestUtil.nullify(programName);
         String ldPathProgram = programManager.getProgramByName(programName);
         if (ldPathProgram == null) {
             return Response.status(Status.NOT_FOUND).build();
@@ -197,9 +199,10 @@ public class SemanticIndexManagerResourc
     @DELETE
     @Path("/program/{name}")
     public Response deleteProgram(@PathParam(value = "name") String programName, @Context HttpHeaders headers) {
-    	if(!programManager.isManagedProgram(programName)){
-    	    throw new WebApplicationException(404);
-    	}
+        programName = RestUtil.nullify(programName);
+        if (!programManager.isManagedProgram(programName)) {
+            throw new WebApplicationException(404);
+        }
         programManager.deleteProgram(programName);
         ResponseBuilder rb = Response.ok();
         addCORSOrigin(servletContext, rb, headers);
@@ -218,6 +221,7 @@ public class SemanticIndexManagerResourc
     @GET
     @Path("/exists")
     public Response isManagedProgram(@QueryParam("name") String programName, @Context HttpHeaders headers) {
+        programName = RestUtil.nullify(programName);
         if (programManager.isManagedProgram(programName)) {
             ResponseBuilder rb = Response.ok();
             addCORSOrigin(servletContext, rb, headers);