JAL-2071 architectural improvement for Plugable Free Text Search Services
[jalview.git] / src / jalview / fts / service / pdb / PDBFTSRestClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.fts.service.pdb;
22
23 import jalview.datamodel.SequenceI;
24 import jalview.fts.api.FTSData;
25 import jalview.fts.api.FTSDataColumnI;
26 import jalview.fts.api.FTSRestClientI;
27 import jalview.fts.core.FTSRestClient;
28 import jalview.fts.core.FTSRestRequest;
29 import jalview.fts.core.FTSRestResponse;
30 import jalview.util.MessageManager;
31
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Objects;
37
38 import javax.ws.rs.core.MediaType;
39
40 import org.json.simple.JSONArray;
41 import org.json.simple.JSONObject;
42 import org.json.simple.parser.JSONParser;
43 import org.json.simple.parser.ParseException;
44
45 import com.sun.jersey.api.client.Client;
46 import com.sun.jersey.api.client.ClientResponse;
47 import com.sun.jersey.api.client.WebResource;
48 import com.sun.jersey.api.client.config.ClientConfig;
49 import com.sun.jersey.api.client.config.DefaultClientConfig;
50
51 /**
52  * A rest client for querying the Search endpoint of the PDB REST API
53  * 
54  * @author tcnofoegbu
55  *
56  */
57 public class PDBFTSRestClient extends FTSRestClient
58 {
59
60   private static FTSRestClientI instance = null;
61
62   public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?";
63
64   private static int DEFAULT_RESPONSE_SIZE = 200;
65
66   protected PDBFTSRestClient()
67   {
68   }
69
70   /**
71    * Takes a PDBRestRequest object and returns a response upon execution
72    * 
73    * @param pdbRestRequest
74    *          the PDBRestRequest instance to be processed
75    * @return the pdbResponse object for the given request
76    * @throws Exception
77    */
78   @Override
79   public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
80           throws Exception
81   {
82     try
83     {
84       ClientConfig clientConfig = new DefaultClientConfig();
85       Client client = Client.create(clientConfig);
86
87       String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(pdbRestRequest
88               .getWantedFields());
89       int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE
90               : pdbRestRequest.getResponseSize();
91       String sortParam = null;
92       if (pdbRestRequest.getFieldToSortBy() == null
93               || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
94       {
95         sortParam = "";
96       }
97       else
98       {
99         if (pdbRestRequest.getFieldToSortBy()
100                 .equalsIgnoreCase("Resolution"))
101         {
102           sortParam = pdbRestRequest.getFieldToSortBy()
103                   + (pdbRestRequest.isAscending() ? " asc" : " desc");
104         }
105         else
106         {
107           sortParam = pdbRestRequest.getFieldToSortBy()
108                   + (pdbRestRequest.isAscending() ? " desc" : " asc");
109         }
110       }
111
112       String facetPivot = (pdbRestRequest.getFacetPivot() == null || pdbRestRequest
113               .getFacetPivot().isEmpty()) ? "" : pdbRestRequest
114               .getFacetPivot();
115       String facetPivotMinCount = String.valueOf(pdbRestRequest
116               .getFacetPivotMinCount());
117
118       String query = pdbRestRequest.getFieldToSearchBy()
119               + pdbRestRequest.getSearchTerm()
120               + (pdbRestRequest.isAllowEmptySeq() ? ""
121                       : " AND molecule_sequence:['' TO *]")
122               + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
123                       : " AND status:REL");
124
125       // Build request parameters for the REST Request
126       WebResource webResource = null;
127       if (pdbRestRequest.isFacet())
128       {
129         webResource = client.resource(PDB_SEARCH_ENDPOINT)
130                 .queryParam("wt", "json").queryParam("fl", wantedFields)
131                 .queryParam("rows", String.valueOf(responseSize))
132                 .queryParam("q", query)
133                 .queryParam("sort", sortParam).queryParam("facet", "true")
134                 .queryParam("facet.pivot", facetPivot)
135                 .queryParam("facet.pivot.mincount", facetPivotMinCount);
136       }
137       else
138       {
139         webResource = client.resource(PDB_SEARCH_ENDPOINT)
140                 .queryParam("wt", "json").queryParam("fl", wantedFields)
141                 .queryParam("rows", String.valueOf(responseSize))
142                 .queryParam("q", query)
143                 .queryParam("sort", sortParam);
144       }
145       // Execute the REST request
146       ClientResponse clientResponse = webResource.accept(
147               MediaType.APPLICATION_JSON).get(ClientResponse.class);
148
149       // Get the JSON string from the response object
150       String responseString = clientResponse.getEntity(String.class);
151       // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
152
153       // Check the response status and report exception if one occurs
154       if (clientResponse.getStatus() != 200)
155       {
156         String errorMessage = "";
157         if (clientResponse.getStatus() == 400)
158         {
159           errorMessage = parseJsonExceptionString(responseString);
160           throw new Exception(errorMessage);
161         }
162         else
163         {
164           errorMessage = getMessageByHTTPStatusCode(clientResponse
165                   .getStatus());
166           throw new Exception(errorMessage);
167         }
168       }
169
170       // Make redundant objects eligible for garbage collection to conserve
171       // memory
172       clientResponse = null;
173       client = null;
174
175       // Process the response and return the result to the caller.
176       return parsePDBJsonResponse(responseString, pdbRestRequest);
177     } catch (Exception e)
178     {
179       String exceptionMsg = e.getMessage();
180       if (exceptionMsg.contains("SocketException"))
181       {
182         // No internet connection
183         throw new Exception(
184                 MessageManager
185                         .getString("exception.unable_to_detect_internet_connection"));
186       }
187       else if (exceptionMsg.contains("UnknownHostException"))
188       {
189         // The server 'www.ebi.ac.uk' is unreachable
190         throw new Exception(
191                 MessageManager
192                         .getString("exception.pdb_server_unreachable"));
193       }
194       else
195       {
196         throw e;
197       }
198     }
199   }
200
201   public String getMessageByHTTPStatusCode(int code)
202   {
203     String message = "";
204     switch (code)
205     {
206     case 410:
207       message = MessageManager
208               .getString("exception.pdb_rest_service_no_longer_available");
209       break;
210     case 403:
211     case 404:
212       message = MessageManager.getString("exception.resource_not_be_found");
213       break;
214     case 408:
215     case 409:
216     case 500:
217     case 501:
218     case 502:
219     case 503:
220     case 504:
221     case 505:
222       message = MessageManager.getString("exception.pdb_server_error");
223       break;
224
225     default:
226       break;
227     }
228     return message;
229   }
230
231   /**
232    * Process error response from PDB server if/when one occurs.
233    * 
234    * @param jsonResponse
235    *          the JSON string containing error message from the server
236    * @return the processed error message from the JSON string
237    */
238   public static String parseJsonExceptionString(String jsonErrorResponse)
239   {
240     StringBuilder errorMessage = new StringBuilder(
241             "\n============= PDB Rest Client RunTime error =============\n");
242
243     try
244     {
245       JSONParser jsonParser = new JSONParser();
246       JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
247       JSONObject errorResponse = (JSONObject) jsonObj.get("error");
248
249       JSONObject responseHeader = (JSONObject) jsonObj
250               .get("responseHeader");
251       JSONObject paramsObj = (JSONObject) responseHeader.get("params");
252       String status = responseHeader.get("status").toString();
253       String message = errorResponse.get("msg").toString();
254       String query = paramsObj.get("q").toString();
255       String fl = paramsObj.get("fl").toString();
256
257       errorMessage.append("Status: ").append(status).append("\n");
258       errorMessage.append("Message: ").append(message).append("\n");
259       errorMessage.append("query: ").append(query).append("\n");
260       errorMessage.append("fl: ").append(fl).append("\n");
261
262     } catch (ParseException e)
263     {
264       e.printStackTrace();
265     }
266     return errorMessage.toString();
267   }
268
269   /**
270    * Parses the JSON response string from PDB REST API. The response is dynamic
271    * hence, only fields specifically requested for in the 'wantedFields'
272    * parameter is fetched/processed
273    * 
274    * @param pdbJsonResponseString
275    *          the JSON string to be parsed
276    * @param pdbRestRequest
277    *          the request object which contains parameters used to process the
278    *          JSON string
279    * @return
280    */
281   @SuppressWarnings("unchecked")
282   public static FTSRestResponse parsePDBJsonResponse(
283           String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
284   {
285     FTSRestResponse searchResult = new FTSRestResponse();
286     List<FTSData> result = null;
287     try
288     {
289       JSONParser jsonParser = new JSONParser();
290       JSONObject jsonObj = (JSONObject) jsonParser
291               .parse(pdbJsonResponseString);
292
293       JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
294       String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
295               "QTime").toString();
296       int numFound = Integer
297               .valueOf(pdbResponse.get("numFound").toString());
298       if (numFound > 0)
299       {
300         result = new ArrayList<FTSData>();
301         JSONArray docs = (JSONArray) pdbResponse.get("docs");
302         for (Iterator<JSONObject> docIter = docs.iterator(); docIter
303                 .hasNext();)
304         {
305           JSONObject doc = docIter.next();
306           result.add(getFTSData(doc, pdbRestRequest));
307         }
308         searchResult.setNumberOfItemsFound(numFound);
309         searchResult.setResponseTime(queryTime);
310         searchResult.setSearchSummary(result);
311       }
312     } catch (ParseException e)
313     {
314       e.printStackTrace();
315     }
316     return searchResult;
317   }
318
319   public static FTSData getFTSData(JSONObject pdbJsonDoc,
320           FTSRestRequest request)
321   {
322
323     String primaryKey = null;
324
325     Object[] summaryRowData;
326
327     SequenceI associatedSequence;
328
329     Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
330     SequenceI associatedSeq = request.getAssociatedSequence();
331     int colCounter = 0;
332     summaryRowData = new Object[(associatedSeq != null) ? diplayFields
333             .size() + 1 : diplayFields.size()];
334     if (associatedSeq != null)
335     {
336       associatedSequence = associatedSeq;
337       summaryRowData[0] = associatedSequence;
338       colCounter = 1;
339     }
340
341     for (FTSDataColumnI field : diplayFields)
342     {
343       String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
344               : pdbJsonDoc.get(field.getCode()).toString();
345       if (field.isPrimaryKeyColumn())
346       {
347         primaryKey = fieldData;
348         summaryRowData[colCounter++] = primaryKey;
349       }
350       else
351       {
352         if (field.getGroup().getName().equals("Quality Measures"))
353         {
354           try
355           {
356             if (fieldData == null || fieldData.isEmpty())
357             {
358               summaryRowData[colCounter++] = null;
359             }
360             else
361             {
362               Double value = Double.valueOf(fieldData);
363               summaryRowData[colCounter++] = value;
364             }
365           } catch (Exception e)
366           {
367             e.printStackTrace();
368             System.out.println("offending value:" + fieldData);
369             summaryRowData[colCounter++] = 0.0;
370           }
371         }
372         else
373         {
374           summaryRowData[colCounter++] = (fieldData == null || fieldData
375                   .isEmpty()) ? null : fieldData;
376         }
377       }
378     }
379
380     final String primaryKey1 = primaryKey;
381
382     final Object[] summaryRowData1 = summaryRowData;
383     return new FTSData()
384     {
385       @Override
386       public Object[] getSummaryData()
387       {
388         return summaryRowData1;
389       }
390
391       @Override
392       public Object getPrimaryKey()
393       {
394         return primaryKey1;
395       }
396
397       /**
398        * Returns a string representation of this object;
399        */
400       @Override
401       public String toString()
402       {
403         StringBuilder summaryFieldValues = new StringBuilder();
404         for (Object summaryField : summaryRowData1)
405         {
406           summaryFieldValues.append(
407                   summaryField == null ? " " : summaryField.toString())
408                   .append("\t");
409         }
410         return summaryFieldValues.toString();
411       }
412
413       /**
414        * Returns hash code value for this object
415        */
416       @Override
417       public int hashCode()
418       {
419         return Objects.hash(primaryKey1, this.toString());
420       }
421     };
422   }
423
424   @Override
425   public String getColumnDataConfigFile()
426   {
427     return getFile("fts/pdb_data_columns.conf");
428   }
429
430
431   public static FTSRestClientI getInstance()
432   {
433     if (instance == null)
434     {
435       instance = new PDBFTSRestClient();
436     }
437     return instance;
438   }
439 }