c5642a9c08929069562f7596e682dc45e3f765e1
[jalview.git] / src / jalview / ws / dbsources / PDBRestClient.java
1 package jalview.ws.dbsources;
2
3 import jalview.ws.uimodel.PDBRestRequest;
4 import jalview.ws.uimodel.PDBRestResponse;
5 import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
6
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Iterator;
10 import java.util.List;
11
12 import javax.ws.rs.core.MediaType;
13
14 import org.json.simple.JSONArray;
15 import org.json.simple.JSONObject;
16 import org.json.simple.parser.JSONParser;
17 import org.json.simple.parser.ParseException;
18
19 import com.sun.jersey.api.client.Client;
20 import com.sun.jersey.api.client.ClientResponse;
21 import com.sun.jersey.api.client.WebResource;
22 import com.sun.jersey.api.client.config.ClientConfig;
23 import com.sun.jersey.api.client.config.DefaultClientConfig;
24 import com.sun.jersey.api.json.JSONConfiguration;
25
26 /**
27  * A rest client for querying the Search endpoing of the PDB REST API
28  * 
29  * @author tcnofoegbu
30  *
31  */
32 public class PDBRestClient
33 {
34   private static String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?";
35
36   private static int DEFAULT_RESPONSE_SIZE = 200;
37
38   /**
39    * Takes a PDBRestRequest object and returns a response upon execution
40    * 
41    * @param pdbRestRequest
42    *          the PDBRestRequest instance to be processed
43    * @return the pdbResponse object for the given request
44    */
45   public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest)
46   {
47     ClientConfig clientConfig = new DefaultClientConfig();
48     clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
49             Boolean.TRUE);
50     Client client = Client.create(clientConfig);
51
52     String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest
53             .getWantedFields());
54     int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE
55             : pdbRestRequest.getResponseSize();
56     String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest
57             .getFieldToSortBy().trim().isEmpty()) ? "" : (pdbRestRequest
58             .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc"
59             : " desc"));
60
61     // Build request parameters for the REST Request
62     WebResource webResource = client.resource(PDB_SEARCH_ENDPOINT)
63             .queryParam("wt", "json").queryParam("fl", wantedFields)
64             .queryParam("rows", String.valueOf(responseSize))
65             .queryParam("q", pdbRestRequest.getQuery())
66             .queryParam("sort", sortParam);
67
68     // Execute the REST request
69     ClientResponse clientResponse = webResource.accept(
70             MediaType.APPLICATION_JSON).get(ClientResponse.class);
71
72     // Get the JSON string from the response object
73     String responseString = clientResponse.getEntity(String.class);
74
75     // Check the response status and report exception if one occurs
76     if (clientResponse.getStatus() != 200)
77     {
78       String errorMessage = "";
79       if (clientResponse.getStatus() == 400)
80       {
81         errorMessage = parseJsonExceptionString(responseString);
82         throw new RuntimeException(errorMessage);
83       }
84       else
85       {
86         errorMessage = "Failed : HTTP error code : "
87                 + clientResponse.getStatus();
88         throw new RuntimeException(errorMessage);
89       }
90     }
91
92     // Make redundant objects eligible for garbage collection to conserve
93     // memory
94     clientResponse = null;
95     client = null;
96
97     // Process the response and return the result to the caller.
98     return parsePDBJsonResponse(responseString, pdbRestRequest);
99   }
100
101   /**
102    * Process error response from PDB server if/when one occurs.
103    * 
104    * @param jsonResponse
105    *          the JSON string containing error message from the server
106    * @return the processed error message from the JSON string
107    */
108   public static String parseJsonExceptionString(String jsonErrorResponse)
109   {
110     StringBuilder errorMessage = new StringBuilder(
111             "\n============= PDB Rest Client RunTime error =============\n");
112
113     try
114     {
115       JSONParser jsonParser = new JSONParser();
116       JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
117       JSONObject errorResponse = (JSONObject) jsonObj.get("error");
118
119       JSONObject responseHeader = (JSONObject) jsonObj
120               .get("responseHeader");
121       JSONObject paramsObj = (JSONObject) responseHeader.get("params");
122       String status = responseHeader.get("status").toString();
123       String message = errorResponse.get("msg").toString();
124       String query = paramsObj.get("q").toString();
125       String fl = paramsObj.get("fl").toString();
126
127       errorMessage.append("Status: ").append(status).append("\n");
128       errorMessage.append("Message: ").append(message).append("\n");
129       errorMessage.append("query: ").append(query).append("\n");
130       errorMessage.append("fl: ").append(fl).append("\n");
131
132     } catch (ParseException e)
133     {
134       e.printStackTrace();
135     }
136     return errorMessage.toString();
137   }
138
139   /**
140    * Parses the JSON response string from PDB REST API. The response is dynamic
141    * hence, only fields specifically requested for in the 'wantedFields'
142    * parameter is fetched/processed
143    * 
144    * @param pdbJsonResponseString
145    *          the JSON string to be parsed
146    * @param pdbRestRequest
147    *          the request object which contains parameters used to process the
148    *          JSON string
149    * @return
150    */
151   @SuppressWarnings("unchecked")
152   public static PDBRestResponse parsePDBJsonResponse(
153           String pdbJsonResponseString, PDBRestRequest pdbRestRequest)
154   {
155     PDBRestResponse searchResult = new PDBRestResponse();
156     List<PDBResponseSummary> result = null;
157     try
158     {
159       JSONParser jsonParser = new JSONParser();
160       JSONObject jsonObj = (JSONObject) jsonParser
161               .parse(pdbJsonResponseString);
162
163       JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
164       String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
165               "QTime").toString();
166       int numFound = Integer
167               .valueOf(pdbResponse.get("numFound").toString());
168       if (numFound > 0)
169       {
170         result = new ArrayList<PDBResponseSummary>();
171         JSONArray docs = (JSONArray) pdbResponse.get("docs");
172         for (Iterator<JSONObject> docIter = docs.iterator(); docIter
173                 .hasNext();)
174         {
175           JSONObject doc = docIter.next();
176           result.add(searchResult.new PDBResponseSummary(doc,
177                   pdbRestRequest));
178         }
179         searchResult.setNumberOfItemsFound(numFound);
180         searchResult.setResponseTime(queryTime);
181         searchResult.setSearchSummary(result);
182       }
183     } catch (ParseException e)
184     {
185       e.printStackTrace();
186     }
187     return searchResult;
188   }
189
190   /**
191    * Takes a collection of PDBDocField and converts its 'code' Field values into
192    * a comma delimited string.
193    * 
194    * @param pdbDocfields
195    *          the collection of PDBDocField to process
196    * @return the comma delimited string from the pdbDocFields collection
197    */
198   public static String getPDBDocFieldsAsCommaDelimitedString(
199           Collection<PDBDocField> pdbDocfields)
200   {
201     String result = "";
202     if (pdbDocfields != null && !pdbDocfields.isEmpty())
203     {
204       StringBuilder returnedFields = new StringBuilder();
205       for (PDBDocField field : pdbDocfields)
206       {
207         returnedFields.append(",").append(field.getCode());
208       }
209       returnedFields.deleteCharAt(0);
210       result = returnedFields.toString();
211     }
212     return result;
213   }
214
215   /**
216    * Determines the column index for 'PDB Id' Fields in the dynamic summary
217    * table. The PDB Id serves as a unique identifier for a given row in the
218    * summary table
219    * 
220    * @param wantedFeilds
221    *          the available table columns in no particular order
222    * @return the pdb id field column index
223    */
224   public static int getPDBIdColumIndex(
225           Collection<PDBDocField> wantedFeilds, boolean hasRefSeq)
226   {
227
228     // If a reference sequence is attached then start counting from 1 else
229     // start from zero
230     int pdbFeildIndexCounter = hasRefSeq ? 1 : 0;
231
232     for (PDBDocField feild : wantedFeilds)
233     {
234       if (feild.equals(PDBDocField.PDB_ID))
235       {
236         break; // Once PDB Id index is determined exit iteration
237       }
238       ++pdbFeildIndexCounter;
239     }
240     return pdbFeildIndexCounter;
241   }
242
243   /**
244    * This enum represents the fields available in the PDB JSON response
245    *
246    */
247   public enum PDBDocField
248   {
249     PDB_ID("PDB Id", "pdb_id"), TITLE("Title", "title"), MOLECULE_NAME(
250             "Molecule", "molecule_name"), MOLECULE_TYPE("Molecule Type",
251             "molecule_type"), MOLECULE_SEQUENCE("Sequence",
252             "molecule_sequence"), PFAM_ACCESSION("PFAM Accession",
253             "pfam_accession"), PFAM_NAME("PFAM Name", "pfam_name"), INTERPRO_NAME(
254             "InterPro Name", "interpro_name"), INTERPRO_ACCESSION(
255             "InterPro Accession", "interpro_accession"), UNIPROT_ID(
256             "UniProt Id", "uniprot_id"), UNIPROT_ACCESSION(
257             "UniProt Accession", "uniprot_accession"), UNIPROT_COVERAGE(
258             "UniProt Coverage", "uniprot_coverage"), UNIPROT_FEATURES(
259             "Uniprot Features", "uniprot_features"), R_FACTOR("R Factor",
260             "r_factor"), RESOLUTION("Resolution", "resolution"), DATA_QUALITY(
261             "Data Quality", "data_quality"), OVERALL_QUALITY(
262             "Overall Quality", "overall_quality"), POLYMER_COUNT(
263             "Number of Polymers", "number_of_polymers"), PROTEIN_CHAIN_COUNT(
264             "Number of Protein Chains", "number_of_protein_chains"), BOUND_MOLECULE_COUNT(
265             "Number of Bound Molecule", "number_of_bound_molecules"), POLYMER_RESIDUE_COUNT(
266             "Number of Polymer Residue", "number_of_polymer_residues"), GENUS(
267             "GENUS", "genus"), GENE_NAME("Gene Name", "gene_name"), EXPERIMENTAL_METHOD(
268             "Experimental Method", "experimental_method"), GO_ID("GO Id",
269             "go_id"), ASSEMBLY_ID("Assembly Id", "assembly_form"), ASSEMBLY_FORM(
270             "Assembly Form", "assembly_id"), ASSEMBLY_TYPE("Assembly Type",
271             "assembly_type"), SPACE_GROUP("Space Group", "spacegroup"), CATH_CODE(
272             "Cath Code", "cath_code"), TAX_ID("Tax Id", "tax_id"), TAX_QUERY(
273             "Tax Query", "tax_query"), INTERACTING_ENTRY_ID(
274             "Interacting Entry Id", "interacting_entry_id"), INTERACTING_ENTITY_ID(
275             "Interacting Entity Id", "interacting_entity_id"), INTERACTING_MOLECULES(
276             "Interacting Molecules", "interacting_molecules"), PUBMED_ID(
277             "Pubmed Id", "pubmed_id"), STATUS("Status", "status"), MODEL_QUALITY(
278             "Model Quality", "model_quality"), PIVOT_RESOLUTION(
279             "Pivot Resolution", "pivot_resolution"), DATA_REDUCTION_SOFTWARE(
280             "Data reduction software", "data_reduction_software"), MAX_OBSERVED_RES(
281             "Max observed residues", "max_observed_residues"), ORG_SCI_NAME(
282             "Organism scientific name", "organism_scientific_name"), SUPER_KINGDOM(
283             "Super kingdom", "superkingdom"), RANK("Rank", "rank"), CRYSTALLISATION_PH(
284             "Crystallisation Ph", "crystallisation_ph"), BIOLOGICAL_FUNCTION(
285             "Biological Function", "biological_function"), BIOLOGICAL_PROCESS(
286             "Biological Process", "biological_process"), BIOLOGICAL_CELL_COMPONENT(
287             "Biological Cell Component", "biological_cell_component"), COMPOUND_NAME(
288             "Compound Name", "compound_name"), COMPOUND_ID("Compound Id",
289             "compound_id"), COMPOUND_WEIGHT("Compound Weight",
290             "compound_weight"), COMPOUND_SYSTEMATIC_NAME(
291             "Compound Systematic Name", "compound_systematic_name"), INTERACTING_LIG(
292             "Interacting Ligands", "interacting_ligands"), JOURNAL(
293             "Journal", "journal"), ALL_AUTHORS("All Authors", "all_authors"), EXPERIMENTAL_DATA_AVAILABLE(
294             "Experiment Data Available", "experiment_data_available"), DIFFRACTION_PROTOCOL(
295             "Diffraction Protocol", "diffraction_protocol"), REFINEMENT_SOFTWARE(
296             "Refinement Software", "refinement_software"), STRUCTURE_DETERMINATION_METHOD(
297             "Structure Determination Method",
298             "structure_determination_method"), SYNCHROTON_SITE(
299             "Synchrotron Site", "synchrotron_site"), SAMPLE_PREP_METHOD(
300             "Sample Preparation Method", "sample_preparation_method"), ENTRY_AUTHORS(
301             "Entry Authors", "entry_authors"), CITATION_TITLE(
302             "Citation Title", "citation_title"), STRUCTURE_SOLUTION_SOFTWARE(
303             "Structure Solution Software", "structure_solution_software"), ENTRY_ENTITY(
304             "Entry Entity", "entry_entity"), R_FREE("R Free", "r_free"), NO_OF_POLYMER_ENTITIES(
305             "Number of Polymer Entities", "number_of_polymer_entities"), NO_OF_BOUND_ENTITIES(
306             "Number of Bound Entities", "number_of_bound_entities"), CRYSTALLISATION_RESERVOIR(
307             "Crystallisation Reservoir", "crystallisation_reservoir"), DATA_SCALING_SW(
308             "Data Scalling Software", "data_scaling_software"), DETECTOR(
309             "Detector", "detector"), DETECTOR_TYPE("Detector Type",
310             "detector_type"), MODIFIED_RESIDUE_FLAG(
311             "Modified Residue Flag", "modified_residue_flag"), NUMBER_OF_COPIES(
312             "Number of Copies", "number_of_copies"), STRUCT_ASYM_ID(
313             "Struc Asym Id", "struct_asym_id"), HOMOLOGUS_PDB_ENTITY_ID(
314             "Homologus PDB Entity Id", "homologus_pdb_entity_id"), MOLECULE_SYNONYM(
315             "Molecule Synonym", "molecule_synonym"), DEPOSITION_SITE(
316             "Deposition Site", "deposition_site"), SYNCHROTRON_BEAMLINE(
317             "Synchrotron Beamline", "synchrotron_beamline"), ENTITY_ID(
318             "Entity Id", "entity_id"), BEAM_SOURCE_NAME("Beam Source Name",
319             "beam_source_name"), PROCESSING_SITE("Processing Site",
320             "processing_site"), ENTITY_WEIGHT("Entity Weight",
321             "entity_weight"), VERSION("Version", "_version_"), ALL("ALL",
322             "text");
323
324     private String name;
325
326     private String code;
327
328     PDBDocField(String name, String code)
329     {
330       this.name = name;
331       this.code = code;
332     }
333
334     public String getName()
335     {
336       return name;
337     }
338
339     public String getCode()
340     {
341       return code;
342     }
343
344     public String toString()
345     {
346       return name;
347     }
348   }
349 }