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