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