1 package jalview.ws.dbsources;
3 import jalview.util.MessageManager;
4 import jalview.ws.uimodel.PDBRestRequest;
5 import jalview.ws.uimodel.PDBRestResponse;
6 import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
8 import java.util.ArrayList;
9 import java.util.Collection;
10 import java.util.Iterator;
11 import java.util.List;
13 import javax.ws.rs.core.MediaType;
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;
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;
27 * A rest client for querying the Search endpoing of the PDB REST API
32 public class PDBRestClient
34 public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?";
36 private static int DEFAULT_RESPONSE_SIZE = 200;
39 * Takes a PDBRestRequest object and returns a response upon execution
41 * @param pdbRestRequest
42 * the PDBRestRequest instance to be processed
43 * @return the pdbResponse object for the given request
46 public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest)
51 ClientConfig clientConfig = new DefaultClientConfig();
52 Client client = Client.create(clientConfig);
54 String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest
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"
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);
69 // Execute the REST request
70 ClientResponse clientResponse = webResource.accept(
71 MediaType.APPLICATION_JSON).get(ClientResponse.class);
73 // Get the JSON string from the response object
74 String responseString = clientResponse.getEntity(String.class);
76 // Check the response status and report exception if one occurs
77 if (clientResponse.getStatus() != 200)
79 String errorMessage = "";
80 if (clientResponse.getStatus() == 400)
82 errorMessage = parseJsonExceptionString(responseString);
83 throw new Exception(errorMessage);
87 errorMessage = getMessageByHTTPStatusCode(clientResponse
89 throw new Exception(errorMessage);
93 // Make redundant objects eligible for garbage collection to conserve
95 clientResponse = null;
98 // Process the response and return the result to the caller.
99 return parsePDBJsonResponse(responseString, pdbRestRequest);
100 } catch (Exception e)
102 String exceptionMsg = e.getMessage();
103 if (exceptionMsg.contains("SocketException"))
105 // No internet connection
108 .getString("exception.unable_to_detect_internet_connection"));
110 else if (exceptionMsg.contains("UnknownHostException"))
112 // The server 'www.ebi.ac.uk' is unreachable
115 .getString("exception.pdb_server_unreachable"));
124 public String getMessageByHTTPStatusCode(int code)
130 message = MessageManager
131 .getString("exception.pdb_rest_service_no_longer_available");
135 message = MessageManager.getString("exception.resource_not_be_found");
145 message = MessageManager.getString("exception.pdb_server_error");
155 * Process error response from PDB server if/when one occurs.
157 * @param jsonResponse
158 * the JSON string containing error message from the server
159 * @return the processed error message from the JSON string
161 public static String parseJsonExceptionString(String jsonErrorResponse)
163 StringBuilder errorMessage = new StringBuilder(
164 "\n============= PDB Rest Client RunTime error =============\n");
168 JSONParser jsonParser = new JSONParser();
169 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
170 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
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();
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");
185 } catch (ParseException e)
189 return errorMessage.toString();
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
197 * @param pdbJsonResponseString
198 * the JSON string to be parsed
199 * @param pdbRestRequest
200 * the request object which contains parameters used to process the
204 @SuppressWarnings("unchecked")
205 public static PDBRestResponse parsePDBJsonResponse(
206 String pdbJsonResponseString, PDBRestRequest pdbRestRequest)
208 PDBRestResponse searchResult = new PDBRestResponse();
209 List<PDBResponseSummary> result = null;
212 JSONParser jsonParser = new JSONParser();
213 JSONObject jsonObj = (JSONObject) jsonParser
214 .parse(pdbJsonResponseString);
216 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
217 String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
219 int numFound = Integer
220 .valueOf(pdbResponse.get("numFound").toString());
223 result = new ArrayList<PDBResponseSummary>();
224 JSONArray docs = (JSONArray) pdbResponse.get("docs");
225 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
228 JSONObject doc = docIter.next();
229 result.add(searchResult.new PDBResponseSummary(doc,
232 searchResult.setNumberOfItemsFound(numFound);
233 searchResult.setResponseTime(queryTime);
234 searchResult.setSearchSummary(result);
236 } catch (ParseException e)
244 * Takes a collection of PDBDocField and converts its 'code' Field values into
245 * a comma delimited string.
247 * @param pdbDocfields
248 * the collection of PDBDocField to process
249 * @return the comma delimited string from the pdbDocFields collection
251 public static String getPDBDocFieldsAsCommaDelimitedString(
252 Collection<PDBDocField> pdbDocfields)
255 if (pdbDocfields != null && !pdbDocfields.isEmpty())
257 StringBuilder returnedFields = new StringBuilder();
258 for (PDBDocField field : pdbDocfields)
260 returnedFields.append(",").append(field.getCode());
262 returnedFields.deleteCharAt(0);
263 result = returnedFields.toString();
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
273 * @param wantedFields
274 * the available table columns in no particular order
275 * @return the pdb id field column index
277 public static int getPDBIdColumIndex(
278 Collection<PDBDocField> wantedFields, boolean hasRefSeq)
281 // If a reference sequence is attached then start counting from 1 else
283 int pdbFieldIndexCounter = hasRefSeq ? 1 : 0;
285 for (PDBDocField field : wantedFields)
287 if (field.equals(PDBDocField.PDB_ID))
289 break; // Once PDB Id index is determined exit iteration
291 ++pdbFieldIndexCounter;
293 return pdbFieldIndexCounter;
297 * This enum represents the fields available in the PDB JSON response
300 public enum PDBDocField
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",
381 PDBDocField(String name, String code)
387 public String getName()
392 public String getCode()
397 public String toString()