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