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