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