You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by rw...@apache.org on 2011/02/14 10:40:02 UTC

svn commit: r1070417 - in /incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey: parsers/ resource/ utils/

Author: rwesten
Date: Mon Feb 14 09:40:01 2011
New Revision: 1070417

URL: http://svn.apache.org/viewvc?rev=1070417&view=rev
Log:
Refactoring to remove duplicate code for parsing similar Requests for the /symbol /sites/ and site/{siteid}/ RESTful service endpoints

The shared functionality has been moved to the JerseyUtils class

Modified:
    incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/parsers/JSONToFieldQuery.java
    incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/ReferencedSiteRootResource.java
    incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SiteManagerRootResource.java
    incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SymbolResource.java
    incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/utils/JerseyUtils.java

Modified: incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/parsers/JSONToFieldQuery.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/parsers/JSONToFieldQuery.java?rev=1070417&r1=1070416&r2=1070417&view=diff
==============================================================================
--- incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/parsers/JSONToFieldQuery.java (original)
+++ incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/parsers/JSONToFieldQuery.java Mon Feb 14 09:40:01 2011
@@ -20,9 +20,9 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 
-import org.apache.stanbol.entityhub.core.query.DefaultQueryFactory;
 import org.apache.stanbol.entityhub.servicesapi.query.Constraint;
 import org.apache.stanbol.entityhub.servicesapi.query.FieldQuery;
+import org.apache.stanbol.entityhub.servicesapi.query.FieldQueryFactory;
 import org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint;
 import org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint;
 import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint;
@@ -43,12 +43,12 @@ import org.slf4j.LoggerFactory;
 public class JSONToFieldQuery {
     private static final Logger log = LoggerFactory.getLogger(JSONToFieldQuery.class);
     
-    public static FieldQuery fromJSON(String jsonQueryString) throws JSONException{
+    public static FieldQuery fromJSON(FieldQueryFactory queryFactory, String jsonQueryString) throws JSONException{
         if(jsonQueryString == null){
             throw new NullPointerException("The parsed JSON object MUST NOT be NULL!");
         }
         JSONObject jQuery = new JSONObject(jsonQueryString);
-        FieldQuery query = DefaultQueryFactory.getInstance().createFieldQuery();
+        FieldQuery query = queryFactory.createFieldQuery();
         if(!jQuery.has("constraints")){
             throw new IllegalArgumentException("The parsed JSON object MUST contain the required key \"constraints\"");
         }

Modified: incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/ReferencedSiteRootResource.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/ReferencedSiteRootResource.java?rev=1070417&r1=1070416&r2=1070417&view=diff
==============================================================================
--- incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/ReferencedSiteRootResource.java (original)
+++ incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/ReferencedSiteRootResource.java Mon Feb 14 09:40:01 2011
@@ -20,8 +20,6 @@ import static javax.ws.rs.core.MediaType
 import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA;
 
 import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Set;
@@ -46,19 +44,13 @@ import javax.ws.rs.core.Response;
 import org.apache.clerezza.rdf.core.serializedform.Serializer;
 import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
 import org.apache.clerezza.rdf.ontologies.RDFS;
-import org.apache.commons.io.FileUtils;
-import org.apache.stanbol.entityhub.core.query.FieldQueryImpl;
-import org.apache.stanbol.entityhub.jersey.parsers.JSONToFieldQuery;
 import org.apache.stanbol.entityhub.jersey.utils.JerseyUtils;
 import org.apache.stanbol.entityhub.servicesapi.model.Sign;
 import org.apache.stanbol.entityhub.servicesapi.query.FieldQuery;
-import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint;
-import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint.PatternType;
 import org.apache.stanbol.entityhub.servicesapi.site.ConfiguredSite;
 import org.apache.stanbol.entityhub.servicesapi.site.ReferencedSite;
 import org.apache.stanbol.entityhub.servicesapi.site.ReferencedSiteException;
 import org.apache.stanbol.entityhub.servicesapi.site.ReferencedSiteManager;
-import org.codehaus.jettison.json.JSONException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -180,18 +172,11 @@ public class ReferencedSiteRootResource 
             @FormParam(value="field") String field,
             @FormParam(value = "lang") String language,
             //@FormParam(value="select") String select,
-            @FormParam(value = "limit") @DefaultValue(value = "-1") int limit, @FormParam(value = "offset") @DefaultValue(value = "0") int offset, @Context HttpHeaders headers) {
-        log.info("site/" + site.getId() + "/find Request");
-        log.info("  > name  : " + name);
-        log.info("  > lang  : " + language);
-        log.info("  > limit : " + limit);
-        log.info("  > offset: " + offset);
-        log.info("  > accept: " + headers.getAcceptableMediaTypes());
-        if (name == null || name.trim().isEmpty()) {
-            log.error("/find Request with invalied name={}!", name);
-        } else {
-            name = name.trim();
-        }
+            @FormParam(value = "limit") Integer limit, 
+            @FormParam(value = "offset") Integer offset, 
+            @Context HttpHeaders headers) {
+        log.debug("site/" + site.getId() + "/find Request");
+        //process the optional search field parameter
         if(field == null){
             field = DEFAULT_FIND_FIELD;
         } else {
@@ -200,36 +185,10 @@ public class ReferencedSiteRootResource 
                 field = DEFAULT_FIND_FIELD;
             }
         }
-        FieldQuery query = new FieldQueryImpl();
-        if (language == null) {
-            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false));
-        } else {
-            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false, language));
-        }
-        Collection<String> selectedFields = new ArrayList<String>();
-        selectedFields.add(field); //select also the field used to find entities
-//        if(select == null ||select.isEmpty()){
-//            selectedFields.addAll(DEFAULT_FIND_SELECTED_FIELDS);
-//        } else {
-//            for(String selected : select.trim().split(" ")){
-//                if(selected != null && !selected.isEmpty()){
-//                    selectedFields.add(selected);
-//                }
-//            }
-//        }
-        query.addSelectedFields(selectedFields);
-        if (limit < 1) {
-            limit = DEFAULT_FIND_RESULT_LIMIT;
-        }
-        query.setLimit(limit);
-        query.setOffset(offset);
-        final MediaType acceptedMediaType = JerseyUtils.getAcceptableMediaType(headers, MediaType.APPLICATION_JSON_TYPE);
-        try {
-            return Response.ok(site.find(query), acceptedMediaType).build();
-        } catch (ReferencedSiteException e) {
-            log.error("ReferencedSiteException while accessing Site " + site.getName() + " (id=" + site.getId() + ")", e);
-            throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
-        }
+        return executeQuery(
+            JerseyUtils.createFieldQueryForFindRequest(name, field, language, 
+                limit == null || limit < 1 ? DEFAULT_FIND_RESULT_LIMIT : limit, offset),
+            headers);
     }
     /**
      * Allows to parse any kind of {@link FieldQuery} in its JSON Representation.
@@ -253,37 +212,19 @@ public class ReferencedSiteRootResource 
             @FormParam("query") String query,
             @FormParam("query") File file,
             @Context HttpHeaders headers) {
-        if(query == null && file == null) {
-            throw new WebApplicationException(new IllegalArgumentException("Query Requests MUST define the \"query\" parameter"), Response.Status.BAD_REQUEST);
-        }
-        FieldQuery fieldQuery = null;
-        JSONException exception = null;
-        if(query != null){
-            try {
-                fieldQuery = JSONToFieldQuery.fromJSON(query);
-            } catch (JSONException e) {
-                log.warn("unable to parse FieldQuery from \"application/x-www-form-urlencoded\" encoded query string "+query);
-                fieldQuery = null;
-                exception = e;
-            }
-        } //else no query via application/x-www-form-urlencoded parsed
-        if(fieldQuery == null && file != null){
-            try {
-                query = FileUtils.readFileToString(file);
-                fieldQuery = JSONToFieldQuery.fromJSON(query);
-            } catch (IOException e) {
-                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
-            } catch (JSONException e) {
-                log.warn("unable to parse FieldQuery from \"multipart/form-data\" encoded query string "+query);
-                exception = e;
-            }
-        }//fieldquery already initialised or no query via multipart/form-data parsed
-        if(fieldQuery == null){
-            throw new WebApplicationException(new IllegalArgumentException("Unable to parse FieldQuery for the parsed query\n"+query, exception),Response.Status.BAD_REQUEST);
-        }
+        return executeQuery(JerseyUtils.parseFieldQuery(query, file), headers);
+    }
+    /**
+     * Executes the query parsed by {@link #queryEntities(String, File, HttpHeaders)}
+     * or created based {@link #findEntity(String, String, String, int, int, HttpHeaders)}
+     * @param query The query to execute
+     * @param headers The headers used to determine the media types
+     * @return the response (results of error)
+     */
+    private Response executeQuery(FieldQuery query,HttpHeaders headers) throws WebApplicationException {
         final MediaType acceptedMediaType = JerseyUtils.getAcceptableMediaType(headers, MediaType.APPLICATION_JSON_TYPE);
         try {
-            return Response.ok(site.find(fieldQuery), acceptedMediaType).build();
+            return Response.ok(site.find(query), acceptedMediaType).build();
         } catch (ReferencedSiteException e) {
             log.error("ReferencedSiteException while accessing Site " + site.getName() + " (id=" + site.getId() + ")", e);
             throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);

Modified: incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SiteManagerRootResource.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SiteManagerRootResource.java?rev=1070417&r1=1070416&r2=1070417&view=diff
==============================================================================
--- incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SiteManagerRootResource.java (original)
+++ incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SiteManagerRootResource.java Mon Feb 14 09:40:01 2011
@@ -30,10 +30,7 @@ import static org.apache.clerezza.rdf.co
 import static org.apache.clerezza.rdf.core.serializedform.SupportedFormat.X_TURTLE;
 
 import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.Set;
 import java.util.TreeSet;
 
@@ -55,17 +52,11 @@ import javax.ws.rs.core.UriInfo;
 
 import org.apache.clerezza.rdf.core.serializedform.Serializer;
 import org.apache.clerezza.rdf.ontologies.RDFS;
-import org.apache.commons.io.FileUtils;
-import org.apache.stanbol.entityhub.core.query.FieldQueryImpl;
-import org.apache.stanbol.entityhub.jersey.parsers.JSONToFieldQuery;
 import org.apache.stanbol.entityhub.jersey.utils.JerseyUtils;
 import org.apache.stanbol.entityhub.servicesapi.model.Sign;
 import org.apache.stanbol.entityhub.servicesapi.query.FieldQuery;
-import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint;
-import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint.PatternType;
 import org.apache.stanbol.entityhub.servicesapi.site.ReferencedSiteManager;
 import org.codehaus.jettison.json.JSONArray;
-import org.codehaus.jettison.json.JSONException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -182,20 +173,10 @@ public class SiteManagerRootResource ext
             @FormParam(value="field") String field,
             @FormParam(value = "lang") String language,
             //@FormParam(value="select") String select,
-            @FormParam(value = "limit") @DefaultValue(value = "-1") int limit,
-            @FormParam(value = "offset") @DefaultValue(value = "0") int offset,
+            @FormParam(value = "limit") Integer limit,
+            @FormParam(value = "offset") Integer offset,
             @Context HttpHeaders headers) {
-        log.info("sites/find Request");
-        log.info("  > name  : " + name);
-        log.info("  > lang  : " + language);
-        log.info("  > limit : " + limit);
-        log.info("  > offset: " + offset);
-        log.info("  > accept: " + headers.getAcceptableMediaTypes());
-        if (name == null || name.trim().isEmpty()) {
-            log.error("/find Request with invalied name={}!", name);
-        } else {
-            name = name.trim();
-        }
+        log.debug("sites/find Request");
         if(field == null){
             field = DEFAULT_FIND_FIELD;
         } else {
@@ -204,29 +185,8 @@ public class SiteManagerRootResource ext
                 field = DEFAULT_FIND_FIELD;
             }
         }
-        FieldQuery query = new FieldQueryImpl();
-        if (language == null) {
-            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false));
-        } else {
-            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false, language));
-        }
-        Collection<String> selectedFields = new ArrayList<String>();
-        selectedFields.add(field); //select also the field used to find entities
-//        if(select == null ||select.isEmpty()){
-//            selectedFields.addAll(DEFAULT_FIND_SELECTED_FIELDS);
-//        } else {
-//            for(String selected : select.trim().split(" ")){
-//                if(selected != null && !selected.isEmpty()){
-//                    selectedFields.add(selected);
-//                }
-//            }
-//        }
-        query.addSelectedFields(selectedFields);
-        if (limit < 1) {
-            limit = DEFAULT_FIND_RESULT_LIMIT;
-        }
-        query.setLimit(limit);
-        query.setOffset(offset);
+        FieldQuery query = JerseyUtils.createFieldQueryForFindRequest(name, field, language, 
+            limit == null || limit < 1 ? DEFAULT_FIND_RESULT_LIMIT : limit, offset);
         final MediaType acceptedMediaType = JerseyUtils.getAcceptableMediaType(headers, APPLICATION_JSON_TYPE);
         return Response.ok(referencedSiteManager.find(query), acceptedMediaType).build();
     }
@@ -249,39 +209,12 @@ public class SiteManagerRootResource ext
     @Consumes( { APPLICATION_FORM_URLENCODED + ";qs=1.0",
             MULTIPART_FORM_DATA + ";qs=0.9" })
     public Response queryEntities(
-            @FormParam("query") String query,
+            @FormParam("query") String queryString,
             @FormParam("query") File file,
             @Context HttpHeaders headers) {
-        if(query == null && file == null) {
-            throw new WebApplicationException(new IllegalArgumentException("Query Requests MUST define the \"query\" parameter"), Response.Status.BAD_REQUEST);
-        }
-        FieldQuery fieldQuery = null;
-        JSONException exception = null;
-        if(query != null){
-            try {
-                fieldQuery = JSONToFieldQuery.fromJSON(query);
-            } catch (JSONException e) {
-                log.warn("unable to parse FieldQuery from \"application/x-www-form-urlencoded\" encoded query string "+query);
-                fieldQuery = null;
-                exception = e;
-            }
-        } //else no query via application/x-www-form-urlencoded parsed
-        if(fieldQuery == null && file != null){
-            try {
-                query = FileUtils.readFileToString(file);
-                fieldQuery = JSONToFieldQuery.fromJSON(query);
-            } catch (IOException e) {
-                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
-            } catch (JSONException e) {
-                log.warn("unable to parse FieldQuery from \"multipart/form-data\" encoded query string "+query);
-                exception = e;
-            }
-        }//fieldquery already initialised or no query via multipart/form-data parsed
-        if(fieldQuery == null){
-            throw new WebApplicationException(new IllegalArgumentException("Unable to parse FieldQuery for the parsed query\n"+query, exception),Response.Status.BAD_REQUEST);
-        }
+        FieldQuery query = JerseyUtils.parseFieldQuery(queryString, file);
         final MediaType acceptedMediaType = JerseyUtils.getAcceptableMediaType(headers, MediaType.APPLICATION_JSON_TYPE);
-        return Response.ok(referencedSiteManager.find(fieldQuery), acceptedMediaType).build();
+        return Response.ok(referencedSiteManager.find(query), acceptedMediaType).build();
     }
     
 }

Modified: incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SymbolResource.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SymbolResource.java?rev=1070417&r1=1070416&r2=1070417&view=diff
==============================================================================
--- incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SymbolResource.java (original)
+++ incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/resource/SymbolResource.java Mon Feb 14 09:40:01 2011
@@ -31,7 +31,6 @@ import static org.apache.clerezza.rdf.co
 import static org.apache.clerezza.rdf.core.serializedform.SupportedFormat.X_TURTLE;
 
 import java.io.File;
-import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -54,18 +53,12 @@ import javax.ws.rs.core.Response;
 import org.apache.clerezza.rdf.core.TripleCollection;
 import org.apache.clerezza.rdf.core.access.TcManager;
 import org.apache.clerezza.rdf.core.serializedform.Serializer;
-import org.apache.commons.io.FileUtils;
-import org.apache.stanbol.entityhub.core.query.FieldQueryImpl;
-import org.apache.stanbol.entityhub.jersey.parsers.JSONToFieldQuery;
 import org.apache.stanbol.entityhub.jersey.utils.JerseyUtils;
 import org.apache.stanbol.entityhub.servicesapi.Entityhub;
 import org.apache.stanbol.entityhub.servicesapi.EntityhubException;
 import org.apache.stanbol.entityhub.servicesapi.model.Symbol;
 import org.apache.stanbol.entityhub.servicesapi.model.rdf.RdfResourceEnum;
 import org.apache.stanbol.entityhub.servicesapi.query.FieldQuery;
-import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint;
-import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint.PatternType;
-import org.codehaus.jettison.json.JSONException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -81,6 +74,10 @@ public class SymbolResource extends Navi
      * The default search field for /find queries is the entityhub-maodel:label
      */
     private static final String DEFAULT_FIND_FIELD = RdfResourceEnum.label.getUri();
+    /**
+     * The default number of maximal results of searched sites.
+     */
+    private static final int DEFAULT_FIND_RESULT_LIMIT = 5;
 
     /**
      * The default result fields for /find queries is the entityhub-maodel:label and the
@@ -165,50 +162,38 @@ public class SymbolResource extends Navi
     public Response findEntity(@FormParam(value = "name") String name, 
             @FormParam(value = "field") String field,
             @FormParam(value = "lang") String language, 
+            @FormParam(value = "limit") Integer limit, 
+            @FormParam(value = "offset") Integer offset, 
+            //TODO: Jersey supports parsing multiple values in Collections. 
+            //      Use this feature here instead of using this hand crafted
+            //      solution!
             @FormParam(value = "select") String select, 
             @Context HttpHeaders headers) {
-        log.info("symbol/find Request");
-        log.info("  > name  : " + name);
-        log.info("  > field : " + field);
-        log.info("  > lang  : " + language);
-        log.info("  > select: " + select);
-        log.info("  > accept: " + headers.getAcceptableMediaTypes());
-        //TODO: Implement by using EntityQuery as soon as implemented
-        if (name == null || name.trim().isEmpty()) {
-            log.error("/find Request with invalied name={}!", name);
-        } else {
-            name = name.trim();
-        }
+        log.debug("symbol/find Request");
         if (field == null || field.trim().isEmpty()) {
             field = DEFAULT_FIND_FIELD;
         } else {
             field = field.trim();
         }
-        FieldQuery query = new FieldQueryImpl();
-        if (language == null) {
-            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false));
-        } else {
-            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false, language));
-        }
-        Collection<String> selectedFields = new ArrayList<String>();
-        selectedFields.add(field); //select also the field used to find entities
+        FieldQuery query = JerseyUtils.createFieldQueryForFindRequest(name, field, language,
+            limit == null || limit <1? DEFAULT_FIND_RESULT_LIMIT:limit, offset);
+
+        // For the Entityhub we support to select additional fields for results
+        // of find requests. For the Sites and {site} endpoint this is currently
+        // deactivated because of very bad performance with OPTIONAL graph patterns
+        // in SPARQL queries. 
+        Collection<String> additionalSelectedFields = new ArrayList<String>();
         if (select == null || select.isEmpty()) {
-            selectedFields.addAll(DEFAULT_FIND_SELECTED_FIELDS);
+            additionalSelectedFields.addAll(DEFAULT_FIND_SELECTED_FIELDS);
         } else {
             for (String selected : select.trim().split(" ")) {
                 if (selected != null && !selected.isEmpty()) {
-                    selectedFields.add(selected);
+                    additionalSelectedFields.add(selected);
                 }
             }
         }
-        query.addSelectedFields(selectedFields);
-        final MediaType acceptedMediaType = JerseyUtils.getAcceptableMediaType(headers, APPLICATION_JSON_TYPE);
-        try {
-            return Response.ok(entityhub.find(query), acceptedMediaType).build();
-        } catch (Exception e) {
-            log.error("Error while accessing Yard of the Entityhub" + entityhub.getYard().getName() + " (id=" + entityhub.getYard().getId() + ")", e);
-            throw new WebApplicationException(e, INTERNAL_SERVER_ERROR);
-        }
+        query.addSelectedFields(additionalSelectedFields);
+        return executeQuery(query, headers);
     }
 
     @DELETE
@@ -239,42 +224,24 @@ public class SymbolResource extends Navi
             @FormParam("query") String query,
             @FormParam("query") File file,
             @Context HttpHeaders headers) {
-        if(query == null && file == null) {
-            throw new WebApplicationException(new IllegalArgumentException("Query Requests MUST define the \"query\" parameter"), Response.Status.BAD_REQUEST);
-        }
-        FieldQuery fieldQuery = null;
-        JSONException exception = null;
-        if(query != null){
-            try {
-                fieldQuery = JSONToFieldQuery.fromJSON(query);
-            } catch (JSONException e) {
-                log.warn("unable to parse FieldQuery from \"application/x-www-form-urlencoded\" encoded query string "+query);
-                fieldQuery = null;
-                exception = e;
-            }
-        } //else no query via application/x-www-form-urlencoded parsed
-        if(fieldQuery == null && file != null){
-            try {
-                query = FileUtils.readFileToString(file);
-                fieldQuery = JSONToFieldQuery.fromJSON(query);
-            } catch (IOException e) {
-                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
-            } catch (JSONException e) {
-                log.warn("unable to parse FieldQuery from \"multipart/form-data\" encoded query string "+query);
-                exception = e;
-            }
-        }//fieldquery already initialised or no query via multipart/form-data parsed
-        if(fieldQuery == null){
-            throw new WebApplicationException(new IllegalArgumentException("Unable to parse FieldQuery for the parsed query\n"+query, exception),Response.Status.BAD_REQUEST);
-        }
+        return executeQuery(JerseyUtils.parseFieldQuery(query, file), headers);
+    }
+
+    /**
+     * Executes the query parsed by {@link #queryEntities(String, File, HttpHeaders)}
+     * or created based {@link #findEntity(String, String, String, String, HttpHeaders)
+     * @param query The query to execute
+     * @param headers The headers used to determine the media types
+     * @return the response (results of error)
+     */
+    private Response executeQuery(FieldQuery query, HttpHeaders headers) throws WebApplicationException {
         final MediaType acceptedMediaType = JerseyUtils.getAcceptableMediaType(headers, MediaType.APPLICATION_JSON_TYPE);
         try {
-            return Response.ok(entityhub.find(fieldQuery), acceptedMediaType).build();
+            return Response.ok(entityhub.find(query), acceptedMediaType).build();
         } catch (EntityhubException e) {
-            log.error("Exception while performing the parsed query on the EntityHub", e);
+            log.error("Exception while performing the FieldQuery on the EntityHub", e);
             log.error("Query:\n"+query);
             throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
         }
-        
     }
 }

Modified: incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/utils/JerseyUtils.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/utils/JerseyUtils.java?rev=1070417&r1=1070416&r2=1070417&view=diff
==============================================================================
--- incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/utils/JerseyUtils.java (original)
+++ incubator/stanbol/trunk/entityhub/jersey/src/main/java/org/apache/stanbol/entityhub/jersey/utils/JerseyUtils.java Mon Feb 14 09:40:01 2011
@@ -16,10 +16,41 @@
  */
 package org.apache.stanbol.entityhub.jersey.utils;
 
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 
+import org.apache.commons.io.FileUtils;
+import org.apache.stanbol.entityhub.core.query.DefaultQueryFactory;
+import org.apache.stanbol.entityhub.jersey.parsers.JSONToFieldQuery;
+import org.apache.stanbol.entityhub.servicesapi.query.FieldQuery;
+import org.apache.stanbol.entityhub.servicesapi.query.FieldQueryFactory;
+import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint;
+import org.apache.stanbol.entityhub.servicesapi.query.TextConstraint.PatternType;
+import org.codehaus.jettison.json.JSONException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+/**
+ * Utility methods used by several of the RESTful service endpoints of the
+ * Entityhub.
+ * @author Rupert Westenthaler
+ *
+ */
 public final class JerseyUtils {
+    
+    private static Logger log = LoggerFactory.getLogger(JerseyUtils.class);
+    
+    /**
+     * This utility class used the {@link DefaultQueryFactory} as
+     * {@link FieldQueryFactory} instance. 
+     */
+    private static FieldQueryFactory queryFactory = DefaultQueryFactory.getInstance();
 
     private JerseyUtils() {/* do not create instance of Util Classes */}
 
@@ -48,5 +79,111 @@ public final class JerseyUtils {
         }
         return acceptedMediaType;
     }
-
+    /**
+     * Returns the {@link FieldQuery} based on the JSON formatted String (in case
+     * of "application/x-www-form-urlencoded" requests) or file (in case of
+     * "multipart/form-data" requests).<p>
+     * @param query the string containing the JSON serialised FieldQuery or
+     * <code>null</code> in case of a "multipart/form-data" request
+     * @param file the temporary file holding the data parsed by the request to
+     * the web server in case of a "multipart/form-data" request or <code>null</code>
+     * in case of the "application/x-www-form-urlencoded" request.
+     * @return the FieldQuery parsed from the string provided by one of the two
+     * parameters
+     * @throws WebApplicationException if both parameter are <code>null</code> or
+     * if the string provided by both parameters could not be used to parse a
+     * {@link FieldQuery} instance.
+     */
+    public static FieldQuery parseFieldQuery(String query, File file) throws WebApplicationException {
+        if(query == null && file == null) {
+            throw new WebApplicationException(new IllegalArgumentException("Query Requests MUST define the \"query\" parameter"), Response.Status.BAD_REQUEST);
+        }
+        FieldQuery fieldQuery = null;
+        JSONException exception = null;
+        if(query != null){
+            try {
+                fieldQuery = JSONToFieldQuery.fromJSON(queryFactory,query);
+            } catch (JSONException e) {
+                log.warn("unable to parse FieldQuery from \"application/x-www-form-urlencoded\" encoded query string "+query);
+                fieldQuery = null;
+                exception = e;
+            }
+        } //else no query via application/x-www-form-urlencoded parsed
+        if(fieldQuery == null && file != null){
+            try {
+                query = FileUtils.readFileToString(file);
+                fieldQuery = JSONToFieldQuery.fromJSON(queryFactory,query);
+            } catch (IOException e) {
+                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
+            } catch (JSONException e) {
+                log.warn("unable to parse FieldQuery from \"multipart/form-data\" encoded query string "+query);
+                exception = e;
+            }
+        }//fieldquery already initialised or no query via multipart/form-data parsed
+        if(fieldQuery == null){
+            throw new WebApplicationException(new IllegalArgumentException("Unable to parse FieldQuery for the parsed query\n"+query, exception),Response.Status.BAD_REQUEST);
+        }
+        return fieldQuery;
+    }
+    /**
+     * Creates an {@link FieldQuery} for parameters parsed by the /find requests
+     * supported by the /symbol, /sites and {siteId} RESTful endpoints.
+     * TODO: This has to be refactored to use "EntityQuery" as soon as Multiple
+     *       query types are implemented for the Entityhub.
+     * @param name the name pattern to search entities for (required)
+     * @param field the field used to search for entities (required)
+     * @param language the language of the parsed name pattern (optional)
+     * @param limit the maximum number of result (optional)
+     * @param offset the offset of the first result (optional)
+     * @return the {@link FieldQuery} representing the parsed parameter
+     * @throws WebApplicationException in case the parsed name pattern is invalid.
+     * The validation of this required parameter provided by the Request is done
+     * by this method.
+     * @throws IllegalArgumentException in case the parsed field is invalid. Callers
+     * of this method need to ensure that this parameter is set to an valid value.
+     */
+    public static FieldQuery createFieldQueryForFindRequest(String name, String field, String language, Integer limit, Integer offset) throws WebApplicationException, IllegalArgumentException{
+        if(name == null || name.trim().isEmpty()){
+            // This throws an WebApplicationException, because the search name is
+            // provided by the caller. So an empty or missing name is interpreted
+            // as an bad Requested sent by the user
+            throw new WebApplicationException(
+                new IllegalArgumentException(
+                    "The parsed \"name\" pattern to search entities for MUST NOT be NULL nor EMPTY"),
+                    Response.Status.BAD_REQUEST);
+        } else {
+            name = name.trim();
+        }
+        if(field == null || field.trim().isEmpty()){
+            // This throws no WebApplicationException, because "field" is an 
+            // optional parameter and callers of this method MUST provide an
+            // valid default value in case the request does not provide any or
+            // valid data. 
+            new IllegalArgumentException("The parsed search \"field\" MUST NOT be NULL nor EMPTY");
+        } else {
+            field = field.trim();
+        }
+        log.debug("Process Find Request:");
+        log.debug("  > name  : " + name);
+        log.debug("  > field  : " + field);
+        log.debug("  > lang  : " + language);
+        log.debug("  > limit : " + limit);
+        log.debug("  > offset: " + offset);
+        FieldQuery query = queryFactory.createFieldQuery();
+        if (language == null) {
+            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false));
+        } else {
+            query.setConstraint(field, new TextConstraint(name, PatternType.wildcard, false, language));
+        }
+        Collection<String> selectedFields = new ArrayList<String>();
+        selectedFields.add(field); //select also the field used to find entities
+        query.addSelectedFields(selectedFields);
+        if (limit != null && limit > 0) {
+            query.setLimit(limit);
+        }
+        if(offset != null && offset > 0) {
+            query.setOffset(offset);
+        }
+        return query;
+    }
 }