JAL-3253 jalview.bin.Instance streamlining
[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.bin.Instance;
24 import jalview.datamodel.SequenceI;
25 import jalview.fts.api.FTSData;
26 import jalview.fts.api.FTSDataColumnI;
27 import jalview.fts.api.FTSRestClientI;
28 import jalview.fts.core.FTSRestClient;
29 import jalview.fts.core.FTSRestRequest;
30 import jalview.fts.core.FTSRestResponse;
31 import jalview.util.JSONUtils;
32 import jalview.util.MessageManager;
33 import jalview.util.Platform;
34
35 import java.net.URI;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Objects;
42
43 import javax.ws.rs.core.MediaType;
44
45 import org.json.simple.parser.ParseException;
46
47 import com.sun.jersey.api.client.Client;
48 import com.sun.jersey.api.client.ClientResponse;
49 import com.sun.jersey.api.client.WebResource;
50 import com.sun.jersey.api.client.config.DefaultClientConfig;
51
52 /**
53  * A rest client for querying the Search endpoint of the PDB API
54  * 
55  * @author tcnofoegbu
56  */
57 public class PDBFTSRestClient extends FTSRestClient
58 {
59
60   public static FTSRestClientI getInstance()
61   {
62     Instance j = Instance.getInstance();
63     return (j.pdbFTSRestClient == null
64             ? j.pdbFTSRestClient = new PDBFTSRestClient()
65             : j.pdbFTSRestClient);
66   }
67
68   public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
69
70   private PDBFTSRestClient()
71   {
72     // singleton -- use getInstance()
73   }
74
75   /**
76    * Takes a PDBRestRequest object and returns a response upon execution
77    * 
78    * @param pdbRestRequest
79    *          the PDBRestRequest instance to be processed
80    * @return the pdbResponse object for the given request
81    * @throws Exception
82    */
83   @SuppressWarnings({ "unused", "unchecked" })
84   @Override
85   public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
86           throws Exception
87   {
88     try
89     {
90       String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
91               pdbRestRequest.getWantedFields());
92       int responseSize = (pdbRestRequest.getResponseSize() == 0)
93               ? getDefaultResponsePageSize()
94               : pdbRestRequest.getResponseSize();
95       int offSet = pdbRestRequest.getOffSet();
96       String sortParam = null;
97       if (pdbRestRequest.getFieldToSortBy() == null
98               || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
99       {
100         sortParam = "";
101       }
102       else
103       {
104         if (pdbRestRequest.getFieldToSortBy()
105                 .equalsIgnoreCase("Resolution"))
106         {
107           sortParam = pdbRestRequest.getFieldToSortBy()
108                   + (pdbRestRequest.isAscending() ? " asc" : " desc");
109         }
110         else
111         {
112           sortParam = pdbRestRequest.getFieldToSortBy()
113                   + (pdbRestRequest.isAscending() ? " desc" : " asc");
114         }
115       }
116
117       String facetPivot = (pdbRestRequest.getFacetPivot() == null
118               || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
119                       : pdbRestRequest.getFacetPivot();
120       String facetPivotMinCount = String
121               .valueOf(pdbRestRequest.getFacetPivotMinCount());
122
123       String query = pdbRestRequest.getFieldToSearchBy()
124               + pdbRestRequest.getSearchTerm()
125               + (pdbRestRequest.isAllowEmptySeq() ? ""
126                       : " AND molecule_sequence:['' TO *]")
127               + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
128                       : " AND status:REL");
129
130       // Build request parameters for the REST Request
131
132       // BH 2018 the trick here is to coerce the classes in Javascript to be 
133       // different from the ones in Java yet still allow this to be correct for Java
134       Client client;
135       Class<ClientResponse> clientResponseClass;
136       if (Platform.isJS())
137       {
138         // JavaScript only -- coerce types to Java types for Java
139         client = (Client) (Object) new jalview.javascript.web.Client();
140         clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
141       }
142       else
143       /**
144        * Java only
145        * 
146        * @j2sIgnore
147        */
148       {
149         client = Client.create(new DefaultClientConfig());
150         clientResponseClass = ClientResponse.class;
151       }
152
153       WebResource webResource;
154       if (pdbRestRequest.isFacet())
155       {
156         webResource = client.resource(PDB_SEARCH_ENDPOINT)
157                 .queryParam("wt", "json").queryParam("fl", wantedFields)
158                 .queryParam("rows", String.valueOf(responseSize))
159                 .queryParam("q", query)
160                 .queryParam("start", String.valueOf(offSet))
161                 .queryParam("sort", sortParam).queryParam("facet", "true")
162                 .queryParam("facet.pivot", facetPivot)
163                 .queryParam("facet.pivot.mincount", facetPivotMinCount);
164       }
165       else
166       {
167         webResource = client.resource(PDB_SEARCH_ENDPOINT)
168                 .queryParam("wt", "json").queryParam("fl", wantedFields)
169                 .queryParam("rows", String.valueOf(responseSize))
170                 .queryParam("start", String.valueOf(offSet))
171                 .queryParam("q", query).queryParam("sort", sortParam);
172       }
173
174       URI uri = webResource.getURI();
175
176       System.out.println(uri);
177
178       // Execute the REST request
179       ClientResponse clientResponse = webResource
180               .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
181
182       int status = clientResponse.getStatus();
183
184       // Get the JSON string from the response object or directly from the
185       // client (JavaScript)
186       Map<String, Object> jsonObj = (Platform.isJS() && status == 200
187               ? clientResponse.getEntity(Map.class)
188               : null);
189       String responseString = (jsonObj == null
190               ? clientResponse.getEntity(String.class)
191               : null);
192
193       // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
194
195       // Check the response status and report exception if one occurs
196       switch (status)
197       {
198       case 200:
199         break;
200       case 400:
201         throw new Exception(parseJsonExceptionString(responseString));
202       default:
203         throw new Exception(getMessageByHTTPStatusCode(status, "PDB"));
204       }
205
206       // Make redundant objects eligible for garbage collection to conserve
207       // memory
208       clientResponse = null;
209       client = null;
210
211       // Process the response and return the result to the caller.
212       return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
213     } catch (Exception e)
214     {
215       String exceptionMsg = e.getMessage();
216       if (exceptionMsg.contains("SocketException"))
217       {
218         // No internet connection
219         throw new Exception(MessageManager.getString(
220                 "exception.unable_to_detect_internet_connection"));
221       }
222       else if (exceptionMsg.contains("UnknownHostException"))
223       {
224         // The server 'www.ebi.ac.uk' is unreachable
225         throw new Exception(MessageManager.formatMessage(
226                 "exception.fts_server_unreachable", "PDB Solr"));
227       }
228       else
229       {
230         throw e;
231       }
232     }
233   }
234
235   /**
236    * Process error response from PDB server if/when one occurs.
237    * 
238    * @param jsonResponse
239    *          the JSON string containing error message from the server
240    * @return the processed error message from the JSON string
241    */
242   @SuppressWarnings("unchecked")
243 public static String parseJsonExceptionString(String jsonErrorResponse)
244   {
245     StringBuilder errorMessage = new StringBuilder(
246             "\n============= PDB Rest Client RunTime error =============\n");
247
248     
249 //    {
250 //      "responseHeader":{
251 //        "status":0,
252 //        "QTime":0,
253 //        "params":{
254 //          "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
255 //          "fl":"pdb_id,title,experimental_method,resolution",
256 //          "start":"0",
257 //          "sort":"overall_quality desc",
258 //          "rows":"500",
259 //          "wt":"json"}},
260 //      "response":{"numFound":1,"start":0,"docs":[
261 //          {
262 //            "experimental_method":["X-ray diffraction"],
263 //            "pdb_id":"4zhp",
264 //            "resolution":2.46,
265 //            "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
266 //      }}
267 //    
268     try
269     {
270       Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
271       Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
272
273       Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
274               .get("responseHeader");
275       Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
276       String status = responseHeader.get("status").toString();
277       String message = errorResponse.get("msg").toString();
278       String query = paramsObj.get("q").toString();
279       String fl = paramsObj.get("fl").toString();
280
281       errorMessage.append("Status: ").append(status).append("\n");
282       errorMessage.append("Message: ").append(message).append("\n");
283       errorMessage.append("query: ").append(query).append("\n");
284       errorMessage.append("fl: ").append(fl).append("\n");
285
286     } catch (ParseException e)
287     {
288       e.printStackTrace();
289     }
290     return errorMessage.toString();
291   }
292
293   /**
294    * Parses the JSON response string from PDB REST API. The response is dynamic
295    * hence, only fields specifically requested for in the 'wantedFields'
296    * parameter is fetched/processed
297    * 
298    * @param pdbJsonResponseString
299    *          the JSON string to be parsed
300    * @param pdbRestRequest
301    *          the request object which contains parameters used to process the
302    *          JSON string
303    * @return
304    */
305   public static FTSRestResponse parsePDBJsonResponse(
306           String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
307   {
308     return parsePDBJsonResponse(pdbJsonResponseString,
309             (Map<String, Object>) null, pdbRestRequest);
310   }
311
312   @SuppressWarnings("unchecked")
313   public static FTSRestResponse parsePDBJsonResponse(
314           String pdbJsonResponseString, Map<String, Object> jsonObj,
315           FTSRestRequest pdbRestRequest)
316   {
317     FTSRestResponse searchResult = new FTSRestResponse();
318     List<FTSData> result = null;
319     try
320     {
321       if (jsonObj == null)
322       {
323         jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
324       }
325       Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
326       String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
327               .get("QTime").toString();
328       int numFound = Integer
329               .valueOf(pdbResponse.get("numFound").toString());
330       if (numFound > 0)
331       {
332         result = new ArrayList<>();
333         List<Object> docs = (List<Object>) pdbResponse.get("docs");
334         for (Iterator<Object> docIter = docs.iterator(); docIter
335                 .hasNext();)
336         {
337           Map<String, Object> doc = (Map<String, Object>) docIter.next();
338           result.add(getFTSData(doc, pdbRestRequest));
339         }
340         searchResult.setNumberOfItemsFound(numFound);
341         searchResult.setResponseTime(queryTime);
342         searchResult.setSearchSummary(result);
343       }
344     } catch (ParseException e)
345     {
346       e.printStackTrace();
347     }
348     return searchResult;
349   }
350
351   public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
352           FTSRestRequest request)
353   {
354
355     String primaryKey = null;
356
357     Object[] summaryRowData;
358
359     SequenceI associatedSequence;
360
361     Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
362     SequenceI associatedSeq = request.getAssociatedSequence();
363     int colCounter = 0;
364     summaryRowData = new Object[(associatedSeq != null)
365             ? diplayFields.size() + 1
366             : diplayFields.size()];
367     if (associatedSeq != null)
368     {
369       associatedSequence = associatedSeq;
370       summaryRowData[0] = associatedSequence;
371       colCounter = 1;
372     }
373
374     for (FTSDataColumnI field : diplayFields)
375     {
376       String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
377               : pdbJsonDoc.get(field.getCode()).toString();
378       if (field.isPrimaryKeyColumn())
379       {
380         primaryKey = fieldData;
381         summaryRowData[colCounter++] = primaryKey;
382       }
383       else if (fieldData == null || fieldData.isEmpty())
384       {
385         summaryRowData[colCounter++] = null;
386       }
387       else
388       {
389         try
390         {
391           summaryRowData[colCounter++] = (field.getDataType()
392                   .getDataTypeClass() == Integer.class)
393                           ? Integer.valueOf(fieldData)
394                           : (field.getDataType()
395                                   .getDataTypeClass() == Double.class)
396                                           ? Double.valueOf(fieldData)
397                                           : sanitiseData(fieldData);
398         } catch (Exception e)
399         {
400           e.printStackTrace();
401           System.out.println("offending value:" + fieldData);
402         }
403       }
404     }
405
406     final String primaryKey1 = primaryKey;
407
408     final Object[] summaryRowData1 = summaryRowData;
409     return new FTSData()
410     {
411       @Override
412       public Object[] getSummaryData()
413       {
414         return summaryRowData1;
415       }
416
417       @Override
418       public Object getPrimaryKey()
419       {
420         return primaryKey1;
421       }
422
423       /**
424        * Returns a string representation of this object;
425        */
426       @Override
427       public String toString()
428       {
429         StringBuilder summaryFieldValues = new StringBuilder();
430         for (Object summaryField : summaryRowData1)
431         {
432           summaryFieldValues.append(
433                   summaryField == null ? " " : summaryField.toString())
434                   .append("\t");
435         }
436         return summaryFieldValues.toString();
437       }
438
439       /**
440        * Returns hash code value for this object
441        */
442       @Override
443       public int hashCode()
444       {
445         return Objects.hash(primaryKey1, this.toString());
446       }
447
448       @Override
449       public boolean equals(Object that)
450       {
451         return this.toString().equals(that.toString());
452       }
453     };
454   }
455
456   private static String sanitiseData(String data)
457   {
458     String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
459             .replaceAll("\\[", "").replaceAll("\\]", "")
460             .replaceAll("\",\"", ", ").replaceAll("\"", "");
461     return cleanData;
462   }
463
464   @Override
465   public String getColumnDataConfigFileName()
466   {
467     return "/fts/pdb_data_columns.txt";
468   }
469
470   private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
471
472   public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
473   {
474     if (allDefaultDisplayedStructureDataColumns == null
475             || allDefaultDisplayedStructureDataColumns.isEmpty())
476     {
477       allDefaultDisplayedStructureDataColumns = new ArrayList<>();
478       allDefaultDisplayedStructureDataColumns
479               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
480     }
481     return allDefaultDisplayedStructureDataColumns;
482   }
483   
484   
485 }