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