JAL-1700 Improved the error handling mechanism for the PDB Rest client
authortcofoegbu <tcnofoegbu@dundee.ac.uk>
Fri, 1 May 2015 16:28:02 +0000 (17:28 +0100)
committertcofoegbu <tcnofoegbu@dundee.ac.uk>
Fri, 1 May 2015 16:28:02 +0000 (17:28 +0100)
src/jalview/gui/PDBSearchPanel.java
src/jalview/gui/StructureChooser.java
src/jalview/ws/dbsources/PDBRestClient.java
test/jalview/ws/dbsources/PDBRestClientTest.java

index 7762605..950c6b7 100644 (file)
@@ -36,6 +36,7 @@ import java.util.Comparator;
 import java.util.HashSet;
 import java.util.List;
 
+import javax.swing.JOptionPane;
 import javax.swing.table.DefaultTableModel;
 
 @SuppressWarnings("serial")
@@ -87,7 +88,18 @@ public class PDBSearchPanel extends GPDBSearchPanel
       request.setWantedFields(wantedFields);
       // System.out.println(">>>>>>>>>>>>>> " + request.getQuery());
       PDBRestClient pdbRestCleint = new PDBRestClient();
-      PDBRestResponse resultList = pdbRestCleint.executeRequest(request);
+      PDBRestResponse resultList;
+      try
+      {
+        resultList = pdbRestCleint.executeRequest(request);
+      } catch (Exception e)
+      {
+        // System.out.println(">>>>>>>>>>>>>>>" + e.getMessage());
+        JOptionPane.showMessageDialog(this, e.getMessage(),
+                "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
+        return;
+      }
+
       if (resultList.getSearchSummary() != null)
       {
         tbl_summary.setModel(PDBRestResponse.getTableModel(request,
index 358412d..142028a 100644 (file)
@@ -46,6 +46,7 @@ import java.util.List;
 import javax.swing.JCheckBox;
 import javax.swing.JComboBox;
 import javax.swing.JLabel;
+import javax.swing.JOptionPane;
 import javax.swing.table.DefaultTableModel;
 
 
@@ -139,6 +140,7 @@ public class StructureChooser extends GStructureChooser
             .getStructureSummaryFields();
 
     discoveredStructuresSet = new LinkedHashSet<PDBResponseSummary>();
+    HashSet<String> errors = new HashSet<String>();
     for (SequenceI seq : selectedSequences)
     {
       PDBRestRequest pdbRequest = new PDBRestRequest();
@@ -149,7 +151,15 @@ public class StructureChooser extends GStructureChooser
       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
       pdbRequest.setAssociatedSequence(seq.getName());
       pdbRestCleint = new PDBRestClient();
-      PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest);
+      PDBRestResponse resultList;
+      try
+      {
+        resultList = pdbRestCleint.executeRequest(pdbRequest);
+      } catch (Exception e)
+      {
+        errors.add(e.getMessage());
+        continue;
+      }
       lastPdbRequest = pdbRequest;
       if (resultList.getSearchSummary() != null
               && !resultList.getSearchSummary().isEmpty())
@@ -160,6 +170,8 @@ public class StructureChooser extends GStructureChooser
     }
 
     int noOfStructuresFound = 0;
+    String totalTime = (System.currentTimeMillis() - startTime)
+            + " milli secs";
     if (discoveredStructuresSet != null
             && !discoveredStructuresSet.isEmpty())
     {
@@ -167,11 +179,25 @@ public class StructureChooser extends GStructureChooser
               discoveredStructuresSet));
       structuresDiscovered = true;
       noOfStructuresFound = discoveredStructuresSet.size();
+      mainFrame.setTitle("Structure Chooser - " + noOfStructuresFound
+              + " Found (" + totalTime + ")");
+    }
+    else
+    {
+      mainFrame
+.setTitle("Structure Chooser - Manual association");
+      if (errors.size() > 0)
+      {
+        StringBuilder errorMsg = new StringBuilder(
+                "Operation was unsucessful due to the following: \n");
+        for (String error : errors)
+        {
+          errorMsg.append(error).append("\n");
+        }
+        JOptionPane.showMessageDialog(this, errorMsg.toString(),
+                "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
+      }
     }
-    String totalTime = (System.currentTimeMillis() - startTime)
-            + " milli secs";
-    mainFrame.setTitle("Structure Chooser - " + noOfStructuresFound
-            + " Found (" + totalTime + ")");
   }
 
   public void loadLocalCachedPDBEntries()
@@ -326,60 +352,77 @@ public class StructureChooser extends GStructureChooser
       public void run()
       {
         long startTime = System.currentTimeMillis();
-        try
+        lbl_loading.setVisible(true);
+        Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
+                .getStructureSummaryFields();
+        Collection<PDBResponseSummary> filteredResponse = new HashSet<PDBResponseSummary>();
+        HashSet<String> errors = new HashSet<String>();
+        for (SequenceI seq : selectedSequences)
         {
-          lbl_loading.setVisible(true);
-
-          Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
-                  .getStructureSummaryFields();
-          Collection<PDBResponseSummary> filteredResponse = new HashSet<PDBResponseSummary>();
-          for (SequenceI seq : selectedSequences)
+          PDBRestRequest pdbRequest = new PDBRestRequest();
+          pdbRequest.setAllowEmptySeq(false);
+          pdbRequest.setResponseSize(1);
+          pdbRequest.setFieldToSearchBy("(text:");
+          pdbRequest.setFieldToSortBy(fieldToFilterBy,
+                  !chk_invertFilter.isSelected());
+          pdbRequest.setSearchTerm(buildQuery(seq) + ")");
+          pdbRequest.setWantedFields(wantedFields);
+          pdbRequest.setAssociatedSequence(seq.getName());
+          pdbRestCleint = new PDBRestClient();
+          PDBRestResponse resultList;
+          try
           {
-            PDBRestRequest pdbRequest = new PDBRestRequest();
-            pdbRequest.setAllowEmptySeq(false);
-            pdbRequest.setResponseSize(1);
-            pdbRequest.setFieldToSearchBy("(text:");
-            pdbRequest.setFieldToSortBy(fieldToFilterBy,
-                    !chk_invertFilter.isSelected());
-            pdbRequest.setSearchTerm(buildQuery(seq) + ")");
-            pdbRequest.setWantedFields(wantedFields);
-            pdbRequest.setAssociatedSequence(seq.getName());
-            pdbRestCleint = new PDBRestClient();
-            PDBRestResponse resultList = pdbRestCleint
-                    .executeRequest(pdbRequest);
-            lastPdbRequest = pdbRequest;
-            if (resultList.getSearchSummary() != null
-                    && !resultList.getSearchSummary().isEmpty())
-            {
-              filteredResponse.addAll(resultList.getSearchSummary());
-            }
+            resultList = pdbRestCleint.executeRequest(pdbRequest);
+          } catch (Exception e)
+          {
+            errors.add(e.getMessage());
+            continue;
           }
-
-          if (!filteredResponse.isEmpty())
+          lastPdbRequest = pdbRequest;
+          if (resultList.getSearchSummary() != null
+                  && !resultList.getSearchSummary().isEmpty())
           {
-            final int filterResponseCount = filteredResponse.size();
-            Collection<PDBResponseSummary> reorderedStructuresSet = new LinkedHashSet<PDBResponseSummary>();
-            reorderedStructuresSet.addAll(filteredResponse);
-            reorderedStructuresSet.addAll(discoveredStructuresSet);
-            tbl_summary.setModel(PDBRestResponse.getTableModel(
-                    lastPdbRequest, reorderedStructuresSet));
+            filteredResponse.addAll(resultList.getSearchSummary());
+          }
+        }
 
-            // Update table selection model here
-            tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
+        String totalTime = (System.currentTimeMillis() - startTime)
+                + " milli secs";
+        if (!filteredResponse.isEmpty())
+        {
+          final int filterResponseCount = filteredResponse.size();
+          Collection<PDBResponseSummary> reorderedStructuresSet = new LinkedHashSet<PDBResponseSummary>();
+          reorderedStructuresSet.addAll(filteredResponse);
+          reorderedStructuresSet.addAll(discoveredStructuresSet);
+          tbl_summary.setModel(PDBRestResponse.getTableModel(
+                  lastPdbRequest, reorderedStructuresSet));
 
-          }
+          // Update table selection model here
+          tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
 
-          lbl_loading.setVisible(false);
-          String totalTime = (System.currentTimeMillis() - startTime)
-                  + " milli secs";
           mainFrame.setTitle("Structure Chooser - Filter time ("
                   + totalTime + ")");
-
-          validateSelections();
-        } catch (Exception e)
+        }
+        else
         {
-          e.printStackTrace();
+          mainFrame.setTitle("Structure Chooser - Filter time ("
+                  + totalTime + ")");
+          if (errors.size() > 0)
+          {
+            StringBuilder errorMsg = new StringBuilder(
+                    "Operation unsucessful due to the following: \n");
+            for (String error : errors)
+            {
+              errorMsg.append(error).append("\n");
+            }
+            JOptionPane.showMessageDialog(null, errorMsg.toString(),
+                    "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
+          }
         }
+
+        lbl_loading.setVisible(false);
+
+        validateSelections();
       }
     });
     filterThread.start();
@@ -460,6 +503,7 @@ public class StructureChooser extends GStructureChooser
     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
     {
+      mainFrame.setTitle(filterTitle);
       idInputAssSeqPanel.loadCmbAssSeq();
       fileChooserAssSeqPanel.loadCmbAssSeq();
     }
@@ -737,7 +781,20 @@ public class StructureChooser extends GStructureChooser
       pdbRequest.setSearchTerm(txt_search.getText() + ")");
       pdbRequest.setAssociatedSequence(selectedSequence.getName());
       pdbRestCleint = new PDBRestClient();
-      PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest);
+      PDBRestResponse resultList;
+      try
+      {
+        resultList = pdbRestCleint.executeRequest(pdbRequest);
+      } catch (Exception e)
+      {
+        JOptionPane.showMessageDialog(this, e.getMessage(),
+                "PDB Web-service Error", JOptionPane.ERROR_MESSAGE);
+        return;
+      } finally
+      {
+        System.out.println(">>>>> executing finally block");
+        validateSelections();
+      }
       if (resultList.getSearchSummary() != null
               && resultList.getSearchSummary().size() > 0)
       {
index 02523da..da50606 100644 (file)
@@ -41,61 +41,115 @@ public class PDBRestClient
    * @param pdbRestRequest
    *          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 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)
+    try
+    {
+      ClientConfig clientConfig = new DefaultClientConfig();
+      clientConfig.getFeatures().put(
+              JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+      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)
+      {
+        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 errorMessage = "";
-      if (clientResponse.getStatus() == 400)
+      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"))
       {
-        errorMessage = parseJsonExceptionString(responseString);
-        throw new RuntimeException(errorMessage);
+        throw new Exception(
+                "Jalview couldn't reach the host server @ www.ebi.ac.uk"
+                        + "\nPlease ensure that you are connected to the internet.");
+        // The server 'www.ebi.ac.uk' is unreachable
       }
       else
       {
-        errorMessage = "Failed : HTTP error code : "
-                + clientResponse.getStatus();
-        throw new RuntimeException(errorMessage);
+        throw e;
       }
     }
+  }
 
-    // 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);
+  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;
   }
 
   /**
@@ -240,7 +294,6 @@ public class PDBRestClient
     return pdbFeildIndexCounter;
   }
 
-
   /**
    * This enum represents the fields available in the PDB JSON response
    *
index 86cb3a3..a97f3e0 100644 (file)
@@ -60,7 +60,16 @@ public class PDBRestClientTest
     request.setSearchTerm("abc");
     request.setWantedFields(wantedFields);
 
-    PDBRestResponse response = new PDBRestClient().executeRequest(request);
+    PDBRestResponse response;
+    try
+    {
+      response = new PDBRestClient().executeRequest(request);
+    } catch (Exception e)
+    {
+      e.printStackTrace();
+      fail("Couldn't execute webservice call!");
+      return;
+    }
     assertTrue(response.getNumberOfItemsFound() > 99);
     assertTrue(response.getSearchSummary() != null);
     assertTrue(response.getSearchSummary().size() > 99);
@@ -121,8 +130,8 @@ public class PDBRestClientTest
     assertEquals(expectedErrorMsg, parsedErrorResponse);
   }
 
-  @Test(expected = RuntimeException.class)
-  public void testForExpectedRuntimeException()
+  @Test(expected = Exception.class)
+  public void testForExpectedRuntimeException() throws Exception
   {
     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
     wantedFields.add(PDBDocField.PDB_ID);