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