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