X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Fws%2Fdbsources%2FPDBRestClient.java;h=09c10ef7715258f637e3c726aa6bd132ab57d805;hb=fddf3084802b37e5cee17829e32692a4aac3e60d;hp=039d23fe2be00d3bef626fa9c53f89efbcb0c5c5;hpb=49207bb4d5c7b380978923817742d095b3f685b3;p=jalview.git diff --git a/src/jalview/ws/dbsources/PDBRestClient.java b/src/jalview/ws/dbsources/PDBRestClient.java index 039d23f..09c10ef 100644 --- a/src/jalview/ws/dbsources/PDBRestClient.java +++ b/src/jalview/ws/dbsources/PDBRestClient.java @@ -21,111 +21,188 @@ import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; + +/** + * A rest client for querying the Search endpoing of the PDB REST API + * + * @author tcnofoegbu + * + */ public class PDBRestClient { - private String pdbSearchEndpoint = "http://wwwdev.ebi.ac.uk/pdbe/search/pdb/select?"; + public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?"; + + private static int DEFAULT_RESPONSE_SIZE = 200; /** * Takes a PDBRestRequest object and returns a response upon execution * * @param pdbRestRequest - * the pdbRequest to be sent - * @return the pdbResponse object for the given pdbRequest + * the PDBRestRequest instance to be processed + * @return the pdbResponse object for the given request + * @throws Exception */ public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest) + throws Exception { - ClientConfig clientConfig = new DefaultClientConfig(); - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, - Boolean.TRUE); - Client client = Client.create(clientConfig); - - String query = pdbRestRequest.getFieldToSearchBy() - + pdbRestRequest.getSearchTerm() - + ((pdbRestRequest.isAllowEmptySeq()) ? "" - : " AND molecule_sequence:['' TO *]"); - - String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest - .getWantedFields()); - - String responseSize = (pdbRestRequest.getResponseSize() == 0) ? "200" - : String.valueOf(pdbRestRequest.getResponseSize()); - String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest - .getFieldToSortBy().trim().isEmpty()) ? "" - : (pdbRestRequest - .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc" - : " desc")); - - WebResource webResource = client.resource(pdbSearchEndpoint) - .queryParam("wt", "json").queryParam("fl", wantedFields) - .queryParam("rows", responseSize) - .queryParam("q", query) - .queryParam("sort", sortParam); - ClientResponse clientResponse = webResource.accept( - MediaType.APPLICATION_JSON).get(ClientResponse.class); - - String responseString = clientResponse.getEntity(String.class); - if (clientResponse.getStatus() != 200) + try { - if (clientResponse.getStatus() == 400) + ClientConfig clientConfig = new DefaultClientConfig(); + Client client = Client.create(clientConfig); + + String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest + .getWantedFields()); + int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE + : pdbRestRequest.getResponseSize(); + String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest + .getFieldToSortBy().trim().isEmpty()) ? "" : (pdbRestRequest + .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc" + : " desc")); + + // Build request parameters for the REST Request + WebResource webResource = client.resource(PDB_SEARCH_ENDPOINT) + .queryParam("wt", "json").queryParam("fl", wantedFields) + .queryParam("rows", String.valueOf(responseSize)) + .queryParam("q", pdbRestRequest.getQuery()) + .queryParam("sort", sortParam); + + // Execute the REST request + ClientResponse clientResponse = webResource.accept( + MediaType.APPLICATION_JSON).get(ClientResponse.class); + + // Get the JSON string from the response object + String responseString = clientResponse.getEntity(String.class); + + // Check the response status and report exception if one occurs + if (clientResponse.getStatus() != 200) { - throw new RuntimeException(parseJsonExceptionString(responseString)); + String errorMessage = ""; + if (clientResponse.getStatus() == 400) + { + errorMessage = parseJsonExceptionString(responseString); + throw new Exception(errorMessage); + } + else + { + errorMessage = getMessageByHTTPStatusCode(clientResponse + .getStatus()); + throw new Exception(errorMessage); + } + } + + // Make redundant objects eligible for garbage collection to conserve + // memory + clientResponse = null; + client = null; + + // Process the response and return the result to the caller. + return parsePDBJsonResponse(responseString, pdbRestRequest); + } catch (Exception e) + { + String exceptionMsg = e.getMessage(); + if (exceptionMsg.contains("SocketException")) + { + throw new Exception( + "Jalview is unable to detect an internet connection"); + // No internet connection + } + else if (exceptionMsg.contains("UnknownHostException")) + { + throw new Exception( + "Jalview is unable to reach the host server \'www.ebi.ac.uk\'. " + + "\nPlease ensure that you are connected to the internet and try again."); + // The server 'www.ebi.ac.uk' is unreachable } else { - throw new RuntimeException("Failed : HTTP error code : " - + clientResponse.getStatus()); + throw e; } } - clientResponse = null; - client = null; - return parsePDBJsonResponse(responseString, pdbRestRequest); + } + + public String getMessageByHTTPStatusCode(int code) + { + String message = ""; + switch (code) + { + case 410: + message = "PDB Rest Service no longer exists!"; + break; + case 403: + case 404: + message = "The requested resource could not be found"; + break; + case 408: + case 409: + case 500: + case 501: + case 502: + case 503: + case 504: + case 505: + message = "There seems to be an error from the PDB Rest API server."; + break; + + default: + break; + } + return message; } /** * Process error response from PDB server if/when one occurs. * * @param jsonResponse - * the json string containing error message from the server - * @return the processed error message from the json string + * the JSON string containing error message from the server + * @return the processed error message from the JSON string */ public static String parseJsonExceptionString(String jsonErrorResponse) { - String errorMessage = "RunTime error"; + StringBuilder errorMessage = new StringBuilder( + "\n============= PDB Rest Client RunTime error =============\n"); + try { JSONParser jsonParser = new JSONParser(); JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse); JSONObject errorResponse = (JSONObject) jsonObj.get("error"); - errorMessage = errorResponse.get("msg").toString(); JSONObject responseHeader = (JSONObject) jsonObj .get("responseHeader"); - errorMessage += responseHeader.get("params").toString(); + JSONObject paramsObj = (JSONObject) responseHeader.get("params"); + String status = responseHeader.get("status").toString(); + String message = errorResponse.get("msg").toString(); + String query = paramsObj.get("q").toString(); + String fl = paramsObj.get("fl").toString(); + + errorMessage.append("Status: ").append(status).append("\n"); + errorMessage.append("Message: ").append(message).append("\n"); + errorMessage.append("query: ").append(query).append("\n"); + errorMessage.append("fl: ").append(fl).append("\n"); + } catch (ParseException e) { e.printStackTrace(); } - return errorMessage; + return errorMessage.toString(); } /** - * Parses json response string from PDB REST API to a PDBRestResponse - * instance. The parsed response is dynamic and based upon some of the request - * parameters. + * Parses the JSON response string from PDB REST API. The response is dynamic + * hence, only fields specifically requested for in the 'wantedFields' + * parameter is fetched/processed * * @param pdbJsonResponseString - * the json string to be parsed + * the JSON string to be parsed * @param pdbRestRequest * the request object which contains parameters used to process the - * json string + * JSON string * @return */ @SuppressWarnings("unchecked") public static PDBRestResponse parsePDBJsonResponse( - String pdbJsonResponseString, - PDBRestRequest pdbRestRequest) + String pdbJsonResponseString, PDBRestRequest pdbRestRequest) { PDBRestResponse searchResult = new PDBRestResponse(); List result = null; @@ -148,7 +225,8 @@ public class PDBRestClient .hasNext();) { JSONObject doc = docIter.next(); - result.add(searchResult.new PDBResponseSummary(doc, pdbRestRequest)); + result.add(searchResult.new PDBResponseSummary(doc, + pdbRestRequest)); } searchResult.setNumberOfItemsFound(numFound); searchResult.setResponseTime(queryTime); @@ -162,11 +240,12 @@ public class PDBRestClient } /** - * Takes a collection of PDBDocField and converts its code values into a comma - * delimited string. + * Takes a collection of PDBDocField and converts its 'code' Field values into + * a comma delimited string. * * @param pdbDocfields - * @return + * the collection of PDBDocField to process + * @return the comma delimited string from the pdbDocFields collection */ public static String getPDBDocFieldsAsCommaDelimitedString( Collection pdbDocfields) @@ -179,7 +258,7 @@ public class PDBRestClient { returnedFields.append(",").append(field.getCode()); } - returnedFields.deleteCharAt(0); + returnedFields.deleteCharAt(0); result = returnedFields.toString(); } return result; @@ -190,29 +269,31 @@ public class PDBRestClient * table. The PDB Id serves as a unique identifier for a given row in the * summary table * - * @param wantedFeilds + * @param wantedFields * the available table columns in no particular order * @return the pdb id field column index */ public static int getPDBIdColumIndex( - Collection wantedFeilds, boolean hasRefSeq) + Collection wantedFields, boolean hasRefSeq) { - int pdbFeildIndexCounter = hasRefSeq ? 1 : 0; // If a reference sequence is - // attached then start counting from - // 1 else start from zero - for (PDBDocField feild : wantedFeilds) + + // If a reference sequence is attached then start counting from 1 else + // start from zero + int pdbFieldIndexCounter = hasRefSeq ? 1 : 0; + + for (PDBDocField field : wantedFields) { - if (feild.equals(PDBDocField.PDB_ID)) + if (field.equals(PDBDocField.PDB_ID)) { - break; // once PDB Id index is determined exit iteration + break; // Once PDB Id index is determined exit iteration } - ++pdbFeildIndexCounter; + ++pdbFieldIndexCounter; } - return pdbFeildIndexCounter; + return pdbFieldIndexCounter; } /** - * Represents the fields retrievable from a PDB Document response + * This enum represents the fields available in the PDB JSON response * */ public enum PDBDocField @@ -252,14 +333,14 @@ public class PDBRestClient "Max observed residues", "max_observed_residues"), ORG_SCI_NAME( "Organism scientific name", "organism_scientific_name"), SUPER_KINGDOM( "Super kingdom", "superkingdom"), RANK("Rank", "rank"), CRYSTALLISATION_PH( - "Crystallisation Ph", "crystallisation_ph"), BIO_FUNCTION( - "Biological Function", "biological_function"), BIO_PROCESS( - "Biological Process", "biological_process"), BIO_CELL_COMP( + "Crystallisation Ph", "crystallisation_ph"), BIOLOGICAL_FUNCTION( + "Biological Function", "biological_function"), BIOLOGICAL_PROCESS( + "Biological Process", "biological_process"), BIOLOGICAL_CELL_COMPONENT( "Biological Cell Component", "biological_cell_component"), COMPOUND_NAME( "Compound Name", "compound_name"), COMPOUND_ID("Compound Id", "compound_id"), COMPOUND_WEIGHT("Compound Weight", - "compound_weight"), COMP_SYS_NAME("Compound Systematic Name", - "compound_systematic_name"), INTERACTING_LIG( + "compound_weight"), COMPOUND_SYSTEMATIC_NAME( + "Compound Systematic Name", "compound_systematic_name"), INTERACTING_LIG( "Interacting Ligands", "interacting_ligands"), JOURNAL( "Journal", "journal"), ALL_AUTHORS("All Authors", "all_authors"), EXPERIMENTAL_DATA_AVAILABLE( "Experiment Data Available", "experiment_data_available"), DIFFRACTION_PROTOCOL( @@ -317,4 +398,4 @@ public class PDBRestClient return name; } } -} +} \ No newline at end of file