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