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