From: <ba...@us...> - 2010-03-29 15:41:14
|
Revision: 3216 http://obo.svn.sourceforge.net/obo/?rev=3216&view=rev Author: balhoff Date: 2010-03-29 15:41:06 +0000 (Mon, 29 Mar 2010) Log Message: ----------- Migrated project to Restlet 2.0. Refactored various resources to reduce duplicated code. Modified Paths: -------------- OBD-WS/trunk/.classpath OBD-WS/trunk/WebContent/WEB-INF/lib/org.json.jar OBD-WS/trunk/WebContent/WEB-INF/lib/org.restlet.jar OBD-WS/trunk/WebContent/WEB-INF/web.xml OBD-WS/trunk/src/org/obd/ws/application/OBDApplication.java OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java OBD-WS/trunk/src/org/obd/ws/resources/AnnotationResource.java OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java OBD-WS/trunk/src/org/obd/ws/resources/HomologyResource.java OBD-WS/trunk/src/org/obd/ws/resources/KbRefreshTimestampResource.java OBD-WS/trunk/src/org/obd/ws/resources/PhenotypeDetailsResource.java OBD-WS/trunk/src/org/obd/ws/resources/PhenotypeSummaryResource.java OBD-WS/trunk/src/org/obd/ws/resources/SquarifiedTaxonMapResource.java OBD-WS/trunk/src/org/obd/ws/resources/TermResource.java OBD-WS/trunk/src/org/obd/ws/statistics/reports/resources/AbstractStatisticalReportGenerator.java OBD-WS/trunk/src/org/obd/ws/statistics/reports/resources/DataConsistencyReportGeneratorForQuestion13.java OBD-WS/trunk/src/org/obd/ws/statistics/reports/resources/DataConsistencyReportGeneratorForQuestion21A.java OBD-WS/trunk/src/org/obd/ws/statistics/reports/resources/DataConsistencyReportGeneratorForQuestion21B.java OBD-WS/trunk/src/org/obd/ws/statistics/reports/resources/DataConsistencyReportGeneratorForQuestion9.java OBD-WS/trunk/src/org/obd/ws/statistics/resources/AbstractStatisticsGenerator.java OBD-WS/trunk/src/org/obd/ws/statistics/resources/CharactersAndGenesByAttribute.java OBD-WS/trunk/src/org/obd/ws/statistics/resources/CharactersAndGenesBySystem.java OBD-WS/trunk/src/org/obd/ws/statistics/resources/CharactersAndGenesBySystemAndClade.java OBD-WS/trunk/src/org/obd/ws/statistics/resources/CharactersDatasetsAndTaxaByClade.java OBD-WS/trunk/src/org/obd/ws/statistics/resources/PhenotypeAnnotationCounts.java OBD-WS/trunk/test/org/obd/ws/resources/OBDResourceTest.java Removed Paths: ------------- OBD-WS/trunk/WebContent/WEB-INF/lib/com.noelios.restlet.ext.servlet_2.5.jar OBD-WS/trunk/WebContent/WEB-INF/lib/com.noelios.restlet.jar OBD-WS/trunk/WebContent/WEB-INF/lib/org.restlet.ext.json_2.0.jar Modified: OBD-WS/trunk/.classpath =================================================================== --- OBD-WS/trunk/.classpath 2010-03-25 17:20:59 UTC (rev 3215) +++ OBD-WS/trunk/.classpath 2010-03-29 15:41:06 UTC (rev 3216) @@ -4,8 +4,19 @@ <classpathentry kind="src" path="test"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v5.5"/> - <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/> <classpathentry kind="lib" path="lib/junit-4.5.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/bbop.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/log4j-1.2.13.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/obdapi.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/obo-vocab.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/obo.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/postgresql-8.2-506.jdbc3.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/javax.servlet.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/org.json.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/org.osgi.core.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/org.restlet.ext.json.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/org.restlet.ext.servlet.jar"/> + <classpathentry kind="lib" path="WebContent/WEB-INF/lib/org.restlet.jar"/> <classpathentry kind="output" path="build/classes"/> </classpath> Deleted: OBD-WS/trunk/WebContent/WEB-INF/lib/com.noelios.restlet.ext.servlet_2.5.jar =================================================================== (Binary files differ) Deleted: OBD-WS/trunk/WebContent/WEB-INF/lib/com.noelios.restlet.jar =================================================================== (Binary files differ) Modified: OBD-WS/trunk/WebContent/WEB-INF/lib/org.json.jar =================================================================== (Binary files differ) Deleted: OBD-WS/trunk/WebContent/WEB-INF/lib/org.restlet.ext.json_2.0.jar =================================================================== (Binary files differ) Modified: OBD-WS/trunk/WebContent/WEB-INF/lib/org.restlet.jar =================================================================== (Binary files differ) Modified: OBD-WS/trunk/WebContent/WEB-INF/web.xml =================================================================== --- OBD-WS/trunk/WebContent/WEB-INF/web.xml 2010-03-25 17:20:59 UTC (rev 3215) +++ OBD-WS/trunk/WebContent/WEB-INF/web.xml 2010-03-29 15:41:06 UTC (rev 3216) @@ -10,7 +10,7 @@ <!-- Restlet adapter --> <servlet> <servlet-name>ServerServlet</servlet-name> - <servlet-class>com.noelios.restlet.ext.servlet.ServerServlet</servlet-class> + <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class> </servlet> <servlet-mapping> Modified: OBD-WS/trunk/src/org/obd/ws/application/OBDApplication.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/application/OBDApplication.java 2010-03-25 17:20:59 UTC (rev 3215) +++ OBD-WS/trunk/src/org/obd/ws/application/OBDApplication.java 2010-03-29 15:41:06 UTC (rev 3216) @@ -19,98 +19,90 @@ import org.obd.ws.util.Queries; import org.obd.ws.util.TTOTaxonomy; import org.restlet.Application; -import org.restlet.Context; import org.restlet.Restlet; -import org.restlet.Router; +import org.restlet.routing.Router; +import org.restlet.routing.Template; public class OBDApplication extends Application { - private Queries queries; - private OBDSQLShard obdsql; - /* Database connection parameters */ - private String selectedDatabaseName,dbHost,uid,pwd; - - /** A structure which maps ontology prefixes to their - * default namespaces */ - private Map<String, Set<String>> prefixToDefaultNamespacesMap; - /** A structure to map default namespaces of ontologies to their - * node ids in the database */ - private Map<String, String> defaultNamespaceToNodeIdMap; + private Queries queries; + private OBDSQLShard obdsql; + /* Database connection parameters */ + private String selectedDatabaseName,dbHost,uid,pwd; - /** GETTER for the map from default namespaces of ontologies - * to their node ids in the database */ - public Map<String, String> getDefaultNamespaceToNodeIdMap() { - return defaultNamespaceToNodeIdMap; - } - /** GETTER for the map from ontology prefixes to default namespaces - */ - public Map<String, Set<String>> getPrefixToDefaultNamespacesMap() { - return prefixToDefaultNamespacesMap; - } + /** A structure which maps ontology prefixes to their + * default namespaces */ + private Map<String, Set<String>> prefixToDefaultNamespacesMap; + /** A structure to map default namespaces of ontologies to their + * node ids in the database */ + private Map<String, String> defaultNamespaceToNodeIdMap; - /* Some static Strings */ - public static final String PREFIX_TO_NS_FILE = - "PrefixToDefaultNamespaceOfOntology.properties"; - public static final String PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING = - "prefixToDefaultNamespacesMap"; - public static final String DEFAULT_NAMESPACE_TO_SOURCE_ID_MAP_STRING = - "defaultNamespacesToSourceIdMap"; - public static final String TTO_TAXONOMY_STRING = "ttoTaxonomy"; - public static final String QUERIES_STRING = "queries"; - public static final String SHARD_STRING = "shard"; - public static final String SELECTED_DATABASE_NAME_STRING = "selectedDatabaseName"; - public static final String DB_HOST_NAME_STRING = "dbHost"; - public static final String UID_STRING = "uid"; - public static final String PWD_STRING = "pwd"; - - /** - * Constructor extends the default superclass constructor - * @param context - */ - public OBDApplication(Context context){ - super(context); + /** GETTER for the map from default namespaces of ontologies + * to their node ids in the database */ + public Map<String, String> getDefaultNamespaceToNodeIdMap() { + return defaultNamespaceToNodeIdMap; } + /** GETTER for the map from ontology prefixes to default namespaces + */ + public Map<String, Set<String>> getPrefixToDefaultNamespacesMap() { + return prefixToDefaultNamespacesMap; + } - /** - * Selects the Shard pointing to the most recently updated database to be used by the - * data services - * Then this method sets a number of context level parameters - * @throws SQLException - * @throws ClassNotFoundException - * @throws IOException - * @throws ParseException - * @throws PhenoscapeDbConnectionException - * @throws DataAdapterException - */ + /* Some static Strings */ + public static final String PREFIX_TO_NS_FILE = + "PrefixToDefaultNamespaceOfOntology.properties"; + public static final String PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING = + "prefixToDefaultNamespacesMap"; + public static final String DEFAULT_NAMESPACE_TO_SOURCE_ID_MAP_STRING = + "defaultNamespacesToSourceIdMap"; + public static final String TTO_TAXONOMY_STRING = "ttoTaxonomy"; + public static final String QUERIES_STRING = "queries"; + public static final String SHARD_STRING = "shard"; + public static final String SELECTED_DATABASE_NAME_STRING = "selectedDatabaseName"; + public static final String DB_HOST_NAME_STRING = "dbHost"; + public static final String UID_STRING = "uid"; + public static final String PWD_STRING = "pwd"; + + /** + * Selects the Shard pointing to the most recently updated database to be used by the + * data services + * Then this method sets a number of context level parameters + * @throws SQLException + * @throws ClassNotFoundException + * @throws IOException + * @throws ParseException + * @throws PhenoscapeDbConnectionException + * @throws DataAdapterException + */ private void connect() throws SQLException, ClassNotFoundException, IOException, ParseException, - PhenoscapeDbConnectionException, DataAdapterException{ - - DatabaseToggler dbToggler = new DatabaseToggler(); - this.prefixToDefaultNamespacesMap = new HashMap<String, Set<String>>(); - this.defaultNamespaceToNodeIdMap = new HashMap<String, String>(); - - obdsql = dbToggler.chooseDatabase(); + PhenoscapeDbConnectionException, DataAdapterException{ + + DatabaseToggler dbToggler = new DatabaseToggler(); + this.prefixToDefaultNamespacesMap = new HashMap<String, Set<String>>(); + this.defaultNamespaceToNodeIdMap = new HashMap<String, String>(); + + obdsql = dbToggler.chooseDatabase(); selectedDatabaseName = dbToggler.getSelectedDatabaseName(); dbHost = dbToggler.getDbHost(); uid = dbToggler.getUid(); pwd = dbToggler.getPwd(); - + if(obdsql != null && selectedDatabaseName != null && dbHost != null && uid != null && pwd != null){ - this.getContext().getAttributes().put(SHARD_STRING, obdsql); - this.getContext().getAttributes().put(SELECTED_DATABASE_NAME_STRING, selectedDatabaseName); - this.getContext().getAttributes().put(DB_HOST_NAME_STRING, dbHost); - this.getContext().getAttributes().put(UID_STRING, uid); - this.getContext().getAttributes().put(PWD_STRING, pwd); - queries = new Queries(obdsql); - this.getContext().getAttributes().put(QUERIES_STRING, queries); - this.constructPrefixToDefaultNamespacesMap(); - this.constructDefaultNamespaceToNodeIdMap(); - this.getContext().getAttributes().put(PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING, this.prefixToDefaultNamespacesMap); - this.getContext().getAttributes().put(DEFAULT_NAMESPACE_TO_SOURCE_ID_MAP_STRING, this.defaultNamespaceToNodeIdMap); + this.getContext().getAttributes().put(SHARD_STRING, obdsql); + this.getContext().getAttributes().put(SELECTED_DATABASE_NAME_STRING, selectedDatabaseName); + this.getContext().getAttributes().put(DB_HOST_NAME_STRING, dbHost); + this.getContext().getAttributes().put(UID_STRING, uid); + this.getContext().getAttributes().put(PWD_STRING, pwd); + queries = new Queries(obdsql); + this.getContext().getAttributes().put(QUERIES_STRING, queries); + this.constructPrefixToDefaultNamespacesMap(); + this.constructDefaultNamespaceToNodeIdMap(); + this.getContext().getAttributes().put(PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING, this.prefixToDefaultNamespacesMap); + this.getContext().getAttributes().put(DEFAULT_NAMESPACE_TO_SOURCE_ID_MAP_STRING, this.defaultNamespaceToNodeIdMap); }else - throw new PhenoscapeDbConnectionException("Failed to obtain a connection to the database. " + - "This is because neither database is ready to be queried. "); - + throw new PhenoscapeDbConnectionException("Failed to obtain a connection to the database. " + + "This is because neither database is ready to be queried. "); + TTOTaxonomy ttoTaxonomy = new TTOTaxonomy(); this.getContext().getAttributes().put(TTO_TAXONOMY_STRING, ttoTaxonomy); } @@ -119,9 +111,10 @@ * The router method. * It holds mappings from URL patterns to the appropriate REST service to be invoked */ - public Restlet createRoot() { + @Override + public Restlet createInboundRoot() { try { - connect(); + connect(); } catch (SQLException e) { log().fatal("Error connecting to SQL shard", e); } catch (ClassNotFoundException e) { @@ -129,13 +122,13 @@ } catch (IOException e) { log().fatal("Error reading connection properties file", e); } catch (ParseException e) { - log().fatal("Error parsing the date", e); + log().fatal("Error parsing the date", e); } catch (PhenoscapeDbConnectionException e) { - log().fatal("Error with the database connection", e); + log().fatal("Error with the database connection", e); } catch (DataAdapterException e) { - log().fatal("Error reading in the OBO files", e); - } - + log().fatal("Error reading in the OBO files", e); + } + final Router router = new Router(this.getContext()); // URL mappings router.attach("/phenotypes", org.obd.ws.resources.PhenotypeDetailsResource.class); @@ -144,81 +137,81 @@ router.attach("/term/search", org.obd.ws.resources.AutoCompleteResource.class); router.attach("/term/{termID}", org.obd.ws.resources.TermResource.class); router.attach("/term/{termID}/homology", org.obd.ws.resources.HomologyResource.class); - router.attach("/timestamp", org.obd.ws.resources.KbRefreshTimestampResource.class); + router.attach("/timestamp", org.obd.ws.resources.KbRefreshTimestampResource.class).setMatchingMode(Template.MODE_STARTS_WITH); router.attach("/taxon/{taxonID}/treemap/",org.obd.ws.resources.SquarifiedTaxonMapResource.class); /* These resources generate data consistency reports*/ router.attach("/statistics/consistencyreports/relationalqualitieswithoutrelatedentities", - org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion21A.class); + org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion21A.class); router.attach("/statistics/consistencyreports/nonrelationalqualitieswithrelatedentities", - org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion21B.class); + org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion21B.class); router.attach("/statistics/consistencyreports/characterswithonlyoneannotatedstate", - org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion9.class); + org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion9.class); router.attach("/statistics/consistencyreports/characterswithonlyoneoftwopossibleannotations", - org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion13.class); + org.obd.ws.statistics.reports.resources.DataConsistencyReportGeneratorForQuestion13.class); /* These resources generate summary statistics of the data */ router.attach("/statistics/phenotypeannotationcount", - org.obd.ws.statistics.resources.PhenotypeAnnotationCounts.class); + org.obd.ws.statistics.resources.PhenotypeAnnotationCounts.class); router.attach("/statistics/countsofgenesandcharactersbyattribute", - org.obd.ws.statistics.resources.CharactersAndGenesByAttribute.class); + org.obd.ws.statistics.resources.CharactersAndGenesByAttribute.class); router.attach("/statistics/countsofgenesandcharactersbysystem", - org.obd.ws.statistics.resources.CharactersAndGenesBySystem.class); + org.obd.ws.statistics.resources.CharactersAndGenesBySystem.class); router.attach("/statistics/countsofgenesandcharactersbysystemandclade", - org.obd.ws.statistics.resources.CharactersAndGenesBySystemAndClade.class); + org.obd.ws.statistics.resources.CharactersAndGenesBySystemAndClade.class); router.attach("/statistics/countsofcharactersdatasetsandtaxabyclade", - org.obd.ws.statistics.resources.CharactersDatasetsAndTaxaByClade.class); + org.obd.ws.statistics.resources.CharactersDatasetsAndTaxaByClade.class); return router; } - + private Logger log() { return Logger.getLogger(this.getClass()); } /** - * PURPOSE This method reads in the list of default namespaces from a file and - * adds the corresponding node ids to a map - * @throws IOException - * @throws SQLException - */ - private void constructDefaultNamespaceToNodeIdMap() throws SQLException{ - String sourceNodeQuery = queries.getQueryForNodeIdsForOntologies(); - String nodeId, uid; - Connection conn = obdsql.getConnection(); - java.sql.Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(sourceNodeQuery); - while(rs.next()){ - nodeId = rs.getString(1); - uid = rs.getString(2); - if(uid.length() > 0){ - this.defaultNamespaceToNodeIdMap.put(uid, nodeId); - } - } - } - - /** - * PURPOSE This method constructs a mapping - * from every prefix used in the autocompletion - * service to the set of default namespaces of the - * ontologies the prefix comes from\n - * PROCEDURE This method reads the allowed - * prefix to namespace mappings from a static text - * file. This is converted into a map - * @throws IOException - */ - private void constructPrefixToDefaultNamespacesMap() - throws IOException{ - InputStream inStream = - this.getClass().getResourceAsStream(PREFIX_TO_NS_FILE); - Properties props = new Properties(); - props.load(inStream); - Set<String> namespaceSet; - for(Object key : props.keySet()){ - String prefix = key.toString(); - String commaDelimitedNamespaces = props.get(key).toString(); - namespaceSet = new HashSet<String>(); - for(String namespace : commaDelimitedNamespaces.split(",")){ - namespaceSet.add(namespace); - } - prefixToDefaultNamespacesMap.put(prefix, namespaceSet); - } - } + * PURPOSE This method reads in the list of default namespaces from a file and + * adds the corresponding node ids to a map + * @throws IOException + * @throws SQLException + */ + private void constructDefaultNamespaceToNodeIdMap() throws SQLException{ + String sourceNodeQuery = queries.getQueryForNodeIdsForOntologies(); + String nodeId, uid; + Connection conn = obdsql.getConnection(); + java.sql.Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(sourceNodeQuery); + while(rs.next()){ + nodeId = rs.getString(1); + uid = rs.getString(2); + if(uid.length() > 0){ + this.defaultNamespaceToNodeIdMap.put(uid, nodeId); + } + } + } + + /** + * PURPOSE This method constructs a mapping + * from every prefix used in the autocompletion + * service to the set of default namespaces of the + * ontologies the prefix comes from\n + * PROCEDURE This method reads the allowed + * prefix to namespace mappings from a static text + * file. This is converted into a map + * @throws IOException + */ + private void constructPrefixToDefaultNamespacesMap() + throws IOException{ + InputStream inStream = + this.getClass().getResourceAsStream(PREFIX_TO_NS_FILE); + Properties props = new Properties(); + props.load(inStream); + Set<String> namespaceSet; + for(Object key : props.keySet()){ + String prefix = key.toString(); + String commaDelimitedNamespaces = props.get(key).toString(); + namespaceSet = new HashSet<String>(); + for(String namespace : commaDelimitedNamespaces.split(",")){ + namespaceSet.add(namespace); + } + prefixToDefaultNamespacesMap.put(prefix, namespaceSet); + } + } } Modified: OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java 2010-03-25 17:20:59 UTC (rev 3215) +++ OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java 2010-03-29 15:41:06 UTC (rev 3216) @@ -5,25 +5,28 @@ import org.apache.log4j.Logger; import org.obd.query.impl.OBDSQLShard; import org.obd.ws.application.OBDApplication; -import org.restlet.Context; -import org.restlet.data.Request; -import org.restlet.data.Response; -import org.restlet.resource.Resource; +import org.restlet.resource.ResourceException; +import org.restlet.resource.ServerResource; -public abstract class AbstractOBDResource extends Resource { +public abstract class AbstractOBDResource extends ServerResource { private static final String DRIVER_NAME = "jdbc:postgresql://"; - protected OBDSQLShard shard; + private OBDSQLShard shard; - public AbstractOBDResource(Context context, Request request, Response response) { - super(context, request, response); + /* (non-Javadoc) + * @see org.restlet.resource.UniformResource#doInit() + * If a subclass overrides this method, it should call super's before its own implementation. + */ + @Override + protected void doInit() throws ResourceException { + super.doInit(); try { this.shard = new OBDSQLShard(); } catch (SQLException e) { log().fatal("Failed to create shard", e); } catch (ClassNotFoundException e) { log().fatal("Failed to create shard", e); - } + } } protected OBDSQLShard getShard() { Modified: OBD-WS/trunk/src/org/obd/ws/resources/AnnotationResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/AnnotationResource.java 2010-03-25 17:20:59 UTC (rev 3215) +++ OBD-WS/trunk/src/org/obd/ws/resources/AnnotationResource.java 2010-03-29 15:41:06 UTC (rev 3216) @@ -4,27 +4,21 @@ import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; -import org.obd.query.impl.OBDSQLShard; import org.obd.ws.application.OBDApplication; import org.obd.ws.util.Queries; import org.obd.ws.util.TTOTaxonomy; import org.obd.ws.util.dto.AnnotationDTO; import org.obd.ws.util.dto.NodeDTO; import org.phenoscape.obd.OBDQuery; -import org.restlet.Context; -import org.restlet.data.MediaType; import org.restlet.data.Reference; -import org.restlet.data.Request; -import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.ext.json.JsonRepresentation; -import org.restlet.resource.Representation; -import org.restlet.resource.Resource; +import org.restlet.representation.Representation; +import org.restlet.representation.Variant; +import org.restlet.resource.Get; import org.restlet.resource.ResourceException; -import org.restlet.resource.Variant; /** * The purpose of this resource is to invoke a query @@ -35,37 +29,23 @@ * endpoint */ -public class AnnotationResource extends Resource { +public class AnnotationResource extends AbstractOBDResource { - private final String driverName = "jdbc:postgresql://"; - - private JSONObject jObjs; - - private OBDSQLShard obdsqlShard; - private final String annotationId; - + private JSONObject jObjs; + + private String annotationId; + private OBDQuery obdq; private Queries queries; - + private TTOTaxonomy ttoTaxonomy; - - /** - * Constructor extends the default constructor - * Initializes the Shard, Queries, OBDQuery and the JSON Object which - * will be returned - * @param context - * @param request - * @param response - * @throws ClassNotFoundException - * @throws SQLException - */ - public AnnotationResource(Context context, Request request, Response response) throws SQLException, ClassNotFoundException { - super(context, request, response); - this.obdsqlShard = new OBDSQLShard(); + + @Override + protected void doInit() throws ResourceException { + super.doInit(); this.queries = (Queries)this.getContext().getAttributes().get(OBDApplication.QUERIES_STRING); this.ttoTaxonomy = (TTOTaxonomy)this.getContext().getAttributes().get(OBDApplication.TTO_TAXONOMY_STRING); - this.annotationId = Reference.decode((String)(request.getAttributes().get("annotation_id"))); - this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); + this.annotationId = Reference.decode(this.getRequestAttributes().get("annotation_id").toString()); this.jObjs = new JSONObject(); } @@ -75,60 +55,34 @@ * packaged into a JSON Object using the {@link #assembleJSONObjectFromAnnotations(List)} * method */ - public Representation represent(Variant variant) throws ResourceException { - - List<List<String[]>> annots; - - try{ - connectShardToDatabase(); - obdq = new OBDQuery(obdsqlShard, queries); - annots = getMetadata(annotationId); - assembleJSONObjectFromAnnotations(annots); - }catch(SQLException sqle){ - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, - "[SQL EXCEPTION] Something broke server side. Consult server logs"); - return null; - } catch (ClassNotFoundException e) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, - "[CLASS NOT FOUND EXCEPTION] Something broke server side. Consult server logs"); - return null; - } catch(JSONException jsone){ - getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, - "[JSON EXCEPTION] JSON object error."); - log().error(jsone); + @Get("json") + public Representation getJSONRepresentation() throws ResourceException { + List<List<String[]>> annots; + try{ + connectShardToDatabase(); + obdq = new OBDQuery(this.getShard(), queries); + annots = getMetadata(annotationId); + assembleJSONObjectFromAnnotations(annots); + }catch(SQLException sqle){ + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, + "[SQL EXCEPTION] Something broke server side. Consult server logs"); return null; - } finally{ - disconnectShardFromDatabase(); - } - return new JsonRepresentation(this.jObjs); + } catch (ClassNotFoundException e) { + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, + "[CLASS NOT FOUND EXCEPTION] Something broke server side. Consult server logs"); + return null; + } catch(JSONException jsone){ + getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, + "[JSON EXCEPTION] JSON object error."); + log().error(jsone); + return null; + } finally{ + disconnectShardFromDatabase(); + } + return new JsonRepresentation(this.jObjs); } - + /** - * This method reads in db connection parameters from app context before connecting - * the Shard to the database - * @throws SQLException - * @throws ClassNotFoundException - */ - private void connectShardToDatabase() throws SQLException, ClassNotFoundException{ - String dbName = (String)this.getContext().getAttributes().get(OBDApplication.SELECTED_DATABASE_NAME_STRING); - String dbHost = (String)this.getContext().getAttributes().get(OBDApplication.DB_HOST_NAME_STRING); - String uid = (String)this.getContext().getAttributes().get(OBDApplication.UID_STRING); - String pwd = (String)this.getContext().getAttributes().get(OBDApplication.PWD_STRING); - - String dbConnString = driverName + dbHost + "/" + dbName; - long connStartTime = System.currentTimeMillis(); - obdsqlShard.connect(dbConnString, uid, pwd); - long connEndTime = System.currentTimeMillis(); - log().trace("It took " + (connEndTime - connStartTime) + " msecs to connect"); - } - - private void disconnectShardFromDatabase(){ - if(obdsqlShard != null) - obdsqlShard.disconnect(); - obdsqlShard = null; - } - - /** * PURPOSE This method invokes the metadata query from * the Queries object and loads it for execution by invoking * the {@link OBDQuery#executeFreeTextQueryAndAssembleResults(Integer)} method. @@ -142,54 +96,54 @@ * @throws SQLException */ private List<List<String[]>> getMetadata(String annotId) throws SQLException{ - - List<List<String[]>> results = new ArrayList<List<String[]>>(); - List<String[]> annots; - - String taxonId, taxon, entityId, entity, qualityId, quality, - publication, curators, charText, charComments, stateText, stateComments, - charNumber; - - String[] annotIds = annotId.split(","); - - try{ - for(String id : annotIds){ - for(AnnotationDTO node : obdq.executeFreeTextQueryAndAssembleResults(Integer.parseInt(id))){ - taxonId = node.getTaxonId(); - taxon = node.getTaxon(); - entityId = node.getEntityId(); - entity = node.getEntity(); - qualityId = node.getQualityId(); - quality = node.getQuality(); - - publication = node.getPublication(); - curators = node.getCurators(); - charText = node.getCharText(); - charComments = node.getCharComments(); - stateText = node.getStateText(); - stateComments = node.getStateComments(); - charNumber = node.getCharNumber(); - annots = new ArrayList<String[]>(); - annots.add(new String[]{taxonId, taxon}); - annots.add(new String[]{entityId, entity}); - annots.add(new String[]{qualityId, quality}); - annots.add(new String[]{publication}); - annots.add(new String[]{curators}); - annots.add(new String[]{charText, charComments, charNumber}); - annots.add(new String[]{stateText, stateComments}); - - results.add(annots); - } - } - } - catch (SQLException sqle){ - sqle.printStackTrace(); - log().error(sqle); - throw sqle; - } - return results; + + List<List<String[]>> results = new ArrayList<List<String[]>>(); + List<String[]> annots; + + String taxonId, taxon, entityId, entity, qualityId, quality, + publication, curators, charText, charComments, stateText, stateComments, + charNumber; + + String[] annotIds = annotId.split(","); + + try{ + for(String id : annotIds){ + for(AnnotationDTO node : obdq.executeFreeTextQueryAndAssembleResults(Integer.parseInt(id))){ + taxonId = node.getTaxonId(); + taxon = node.getTaxon(); + entityId = node.getEntityId(); + entity = node.getEntity(); + qualityId = node.getQualityId(); + quality = node.getQuality(); + + publication = node.getPublication(); + curators = node.getCurators(); + charText = node.getCharText(); + charComments = node.getCharComments(); + stateText = node.getStateText(); + stateComments = node.getStateComments(); + charNumber = node.getCharNumber(); + annots = new ArrayList<String[]>(); + annots.add(new String[]{taxonId, taxon}); + annots.add(new String[]{entityId, entity}); + annots.add(new String[]{qualityId, quality}); + annots.add(new String[]{publication}); + annots.add(new String[]{curators}); + annots.add(new String[]{charText, charComments, charNumber}); + annots.add(new String[]{stateText, stateComments}); + + results.add(annots); + } + } + } + catch (SQLException sqle){ + sqle.printStackTrace(); + log().error(sqle); + throw sqle; + } + return results; } - + /** * This method takes in a data structure of the annotations * obtained from the {@link #getMetadata(String)} method and @@ -198,66 +152,60 @@ * @throws JSONException */ private void assembleJSONObjectFromAnnotations(List<List<String[]>> annots) throws JSONException{ - List<JSONObject> sourceObjs = new ArrayList<JSONObject>(); - JSONObject phenotypeObj, sourceObj; - JSONObject entityObj, taxonObj, qualityObj, rankObj; - - if(annots != null && annots.size() > 0){ - phenotypeObj = new JSONObject(); - for(List<String[]> annot : annots){ - entityObj = new JSONObject(); - taxonObj = new JSONObject(); - qualityObj = new JSONObject(); - - sourceObj = new JSONObject(); - - taxonObj.put("id", annot.get(0)[0]); - taxonObj.put("name", annot.get(0)[1]); - - if(annot.get(0)[0].startsWith("TTO")){ - NodeDTO taxonDTO = new NodeDTO(annot.get(0)[0]); - taxonDTO.setName(annot.get(0)[1]); - rankObj = new JSONObject(); - NodeDTO rankDTO = ttoTaxonomy.getTaxonToRankMap().get(taxonDTO); - if(rankDTO != null){ - rankObj.put("id", rankDTO.getId()); - rankObj.put("name", rankDTO.getName()); - } - else{ - rankObj.put("id", ""); - rankObj.put("name", ""); - } - taxonObj.put("rank", rankObj); - } - - entityObj.put("id", annot.get(1)[0]); - entityObj.put("name", annot.get(1)[1]); - qualityObj.put("id", annot.get(2)[0]); - qualityObj.put("name", annot.get(2)[1]); - - phenotypeObj.put("subject", taxonObj); - phenotypeObj.put("entity", entityObj); - phenotypeObj.put("quality", qualityObj); - - sourceObj.put("publication", annot.get(3)[0]); - sourceObj.put("curated_by", annot.get(4)[0]); - sourceObj.put("character_text", annot.get(5)[0]); - sourceObj.put("character_comment", annot.get(5)[1]); - sourceObj.put("character_number", annot.get(5)[2]); - sourceObj.put("state_text", annot.get(6)[0]); - sourceObj.put("state_comment", annot.get(6)[1]); - - sourceObjs.add(sourceObj); - } - jObjs.put("phenotype", phenotypeObj); - jObjs.put("sources", sourceObjs); - } + List<JSONObject> sourceObjs = new ArrayList<JSONObject>(); + JSONObject phenotypeObj, sourceObj; + JSONObject entityObj, taxonObj, qualityObj, rankObj; + + if(annots != null && annots.size() > 0){ + phenotypeObj = new JSONObject(); + for(List<String[]> annot : annots){ + entityObj = new JSONObject(); + taxonObj = new JSONObject(); + qualityObj = new JSONObject(); + + sourceObj = new JSONObject(); + + taxonObj.put("id", annot.get(0)[0]); + taxonObj.put("name", annot.get(0)[1]); + + if(annot.get(0)[0].startsWith("TTO")){ + NodeDTO taxonDTO = new NodeDTO(annot.get(0)[0]); + taxonDTO.setName(annot.get(0)[1]); + rankObj = new JSONObject(); + NodeDTO rankDTO = ttoTaxonomy.getTaxonToRankMap().get(taxonDTO); + if(rankDTO != null){ + rankObj.put("id", rankDTO.getId()); + rankObj.put("name", rankDTO.getName()); + } + else{ + rankObj.put("id", ""); + rankObj.put("name", ""); + } + taxonObj.put("rank", rankObj); + } + + entityObj.put("id", annot.get(1)[0]); + entityObj.put("name", annot.get(1)[1]); + qualityObj.put("id", annot.get(2)[0]); + qualityObj.put("name", annot.get(2)[1]); + + phenotypeObj.put("subject", taxonObj); + phenotypeObj.put("entity", entityObj); + phenotypeObj.put("quality", qualityObj); + + sourceObj.put("publication", annot.get(3)[0]); + sourceObj.put("curated_by", annot.get(4)[0]); + sourceObj.put("character_text", annot.get(5)[0]); + sourceObj.put("character_comment", annot.get(5)[1]); + sourceObj.put("character_number", annot.get(5)[2]); + sourceObj.put("state_text", annot.get(6)[0]); + sourceObj.put("state_comment", annot.get(6)[1]); + + sourceObjs.add(sourceObj); + } + jObjs.put("phenotype", phenotypeObj); + jObjs.put("sources", sourceObjs); + } } - - /** - * This method returns a logger (log4j) - */ - private Logger log() { - return Logger.getLogger(this.getClass()); - } + } Modified: OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java 2010-03-25 17:20:59 UTC (rev 3215) +++ OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java 2010-03-29 15:41:06 UTC (rev 3216) @@ -11,339 +11,289 @@ import java.util.Map; import java.util.Set; -import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; -import org.obd.query.impl.OBDSQLShard; import org.obd.ws.application.OBDApplication; import org.obd.ws.util.Queries; import org.phenoscape.obd.OBDQuery; -import org.restlet.Context; -import org.restlet.data.MediaType; import org.restlet.data.Reference; -import org.restlet.data.Request; -import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.ext.json.JsonRepresentation; -import org.restlet.resource.Representation; -import org.restlet.resource.Resource; +import org.restlet.representation.Representation; +import org.restlet.resource.Get; import org.restlet.resource.ResourceException; -import org.restlet.resource.Variant; -public class AutoCompleteResource extends Resource { +public class AutoCompleteResource extends AbstractOBDResource { - private final String driverName = "jdbc:postgresql://"; - - private String searchTerm; - private String synonymOption; - private String definitionOption; - /** The list of ontologies whose terms are to be searched */ - private String ontologyOption; - - private JSONObject jObjs; - private OBDSQLShard obdsqlShard; - private Logger log; - private Queries queries; - /** The map from default namespaces of the ontologies to their corr. node ids in the database */ - private Map<String, String> nsToSourceIdMap; - /** The map from prefixes of the terms to the default namespaces of the ontologies they come from */ - private Map<String, Set<String>> prefixToNSMap; - + private String searchTerm; + private String synonymOption; + private String definitionOption; + /** The list of ontologies whose terms are to be searched */ + private String ontologyOption; - /** A parameter to limit the number of matches */ - private Integer limitOfMatches = null; - - /** A structure to keep track of the search options input - * from the form such as ontologyList, synonyms, definitions - * etc. - */ - private Map<String, String> searchOptions; - - private static final String ID_STRING = "id"; - private static final String NAME_STRING = "name"; - private static final String SYNONYM_STRING = "synonym"; - private static final String DEF_STRING = "definition"; - private static final String MATCH_TYPE_STRING = "match_type"; - private static final String MATCH_TEXT_STRING = "match_text"; - private static final String MATCHES_STRING = "matches"; - - private static final String ONTOLOGY_OPTION_STRING = "ontologyOption"; - private static final String SYNONYM_OPTION_STRING = "synonymOption"; - private static final String DEFINITION_OPTION_STRING = "definitionOption"; - - private static final String INPUT_TEXT_STRING = "text"; - private static final String INPUT_SYN_STRING = "syn"; - private static final String INPUT_DEF_STRING = "def"; - private static final String INPUT_ONTOLOGY_STRING = "ontology"; - private static final String INPUT_LIMIT_STRING = "limit"; - - /** - * This comparator is used to order collections of JSON objects. - * The property values for the {@literal #MATCH_TEXT_STRING} is used - * to compare the JSON objects - */ - private static final Comparator<JSONObject> MATCHES_COMPARATOR = new Comparator<JSONObject>() { - public int compare(JSONObject o1, JSONObject o2) { - try { - return ((String)o1.get(MATCH_TEXT_STRING)).compareToIgnoreCase((String)o2.get(MATCH_TEXT_STRING)); - } catch (JSONException e) { - return 0; - } - } - }; - - /** - * PURPOSE This construnctor instantiates all the instance variables and also - * reads in the form parameters. It also does a little work towards setting up the final query - * to be executed\n - * @param context - the application context - * @param request - the Rest request - * @param response - the Rest response - * @throws SQLException - * @throws ClassNotFoundException - */ - public AutoCompleteResource(Context context, Request request, Response response) throws SQLException, ClassNotFoundException { - super(context, request, response); - this.obdsqlShard = new OBDSQLShard(); - this.queries = (Queries)this.getContext().getAttributes().get(OBDApplication.QUERIES_STRING); - this.prefixToNSMap = - (Map<String, Set<String>>)this.getContext().getAttributes().get(OBDApplication.PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING); - this.nsToSourceIdMap = - (Map<String, String>)this.getContext().getAttributes().get(OBDApplication.DEFAULT_NAMESPACE_TO_SOURCE_ID_MAP_STRING); - this.log = Logger.getLogger(this.getClass()); - this.searchOptions = new HashMap<String, String>(); - - this.getVariants().add(new Variant(MediaType.APPLICATION_JSON)); - - this.searchTerm = Reference.decode((String) request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_TEXT_STRING)); + private JSONObject jObjs; + private Queries queries; + /** The map from default namespaces of the ontologies to their corr. node ids in the database */ + private Map<String, String> nsToSourceIdMap; + /** The map from prefixes of the terms to the default namespaces of the ontologies they come from */ + private Map<String, Set<String>> prefixToNSMap; + + + /** A parameter to limit the number of matches */ + private Integer limitOfMatches = null; + + /** A structure to keep track of the search options input + * from the form such as ontologyList, synonyms, definitions + * etc. + */ + private Map<String, String> searchOptions; + + private static final String ID_STRING = "id"; + private static final String NAME_STRING = "name"; + private static final String SYNONYM_STRING = "synonym"; + private static final String DEF_STRING = "definition"; + private static final String MATCH_TYPE_STRING = "match_type"; + private static final String MATCH_TEXT_STRING = "match_text"; + private static final String MATCHES_STRING = "matches"; + + private static final String ONTOLOGY_OPTION_STRING = "ontologyOption"; + private static final String SYNONYM_OPTION_STRING = "synonymOption"; + private static final String DEFINITION_OPTION_STRING = "definitionOption"; + + private static final String INPUT_TEXT_STRING = "text"; + private static final String INPUT_SYN_STRING = "syn"; + private static final String INPUT_DEF_STRING = "def"; + private static final String INPUT_ONTOLOGY_STRING = "ontology"; + private static final String INPUT_LIMIT_STRING = "limit"; + + /** + * This comparator is used to order collections of JSON objects. + * The property values for the {@literal #MATCH_TEXT_STRING} is used + * to compare the JSON objects + */ + private static final Comparator<JSONObject> MATCHES_COMPARATOR = new Comparator<JSONObject>() { + public int compare(JSONObject o1, JSONObject o2) { + try { + return ((String)o1.get(MATCH_TEXT_STRING)).compareToIgnoreCase((String)o2.get(MATCH_TEXT_STRING)); + } catch (JSONException e) { + return 0; + } + } + }; + + @SuppressWarnings("unchecked") + @Override + protected void doInit() throws ResourceException { + super.doInit(); + this.queries = (Queries)this.getContext().getAttributes().get(OBDApplication.QUERIES_STRING); + this.prefixToNSMap = (Map<String, Set<String>>)this.getContext().getAttributes().get(OBDApplication.PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING); + this.nsToSourceIdMap = (Map<String, String>)this.getContext().getAttributes().get(OBDApplication.DEFAULT_NAMESPACE_TO_SOURCE_ID_MAP_STRING); + this.searchOptions = new HashMap<String, String>(); + + this.searchTerm = Reference.decode((String) this.getQuery().getFirstValue(INPUT_TEXT_STRING)); searchTerm = searchTerm.trim().toLowerCase(); - if(request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_SYN_STRING) != null) - synonymOption = Reference.decode((String) request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_SYN_STRING)); - if(request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_DEF_STRING ) != null) - definitionOption = Reference.decode((String) request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_DEF_STRING )); - if(request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_ONTOLOGY_STRING) != null) - ontologyOption = Reference.decode((String) request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_ONTOLOGY_STRING)); - - final String limitParameter = request.getResourceRef().getQueryAsForm().getFirstValue(INPUT_LIMIT_STRING); - if (limitParameter != null) - this.limitOfMatches = Integer.parseInt(limitParameter); - if(!inputFormParametersAreValid()){ - throw new IllegalArgumentException("Invalid form parameters"); - } - searchOptions.put(SYNONYM_OPTION_STRING, synonymOption); - searchOptions.put(DEFINITION_OPTION_STRING, definitionOption); - searchOptions.put(ONTOLOGY_OPTION_STRING, ontologyOption); - } - - /** - * A method to check if input parameters from the form are valid - * @return a boolean to indicate if the input form parameters are valid - */ - private boolean inputFormParametersAreValid(){ - if(searchTerm == null){ - getResponse().setStatus( - Status.CLIENT_ERROR_BAD_REQUEST, - "ERROR: Please specify a string to search for"); - return false; - } - if (limitOfMatches != null) { - try { - if (this.limitOfMatches < 1) { - this.limitOfMatches = null; - } - } catch (NumberFormatException e) { - log.error("The value for the limit parameter was not a valid integer", e); - this.limitOfMatches = null; - return false; - } - } - return true; - } + if(this.getQuery().getFirstValue(INPUT_SYN_STRING) != null) + synonymOption = Reference.decode((String) this.getQuery().getFirstValue(INPUT_SYN_STRING)); + if(this.getQuery().getFirstValue(INPUT_DEF_STRING ) != null) + definitionOption = Reference.decode((String) this.getQuery().getFirstValue(INPUT_DEF_STRING )); + if(this.getQuery().getFirstValue(INPUT_ONTOLOGY_STRING) != null) + ontologyOption = Reference.decode((String) this.getQuery().getFirstValue(INPUT_ONTOLOGY_STRING)); + final String limitParameter = this.getQuery().getFirstValue(INPUT_LIMIT_STRING); + if (limitParameter != null) + this.limitOfMatches = Integer.parseInt(limitParameter); + if(!inputFormParametersAreValid()){ + throw new IllegalArgumentException("Invalid form parameters"); + } + searchOptions.put(SYNONYM_OPTION_STRING, synonymOption); + searchOptions.put(DEFINITION_OPTION_STRING, definitionOption); + searchOptions.put(ONTOLOGY_OPTION_STRING, ontologyOption); + } + + + /** + * A method to check if input parameters from the form are valid + * @return a boolean to indicate if the input form parameters are valid + */ + private boolean inputFormParametersAreValid(){ + if(searchTerm == null){ + getResponse().setStatus( + Status.CLIENT_ERROR_BAD_REQUEST, + "ERROR: Please specify a string to search for"); + return false; + } + if (limitOfMatches != null) { + try { + if (this.limitOfMatches < 1) { + this.limitOfMatches = null; + } + } catch (NumberFormatException e) { + log().error("The value for the limit parameter was not a valid integer", e); + this.limitOfMatches = null; + return false; + } + } + return true; + } + + /** * This method is responsible for creating the representation of the JSON Object * from the query results which will be forwarded to the invoking client */ - @Override - public Representation represent(Variant variant) - throws ResourceException { + @Get("json") + public Representation getJSONRepresentation() throws ResourceException { - Representation rep = null; - try { - connectShardToDatabase(); - this.jObjs = getTextMatches(); - } catch (JSONException e) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, - "[JSON EXCEPTION] Something broke on the JSON Object side. Consult server logs"); - log.error(e); + Representation rep = null; + try { + connectShardToDatabase(); + this.jObjs = getTextMatches(); + } catch (JSONException e) { + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, + "[JSON EXCEPTION] Something broke on the JSON Object side. Consult server logs"); + log().error(e); return null; - } catch (SQLException e) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, - "[SQL EXCEPTION] Something broke on the SQL query. Consult server logs"); - log.error(e); + } catch (SQLException e) { + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, + "[SQL EXCEPTION] Something broke on the SQL query. Consult server logs"); + log().error(e); return null; - } catch (ClassNotFoundException e) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, - "[CLASS NOT FOUND EXCEPTION] Something broke on the SQL query. Consult server logs"); - log.error(e); - return null; - } finally{ - disconnectShardFromDatabase(); - } - rep = new JsonRepresentation(this.jObjs); - return rep; - } + } catch (ClassNotFoundException e) { + getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, + "[CLASS NOT FOUND EXCEPTION] Something broke on the SQL query. Consult server logs"); + log().error(e); + return null; + } finally{ + disconnectShardFromDatabase(); + } + rep = new JsonRepresentation(this.jObjs); + return rep; + } /** - * This method reads in db connection parameters from app context and connects the Shard to the - * database + * This method arranges the user defined options and invokes the + * {@link OBDQuery#getAutocompletionsForSearchTerm(String, Map)} method to find + * label (default), synonym and definition (optional) matches for the search string. + * @return JSON object to be sent to the UI + * @throws IOException * @throws SQLException * @throws ClassNotFoundException + * @throws JSONException */ - private void connectShardToDatabase() throws SQLException, ClassNotFoundException{ - String dbName = (String)this.getContext().getAttributes().get(OBDApplication.SELECTED_DATABASE_NAME_STRING); - String dbHost = (String)this.getContext().getAttributes().get(OBDApplication.DB_HOST_NAME_STRING); - String uid = (String)this.getContext().getAttributes().get(OBDApplication.UID_STRING); - String pwd = (String)this.getContext().getAttributes().get(OBDApplication.PWD_STRING); - - String dbConnString = driverName + dbHost + "/" + dbName; - long connStartTime = System.currentTimeMillis(); - obdsqlShard.connect(dbConnString, uid, pwd); - long connEndTime = System.currentTimeMillis(); - log.trace("It took " + (connEndTime - connStartTime) + " msecs to connect"); + private JSONObject getTextMatches() throws JSONException, SQLException { + + JSONObject jObj = new JSONObject(); + OBDQuery obdq = new OBDQuery(this.getShard(), this.queries, this.nsToSourceIdMap, this.prefixToNSMap); + //For search terms shorter than 3, only "begins with" searches are done + String term = searchTerm.length() > 3 ? "%" + searchTerm + "%" : searchTerm + "%"; + Map<String, List<List<String>>> results = + obdq.getAutocompletionsForSearchTerm(term, searchOptions); + + List<List<String>> labelMatches = + results.get(OBDQuery.AutoCompletionMatchTypes.LABEL_MATCH.name()); + List<List<String>> synonymMatches = + results.get(OBDQuery.AutoCompletionMatchTypes.SYNONYM_MATCH.name()); + List<List<String>> definitionMatches = + results.get(OBDQuery.AutoCompletionMatchTypes.DEFINITION_MATCH.name()); + + Set<JSONObject> matches = new HashSet<JSONObject>(); + int i = 0, j = 0, k = 0; + if(labelMatches.size() > 0){ + for(List<String> label : labelMatches){ + JSONObject nameMatch = new JSONObject(); + nameMatch.put(ID_STRING, label.get(0)); + nameMatch.put(NAME_STRING, label.get(1)); + nameMatch.put(MATCH_TYPE_STRING, NAME_STRING); + nameMatch.put(MATCH_TEXT_STRING, label.get(1)); + matches.add(nameMatch); + log().debug( ++i + ". Name matches for search term: " + searchTerm + "\tID: " + label.get(0) + "\tLABEL: " + label.get(1)); + } + } + if(synonymMatches != null && synonymMatches.size() > 0){ + for(List<String> synonym : synonymMatches){ + JSONObject synonymMatch = new JSONObject(); + synonymMatch.put(ID_STRING, synonym.get(0)); + synonymMatch.put(NAME_STRING, synonym.get(1)); + synonymMatch.put(MATCH_TYPE_STRING, SYNONYM_STRING); + synonymMatch.put(MATCH_TEXT_STRING, synonym.get(2)); + matches.add(synonymMatch); + log().debug(++j + ". Synonym matches for search term: " + searchTerm + "\tID: " + synonym.get(0) + "\tLABEL: " + + synonym.get(1) + "\tSYNONYM: " + synonym.get(2)); + } + } + if(definitionMatches != null && definitionMatches.size() > 0){ + for(List<String> definition : definitionMatches){ + JSONObject definitionMatch = new JSONObject(); + definitionMatch.put(ID_STRING, definition.get(0)); + definitionMatch.put(NAME_STRING, definition.get(1)); + definitionMatch.put(MATCH_TYPE_STRING, DEF_STRING); + definitionMatch.put(MATCH_TEXT_STRING, definition.get(3)); + matches.add(definitionMatch); + log().debug(++k + ". Definition matches for search term: " + searchTerm + "\tID: " + definition.get(0) + "\tLABEL: " + + definition.get(1) + "\tDefinition: " + definition.get(3)); + } + } + jObj.put("search_term", searchTerm); + try{ + List<JSONObject> sortedMatches = sortJsonObjects(matches, searchTerm); + jObj.put(MATCHES_STRING, sortedMatches); + } + catch(JSONException e){ + log().error("JSON Exception: " + e.getMessage()); + jObj.put(MATCHES_STRING, matches); + /* FIXME why are we swallowing this exception? */ + } + return jObj; } - - private void disconnectShardFromDatabase(){ - if(obdsqlShard != null) - obdsqlShard.disconnect(); - obdsqlShard = null; - } - - /** - * This method arranges the user defined options and invokes the - * {@link OBDQuery#getAutocompletionsForSearchTerm(String, Map)} method to find - * label (default), synonym and definition (optional) matches for the search string. - * @return JSON object to be sent to the UI - * @throws IOException - * @throws SQLException - * @throws ClassNotFoundException - * @throws JSONException - */ - private JSONObject getTextMatches() - throws JSONException, SQLException { - JSONObject jObj = new JSONObject(); - OBDQuery obdq = new OBDQuery(obdsqlShard, this.queries, this.nsToSourceIdMap, this.prefixToNSMap); - //For search terms shorter than 3, only "begins with" searches are done - String term = searchTerm.length() > 3 ? "%" + searchTerm + "%" : searchTerm + "%"; - Map<String, List<List<String>>> results = - obdq.getAutocompletionsForSearchTerm(term, searchOptions); - - List<List<String>> labelMatches = - results.get(OBDQuery.AutoCompletionMatchTypes.LABEL_MATCH.name()); - List<List<String>> synonymMatches = - results.get(OBDQuery.AutoCompletionMatchTypes.SYNONYM_MATCH.name()); - List<List<String>> definitionMatches = - results.get(OBDQuery.AutoCompletionMatchTypes.DEFINITION_MATCH.name()); - - Set<JSONObject> matches = new HashSet<JSONObject>(); - int i = 0, j = 0, k = 0; - if(labelMatches.size() > 0){ - for(List<String> label : labelMatches){ - JSONObject nameMatch = new JSONObject(); - nameMatch.put(ID_STRING, label.get(0)); - nameMatch.put(NAME_STRING, label.get(1)); - nameMatch.put(MATCH_TYPE_STRING, NAME_STRING); - nameMatch.put(MATCH_TEXT_STRING, label.get(1)); - matches.add(nameMatch); - log.debug( ++i + ". Name matches for search term: " + searchTerm + "\tID: " + label.get(0) + "\tLABEL: " + label.ge... [truncated message content] |