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