dc7fe412857737f88b4c4549a301821a932150c4
[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.datamodel.SequenceI;
41 import jalview.fts.api.FTSData;
42 import jalview.fts.api.FTSDataColumnI;
43 import jalview.fts.api.FTSRestClientI;
44 import jalview.fts.core.FTSRestClient;
45 import jalview.fts.core.FTSRestRequest;
46 import jalview.fts.core.FTSRestResponse;
47 import jalview.util.JSONUtils;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
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        * @j2sIgnore
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       // Get the JSON string from the response object or directly from the
175       // client (JavaScript)
176       Map<String, Object> jsonObj = null;
177       String responseString = null;
178
179       System.out.println("query >>>>>>> " + pdbRestRequest.toString());
180
181       // Check the response status and report exception if one occurs
182       int responseStatus = clientResponse.getStatus();
183       switch (responseStatus)
184       {
185       case 200:
186         if (Platform.isJS())
187         {
188           jsonObj = clientResponse.getEntity(Map.class);
189         }
190         else
191         {
192           responseString = clientResponse.getEntity(String.class);
193         }
194         break;
195       case 400:
196         throw new Exception(parseJsonExceptionString(responseString));
197       default:
198         throw new Exception(
199                 getMessageByHTTPStatusCode(responseStatus, "PDB"));
200       }
201
202       // Process the response and return the result to the caller.
203       return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
204     } catch (Exception e)
205     {
206       String exceptionMsg = e.getMessage();
207       if (exceptionMsg.contains("SocketException"))
208       {
209         // No internet connection
210         throw new Exception(MessageManager.getString(
211                 "exception.unable_to_detect_internet_connection"));
212       }
213       else if (exceptionMsg.contains("UnknownHostException"))
214       {
215         // The server 'www.ebi.ac.uk' is unreachable
216         throw new Exception(MessageManager.formatMessage(
217                 "exception.fts_server_unreachable", "PDB Solr"));
218       }
219       else
220       {
221         throw e;
222       }
223     }
224   }
225
226   /**
227    * Process error response from PDB server if/when one occurs.
228    * 
229    * @param jsonResponse
230    *          the JSON string containing error message from the server
231    * @return the processed error message from the JSON string
232    */
233   @SuppressWarnings("unchecked")
234 public static String parseJsonExceptionString(String jsonErrorResponse)
235   {
236     StringBuilder errorMessage = new StringBuilder(
237             "\n============= PDB Rest Client RunTime error =============\n");
238
239     
240 //    {
241 //      "responseHeader":{
242 //        "status":0,
243 //        "QTime":0,
244 //        "params":{
245 //          "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
246 //          "fl":"pdb_id,title,experimental_method,resolution",
247 //          "start":"0",
248 //          "sort":"overall_quality desc",
249 //          "rows":"500",
250 //          "wt":"json"}},
251 //      "response":{"numFound":1,"start":0,"docs":[
252 //          {
253 //            "experimental_method":["X-ray diffraction"],
254 //            "pdb_id":"4zhp",
255 //            "resolution":2.46,
256 //            "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
257 //      }}
258 //    
259     try
260     {
261       Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
262       Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
263
264       Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
265               .get("responseHeader");
266       Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
267       String status = responseHeader.get("status").toString();
268       String message = errorResponse.get("msg").toString();
269       String query = paramsObj.get("q").toString();
270       String fl = paramsObj.get("fl").toString();
271
272       errorMessage.append("Status: ").append(status).append("\n");
273       errorMessage.append("Message: ").append(message).append("\n");
274       errorMessage.append("query: ").append(query).append("\n");
275       errorMessage.append("fl: ").append(fl).append("\n");
276
277     } catch (ParseException e)
278     {
279       e.printStackTrace();
280     }
281     return errorMessage.toString();
282   }
283
284   /**
285    * Parses the JSON response string from PDB REST API. The response is dynamic
286    * hence, only fields specifically requested for in the 'wantedFields'
287    * parameter is fetched/processed
288    * 
289    * @param pdbJsonResponseString
290    *          the JSON string to be parsed
291    * @param pdbRestRequest
292    *          the request object which contains parameters used to process the
293    *          JSON string
294    * @return
295    */
296   public static FTSRestResponse parsePDBJsonResponse(
297           String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
298   {
299     return parsePDBJsonResponse(pdbJsonResponseString,
300             (Map<String, Object>) null, pdbRestRequest);
301   }
302
303   @SuppressWarnings("unchecked")
304   public static FTSRestResponse parsePDBJsonResponse(
305           String pdbJsonResponseString, Map<String, Object> jsonObj,
306           FTSRestRequest pdbRestRequest)
307   {
308     FTSRestResponse searchResult = new FTSRestResponse();
309     List<FTSData> result = null;
310     try
311     {
312       if (jsonObj == null)
313       {
314         jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
315       }
316       Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
317       String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
318               .get("QTime").toString();
319       int numFound = Integer
320               .valueOf(pdbResponse.get("numFound").toString());
321       if (numFound > 0)
322       {
323         result = new ArrayList<>();
324         List<Object> docs = (List<Object>) pdbResponse.get("docs");
325         for (Iterator<Object> docIter = docs.iterator(); docIter
326                 .hasNext();)
327         {
328           Map<String, Object> doc = (Map<String, Object>) docIter.next();
329           result.add(getFTSData(doc, pdbRestRequest));
330         }
331         searchResult.setNumberOfItemsFound(numFound);
332         searchResult.setResponseTime(queryTime);
333         searchResult.setSearchSummary(result);
334       }
335     } catch (ParseException e)
336     {
337       e.printStackTrace();
338     }
339     return searchResult;
340   }
341
342   public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
343           FTSRestRequest request)
344   {
345
346     String primaryKey = null;
347
348     Object[] summaryRowData;
349
350     SequenceI associatedSequence;
351
352     Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
353     SequenceI associatedSeq = request.getAssociatedSequence();
354     int colCounter = 0;
355     summaryRowData = new Object[(associatedSeq != null)
356             ? diplayFields.size() + 1
357             : diplayFields.size()];
358     if (associatedSeq != null)
359     {
360       associatedSequence = associatedSeq;
361       summaryRowData[0] = associatedSequence;
362       colCounter = 1;
363     }
364
365     for (FTSDataColumnI field : diplayFields)
366     {
367       //System.out.println("Field " + field);
368       String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
369               : pdbJsonDoc.get(field.getCode()).toString();
370       //System.out.println("Field Data : " + fieldData);
371       if (field.isPrimaryKeyColumn())
372       {
373         primaryKey = fieldData;
374         summaryRowData[colCounter++] = primaryKey;
375       }
376       else if (fieldData == null || fieldData.isEmpty())
377       {
378         summaryRowData[colCounter++] = null;
379       }
380       else
381       {
382         try
383         {
384           summaryRowData[colCounter++] = (field.getDataType()
385                   .getDataTypeClass() == Integer.class)
386                           ? Integer.valueOf(fieldData)
387                           : (field.getDataType()
388                                   .getDataTypeClass() == Double.class)
389                                           ? Double.valueOf(fieldData)
390                                           : sanitiseData(fieldData);
391         } catch (Exception e)
392         {
393           e.printStackTrace();
394           System.out.println("offending value:" + fieldData);
395         }
396       }
397     }
398
399     final String primaryKey1 = primaryKey;
400
401     final Object[] summaryRowData1 = summaryRowData;
402     return new FTSData()
403     {
404       @Override
405       public Object[] getSummaryData()
406       {
407         return summaryRowData1;
408       }
409
410       @Override
411       public Object getPrimaryKey()
412       {
413         return primaryKey1;
414       }
415
416       /**
417        * Returns a string representation of this object;
418        */
419       @Override
420       public String toString()
421       {
422         StringBuilder summaryFieldValues = new StringBuilder();
423         for (Object summaryField : summaryRowData1)
424         {
425           summaryFieldValues.append(
426                   summaryField == null ? " " : summaryField.toString())
427                   .append("\t");
428         }
429         return summaryFieldValues.toString();
430       }
431
432       /**
433        * Returns hash code value for this object
434        */
435       @Override
436       public int hashCode()
437       {
438         return Objects.hash(primaryKey1, this.toString());
439       }
440
441       @Override
442       public boolean equals(Object that)
443       {
444         return this.toString().equals(that.toString());
445       }
446     };
447   }
448
449   private static String sanitiseData(String data)
450   {
451     String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
452             .replaceAll("\\[", "").replaceAll("\\]", "")
453             .replaceAll("\",\"", ", ").replaceAll("\"", "");
454     return cleanData;
455   }
456
457   @Override
458   public String getColumnDataConfigFileName()
459   {
460     return "/fts/pdb_data_columns.txt";
461   }
462
463   public static FTSRestClientI getInstance()
464   {
465     if (instance == null)
466     {
467       instance = new PDBFTSRestClient();
468     }
469     return instance;
470   }
471
472   private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
473
474   public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
475   {
476     if (allDefaultDisplayedStructureDataColumns == null
477             || allDefaultDisplayedStructureDataColumns.isEmpty())
478     {
479       allDefaultDisplayedStructureDataColumns = new ArrayList<>();
480       allDefaultDisplayedStructureDataColumns
481               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
482     }
483     return allDefaultDisplayedStructureDataColumns;
484   }
485   
486   
487 }