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