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