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;
28 * A rest client for querying the Search endpoing of the PDB REST API
33 public class PDBRestClient
35 public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?";
37 private static int DEFAULT_RESPONSE_SIZE = 200;
40 * Takes a PDBRestRequest object and returns a response upon execution
42 * @param pdbRestRequest
43 * the PDBRestRequest instance to be processed
44 * @return the pdbResponse object for the given request
47 public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest)
52 ClientConfig clientConfig = new DefaultClientConfig();
53 Client client = Client.create(clientConfig);
55 String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest
57 int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE
58 : pdbRestRequest.getResponseSize();
59 String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest
60 .getFieldToSortBy().trim().isEmpty()) ? "" : (pdbRestRequest
61 .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc"
63 // Build request parameters for the REST Request
64 WebResource webResource = client.resource(PDB_SEARCH_ENDPOINT)
65 .queryParam("wt", "json").queryParam("fl", wantedFields)
66 .queryParam("rows", String.valueOf(responseSize))
67 .queryParam("q", pdbRestRequest.getQuery())
68 .queryParam("sort", sortParam);
70 // Execute the REST request
71 ClientResponse clientResponse = webResource.accept(
72 MediaType.APPLICATION_JSON).get(ClientResponse.class);
74 // Get the JSON string from the response object
75 String responseString = clientResponse.getEntity(String.class);
77 // Check the response status and report exception if one occurs
78 if (clientResponse.getStatus() != 200)
80 String errorMessage = "";
81 if (clientResponse.getStatus() == 400)
83 errorMessage = parseJsonExceptionString(responseString);
84 throw new Exception(errorMessage);
88 errorMessage = getMessageByHTTPStatusCode(clientResponse
90 throw new Exception(errorMessage);
94 // Make redundant objects eligible for garbage collection to conserve
96 clientResponse = null;
99 // Process the response and return the result to the caller.
100 return parsePDBJsonResponse(responseString, pdbRestRequest);
101 } catch (Exception e)
103 String exceptionMsg = e.getMessage();
104 if (exceptionMsg.contains("SocketException"))
106 // No internet connection
109 .getString("exception.unable_to_detect_internet_connection"));
111 else if (exceptionMsg.contains("UnknownHostException"))
113 // The server 'www.ebi.ac.uk' is unreachable
116 .getString("exception.pdb_server_unreachable"));
125 public String getMessageByHTTPStatusCode(int code)
131 message = MessageManager
132 .getString("exception.pdb_rest_service_no_longer_available");
136 message = MessageManager.getString("exception.resource_not_be_found");
146 message = MessageManager.getString("exception.pdb_server_error");
156 * Process error response from PDB server if/when one occurs.
158 * @param jsonResponse
159 * the JSON string containing error message from the server
160 * @return the processed error message from the JSON string
162 public static String parseJsonExceptionString(String jsonErrorResponse)
164 StringBuilder errorMessage = new StringBuilder(
165 "\n============= PDB Rest Client RunTime error =============\n");
169 JSONParser jsonParser = new JSONParser();
170 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
171 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
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();
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");
186 } catch (ParseException e)
190 return errorMessage.toString();
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
198 * @param pdbJsonResponseString
199 * the JSON string to be parsed
200 * @param pdbRestRequest
201 * the request object which contains parameters used to process the
205 @SuppressWarnings("unchecked")
206 public static PDBRestResponse parsePDBJsonResponse(
207 String pdbJsonResponseString, PDBRestRequest pdbRestRequest)
209 PDBRestResponse searchResult = new PDBRestResponse();
210 List<PDBResponseSummary> result = null;
213 JSONParser jsonParser = new JSONParser();
214 JSONObject jsonObj = (JSONObject) jsonParser
215 .parse(pdbJsonResponseString);
217 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
218 String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
220 int numFound = Integer
221 .valueOf(pdbResponse.get("numFound").toString());
224 result = new ArrayList<PDBResponseSummary>();
225 JSONArray docs = (JSONArray) pdbResponse.get("docs");
226 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
229 JSONObject doc = docIter.next();
230 result.add(searchResult.new PDBResponseSummary(doc,
233 searchResult.setNumberOfItemsFound(numFound);
234 searchResult.setResponseTime(queryTime);
235 searchResult.setSearchSummary(result);
237 } catch (ParseException e)
245 * Takes a collection of PDBDocField and converts its 'code' Field values into
246 * a comma delimited string.
248 * @param pdbDocfields
249 * the collection of PDBDocField to process
250 * @return the comma delimited string from the pdbDocFields collection
252 public static String getPDBDocFieldsAsCommaDelimitedString(
253 Collection<PDBDocField> pdbDocfields)
256 if (pdbDocfields != null && !pdbDocfields.isEmpty())
258 StringBuilder returnedFields = new StringBuilder();
259 for (PDBDocField field : pdbDocfields)
261 returnedFields.append(",").append(field.getCode());
263 returnedFields.deleteCharAt(0);
264 result = returnedFields.toString();
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
274 * @param wantedFields
275 * the available table columns in no particular order
276 * @return the pdb id field column index
278 public static int getPDBIdColumIndex(
279 Collection<PDBDocField> wantedFields, boolean hasRefSeq)
282 // If a reference sequence is attached then start counting from 1 else
284 int pdbFieldIndexCounter = hasRefSeq ? 1 : 0;
286 for (PDBDocField field : wantedFields)
288 if (field.equals(PDBDocField.PDB_ID))
290 break; // Once PDB Id index is determined exit iteration
292 ++pdbFieldIndexCounter;
294 return pdbFieldIndexCounter;
298 * This enum represents the fields available in the PDB JSON response
301 public enum PDBDocField
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",
382 PDBDocField(String name, String code)
388 public String getName()
393 public String getCode()
398 public String toString()