8a10c665328db2db3a399d36a82e8b13e9fa3aa2
[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       System.out.println(uri);
169
170       // Execute the REST request
171       ClientResponse clientResponse = webResource
172               .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
173
174       int status = clientResponse.getStatus();
175
176       // Get the JSON string from the response object or directly from the
177       // client (JavaScript)
178       Map<String, Object> jsonObj = (status == 200
179               ? clientResponse.getEntity(Map.class)
180               : null);
181       String responseString = (jsonObj == null
182               ? clientResponse.getEntity(String.class)
183               : null);
184
185       // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
186
187       // Check the response status and report exception if one occurs
188       switch (status)
189       {
190       case 200:
191         break;
192       case 400:
193         throw new Exception(parseJsonExceptionString(responseString));
194       default:
195         throw new Exception(getMessageByHTTPStatusCode(status, "PDB"));
196       }
197
198       // Make redundant objects eligible for garbage collection to conserve
199       // memory
200       clientResponse = null;
201       client = null;
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       if (numFound > 0)
323       {
324         result = new ArrayList<>();
325         List<Object> docs = (List<Object>) pdbResponse.get("docs");
326         for (Iterator<Object> docIter = docs.iterator(); docIter
327                 .hasNext();)
328         {
329           Map<String, Object> doc = (Map<String, Object>) docIter.next();
330           result.add(getFTSData(doc, pdbRestRequest));
331         }
332         searchResult.setNumberOfItemsFound(numFound);
333         searchResult.setResponseTime(queryTime);
334         searchResult.setSearchSummary(result);
335       }
336     } catch (ParseException e)
337     {
338       e.printStackTrace();
339     }
340     return searchResult;
341   }
342
343   public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
344           FTSRestRequest request)
345   {
346
347     String primaryKey = null;
348
349     Object[] summaryRowData;
350
351     SequenceI associatedSequence;
352
353     Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
354     SequenceI associatedSeq = request.getAssociatedSequence();
355     int colCounter = 0;
356     summaryRowData = new Object[(associatedSeq != null)
357             ? diplayFields.size() + 1
358             : diplayFields.size()];
359     if (associatedSeq != null)
360     {
361       associatedSequence = associatedSeq;
362       summaryRowData[0] = associatedSequence;
363       colCounter = 1;
364     }
365
366     for (FTSDataColumnI field : diplayFields)
367     {
368       String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
369               : pdbJsonDoc.get(field.getCode()).toString();
370       if (field.isPrimaryKeyColumn())
371       {
372         primaryKey = fieldData;
373         summaryRowData[colCounter++] = primaryKey;
374       }
375       else if (fieldData == null || fieldData.isEmpty())
376       {
377         summaryRowData[colCounter++] = null;
378       }
379       else
380       {
381         try
382         {
383           summaryRowData[colCounter++] = (field.getDataType()
384                   .getDataTypeClass() == Integer.class)
385                           ? Integer.valueOf(fieldData)
386                           : (field.getDataType()
387                                   .getDataTypeClass() == Double.class)
388                                           ? Double.valueOf(fieldData)
389                                           : sanitiseData(fieldData);
390         } catch (Exception e)
391         {
392           e.printStackTrace();
393           System.out.println("offending value:" + fieldData);
394         }
395       }
396     }
397
398     final String primaryKey1 = primaryKey;
399
400     final Object[] summaryRowData1 = summaryRowData;
401     return new FTSData()
402     {
403       @Override
404       public Object[] getSummaryData()
405       {
406         return summaryRowData1;
407       }
408
409       @Override
410       public Object getPrimaryKey()
411       {
412         return primaryKey1;
413       }
414
415       /**
416        * Returns a string representation of this object;
417        */
418       @Override
419       public String toString()
420       {
421         StringBuilder summaryFieldValues = new StringBuilder();
422         for (Object summaryField : summaryRowData1)
423         {
424           summaryFieldValues.append(
425                   summaryField == null ? " " : summaryField.toString())
426                   .append("\t");
427         }
428         return summaryFieldValues.toString();
429       }
430
431       /**
432        * Returns hash code value for this object
433        */
434       @Override
435       public int hashCode()
436       {
437         return Objects.hash(primaryKey1, this.toString());
438       }
439
440       @Override
441       public boolean equals(Object that)
442       {
443         return this.toString().equals(that.toString());
444       }
445     };
446   }
447
448   private static String sanitiseData(String data)
449   {
450     String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
451             .replaceAll("\\[", "").replaceAll("\\]", "")
452             .replaceAll("\",\"", ", ").replaceAll("\"", "");
453     return cleanData;
454   }
455
456   @Override
457   public String getColumnDataConfigFileName()
458   {
459     return "/fts/pdb_data_columns.txt";
460   }
461
462   public static FTSRestClientI getInstance()
463   {
464     if (instance == null)
465     {
466       instance = new PDBFTSRestClient();
467     }
468     return instance;
469   }
470
471   private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
472
473   public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
474   {
475     if (allDefaultDisplayedStructureDataColumns == null
476             || allDefaultDisplayedStructureDataColumns.isEmpty())
477     {
478       allDefaultDisplayedStructureDataColumns = new ArrayList<>();
479       allDefaultDisplayedStructureDataColumns
480               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
481     }
482     return allDefaultDisplayedStructureDataColumns;
483   }
484   
485   @SuppressWarnings("unchecked")
486 public static void main(String[] args) {
487     
488     
489     // check for transpiler fix associated with JSONParser yylex.java use of charAt()
490     // instead of codePointAt()
491
492     String s = "e";
493     char c = 'c';
494     char f = 'f';
495     s += c | f; 
496     int x = c&f;
497     int y = 2 & c;
498     int z = c ^ 5;
499     String result = s +x + y + z;
500     assert (result == "e103982102");
501     try
502     {
503       Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse("{\"a\":3}");
504       System.out.println(jsonObj);
505     } catch (ParseException e)
506     {
507       e.printStackTrace();
508     }
509     
510   }
511   
512   
513 }