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