8263b22fc4124c5bd917bf8fbbd4c0fff6b9236c
[jalview.git] / src / jalview / fts / service / threedbeacons / TDBeaconsFTSRestClient.java
1 package jalview.fts.service.threedbeacons;
2
3 import java.net.URI;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Objects;
10
11 import javax.ws.rs.core.MediaType;
12
13 import org.json.simple.parser.ParseException;
14
15 import com.sun.jersey.api.client.Client;
16 import com.sun.jersey.api.client.ClientResponse;
17 import com.sun.jersey.api.client.WebResource;
18 import com.sun.jersey.api.client.config.DefaultClientConfig;
19
20 import jalview.datamodel.SequenceI;
21 import jalview.fts.api.FTSData;
22 import jalview.fts.api.FTSDataColumnI;
23 import jalview.fts.api.FTSRestClientI;
24 import jalview.fts.api.StructureFTSRestClientI;
25 import jalview.fts.core.FTSRestClient;
26 import jalview.fts.core.FTSRestRequest;
27 import jalview.fts.core.FTSRestResponse;
28 import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
29 import jalview.fts.service.pdb.PDBFTSRestClient;
30 import jalview.util.JSONUtils;
31 import jalview.util.MessageManager;
32 import jalview.util.Platform;
33
34 public class TDBeaconsFTSRestClient extends FTSRestClient
35         implements StructureFTSRestClientI
36 {
37   /**
38    * production server URI
39    */
40   private static String TDB_PROD_API="https://www.ebi.ac.uk/pdbe/pdbe-kb/3dbeacons/api/uniprot/summary/";
41   /**
42    * dev server URI
43    */
44   private static String TDB_DEV_API="https://wwwdev.ebi.ac.uk/pdbe/pdbe-kb/3dbeacons/api/uniprot/summary/";
45   private static String DEFAULT_THREEDBEACONS_DOMAIN = TDB_PROD_API; 
46
47   public static FTSRestClientI instance = null;
48
49   protected TDBeaconsFTSRestClient()
50   {
51   }
52   @SuppressWarnings("unchecked")
53   @Override
54   public FTSRestResponse executeRequest(FTSRestRequest tdbRestRequest)
55           throws Exception
56   {
57     try
58     {
59       String query = tdbRestRequest.getSearchTerm();
60       Client client;
61       Class<ClientResponse> clientResponseClass;
62       if (Platform.isJS())
63       {
64         // JavaScript only
65         client = (Client) (Object) new jalview.javascript.web.Client();
66         clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
67       }
68       else
69       /**
70        * Java only
71        * 
72        * @j2sIgnore
73        */
74       {
75         client = Client.create(new DefaultClientConfig());
76         clientResponseClass = ClientResponse.class;
77       }
78
79       WebResource webResource;
80       webResource = client.resource(DEFAULT_THREEDBEACONS_DOMAIN+query);
81
82       URI uri = webResource.getURI();
83       System.out.println(uri.toString());
84
85       // Execute the REST request
86       ClientResponse clientResponse;
87       if (isMocked()) { 
88         clientResponse = null;
89       }
90       else
91       {
92         clientResponse = webResource.accept(MediaType.APPLICATION_JSON)
93                 .get(clientResponseClass);
94       }
95
96       // Get the JSON string from the response object or directly from the
97       // client (JavaScript)
98       Map<String, Object> jsonObj = null;
99       String responseString = null;
100
101       // Check the response status and report exception if one occurs
102       int responseStatus = isMocked() ? (mockQuery.equals(query) ? 200 : 404) : clientResponse.getStatus();
103       switch (responseStatus)
104       {
105       // if success
106       case 200:
107         if (Platform.isJS())
108         {
109           jsonObj = clientResponse.getEntity(Map.class);
110         }
111         else
112         {
113           responseString = isMocked() ? mockResponse: clientResponse.getEntity(String.class);
114         }
115         break;
116       case 400:
117         throw new Exception(parseJsonExceptionString(responseString));
118       case 404:
119         return emptyTDBeaconsJsonResponse();
120       default:
121         throw new Exception(
122                 getMessageByHTTPStatusCode(responseStatus, "3DBeacons"));
123       }
124       // Process the response and return the result to the caller.
125       return parseTDBeaconsJsonResponse(responseString, jsonObj,
126               tdbRestRequest);
127     } catch (Exception e)
128     {
129       String exceptionMsg = e.getMessage();
130       if (exceptionMsg.contains("SocketException"))
131       {
132         // No internet connection
133         throw new Exception(MessageManager.getString(
134                 "exception.unable_to_detect_internet_connection"));
135       }
136       else if (exceptionMsg.contains("UnknownHostException"))
137       {
138         // The server is unreachable
139         throw new Exception(MessageManager.formatMessage(
140                 "exception.fts_server_unreachable", "3DB Hub"));
141       }
142       else
143       {
144         throw e;
145       }
146     }
147
148   }
149
150   /**
151    * returns response for when the 3D-Beacons service doesn't have a record for
152    * the given query - in 2.11.2 this triggers a failover to the PDBe FTS 
153    * 
154    * @return null
155    */
156   private FTSRestResponse emptyTDBeaconsJsonResponse()
157   {
158     return null;
159   }
160
161   public String setSearchTerm(String term)
162   {
163     return term;
164   }
165
166   public static FTSRestResponse parseTDBeaconsJsonResponse(
167           String tdbJsonResponseString, FTSRestRequest tdbRestRequest)
168   {
169     return parseTDBeaconsJsonResponse(tdbJsonResponseString,
170             (Map<String, Object>) null, tdbRestRequest);
171   }
172
173   @SuppressWarnings("unchecked")
174   public static FTSRestResponse parseTDBeaconsJsonResponse(
175           String tdbJsonResponseString, Map<String, Object> jsonObj,
176           FTSRestRequest tdbRestRequest)
177   {
178     FTSRestResponse searchResult = new FTSRestResponse();
179     List<FTSData> result = null;
180
181     try
182     {
183       if (jsonObj == null)
184       {
185         jsonObj = (Map<String, Object>) JSONUtils
186                 .parse(tdbJsonResponseString);
187       }
188
189       Object uniprot_entry = jsonObj.get("uniprot_entry");
190       // TODO: decide if anything from uniprot_entry needs to be reported via
191       // the FTSRestResponse object
192       // Arnaud added seqLength = (Long) ((Map<String, Object>)
193       // jsonObj.get("uniprot_entry")).get("sequence_length");
194
195       List<Object> structures = (List<Object>) jsonObj.get("structures");
196       result = new ArrayList<>();
197
198       int numFound = 0;
199       for (Iterator<Object> strucIter = structures.iterator(); strucIter
200               .hasNext();)
201       {
202         Map<String, Object> structure = (Map<String, Object>) strucIter
203                 .next();
204         result.add(getFTSData(structure, tdbRestRequest));
205         numFound++;
206       }
207
208       searchResult.setNumberOfItemsFound(numFound);
209       searchResult.setSearchSummary(result);
210
211     } catch (ParseException e)
212     {
213       e.printStackTrace();
214     }
215     return searchResult;
216   }
217
218   private static FTSData getFTSData(Map<String, Object> tdbJsonStructure,
219           FTSRestRequest tdbRequest)
220   {
221     // TODO: consider reusing PDBFTSRestClient.getFTSData ?
222
223     String primaryKey = null;
224     Object[] summaryRowData;
225
226     SequenceI associatedSequence;
227
228     Collection<FTSDataColumnI> displayFields = tdbRequest.getWantedFields();
229     SequenceI associatedSeq = tdbRequest.getAssociatedSequence();
230     int colCounter = 0;
231     summaryRowData = new Object[(associatedSeq != null)
232                                 ? displayFields.size() + 1
233                                 : displayFields.size()];
234                         if (associatedSeq != null)
235                         {
236                           associatedSequence = associatedSeq;
237                           summaryRowData[0] = associatedSequence;
238                           colCounter = 1;
239                         }
240
241     for (FTSDataColumnI field : displayFields)
242     {
243       String fieldData = (tdbJsonStructure.get(field.getCode()) == null)
244               ? " "
245               : tdbJsonStructure.get(field.getCode()).toString();
246       // System.out.println("Field : " + field + " Data : " + fieldData);
247       if (field.isPrimaryKeyColumn())
248       {
249         primaryKey = fieldData;
250         summaryRowData[colCounter++] = primaryKey;
251       }
252       else if (fieldData == null || fieldData.trim().isEmpty())
253       {
254         summaryRowData[colCounter++] = null;
255       }
256       else
257       {
258         try
259         {
260           summaryRowData[colCounter++] = (field.getDataType()
261                   .getDataTypeClass() == Integer.class)
262                           ? Integer.valueOf(fieldData)
263                           : (field.getDataType()
264                                   .getDataTypeClass() == Double.class)
265                                           ? Double.valueOf(fieldData)
266                                           : fieldData;
267         } catch (Exception e)
268         {
269           // e.printStackTrace();
270           System.out.println("offending value:" + fieldData + fieldData);
271         }
272       }
273     }
274     final String primaryKey1 = primaryKey;
275     final Object[] summaryRowData1 = summaryRowData;
276
277     return new FTSData()
278     {
279
280       @Override
281       public Object[] getSummaryData()
282       {
283         return summaryRowData1;
284       }
285
286       @Override
287       public Object getPrimaryKey()
288       {
289         return primaryKey1;
290       }
291
292       /**
293        * Returns a string representation of this object;
294        */
295       @Override
296       public String toString()
297       {
298         StringBuilder summaryFieldValues = new StringBuilder();
299         for (Object summaryField : summaryRowData1)
300         {
301           summaryFieldValues.append(
302                   summaryField == null ? " " : summaryField.toString())
303                   .append("\t");
304         }
305         return summaryFieldValues.toString();
306       }
307
308       /**
309        * Returns hash code value for this object
310        */
311       @Override
312       public int hashCode()
313       {
314         return Objects.hash(primaryKey1, this.toString());
315       }
316
317       @Override
318       public boolean equals(Object that)
319       {
320         return this.toString().equals(that.toString());
321       }
322     };
323   }
324
325   // private static FTSData getFTSData(Map<String, Object> doc,
326   // FTSRestRequest tdbRestRequest)
327   // {
328   // String primaryKey = null;
329   //
330   // Object[] summaryRowData;
331   //
332   // Collection<FTSDataColumnI> displayFields =
333   // tdbRestRequest.getWantedFields();
334   // int colCounter = 0;
335   // summaryRowData = new Object[displayFields.size() + 1];
336   //
337   // return null;
338   // }
339
340   private String parseJsonExceptionString(String jsonErrorString)
341   {
342     // TODO Auto-generated method stub
343     return null;
344   }
345
346   @Override
347   public String getColumnDataConfigFileName()
348   {
349     return "/fts/tdbeacons_data_columns.txt";
350   }
351
352   public static FTSRestClientI getInstance()
353   {
354     if (instance == null)
355     {
356       instance = new TDBeaconsFTSRestClient();
357     }
358     return instance;
359   }
360
361   private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
362
363   public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
364   {
365     if (allDefaultDisplayedStructureDataColumns == null
366             || allDefaultDisplayedStructureDataColumns.isEmpty())
367     {
368       allDefaultDisplayedStructureDataColumns = new ArrayList<>();
369       allDefaultDisplayedStructureDataColumns
370               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
371     }
372     return allDefaultDisplayedStructureDataColumns;
373   }
374
375   @Override
376   public String[] getPreferencesColumnsFor(PreferenceSource source)
377   {
378     String[] columnNames = null;
379     switch (source)
380     {
381     case SEARCH_SUMMARY:
382       columnNames = new String[] { "", "Display", "Group" };
383       break;
384     case STRUCTURE_CHOOSER:
385       columnNames = new String[] { "", "Display", "Group" };
386       break;
387     case PREFERENCES:
388       columnNames = new String[] { "3DB Beacons Field", "Show in search summary",
389           "Show in structure summary" };
390       break;
391     default:
392       break;
393     }
394     return columnNames;
395   }
396 }