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