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