JAL-1667 updated test and internationalization messages
[jalview.git] / src / jalview / ws / dbsources / PDBRestClient.java
index e00d9ac..85701b2 100644 (file)
@@ -1,8 +1,8 @@
 package jalview.ws.dbsources;
 
-import jalview.ws.uimodel.PDBSearchRequest;
-import jalview.ws.uimodel.PDBSearchResponse;
-import jalview.ws.uimodel.PDBSearchResponse.PDBResponseSummary;
+import jalview.ws.uimodel.PDBRestRequest;
+import jalview.ws.uimodel.PDBRestResponse;
+import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
 
 import java.util.ArrayList;
 import java.util.Iterator;
@@ -26,44 +26,35 @@ public class PDBRestClient
 {
   private String pdbSearchEndpoint = "http://wwwdev.ebi.ac.uk/pdbe/search/pdb/select?";
 
-  public static void main(String[] args)
-  {
-    PDBSearchRequest request = new PDBSearchRequest();
-    request.setAllowEmptySeq(false);
-    request.setResponseSize(100);
-    request.setFieldToSearchBy("pfam_name");
-    request.setSearchTerm("Lipoc*");
-    List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
-    wantedFields.add(PDBDocField.MOLECULE_TYPE);
-    wantedFields.add(PDBDocField.PDB_ID);
-    wantedFields.add(PDBDocField.GENUS);
-    wantedFields.add(PDBDocField.GENE_NAME);
-    wantedFields.add(PDBDocField.TITLE);
-    request.setWantedFields(wantedFields);
-    new PDBRestClient().executeRequest(request);
-  }
-
-  public PDBSearchResponse executeRequest(PDBSearchRequest request)
+  /**
+   * 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
+   */
+  public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest)
   {
     ClientConfig clientConfig = new DefaultClientConfig();
     clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
             Boolean.TRUE);
     Client client = Client.create(clientConfig);
 
-    String query = request.getFieldToSearchBy()
-            + request.getSearchTerm()
-            + ((request.isAllowEmptySeq()) ? ""
+    String query = pdbRestRequest.getFieldToSearchBy()
+            + pdbRestRequest.getSearchTerm()
+            + ((pdbRestRequest.isAllowEmptySeq()) ? ""
                     : " AND molecule_sequence:['' TO *]");
 
-    String wantedFields = getFieldsAsCommaDelimitedString(request
+    String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest
             .getWantedFields());
 
-    String responseSize = (request.getResponseSize() == 0) ? "200" : String
-            .valueOf(request.getResponseSize());
-    String sortParam = (request.getFieldToSortBy() == null || request
+    String responseSize = (pdbRestRequest.getResponseSize() == 0) ? "200"
+            : String.valueOf(pdbRestRequest.getResponseSize());
+    String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest
             .getFieldToSortBy().trim().isEmpty()) ? ""
-            : (request
-            .getFieldToSortBy() + (request.isAscending() ? " asc" : " desc"));
+ : (pdbRestRequest
+            .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc"
+            : " desc"));
 
     WebResource webResource = client.resource(pdbSearchEndpoint)
             .queryParam("wt", "json").queryParam("fl", wantedFields)
@@ -78,7 +69,7 @@ public class PDBRestClient
     {
       if (clientResponse.getStatus() == 400)
       {
-        throw new RuntimeException(parseException(responseString));
+        throw new RuntimeException(parseJsonExceptionString(responseString));
       }
       else
       {
@@ -86,18 +77,25 @@ public class PDBRestClient
               + clientResponse.getStatus());
       }
     }
-    // System.out.println("--------------> " + responseString);
-    return parseResponse(responseString, request.getWantedFields(),
-            request.getAssociatedSequence());
+    clientResponse = null;
+    client = null;
+    return parsePDBJsonResponse(responseString, pdbRestRequest);
   }
 
-  private String parseException(String jsonResponse)
+  /**
+   * 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
+   */
+  public static String parseJsonExceptionString(String jsonErrorResponse)
   {
     String errorMessage = "RunTime error";
     try
     {
       JSONParser jsonParser = new JSONParser();
-      JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonResponse);
+      JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
       JSONObject errorResponse = (JSONObject) jsonObj.get("error");
       errorMessage = errorResponse.get("msg").toString();
 
@@ -111,17 +109,30 @@ public class PDBRestClient
     return errorMessage;
   }
 
+  /**
+   * 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.
+   * 
+   * @param pdbJsonResponseString
+   *          the json string to be parsed
+   * @param pdbRestRequest
+   *          the request object which contains parameters used to process the
+   *          json string
+   * @return
+   */
   @SuppressWarnings("unchecked")
-  private PDBSearchResponse parseResponse(String jsonResponse,
-          List<PDBDocField> wantedFields, String associatedSequence)
+  public static PDBRestResponse parsePDBJsonResponse(
+          String pdbJsonResponseString,
+          PDBRestRequest pdbRestRequest)
   {
-    PDBSearchResponse searchResult = new PDBSearchResponse();
+    PDBRestResponse searchResult = new PDBRestResponse();
     List<PDBResponseSummary> result = null;
     try
     {
       JSONParser jsonParser = new JSONParser();
       JSONObject jsonObj = (JSONObject) jsonParser
-.parse(jsonResponse);
+              .parse(pdbJsonResponseString);
 
       JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
       String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
@@ -138,11 +149,10 @@ public class PDBRestClient
           JSONObject doc = docIter.next();
           // if (doc.get("molecule_sequence") != null)
           // {
-          result.add(searchResult.new PDBResponseSummary(doc, wantedFields,
-                  associatedSequence));
+          result.add(searchResult.new PDBResponseSummary(doc, pdbRestRequest));
           // }
         }
-        searchResult.setItemsFound(numFound);
+        searchResult.setNumberOfItemsFound(numFound);
         searchResult.setResponseTime(queryTime);
         searchResult.setSearchSummary(result);
       }
@@ -154,23 +164,35 @@ public class PDBRestClient
     return searchResult;
   }
 
-  private String getFieldsAsCommaDelimitedString(List<PDBDocField> fields)
+  /**
+   * Takes a collection of PDBDocField and converts it into a comma delimited
+   * string.
+   * 
+   * @param pdbDocfields
+   * @return
+   */
+  public static String getPDBDocFieldsAsCommaDelimitedString(
+          List<PDBDocField> pdbDocfields)
   {
     String result = "";
-    if (fields != null && !fields.isEmpty())
+    if (pdbDocfields != null && !pdbDocfields.isEmpty())
     {
       StringBuilder returnedFields = new StringBuilder();
-      for (PDBDocField field : fields)
+      for (PDBDocField field : pdbDocfields)
       {
         returnedFields.append(",").append(field.getCode());
       }
-      returnedFields.deleteCharAt(0);
+      returnedFields.deleteCharAt(0); 
       result = returnedFields.toString();
     }
     return result;
   }
 
 
+  /**
+   * Represents the fields retrievable from a PDB Document response
+   *
+   */
   public enum PDBDocField
   {
     PDB_ID("PDB Id", "pdb_id"), TITLE("Title", "title"), MOLECULE_NAME(
@@ -189,7 +211,9 @@ public class PDBRestClient
             "Bound Molecule Count", "number_of_bound_molecules"), POLYMER_RESIDUE_COUNT(
             "Polymer Residue Count", "number_of_polymer_residues"), UNIPROT_COVERAGE(
             "UniProt Coverage", "uniprot_coverage"), GENUS("GENUS", "genus"), GENE_NAME(
-            "Gene Name", "gene_name"), ALL("ALL", "text");
+            "Gene Name", "gene_name"), EXPERIMENTAL_METHOD(
+            "Experimental Method", "experimental_method"), ALL("ALL",
+            "text");
 
     private String name;