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