Merge branch 'feature/JAL-3144noJTree' into
[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.bin.Jalview;
24 import jalview.datamodel.SequenceI;
25 import jalview.fts.api.FTSData;
26 import jalview.fts.api.FTSDataColumnI;
27 import jalview.fts.api.FTSRestClientI;
28 import jalview.fts.core.FTSRestClient;
29 import jalview.fts.core.FTSRestRequest;
30 import jalview.fts.core.FTSRestResponse;
31 import jalview.util.MessageManager;
32
33 import java.net.URI;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Objects;
39
40 import javax.ws.rs.core.MediaType;
41
42 import org.json.simple.JSONArray;
43 import org.json.simple.JSONObject;
44 import org.json.simple.parser.JSONParser;
45 import org.json.simple.parser.ParseException;
46
47 import com.sun.jersey.api.client.Client;
48 import com.sun.jersey.api.client.ClientResponse;
49 import com.sun.jersey.api.client.WebResource;
50 import com.sun.jersey.api.client.config.DefaultClientConfig;
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 (Jalview.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         client = Client.create(new DefaultClientConfig());
139         clientResponseClass = ClientResponse.class;
140       }
141
142       WebResource webResource;
143       if (pdbRestRequest.isFacet())
144       {
145         webResource = client.resource(PDB_SEARCH_ENDPOINT)
146                 .queryParam("wt", "json").queryParam("fl", wantedFields)
147                 .queryParam("rows", String.valueOf(responseSize))
148                 .queryParam("q", query)
149                 .queryParam("start", String.valueOf(offSet))
150                 .queryParam("sort", sortParam).queryParam("facet", "true")
151                 .queryParam("facet.pivot", facetPivot)
152                 .queryParam("facet.pivot.mincount", facetPivotMinCount);
153       }
154       else
155       {
156         webResource = client.resource(PDB_SEARCH_ENDPOINT)
157                 .queryParam("wt", "json").queryParam("fl", wantedFields)
158                 .queryParam("rows", String.valueOf(responseSize))
159                 .queryParam("start", String.valueOf(offSet))
160                 .queryParam("q", query).queryParam("sort", sortParam);
161       }
162
163       URI uri = webResource.getURI();
164
165       // Execute the REST request
166       ClientResponse clientResponse = webResource
167               .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
168
169       // Get the JSON string from the response object
170       String responseString = clientResponse.getEntity(String.class);
171       // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
172
173       // Check the response status and report exception if one occurs
174       if (clientResponse.getStatus() != 200)
175       {
176         String errorMessage = "";
177         if (clientResponse.getStatus() == 400)
178         {
179           errorMessage = parseJsonExceptionString(responseString);
180           throw new Exception(errorMessage);
181         }
182         else
183         {
184           errorMessage = getMessageByHTTPStatusCode(
185                   clientResponse.getStatus(), "PDB");
186           throw new Exception(errorMessage);
187         }
188       }
189
190       // Make redundant objects eligible for garbage collection to conserve
191       // memory
192       clientResponse = null;
193       client = null;
194
195       // Process the response and return the result to the caller.
196       return parsePDBJsonResponse(responseString, pdbRestRequest);
197     } catch (Exception e)
198     {
199       String exceptionMsg = e.getMessage();
200       if (exceptionMsg.contains("SocketException"))
201       {
202         // No internet connection
203         throw new Exception(MessageManager.getString(
204                 "exception.unable_to_detect_internet_connection"));
205       }
206       else if (exceptionMsg.contains("UnknownHostException"))
207       {
208         // The server 'www.ebi.ac.uk' is unreachable
209         throw new Exception(MessageManager.formatMessage(
210                 "exception.fts_server_unreachable", "PDB Solr"));
211       }
212       else
213       {
214         throw e;
215       }
216     }
217   }
218
219   /**
220    * Process error response from PDB server if/when one occurs.
221    * 
222    * @param jsonResponse
223    *          the JSON string containing error message from the server
224    * @return the processed error message from the JSON string
225    */
226   public static String parseJsonExceptionString(String jsonErrorResponse)
227   {
228     StringBuilder errorMessage = new StringBuilder(
229             "\n============= PDB Rest Client RunTime error =============\n");
230
231     
232 //    {
233 //      "responseHeader":{
234 //        "status":0,
235 //        "QTime":0,
236 //        "params":{
237 //          "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
238 //          "fl":"pdb_id,title,experimental_method,resolution",
239 //          "start":"0",
240 //          "sort":"overall_quality desc",
241 //          "rows":"500",
242 //          "wt":"json"}},
243 //      "response":{"numFound":1,"start":0,"docs":[
244 //          {
245 //            "experimental_method":["X-ray diffraction"],
246 //            "pdb_id":"4zhp",
247 //            "resolution":2.46,
248 //            "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
249 //      }}
250 //    
251     try
252     {
253       JSONParser jsonParser = new JSONParser();
254       JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
255       JSONObject errorResponse = (JSONObject) jsonObj.get("error");
256
257       JSONObject responseHeader = (JSONObject) jsonObj
258               .get("responseHeader");
259       JSONObject paramsObj = (JSONObject) responseHeader.get("params");
260       String status = responseHeader.get("status").toString();
261       String message = errorResponse.get("msg").toString();
262       String query = paramsObj.get("q").toString();
263       String fl = paramsObj.get("fl").toString();
264
265       errorMessage.append("Status: ").append(status).append("\n");
266       errorMessage.append("Message: ").append(message).append("\n");
267       errorMessage.append("query: ").append(query).append("\n");
268       errorMessage.append("fl: ").append(fl).append("\n");
269
270     } catch (ParseException e)
271     {
272       e.printStackTrace();
273     }
274     return errorMessage.toString();
275   }
276
277   /**
278    * Parses the JSON response string from PDB REST API. The response is dynamic
279    * hence, only fields specifically requested for in the 'wantedFields'
280    * parameter is fetched/processed
281    * 
282    * @param pdbJsonResponseString
283    *          the JSON string to be parsed
284    * @param pdbRestRequest
285    *          the request object which contains parameters used to process the
286    *          JSON string
287    * @return
288    */
289   @SuppressWarnings("unchecked")
290   public static FTSRestResponse parsePDBJsonResponse(
291           String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
292   {
293     FTSRestResponse searchResult = new FTSRestResponse();
294     List<FTSData> result = null;
295     try
296     {
297       JSONParser jsonParser = new JSONParser();
298       JSONObject jsonObj = (JSONObject) jsonParser
299               .parse(pdbJsonResponseString);
300
301       JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
302       String queryTime = ((JSONObject) 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<FTSData>();
309         JSONArray docs = (JSONArray) pdbResponse.get("docs");
310         for (Iterator<JSONObject> docIter = docs.iterator(); docIter
311                 .hasNext();)
312         {
313           JSONObject doc = 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(JSONObject 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<FTSDataColumnI>();
463       allDefaultDisplayedStructureDataColumns
464               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
465     }
466     return allDefaultDisplayedStructureDataColumns;
467   }
468   
469   public static void main(String[] args) {
470     
471     
472     // check for transpiler fix associated with JSONParser yylex.java use of charAt()
473     // instead of codePointAt()
474
475     String s = "e";
476     char c = 'c';
477     char f = 'f';
478     s += c | f; 
479     int x = c&f;
480     int y = 2 & c;
481     int z = c ^ 5;
482     String result = s +x + y + z;
483     assert (result == "e103982102");
484     JSONParser jsonParser = new JSONParser();
485     try
486     {
487       JSONObject jsonObj = (JSONObject) jsonParser.parse("{\"a\":3}");
488       System.out.println(jsonObj);
489     } catch (ParseException e)
490     {
491       e.printStackTrace();
492     }
493     
494   }
495   
496   
497 }