2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ws.dbsources;
23 import jalview.util.MessageManager;
24 import jalview.ws.uimodel.PDBRestRequest;
25 import jalview.ws.uimodel.PDBRestResponse;
26 import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Iterator;
31 import java.util.List;
33 import javax.ws.rs.core.MediaType;
35 import org.json.simple.JSONArray;
36 import org.json.simple.JSONObject;
37 import org.json.simple.parser.JSONParser;
38 import org.json.simple.parser.ParseException;
40 import com.sun.jersey.api.client.Client;
41 import com.sun.jersey.api.client.ClientResponse;
42 import com.sun.jersey.api.client.WebResource;
43 import com.sun.jersey.api.client.config.ClientConfig;
44 import com.sun.jersey.api.client.config.DefaultClientConfig;
47 * A rest client for querying the Search endpoing of the PDB REST API
52 public class PDBRestClient
54 public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?";
56 private static int DEFAULT_RESPONSE_SIZE = 200;
59 * Takes a PDBRestRequest object and returns a response upon execution
61 * @param pdbRestRequest
62 * the PDBRestRequest instance to be processed
63 * @return the pdbResponse object for the given request
66 public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest)
71 ClientConfig clientConfig = new DefaultClientConfig();
72 Client client = Client.create(clientConfig);
74 String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest
76 int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE
77 : pdbRestRequest.getResponseSize();
78 String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest
79 .getFieldToSortBy().trim().isEmpty()) ? "" : (pdbRestRequest
80 .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc"
82 // Build request parameters for the REST Request
83 WebResource webResource = client.resource(PDB_SEARCH_ENDPOINT)
84 .queryParam("wt", "json").queryParam("fl", wantedFields)
85 .queryParam("rows", String.valueOf(responseSize))
86 .queryParam("q", pdbRestRequest.getQuery())
87 .queryParam("sort", sortParam);
89 // Execute the REST request
90 ClientResponse clientResponse = webResource.accept(
91 MediaType.APPLICATION_JSON).get(ClientResponse.class);
93 // Get the JSON string from the response object
94 String responseString = clientResponse.getEntity(String.class);
96 // Check the response status and report exception if one occurs
97 if (clientResponse.getStatus() != 200)
99 String errorMessage = "";
100 if (clientResponse.getStatus() == 400)
102 errorMessage = parseJsonExceptionString(responseString);
103 throw new Exception(errorMessage);
107 errorMessage = getMessageByHTTPStatusCode(clientResponse
109 throw new Exception(errorMessage);
113 // Make redundant objects eligible for garbage collection to conserve
115 clientResponse = null;
118 // Process the response and return the result to the caller.
119 return parsePDBJsonResponse(responseString, pdbRestRequest);
120 } catch (Exception e)
122 String exceptionMsg = e.getMessage();
123 if (exceptionMsg.contains("SocketException"))
125 // No internet connection
128 .getString("exception.unable_to_detect_internet_connection"));
130 else if (exceptionMsg.contains("UnknownHostException"))
132 // The server 'www.ebi.ac.uk' is unreachable
135 .getString("exception.pdb_server_unreachable"));
144 public String getMessageByHTTPStatusCode(int code)
150 message = MessageManager
151 .getString("exception.pdb_rest_service_no_longer_available");
155 message = MessageManager.getString("exception.resource_not_be_found");
165 message = MessageManager.getString("exception.pdb_server_error");
175 * Process error response from PDB server if/when one occurs.
177 * @param jsonResponse
178 * the JSON string containing error message from the server
179 * @return the processed error message from the JSON string
181 public static String parseJsonExceptionString(String jsonErrorResponse)
183 StringBuilder errorMessage = new StringBuilder(
184 "\n============= PDB Rest Client RunTime error =============\n");
188 JSONParser jsonParser = new JSONParser();
189 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
190 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
192 JSONObject responseHeader = (JSONObject) jsonObj
193 .get("responseHeader");
194 JSONObject paramsObj = (JSONObject) responseHeader.get("params");
195 String status = responseHeader.get("status").toString();
196 String message = errorResponse.get("msg").toString();
197 String query = paramsObj.get("q").toString();
198 String fl = paramsObj.get("fl").toString();
200 errorMessage.append("Status: ").append(status).append("\n");
201 errorMessage.append("Message: ").append(message).append("\n");
202 errorMessage.append("query: ").append(query).append("\n");
203 errorMessage.append("fl: ").append(fl).append("\n");
205 } catch (ParseException e)
209 return errorMessage.toString();
213 * Parses the JSON response string from PDB REST API. The response is dynamic
214 * hence, only fields specifically requested for in the 'wantedFields'
215 * parameter is fetched/processed
217 * @param pdbJsonResponseString
218 * the JSON string to be parsed
219 * @param pdbRestRequest
220 * the request object which contains parameters used to process the
224 @SuppressWarnings("unchecked")
225 public static PDBRestResponse parsePDBJsonResponse(
226 String pdbJsonResponseString, PDBRestRequest pdbRestRequest)
228 PDBRestResponse searchResult = new PDBRestResponse();
229 List<PDBResponseSummary> result = null;
232 JSONParser jsonParser = new JSONParser();
233 JSONObject jsonObj = (JSONObject) jsonParser
234 .parse(pdbJsonResponseString);
236 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
237 String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
239 int numFound = Integer
240 .valueOf(pdbResponse.get("numFound").toString());
243 result = new ArrayList<PDBResponseSummary>();
244 JSONArray docs = (JSONArray) pdbResponse.get("docs");
245 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
248 JSONObject doc = docIter.next();
249 result.add(searchResult.new PDBResponseSummary(doc,
252 searchResult.setNumberOfItemsFound(numFound);
253 searchResult.setResponseTime(queryTime);
254 searchResult.setSearchSummary(result);
256 } catch (ParseException e)
264 * Takes a collection of PDBDocField and converts its 'code' Field values into
265 * a comma delimited string.
267 * @param pdbDocfields
268 * the collection of PDBDocField to process
269 * @return the comma delimited string from the pdbDocFields collection
271 public static String getPDBDocFieldsAsCommaDelimitedString(
272 Collection<PDBDocField> pdbDocfields)
275 if (pdbDocfields != null && !pdbDocfields.isEmpty())
277 StringBuilder returnedFields = new StringBuilder();
278 for (PDBDocField field : pdbDocfields)
280 returnedFields.append(",").append(field.getCode());
282 returnedFields.deleteCharAt(0);
283 result = returnedFields.toString();
289 * Determines the column index for 'PDB Id' Fields in the dynamic summary
290 * table. The PDB Id serves as a unique identifier for a given row in the
293 * @param wantedFields
294 * the available table columns in no particular order
295 * @return the pdb id field column index
297 public static int getPDBIdColumIndex(
298 Collection<PDBDocField> wantedFields, boolean hasRefSeq)
301 // If a reference sequence is attached then start counting from 1 else
303 int pdbFieldIndexCounter = hasRefSeq ? 1 : 0;
305 for (PDBDocField field : wantedFields)
307 if (field.equals(PDBDocField.PDB_ID))
309 break; // Once PDB Id index is determined exit iteration
311 ++pdbFieldIndexCounter;
313 return pdbFieldIndexCounter;
317 * This enum represents the fields available in the PDB JSON response
320 public enum PDBDocField
322 PDB_ID("PDB Id", "pdb_id"), TITLE("Title", "title"), MOLECULE_NAME(
323 "Molecule", "molecule_name"), MOLECULE_TYPE("Molecule Type",
324 "molecule_type"), MOLECULE_SEQUENCE("Sequence",
325 "molecule_sequence"), PFAM_ACCESSION("PFAM Accession",
326 "pfam_accession"), PFAM_NAME("PFAM Name", "pfam_name"), INTERPRO_NAME(
327 "InterPro Name", "interpro_name"), INTERPRO_ACCESSION(
328 "InterPro Accession", "interpro_accession"), UNIPROT_ID(
329 "UniProt Id", "uniprot_id"), UNIPROT_ACCESSION(
330 "UniProt Accession", "uniprot_accession"), UNIPROT_COVERAGE(
331 "UniProt Coverage", "uniprot_coverage"), UNIPROT_FEATURES(
332 "Uniprot Features", "uniprot_features"), R_FACTOR("R Factor",
333 "r_factor"), RESOLUTION("Resolution", "resolution"), DATA_QUALITY(
334 "Data Quality", "data_quality"), OVERALL_QUALITY(
335 "Overall Quality", "overall_quality"), POLYMER_COUNT(
336 "Number of Polymers", "number_of_polymers"), PROTEIN_CHAIN_COUNT(
337 "Number of Protein Chains", "number_of_protein_chains"), BOUND_MOLECULE_COUNT(
338 "Number of Bound Molecule", "number_of_bound_molecules"), POLYMER_RESIDUE_COUNT(
339 "Number of Polymer Residue", "number_of_polymer_residues"), GENUS(
340 "GENUS", "genus"), GENE_NAME("Gene Name", "gene_name"), EXPERIMENTAL_METHOD(
341 "Experimental Method", "experimental_method"), GO_ID("GO Id",
342 "go_id"), ASSEMBLY_ID("Assembly Id", "assembly_form"), ASSEMBLY_FORM(
343 "Assembly Form", "assembly_id"), ASSEMBLY_TYPE("Assembly Type",
344 "assembly_type"), SPACE_GROUP("Space Group", "spacegroup"), CATH_CODE(
345 "Cath Code", "cath_code"), TAX_ID("Tax Id", "tax_id"), TAX_QUERY(
346 "Tax Query", "tax_query"), INTERACTING_ENTRY_ID(
347 "Interacting Entry Id", "interacting_entry_id"), INTERACTING_ENTITY_ID(
348 "Interacting Entity Id", "interacting_entity_id"), INTERACTING_MOLECULES(
349 "Interacting Molecules", "interacting_molecules"), PUBMED_ID(
350 "Pubmed Id", "pubmed_id"), STATUS("Status", "status"), MODEL_QUALITY(
351 "Model Quality", "model_quality"), PIVOT_RESOLUTION(
352 "Pivot Resolution", "pivot_resolution"), DATA_REDUCTION_SOFTWARE(
353 "Data reduction software", "data_reduction_software"), MAX_OBSERVED_RES(
354 "Max observed residues", "max_observed_residues"), ORG_SCI_NAME(
355 "Organism scientific name", "organism_scientific_name"), SUPER_KINGDOM(
356 "Super kingdom", "superkingdom"), RANK("Rank", "rank"), CRYSTALLISATION_PH(
357 "Crystallisation Ph", "crystallisation_ph"), BIOLOGICAL_FUNCTION(
358 "Biological Function", "biological_function"), BIOLOGICAL_PROCESS(
359 "Biological Process", "biological_process"), BIOLOGICAL_CELL_COMPONENT(
360 "Biological Cell Component", "biological_cell_component"), COMPOUND_NAME(
361 "Compound Name", "compound_name"), COMPOUND_ID("Compound Id",
362 "compound_id"), COMPOUND_WEIGHT("Compound Weight",
363 "compound_weight"), COMPOUND_SYSTEMATIC_NAME(
364 "Compound Systematic Name", "compound_systematic_name"), INTERACTING_LIG(
365 "Interacting Ligands", "interacting_ligands"), JOURNAL(
366 "Journal", "journal"), ALL_AUTHORS("All Authors", "all_authors"), EXPERIMENTAL_DATA_AVAILABLE(
367 "Experiment Data Available", "experiment_data_available"), DIFFRACTION_PROTOCOL(
368 "Diffraction Protocol", "diffraction_protocol"), REFINEMENT_SOFTWARE(
369 "Refinement Software", "refinement_software"), STRUCTURE_DETERMINATION_METHOD(
370 "Structure Determination Method",
371 "structure_determination_method"), SYNCHROTON_SITE(
372 "Synchrotron Site", "synchrotron_site"), SAMPLE_PREP_METHOD(
373 "Sample Preparation Method", "sample_preparation_method"), ENTRY_AUTHORS(
374 "Entry Authors", "entry_authors"), CITATION_TITLE(
375 "Citation Title", "citation_title"), STRUCTURE_SOLUTION_SOFTWARE(
376 "Structure Solution Software", "structure_solution_software"), ENTRY_ENTITY(
377 "Entry Entity", "entry_entity"), R_FREE("R Free", "r_free"), NO_OF_POLYMER_ENTITIES(
378 "Number of Polymer Entities", "number_of_polymer_entities"), NO_OF_BOUND_ENTITIES(
379 "Number of Bound Entities", "number_of_bound_entities"), CRYSTALLISATION_RESERVOIR(
380 "Crystallisation Reservoir", "crystallisation_reservoir"), DATA_SCALING_SW(
381 "Data Scalling Software", "data_scaling_software"), DETECTOR(
382 "Detector", "detector"), DETECTOR_TYPE("Detector Type",
383 "detector_type"), MODIFIED_RESIDUE_FLAG(
384 "Modified Residue Flag", "modified_residue_flag"), NUMBER_OF_COPIES(
385 "Number of Copies", "number_of_copies"), STRUCT_ASYM_ID(
386 "Struc Asym Id", "struct_asym_id"), HOMOLOGUS_PDB_ENTITY_ID(
387 "Homologus PDB Entity Id", "homologus_pdb_entity_id"), MOLECULE_SYNONYM(
388 "Molecule Synonym", "molecule_synonym"), DEPOSITION_SITE(
389 "Deposition Site", "deposition_site"), SYNCHROTRON_BEAMLINE(
390 "Synchrotron Beamline", "synchrotron_beamline"), ENTITY_ID(
391 "Entity Id", "entity_id"), BEAM_SOURCE_NAME("Beam Source Name",
392 "beam_source_name"), PROCESSING_SITE("Processing Site",
393 "processing_site"), ENTITY_WEIGHT("Entity Weight",
394 "entity_weight"), VERSION("Version", "_version_"), ALL("ALL",
401 PDBDocField(String name, String code)
407 public String getName()
412 public String getCode()
417 public String toString()