From: <ba...@us...> - 2010-05-27 02:37:21
|
Revision: 3342 http://obo.svn.sourceforge.net/obo/?rev=3342&view=rev Author: balhoff Date: 2010-05-27 02:37:13 +0000 (Thu, 27 May 2010) Log Message: ----------- Reorganization of classes. Updated timestamp resource to use new data source. Modified Paths: -------------- OBD-WS/trunk/src/org/phenoscape/obd/model/PhenoscapeDataStore.java OBD-WS/trunk/src/org/phenoscape/ws/application/PhenoscapeWebServiceApplication.java OBD-WS/trunk/src/org/phenoscape/ws/resource/statistics/AbstractStatisticsGenerator.java OBD-WS/trunk/src/org/phenoscape/ws/resource/statistics/reports/AbstractStatisticalReportGenerator.java Added Paths: ----------- OBD-WS/trunk/src/org/phenoscape/ws/resource/KBTimestampResource.java OBD-WS/trunk/src/org/phenoscape/ws/resource/statistics/AbstractOBDResource.java Removed Paths: ------------- OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java OBD-WS/trunk/src/org/obd/ws/resources/KBTimestampResource.java OBD-WS/trunk/src/org/obd/ws/resources/SquarifiedTaxonMapResource.java OBD-WS/trunk/src/org/phenoscape/obd/query/OBDQuery.java OBD-WS/trunk/src/org/phenoscape/obd/query/Queries.java Deleted: OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/obd/ws/resources/AbstractOBDResource.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -1,49 +0,0 @@ -package org.obd.ws.resources; - -import java.sql.SQLException; - -import javax.sql.DataSource; - -import org.apache.log4j.Logger; -import org.obd.query.impl.OBDSQLShard; -import org.phenoscape.ws.application.PhenoscapeWebServiceApplication; -import org.restlet.resource.ResourceException; -import org.restlet.resource.ServerResource; - -public abstract class AbstractOBDResource extends ServerResource { - - private OBDSQLShard shard; - - /* (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(); - this.shard = new OBDSQLShard(); - } - - protected OBDSQLShard getShard() { - return this.shard; - } - - /** - * This method reads in db connection parameters from app context before connecting - * the Shard to the database - * @throws SQLException - * @throws ClassNotFoundException - */ - protected void connectShardToDatabase() throws SQLException, ClassNotFoundException{ - this.shard.connect((DataSource)(this.getContext().getAttributes().get(PhenoscapeWebServiceApplication.DATA_SOURCE_KEY))); - } - - protected void disconnectShardFromDatabase() { - this.shard.disconnect(); - } - - protected Logger log() { - return Logger.getLogger(this.getClass()); - } - -} Deleted: OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/obd/ws/resources/AutoCompleteResource.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -1,299 +0,0 @@ -package org.obd.ws.resources; - -import java.io.IOException; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.json.JSONException; -import org.json.JSONObject; -import org.phenoscape.obd.query.OBDQuery; -import org.phenoscape.obd.query.Queries; -import org.phenoscape.ws.application.PhenoscapeWebServiceApplication; -import org.restlet.data.Reference; -import org.restlet.data.Status; -import org.restlet.ext.json.JsonRepresentation; -import org.restlet.representation.Representation; -import org.restlet.resource.Get; -import org.restlet.resource.ResourceException; - -public class AutoCompleteResource extends AbstractOBDResource { - - 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 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(PhenoscapeWebServiceApplication.QUERIES_STRING); - this.prefixToNSMap = (Map<String, Set<String>>)this.getContext().getAttributes().get(PhenoscapeWebServiceApplication.PREFIX_TO_DEFAULT_NAMESPACE_MAP_STRING); - this.nsToSourceIdMap = (Map<String, String>)this.getContext().getAttributes().get(PhenoscapeWebServiceApplication.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(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 - */ - @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); - 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); - 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; - } - - /** - * 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(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; - } - - /** - * PURPOSE This method uses the {@link #MATCHES_COMPARATOR} to sort - * the input set of JSON Objects in such a way that: - * + objects containing labels and synonyms, which start with the search term are - * sorted first - * + objects containing labels and synonyms, which contain the search term are sorted - * second - * + objects containing definitions containing the search term are sorted - * third - * @param matchObjs - the set of JSON objects to be sorted - * @param term - the search term, which is to be used in the sorting - * process - * @return - properly sorted list of JSON Objects - * @throws JSONException - */ - private List<JSONObject> sortJsonObjects(Set<JSONObject> matchObjs, String term) throws JSONException{ - List<JSONObject> sortedMatches = new ArrayList<JSONObject>(); - List<JSONObject> startsWithMatches = new ArrayList<JSONObject>(); - List<JSONObject> containedInMatches = new ArrayList<JSONObject>(); - List<JSONObject> definitionMatches = new ArrayList<JSONObject>(); - - for (JSONObject matchObj : matchObjs){ - if (matchObj.get(MATCH_TYPE_STRING).equals(DEF_STRING)) { - definitionMatches.add(matchObj); - } else if (matchObj.get(MATCH_TYPE_STRING).equals(SYNONYM_STRING)) { - if(matchObj.getString(MATCH_TEXT_STRING).toLowerCase().startsWith(term.toLowerCase())){ - startsWithMatches.add(matchObj); - } else { - containedInMatches.add(matchObj); - } - } else { //actual name matches - if (matchObj.getString(MATCH_TEXT_STRING).toLowerCase().startsWith(term.toLowerCase())){ - startsWithMatches.add(matchObj); - } else { - containedInMatches.add(matchObj); - } - } - } - Collections.sort(startsWithMatches, MATCHES_COMPARATOR); - Collections.sort(containedInMatches, MATCHES_COMPARATOR); - Collections.sort(definitionMatches, MATCHES_COMPARATOR); - sortedMatches.addAll(startsWithMatches); - sortedMatches.addAll(containedInMatches); - sortedMatches.addAll(definitionMatches); - if (this.limitOfMatches != null && this.limitOfMatches < sortedMatches.size()) { - return sortedMatches.subList(0, this.limitOfMatches); - } else { - return sortedMatches; - } - } -} Deleted: OBD-WS/trunk/src/org/obd/ws/resources/KBTimestampResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/KBTimestampResource.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/obd/ws/resources/KBTimestampResource.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -1,64 +0,0 @@ -package org.obd.ws.resources; - -import java.sql.SQLException; - -import org.json.JSONException; -import org.json.JSONObject; -import org.phenoscape.obd.query.OBDQuery; -import org.phenoscape.obd.query.Queries; -import org.phenoscape.ws.application.PhenoscapeWebServiceApplication; -import org.restlet.data.Status; -import org.restlet.ext.json.JsonRepresentation; -import org.restlet.representation.Representation; -import org.restlet.resource.Get; -import org.restlet.resource.ResourceException; - -public class KBTimestampResource extends AbstractOBDResource { - - private JSONObject jObjs; - private OBDQuery obdq; - private Queries queries; - - @Override - protected void doInit() throws ResourceException { - super.doInit(); - this.queries = (Queries)this.getContext().getAttributes().get(PhenoscapeWebServiceApplication.QUERIES_STRING); - this.jObjs = new JSONObject(); - } - - @Get("json") - public Representation getJSONRepresentation() throws ResourceException { - String timestamp; - try{ - connectShardToDatabase(); - obdq = new OBDQuery(this.getShard(), queries); - timestamp = getTimeStamp(); - assembleJSONObjectFromTimestamp(timestamp); - } 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); - return null; - } finally { - disconnectShardFromDatabase(); - } - return new JsonRepresentation(this.jObjs); - } - - private String getTimeStamp() throws SQLException { - return obdq.executeTimestampQuery(); - } - - private void assembleJSONObjectFromTimestamp(String timestamp) throws JSONException { - jObjs.put("timestamp", timestamp); - } - -} Deleted: OBD-WS/trunk/src/org/obd/ws/resources/SquarifiedTaxonMapResource.java =================================================================== --- OBD-WS/trunk/src/org/obd/ws/resources/SquarifiedTaxonMapResource.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/obd/ws/resources/SquarifiedTaxonMapResource.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -1,142 +0,0 @@ -package org.obd.ws.resources; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.json.JSONException; -import org.json.JSONObject; -import org.phenoscape.obd.query.OBDQuery; -import org.phenoscape.obd.query.Queries; -import org.phenoscape.util.PhenotypeAndAnnotatedSubtaxonCountDTO; -import org.phenoscape.ws.application.PhenoscapeWebServiceApplication; -import org.restlet.data.Reference; -import org.restlet.data.Status; -import org.restlet.ext.json.JsonRepresentation; -import org.restlet.representation.Representation; -import org.restlet.resource.Get; -import org.restlet.resource.ResourceException; - -public class SquarifiedTaxonMapResource extends AbstractOBDResource { - - private String taxonID; - private OBDQuery obdq; - private Queries queries; - - @Override - protected void doInit() throws ResourceException { - super.doInit(); - this.taxonID = Reference.decode((String)(this.getRequestAttributes().get("taxonID"))); - this.queries = (Queries)this.getContext().getAttributes().get(PhenoscapeWebServiceApplication.QUERIES_STRING); - } - - @Get("json") - public Representation getJSONRepresentation() throws ResourceException { - try { - this.connectShardToDatabase(); - if(!inputFormParametersAreValid()){ - this.disconnectShardFromDatabase(); - return null; - } - obdq = new OBDQuery(this.getShard(), queries); - final JSONObject json = this.assembleJSONObject(taxonID); - // the value for the "$area" key should be the - // result of getCountOfAnnotationsWithinTaxon(), instead of 42 - // the value for the "species" key should be the - // number of taxa of rank species within the given taxon - // - // return children only one level deep - all children have an empty - // children list - - // {id: "TTO:151", name: "Halecostomi", data:{"$area": 42, species: 1234}, children: [ - //{"id":"TTO:10000323","name":"Pachycormidae", data:{"$area": 42, species: 1234}, children: []}, - //{"id":"TTO:1220", "name":"Amiiformes", data:{"$area": 42, species: 1234}, children: []}, - //{"id":"TTO:10000305","name":"Aspidorhynchiformes", data:{"$area": 42, species: 1234}, children: []}, - //{"id":"TTO:201","name":"Teleostei", data:{"$area": 42, species: 1234}, children: []}, - // {"id":"TTO:10000290","name":"Parasemionotidae", data:{"$area": 42, species: 1234}, children: []} - //]} - - return new JsonRepresentation(json); - } catch (SQLException sqle) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "[SQL EXCEPTION] Something broke server side. Consult server logs"); - } catch (ClassNotFoundException e) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "[CLASS NOT FOUND EXCEPTION] Something broke server side. Consult server logs"); - } catch (JSONException e) { - getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, "[JSON EXCEPTION] Error with JSON Object"); - } finally { - disconnectShardFromDatabase(); - } - return null; - } - - private boolean inputFormParametersAreValid(){ - if (taxonID == null) { - getResponse().setStatus( - Status.CLIENT_ERROR_BAD_REQUEST, - "ERROR: The input parameter for taxon " - + "is null"); - return false; - } - return true; - } - - protected JSONObject assembleJSONObject(String taxonUID) throws SQLException, JSONException { - - JSONObject searchObj, dataObj, childObj; - List<JSONObject> childObjs = new ArrayList<JSONObject>(); - List<JSONObject> childrenOfChildObj = new ArrayList<JSONObject>(); - - List<PhenotypeAndAnnotatedSubtaxonCountDTO> results = obdq.executeQueryForSquarifiedTaxonMapResource(taxonID); - - PhenotypeAndAnnotatedSubtaxonCountDTO searchTaxonObject = results.remove(0); - final String id = searchTaxonObject.getId(); - final String name = searchTaxonObject.getName(); - final int phenotypeCount = searchTaxonObject.getPhenotypeCount(); - final double subtaxonCount; - - if(searchTaxonObject.getSubtaxonCount() > 1) - subtaxonCount = Math.log(searchTaxonObject.getSubtaxonCount());//getting log values to reduce scales of comparison - else - subtaxonCount = searchTaxonObject.getSubtaxonCount(); - - searchObj = new JSONObject(); - searchObj.put("id", id); - searchObj.put("name", name); - - dataObj = new JSONObject(); - dataObj.put("$area", subtaxonCount); - dataObj.put("$color", phenotypeCount); - - searchObj.put("data", dataObj); - - for (PhenotypeAndAnnotatedSubtaxonCountDTO child : results) { - childObj = new JSONObject(); - - final String childID = child.getId(); - final String childName = child.getName(); - final int childPhenotypeCount = child.getPhenotypeCount(); - final double childSubtaxonCount; - - if(child.getSubtaxonCount() > 1) - childSubtaxonCount = Math.log(child.getSubtaxonCount());//getting log values to reduce scales of comparison - else - childSubtaxonCount = child.getSubtaxonCount(); - - childObj.put("id", childID); - childObj.put("name", childName); - - dataObj = new JSONObject(); - dataObj.put("$area", childSubtaxonCount); - dataObj.put("$color", (((childPhenotypeCount*1.0)/phenotypeCount)*100)); - - childObj.put("data", dataObj); - childObj.put("children", childrenOfChildObj); - childObjs.add(childObj); - } - - searchObj.put("children", childObjs); - - return searchObj; - } - -} Modified: OBD-WS/trunk/src/org/phenoscape/obd/model/PhenoscapeDataStore.java =================================================================== --- OBD-WS/trunk/src/org/phenoscape/obd/model/PhenoscapeDataStore.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/phenoscape/obd/model/PhenoscapeDataStore.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -24,7 +24,7 @@ public Date getRefreshDate() throws ParseException { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - //TODO this is a placeholder date + //TODO this is a placeholder date - retrieve from database return formatter.parse("1859-11-24"); } Deleted: OBD-WS/trunk/src/org/phenoscape/obd/query/OBDQuery.java =================================================================== --- OBD-WS/trunk/src/org/phenoscape/obd/query/OBDQuery.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/phenoscape/obd/query/OBDQuery.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -1,734 +0,0 @@ -package org.phenoscape.obd.query; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.sql.DataSource; - -import org.apache.log4j.Logger; -import org.obd.model.CompositionalDescription; -import org.obd.model.Node; -import org.obd.query.Shard; -import org.obd.ws.resources.AutoCompleteResource; -import org.phenoscape.util.AnnotationDTO; -import org.phenoscape.util.Collections; -import org.phenoscape.util.HomologDTO; -import org.phenoscape.util.PhenotypeAndAnnotatedSubtaxonCountDTO; -import org.phenoscape.util.PhenotypeDTO; -import org.phenoscape.ws.application.PhenoscapeWebServiceApplication; - -/** - * This class interfaces with methods from the OBDAPI, specifically - * in the Shard class hierarchy, and invokes these methods. Methods - * defined in this class return their results to invoking REST - * resources - */ - -public class OBDQuery { - - private final Shard shard; - public Logger log; - private Queries queries; - - public static enum AutoCompletionMatchTypes{ - LABEL_MATCH, SYNONYM_MATCH, DEFINITION_MATCH - }; - - /** 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; - /** An enumeration of the possible match types for the - * {@see #getAutocompletionsForSearchTerm} method */ - - /** 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; - } - - /** - * Mapping for how to represent relations used in post-comp differentia when generating a human-readable label. - * If the relation is not in this map, use "of". - */ - private static final Map<String, String> POSTCOMP_RELATIONS = new HashMap<String, String>(); - static { - POSTCOMP_RELATIONS.put("OBO_REL:connected_to", "on"); - POSTCOMP_RELATIONS.put("connected_to", "on"); - POSTCOMP_RELATIONS.put("anterior_to", "anterior to"); - POSTCOMP_RELATIONS.put("BSPO:0000096", "anterior to"); - POSTCOMP_RELATIONS.put("posterior_to", "posterior to"); - POSTCOMP_RELATIONS.put("BSPO:0000099", "posterior to"); - POSTCOMP_RELATIONS.put("adjacent_to", "adjacent to"); - POSTCOMP_RELATIONS.put("OBO_REL:adjacent_to", "adjacent to"); - } - - /** - * This is the default constructor. - * @param shard = the shard to use. THis has to be an AbstractSQLShard to use the connection - * it comes with - * @throws SQLException - */ - public OBDQuery(Shard shard) throws SQLException{ - this.shard = shard; - this.log = Logger.getLogger(this.getClass()); - } - - /** - * Overloaded constructor. This will optimize the use of the Queries object throughout - * the application - * @param shard - the shard to use - * @param queries - the instance of the Queries class - * @throws SQLException - */ - public OBDQuery(Shard shard, Queries queries) throws SQLException{ - this(shard); - this.queries = queries; - } - - /** - * This constructor is meant for use by the auto completion and term info service. This is - * because this uses maps that are passed to it by the invoking service. These services - * obtain the maps from the application context - * @param shard - * @param queries - * @param nsToSourceIdMap - * @param prefixToNSMap - * @throws SQLException - */ - public OBDQuery(Shard shard, Queries queries, Map<String, String> nsToSourceIdMap, - Map<String, Set<String>> prefixToNSMap) throws SQLException{ - this(shard, queries); - this.defaultNamespaceToNodeIdMap = nsToSourceIdMap; - this.prefixToDefaultNamespacesMap = prefixToNSMap; - } - - public List<PhenotypeAndAnnotatedSubtaxonCountDTO> executeQueryForSquarifiedTaxonMapResource(String taxonUID) throws SQLException { - - List<PhenotypeAndAnnotatedSubtaxonCountDTO> results = - new ArrayList<PhenotypeAndAnnotatedSubtaxonCountDTO>(); - PhenotypeAndAnnotatedSubtaxonCountDTO pascDTO; - String id, name; - int phenotypeCount, subtaxonCount; - PreparedStatement ps1 = null, ps2 = null; - final Connection conn = this.createConnection(); - try { - ps1 = conn.prepareStatement(queries.getQueryForSquarifiedTaxonMapResource2()); - ps1.setString(1, taxonUID); - ResultSet rs1 = ps1.executeQuery(); - while(rs1.next()){ - id = rs1.getString(1); - name = rs1.getString(2); - phenotypeCount = rs1.getInt(3); - subtaxonCount = rs1.getInt(4); - - pascDTO = new PhenotypeAndAnnotatedSubtaxonCountDTO(id, name); - pascDTO.setPhenotypeCount(phenotypeCount); - pascDTO.setSubtaxonCount(subtaxonCount); - results.add(pascDTO); - } - - ps2 = conn.prepareStatement(queries.getQueryForSquarifiedTaxonMapResource1()); - ps2.setString(1, taxonUID); - ResultSet rs2 = ps2.executeQuery(); - while(rs2.next()){ - id = rs2.getString(1); - name = rs2.getString(2); - phenotypeCount = rs2.getInt(3); - subtaxonCount = rs2.getInt(4); - - pascDTO = new PhenotypeAndAnnotatedSubtaxonCountDTO(id, name); - pascDTO.setPhenotypeCount(phenotypeCount); - pascDTO.setSubtaxonCount(subtaxonCount); - results.add(pascDTO); - } - } catch (SQLException sqle) { - log.error(sqle); - throw sqle; - } - finally { - if (ps1 != null) { - ps1.close(); - } - if(ps2 != null) { - ps2.close(); - } - if (conn != null) { - conn.commit(); - conn.close(); - } - } - return results; - } - - /** - * This query returns the timestamp when the database was refreshed - * @return the timestamp - * @throws SQLException - */ - public String executeTimestampQuery() throws SQLException{ - String timestamp = "2009-07-24"; - PreparedStatement pStmt = null; - final Connection conn = this.createConnection(); - try{ - pStmt = conn.prepareStatement(queries.getTimestampQuery()); - log.trace(pStmt.toString()); - long startTime = System.currentTimeMillis(); - ResultSet rs = pStmt.executeQuery(); - long endTime = System.currentTimeMillis(); - log.trace("Query execution took " + (endTime -startTime) + " milliseconds"); - if(rs.next()){ - timestamp = rs.getString(1); - } - if(timestamp.contains("_")) - timestamp = timestamp.substring(0, timestamp.indexOf("_")); - } - catch(SQLException sqle){ - log.error(sqle); - throw sqle; - } - finally { - if (pStmt != null) { - pStmt.close(); - } - if(conn != null){ - conn.commit(); - conn.close(); - } - } - return timestamp; - } - - /** - * @param reifLinkId - the search parameter for the SQL query. This is an INTEGER - * which is provided by the invoking REST service. - * @return a collection of DTOs, one for each row returned by the query - * @throws SQLException - * The purpose of this query is to return all the free text data - * (metadata) associated with a given <TAXON><EXHIBITS><PHENOTYPE> assertion - * The metadata is packaged into a collection of Nodes which are then returned - * back - */ - public Collection<AnnotationDTO> executeFreeTextQueryAndAssembleResults(Integer reifLinkId) throws SQLException{ - - Collection<AnnotationDTO> results = new ArrayList<AnnotationDTO>(); - PreparedStatement pStmt = null; - - String entityId, entity, qualityId, quality, relEntityId, relEntity; - final Connection conn = this.createConnection(); - try{ - pStmt = conn.prepareStatement(queries.getFreeTextDataQuery()); - pStmt.setInt(1, reifLinkId); - log.trace(pStmt.toString()); - long startTime = System.currentTimeMillis(); - ResultSet rs = pStmt.executeQuery(); - long endTime = System.currentTimeMillis(); - log.trace("Query execution took " + (endTime -startTime) + " milliseconds"); - if(rs.next()){ - AnnotationDTO dto = new AnnotationDTO(rs.getString(1)); - - dto.setTaxonId(rs.getString(2)); - dto.setTaxon(rs.getString(3)); - - entityId = rs.getString(4); - entity = rs.getString(5); - - relEntityId = rs.getString(15); - relEntity = rs.getString(16); - - //Handling post compositions. TODO THis has to be streamlined - if(entity == null || entity.length() == 0){ - entity = simpleLabel(entityId); - } - - qualityId = rs.getString(6); - quality = rs.getString(7); - - //TODO Streamline post compositions handling method here - if(quality == null || quality.length() == 0){ - quality = semanticLabel(qualityId); - } - if(relEntityId != null){ - if(relEntity == null) - relEntity = simpleLabel(relEntityId); - if(quality.trim().endsWith("from") || quality.trim().endsWith("to") || quality.trim().endsWith("with")) - quality += " " + relEntity; - else - quality += " towards " + relEntity; - } - dto.setEntityId(entityId); - dto.setEntity(entity); - dto.setQualityId(qualityId); - dto.setQuality(quality); - - dto.setPublication(rs.getString(8)); - - dto.setCharText(rs.getString(9)); - dto.setCharComments(rs.getString(10)); - dto.setCharNumber(rs.getString(11)); - - dto.setStateText(rs.getString(12)); - dto.setStateComments(rs.getString(13)); - - dto.setCurators(rs.getString(14)); - - results.add(dto); - } - } - catch(SQLException sqle){ - log.error(sqle); - throw sqle; - } - finally { - if (pStmt != null) { - pStmt.close(); - } - if (conn != null) { conn.close(); } - } - - return results; - } - - /** - * @param searchTerm - the search parameter for the SQL query. This term comes from the REST - * service - * @return a collection of nodes - * @throws SQLException - * The purpose of this method is to retrieve all the homolog information from - * the database and package them into a collection of nodes. All the retrieved information - * is added to these Nodes via links - */ - public Collection<HomologDTO> executeHomologyQueryAndAssembleResults(String searchTerm) - throws SQLException{ - Collection<HomologDTO> results = new ArrayList<HomologDTO>(); - PreparedStatement pStmt = null; - final Connection conn = this.createConnection(); - try{ - pStmt = conn.prepareStatement(queries.getHomologyQuery()); - for(int i = 1; i <= pStmt.getParameterMetaData().getParameterCount(); i++) - pStmt.setString(i, searchTerm); - log.trace(pStmt.toString()); - long startTime = System.currentTimeMillis(); - ResultSet rs = pStmt.executeQuery(); - long endTime = System.currentTimeMillis(); - log.trace("Query execution took " + (endTime -startTime) + " milliseconds"); - while(rs.next()){ - HomologDTO dto = new HomologDTO(rs.getString(1) + "\t" + rs.getString(6)); - dto.setLhTaxonId(rs.getString(2)); - dto.setLhTaxon(rs.getString(3)); - dto.setRhTaxonId(rs.getString(7)); - dto.setRhTaxon(rs.getString(8)); - dto.setLhEntityId(rs.getString(4)); - dto.setLhEntity(rs.getString(5)); - dto.setRhEntityId(rs.getString(9)); - dto.setRhEntity(rs.getString(10)); - - dto.setPublication(rs.getString(11)); - dto.setEvidenceCode(rs.getString(12)); - dto.setEvidence(rs.getString(13)); - - results.add(dto); - } - } - catch(SQLException sqle){ - log.error(sqle); - throw sqle; - } - finally { - if (pStmt != null) { - pStmt.close(); - - } - if(conn != null){ - conn.commit(); - conn.close(); - } - } - return results; - } - - /**@throws SQLException - * The purpose of this method is to execute the given query with set search term and assemble the results into a - * makeshift persistence layer. The persistence layer is a collection of Data Transfer Objects. Each row is packaged into - * a single PhenotypeDTO object. The phenotype is the central entity in this querying procedure. - * Therefore, the IDs of the each node are set to be the retrieved phenotype. The method assembles - * these DTOs into a collection, which are returned - * @param queryStr - this is provided by the invoking REST service. This is the SQL query to be executed - * @param searchTerm - the UID (eg: TAO:0000108) to search for. Also provided by the invoking REST service - * @param filterOptions - the rows retrieved by the query execution are filtered through these values which are provided - * by the invoking REST service - */ - - public Collection<PhenotypeDTO> executeQueryAndAssembleResults(String queryStr, String searchTerm) - throws SQLException{ - /** <a> annotationToReifsMap </a> - * This new map has been added tp consolidate reif ids for a TAXON to PHENOTYPE assertion*/ - Map<PhenotypeDTO, Set<String>> annotationToReifsMap = new HashMap<PhenotypeDTO, Set<String>>(); - final Connection conn = this.createConnection(); - String entityLabel, entityId; - PreparedStatement pstmt = null; - try { - pstmt = conn.prepareStatement(queryStr); - for(int i = 1; i <= pstmt.getParameterMetaData().getParameterCount(); i++) - pstmt.setString(i, searchTerm); - log.trace(pstmt.toString()); - long startTime = System.currentTimeMillis(); - ResultSet rs = pstmt.executeQuery(); - long endTime = System.currentTimeMillis(); - log.trace("Query execution took " + (endTime -startTime) + " milliseconds"); - while(rs.next()){ - PhenotypeDTO dto = new PhenotypeDTO(rs.getString(1)); - - dto.setTaxon(rs.getString(3)); - dto.setTaxonId(rs.getString(2)); - dto.setQuality(rs.getString(5)); - dto.setQualityId(rs.getString(4)); - dto.setCharacter(rs.getString(7)); - dto.setCharacterId(rs.getString(6)); - entityLabel = rs.getString(9); - entityId = rs.getString(8); - dto.setEntity(entityLabel); - dto.setEntityId(entityId); - String reif = rs.getString(10); - dto.setNumericalCount(rs.getString(11)); - dto.setRelatedEntityId(rs.getString(12)); - dto.setRelatedEntity(rs.getString(13)); - dto.setPublication(rs.getString(14)); - - //we collect all the reif ids associated with each DTO object - Set<String> reifs = annotationToReifsMap.get(dto); - if(reifs == null) - reifs = new HashSet<String>(); - reifs.add(reif); - annotationToReifsMap.put(dto, reifs); - } - for(PhenotypeDTO dto : annotationToReifsMap.keySet()){ - //here we reassign the reif ids to the DTO - for(String reif : annotationToReifsMap.get(dto)){ - dto.addReifId(reif); - } - } - } - catch(SQLException sqle){ - log.error(sqle); - throw sqle; - } - finally { - if (pstmt != null) { - pstmt.close(); - } - if(conn != null){ - conn.commit(); - conn.close(); - } - } - return annotationToReifsMap.keySet(); - } - - /** - * Return a label for any node in a shard. If the node has no label, a label is generated recursively based on the - * node's properties as a compositional descripton. - * @param node The Node for which to return or generate a label. - */ - public String semanticLabel(Node node) { - if (node.getLabel() != null) { - return node.getLabel(); - } else { - final CompositionalDescription desc = this.shard.getCompositionalDescription(node.getId(), false); - final List<String> differentia = new ArrayList<String>(); - final Collection<CompositionalDescription> differentiaArguments = desc.getDifferentiaArguments(); - if (differentiaArguments == null) { - log.error("No differentia arguments for: " + node.getId()); - return node.getId(); - } - for (CompositionalDescription differentium : differentiaArguments) { - final StringBuffer buffer = new StringBuffer(); - buffer.append(semanticLabel(differentium.getRelationId())); - buffer.append("("); - buffer.append(semanticLabel(differentium.getRestriction().getTargetId())); - buffer.append(")"); - differentia.add(buffer.toString()); - } - return semanticLabel(desc.getGenus().getNodeId()) + "("+ Collections.join(differentia, ", ") + ")"; - } - } - - /** - * Return a label for any node in a shard. If the node has no label, a label is generated recursively based on the - * node's properties as a compositional descripton. - * @param id The identifier of a Node for which to return or generate a label. - */ - public String semanticLabel(String id) { - final Node node = this.shard.getNode(id); - if (node != null) { - return semanticLabel(node); - } - else { - return id; - } - } - - /** - * @param node - a post composition node - * @return - a human readable label generated from the post composition - */ - public String simpleLabel(Node node) { - if (node.getLabel() != null) { - return node.getLabel(); - } else { - final CompositionalDescription desc = this.shard.getCompositionalDescription(node.getId(), false); - final List<String> differentia = new ArrayList<String>(); - final Collection<CompositionalDescription> differentiaArguments = desc.getDifferentiaArguments(); - if (differentiaArguments == null) { - log.error("No differentia arguments for: " + node.getId()); - return node.getId(); - } - for (CompositionalDescription differentium : differentiaArguments) { - final String relationID = differentium.getRestriction().getRelationId(); - final String relationSubstitute; - if (POSTCOMP_RELATIONS.containsKey(relationID)) { - relationSubstitute = POSTCOMP_RELATIONS.get(relationID); - } else { - relationSubstitute = "of"; - } - final StringBuffer buffer = new StringBuffer(); - buffer.append(" "); - buffer.append(relationSubstitute); - buffer.append(" "); - buffer.append(simpleLabel(differentium.getRestriction().getTargetId())); - differentia.add(buffer.toString()); - } - return simpleLabel(desc.getGenus().getNodeId()) + Collections.join(differentia, ", "); - } - } - - public String simpleLabel(String id) { - final Node node = this.shard.getNode(id); - return simpleLabel(node); - } - - /** - * This method uses the input search term from the form, and the - * specified search options to first construct an SQL query and then - * return the autocompletions returned by the query execution as a - * data structure to the {@link AutoCompleteResource} - * @param searchTerm - the input search term from the form - * @param searchOptions - the search options specified in the form - * @return - a data structure which groups the autocompletions under - * different categories viz. label match, synonym match and definition - * match - * @throws SQLException - */ - public Map<String, List<List<String>>> getAutocompletionsForSearchTerm(String searchTerm, - Map<String, String> searchOptions) throws SQLException{ - List<String> ontologySourceIds = createSourceIdListFromOntologyOptions(searchOptions); - String query = - constructAutocompleteQueryFromSearchTermAndSearchOptions(searchTerm, searchOptions); - return executeAutocompletionQueryAndProcessResults(query, ontologySourceIds); - } - - private Connection createConnection() throws SQLException { - final DataSource ds = (DataSource)(PhenoscapeWebServiceApplication.getCurrent().getContext().getAttributes().get(PhenoscapeWebServiceApplication.DATA_SOURCE_KEY)); - return ds.getConnection(); - } - - /** - * This method uses the input search term and input specified - * search options to construct an SQL query, which will be executed by the - * {@link #executeAutocompletionQueryAndProcessResults(String, List)} method - * @param searchTerm - the input search term (comes from the form) - * @param searchOptions - search options specified in the form - * @return a SQL query string - */ - private String constructAutocompleteQueryFromSearchTermAndSearchOptions(String searchTerm, - Map<String, String> searchOptions){ - String completedQueryString = ""; - - String synonymOption = searchOptions.get("synonymOption"); - String definitionOption = searchOptions.get("definitionOption"); - - String autocompleteLabelQuery = queries.getAutocompleteLabelQuery() + - "'" + searchTerm + "'"; - String autocompleteSynonymQuery = queries.getAutocompleteSynonymQuery() + - "'" + searchTerm + "'"; - String autocompleteDefinitonQuery = queries.getAutocompleteDefinitionQuery() + - "'" + searchTerm + "'"; - completedQueryString = autocompleteLabelQuery; - - if(Boolean.parseBoolean(synonymOption)){ - completedQueryString += " UNION " + autocompleteSynonymQuery; - } - if(Boolean.parseBoolean(definitionOption)){ - completedQueryString += " UNION " + autocompleteDefinitonQuery; - } - return completedQueryString; - } - - /** - * This query executes the given query and iterates through the - * returned result set to construct a data structure, which groups each - * result under one of label match, synonym match or definition match - * @param query - the SQL query, which is assembled by the - * {@link #constructAutocompleteQueryFromSearchTermAndSearchOptions(String, Map)} method - * @return - a data structure which groups the autocompletions under - * different categories viz. label match, synonym match and definition - * match - * @throws SQLException - * @throws SQLException - */ - private Map<String, List<List<String>>> executeAutocompletionQueryAndProcessResults(String query, List<String> sourceIdList) throws SQLException { - - Map<String, List<List<String>>> resultsFromDifferentCategories = new HashMap<String, List<List<String>>>(); - List<List<String>> labelMatches = new ArrayList<List<String>>(); - List<List<String>> synonymMatches = new ArrayList<List<String>>(); - List<List<String>> definitionMatches = new ArrayList<List<String>>(); - Connection conn = null; - try { - conn = this.createConnection(); - java.sql.Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(query); - List<String> row; - String uid, label, definition, synonym, sourceId; - while (rs.next()) { - row = new ArrayList<String>(); - uid = rs.getString(1); - label = rs.getString(2); - synonym = rs.getString(3); - definition = rs.getString(4); - sourceId = rs.getString(5); - - if(!uid.contains("GENE")){ //GENEs dont have source ids - if(isToBeFiltered(sourceId, sourceIdList)) - continue; - } - row.add(uid); - row.add(label); - row.add(synonym); - row.add(definition); - - if(definition != null && definition.length() > 0) - definitionMatches.add(row); - else if(synonym != null && synonym.length() > 0) - synonymMatches.add(row); - else - labelMatches.add(row); - } - resultsFromDifferentCategories.put(AutoCompletionMatchTypes.LABEL_MATCH.name(), - labelMatches); - resultsFromDifferentCategories.put(AutoCompletionMatchTypes.SYNONYM_MATCH.name(), - synonymMatches); - resultsFromDifferentCategories.put(AutoCompletionMatchTypes.DEFINITION_MATCH.name(), - definitionMatches); - } catch (SQLException e) { - throw(e); - } finally { - if (conn != null) { - conn.commit(); - conn.close(); - } - } - return resultsFromDifferentCategories; - } - - /** - * This method creates a list of source ids from the database - * given the list of ontologies to be searched - * @param searchOptions - the search options input from the - * form. This includes the list of ontologies to be searched - * @return a list of source ids for every ontology in the list - */ - private List<String> createSourceIdListFromOntologyOptions( - Map<String, String> searchOptions){ - List<String> sourceIdList = new ArrayList<String>(); - String ontologyOption = searchOptions.get("ontologyOption"); - if(ontologyOption != null && ontologyOption.length() > 0){ - for(String prefix : ontologyOption.split(",")){ - if(prefixToDefaultNamespacesMap.get(prefix) != null){ - for(String namespace : - prefixToDefaultNamespacesMap.get(prefix)){ - sourceIdList.add(this.defaultNamespaceToNodeIdMap.get(namespace)); - } - } - } - } - return sourceIdList; - } - /** - * This method decides if a result is to be - * filtered given the source id. - * The input source id is compared with the - * list of source ids of the ontologies whose terms are - * to be included in the results - * @param sourceId - the source id of the result - * @param sourceIdList - the list of source ids corr. - * to the ontologies whose terms are to be included - * in the results - * @return a boolean to indicate if this result is to be - * filtered - */ - private boolean isToBeFiltered(String sourceId, - List<String> sourceIdList) { - if(sourceId == null) return true; - if(sourceIdList != null && sourceIdList.size() > 0){ - if(sourceIdList.contains(sourceId)) - return false; - else - return true; - } - return false; - } - - @Deprecated - /** - * The purpose of this method is to return matching nodes for - * autocompletion - * @author cartik - * @param term - search term - * @param ontologyList - list of ontologies to filter terms from - * @param zfinOption - set separately because GENEs are not read from ontologies and - * must be queried separately - * @param synOption - synonym option - * @param defOption - definition option - * @return - * @throws SQLException - */ - public Map<String, Collection<Node>> getCompletionsForSearchTerm(String term, boolean zfinOption, - List<String> ontologyList, boolean synOption, boolean defOption) throws SQLException{ - - Map<String, Collection<Node>> results = new HashMap<String, Collection<Node>>(); - try{ - Collection<Node> nodesByName = this.shard.getNodesForSearchTermByLabel(term, zfinOption, ontologyList); - - results.put(AutoCompletionMatchTypes.LABEL_MATCH.name(), nodesByName); - if(synOption){ - Collection<Node> nodesBySynonym = this.shard.getNodesForSearchTermBySynonym(term, zfinOption, ontologyList, true); - results.put(AutoCompletionMatchTypes.SYNONYM_MATCH.name(), nodesBySynonym); - } - if(defOption){ - Collection<Node> nodesByDefinition = this.shard.getNodesForSearchTermByDefinition(term, zfinOption, ontologyList); - results.put(AutoCompletionMatchTypes.DEFINITION_MATCH.name(), nodesByDefinition); - } - } - catch(SQLException e){ - log.error(e); - throw e; - } - return results; - } -} Deleted: OBD-WS/trunk/src/org/phenoscape/obd/query/Queries.java =================================================================== --- OBD-WS/trunk/src/org/phenoscape/obd/query/Queries.java 2010-05-25 19:36:11 UTC (rev 3341) +++ OBD-WS/trunk/src/org/phenoscape/obd/query/Queries.java 2010-05-27 02:37:13 UTC (rev 3342) @@ -1,804 +0,0 @@ -package org.phenoscape.obd.query; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.obd.query.Shard; -import org.obd.query.impl.OBDSQLShard; - -/** - * This class contains queries (Strings), which are to be executed against the database - * to retrieve results for the different REST services - * <p> Query Strings are processed before being accessed - * by methods from the {@link OBDQuery} class which executes them - * @author cartik - */ - -public class Queries { - - /** - * relationNodeIds is a map of actual relation nodes ids that are used in links and the - * node ids they are assigned by the database. For example, a row from the NODE table - * in the database would be - * - * NODE_ID UID LABEL - * ------- ---- ----- - * 123 OBO_REL:is_a is_a - * - * In relationNodeIds, we store the Node-Ids associated with the UIDs because the queries - * (see below) need them - */ - private Map<String, Integer> relationNodeIds; - - /* - * These are actual relation UIDs coming from the OBO Relation and - * PHENOSCAPE VOCAB ontologies - */ - private final static String IS_A_RELATION_ID = "OBO_REL:is_a"; - private final static String INHERES_IN_RELATION_ID = "OBO_REL:inheres_in"; - private final static String HAS_ALLELE_RELATION_ID = "PHENOSCAPE:has_allele"; - private final static String EXHIBITS_RELATION_ID = "PHENOSCAPE:exhibits"; - private final static String VALUE_FOR_RELATION_ID = "PHENOSCAPE:value_for"; - - private static final String HOMOLOG_TO_RELATION_ID = "OBO_REL:homologous_to"; - private static final String IN_TAXON_RELATION_ID = "PHENOSCAPE:in_taxon"; - private static final String HAS_PUBLICATION_RELATION_ID = "PHENOSCAPE:has_publication"; - private static final String HAS_EVIDENCE_CODE_RELATION_ID = "PHENOSCAPE:has_evidence_code"; - - private static final String POSITED_BY_RELATION_ID = "posited_by"; - private static final String HAS_STATE_RELATION_ID = "cdao:has_State"; - private static final String HAS_DATUM_RELATION_ID = "cdao:has_Datum"; - private static final String HAS_CURATORS_RELATION_ID = "PHENOSCAPE:has_curators"; - private static final String HAS_COMMENT_RELATION_ID = "PHENOSCAPE:has_comment"; - private static final String HAS_NUMBER_RELATION_ID = "PHENOSCAPE:has_number"; - - private static final String OBO_COMMENT_TAG_ID = "oboInOwl:comment"; - - /** - * An enumeration to keep track of the placeholder patterns to look for - * in the raw query - */ - - public static enum QueryPlaceholder{ - INHERES_IN("___inheres_in", INHERES_IN_RELATION_ID), - VALUE_FOR("___value_for", VALUE_FOR_RELATION_ID), - EXHIBITS("___exhibits", EXHIBITS_RELATION_ID), - HAS_ALLELE("___has_allele", HAS_ALLELE_RELATION_ID), - IS_A("___is_a", IS_A_RELATION_ID), - HOMOLOGOUS_TO("___homologous_to", HOMOLOG_TO_RELATION_ID), - IN_TAXON("___in_taxon", IN_TAXON_RELATION_ID), - HAS_PUBLICATION("___has_publication", HAS_PUBLICATION_RELATION_ID), - HAS_EVIDENCE_CODE("___has_evidence_code", HAS_EVIDENCE_CODE_RELATION_ID), - POSITED_BY("___posited_by", POSITED_BY_RELATION_ID), - HAS_STATE("___has_State", HAS_STATE_RELATION_ID), - HAS_DATUM("___has_Datum", HAS_DATUM_RELATION_ID), - HAS_CURATORS("___has_curators", HAS_CURATORS_RELATION_ID), - HAS_COMMENT("___has_comment", HAS_COMMENT_RELATION_ID), - HAS_NUMBER("___has_number", HAS_NUMBER_RELATION_ID), - COMMENT("___comment", OBO_COMMENT_TAG_ID); - - - QueryPlaceholder(String name, String rId){ - this.pattern = name; - this.relationUid = rId; - } - - private final String pattern; - private final String relationUid; - - public String pattern(){return pattern;} - public String relationUid(){return relationUid;} - }; - - private Shard shard; - - public Logger log; - - /* - * These are the queries we are using now. - */ - - /** - * This query retrieves the database refresh timestamp - */ - private String timestampQuery = - "SELECT notes FROM obd_schema_metadata"; - - /** - * INPUT: An anatomical entity (E) - * This is a variant of the {@link #anatomyQuery} - */ - private String genericPhenotypeQuery = - "SELECT " + - "p1.phenotype_uid AS phenotype_uid, " + - "p1.subject_uid AS subject_uid, p1.subject_label AS subject_Label, " + - "p1.quality_uid AS quality_uid, p1.quality_label AS quality_label, " + - "p1.character_uid AS character_uid, p1.character_label AS character_label, " + - "p1.entity_uid AS entity_uid, p1.entity_label AS entity_label, " + - "p1.reif_id AS reif_id, p1.count AS count, " + - "p1.related_entity_uid AS related_entity_uid, " + - "p1.related_entity_label AS related_entity_label, " + - "pub_reif.publication AS publication " + - "FROM " + - "phenotype_by_entity_character AS p1 " + - "LEFT OUTER JOIN (li... [truncated message content] |