JAL-3829 attempt to fix my changes to follow the Jira issue
[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.core.FTSRestClient;
25 import jalview.fts.core.FTSRestRequest;
26 import jalview.fts.core.FTSRestResponse;
27 import jalview.fts.service.pdb.PDBFTSRestClient;
28 import jalview.util.JSONUtils;
29 import jalview.util.MessageManager;
30 import jalview.util.Platform;
31
32 public class TDBeaconsFTSRestClient extends FTSRestClient
33 {
34   private static final String DEFAULT_THREEDBEACONS_DOMAIN = 
35           "https://wwwdev.ebi.ac.uk/pdbe/pdbe-kb/3dbeacons-hub-api/uniprot/";
36   
37   private static FTSRestClientI instance = null;
38   
39   protected TDBeaconsFTSRestClient()
40   {   
41   }
42   
43   @SuppressWarnings("unchecked")
44   @Override
45   public FTSRestResponse executeRequest(FTSRestRequest tdbRestRequest)
46           throws Exception
47   {
48     try
49     {
50       String query = tdbRestRequest.getFieldToSearchBy()
51               + tdbRestRequest.getSearchTerm();
52       Client client;
53       Class<ClientResponse> clientResponseClass;
54       if (Platform.isJS())
55       {
56         // JavaScript only
57         client = (Client) (Object) new jalview.javascript.web.Client();
58         clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
59       }
60       else
61       /**
62        * Java only
63        * @j2sIgnore
64        */
65       {
66         client = Client.create(new DefaultClientConfig());
67         clientResponseClass = ClientResponse.class;
68       }
69       WebResource webResource;
70       webResource = client.resource(DEFAULT_THREEDBEACONS_DOMAIN)
71               .path(query);
72       URI uri = webResource.getURI();
73       System.out.println(uri.toString());
74         
75       // Execute the REST request
76       ClientResponse clientResponse = webResource
77               .accept(MediaType.APPLICATION_JSON).get(clientResponseClass);
78   
79       // Get the JSON string from the response object or directly from the
80       // client (JavaScript)
81       Map<String, Object> jsonObj = null;
82       String responseString = null;
83   
84       // Check the response status and report exception if one occurs
85       int responseStatus = clientResponse.getStatus();
86       switch (responseStatus)
87       {
88       // if success
89       case 200:
90         if (Platform.isJS())
91         {
92           jsonObj = clientResponse.getEntity(Map.class);
93         }
94         else
95         {
96           responseString = clientResponse.getEntity(String.class);
97         }
98         break;
99       case 400:
100         throw new Exception(parseJsonExceptionString(responseString));
101       default:
102         throw new Exception(
103                 getMessageByHTTPStatusCode(responseStatus, "3DBeacons"));
104       }
105       // Process the response and return the result to the caller.
106       return parseTDBeaconsJsonResponse(responseString, jsonObj, tdbRestRequest);
107     } catch (Exception e)
108     {
109       String exceptionMsg = e.getMessage();
110       if (exceptionMsg.contains("SocketException"))
111       {
112         // No internet connection
113         throw new Exception(MessageManager.getString(
114                 "exception.unable_to_detect_internet_connection"));
115       }
116       else if (exceptionMsg.contains("UnknownHostException"))
117       {
118         // The server is unreachable
119         throw new Exception(MessageManager.formatMessage(
120                 "exception.fts_server_unreachable", "3DB Hub"));
121       }
122       else
123       {
124         throw e;
125       }
126     }
127       
128   }
129   
130   public String setSearchTerm(String term) {
131     return term;
132   }
133   
134   public static FTSRestResponse parseTDBeaconsJsonResponse(
135           String tdbJsonResponseString, FTSRestRequest tdbRestRequest)
136   {
137     return parseTDBeaconsJsonResponse(tdbJsonResponseString,
138             (Map<String, Object>) null, tdbRestRequest);
139   }
140   
141   @SuppressWarnings("unchecked")
142   public static FTSRestResponse parseTDBeaconsJsonResponse(String tdbJsonResponseString,
143           Map<String, Object> jsonObj, FTSRestRequest tdbRestRequest)
144   {
145     FTSRestResponse searchResult = new FTSRestResponse();
146     List<FTSData> result = null;
147     
148     try
149     {
150       if (jsonObj == null)
151       {
152         jsonObj = (Map<String, Object>) JSONUtils.parse(tdbJsonResponseString);
153       }
154       
155       Object uniprot_entry = jsonObj.get("uniprot_entry"); 
156       Long seqLength = (Long) ((Map<String, Object>) jsonObj.get("uniprot_entry")).get("sequence_length");
157       //System.out.println(uniprot_entry);
158       //System.out.println(jsonObj);
159       //System.out.println("seqLenght :" + seqLength);
160       
161       //Map<String, Object> tdbResponse = (Map<String, Object>) jsonObj.get("structures");
162       List<Object> structures = (List<Object>) jsonObj.get("structures");
163       result = new ArrayList<>();
164       
165       int numFound = 0;
166       for (Iterator<Object> strucIter = structures.iterator(); strucIter.hasNext();)
167       {
168         Map<String, Object> structure = (Map<String, Object>) strucIter.next();
169         result.add(getFTSData(structure, tdbRestRequest));
170         numFound++;
171         //System.out.println(structure);
172       }
173       
174       System.out.println("1 : " + structures.get(1));
175       searchResult.setNumberOfItemsFound(numFound); 
176       searchResult.setSearchSummary(result);
177       searchResult.setSequenceLength(seqLength);
178         
179     } catch (ParseException e)
180     {
181       e.printStackTrace();
182     }
183     return searchResult;
184   }
185
186 private static FTSData getFTSData(Map<String, Object> tdbJsonStructure,
187           FTSRestRequest tdbRequest)
188   {
189     // TODO Auto-generated method stub
190     String primaryKey = null;
191     Object[] summaryRowData;
192     Collection<FTSDataColumnI> displayFields = tdbRequest.getWantedFields();
193     int colCounter = 0;
194     summaryRowData = new Object[displayFields.size()];
195     
196     for (FTSDataColumnI field : displayFields) {
197       System.out.println("Field " + field);
198       String fieldData = (tdbJsonStructure.get(field.getCode()) == null) ? " " 
199               : tdbJsonStructure.get(field.getCode()).toString();
200       System.out.println("Field Data : " + fieldData);
201       if (field.isPrimaryKeyColumn())
202       {
203         primaryKey = fieldData;
204         summaryRowData[colCounter++] = primaryKey;
205       }
206       else if (fieldData == null || fieldData.isEmpty())
207       {
208         summaryRowData[colCounter++] = null;
209       }
210       else 
211       {
212         try
213         {
214           summaryRowData[colCounter++] = (field.getDataType()
215                   .getDataTypeClass() == Integer.class)
216                           ? Integer.valueOf(fieldData)
217                           : (field.getDataType()
218                                   .getDataTypeClass() == Double.class)
219                                           ? Double.valueOf(fieldData)
220                                           : fieldData;
221         } catch (Exception e)
222         {
223           //e.printStackTrace();
224           System.out.println("offending value:" + fieldData);
225         }
226       }
227     }
228     final String primaryKey1 = primaryKey;
229     final Object[] summaryRowData1 = summaryRowData;
230     
231     return new FTSData()
232     {
233
234       @Override
235       public Object[] getSummaryData()
236       {
237         return summaryRowData1;
238       }
239
240       @Override
241       public Object getPrimaryKey()
242       {
243         return primaryKey1;
244       }
245       
246       /**
247        * Returns a string representation of this object;
248        */
249       @Override
250       public String toString()
251       {
252         StringBuilder summaryFieldValues = new StringBuilder();
253         for (Object summaryField : summaryRowData1)
254         {
255           summaryFieldValues.append(
256                   summaryField == null ? " " : summaryField.toString())
257                   .append("\t");
258         }
259         return summaryFieldValues.toString();
260       }
261       
262       /**
263        * Returns hash code value for this object
264        */
265       @Override
266       public int hashCode()
267       {
268         return Objects.hash(primaryKey1, this.toString());
269       }
270
271       @Override
272       public boolean equals(Object that)
273       {
274         return this.toString().equals(that.toString());
275       }
276     };
277   }
278
279 //  private static FTSData getFTSData(Map<String, Object> doc,
280 //          FTSRestRequest tdbRestRequest)
281 //  {
282 //    String primaryKey = null;
283 //
284 //    Object[] summaryRowData;
285 //
286 //    Collection<FTSDataColumnI> displayFields = tdbRestRequest.getWantedFields();
287 //    int colCounter = 0;
288 //    summaryRowData = new Object[displayFields.size() + 1];
289 // 
290 //    return null;
291 //  }
292
293   private String parseJsonExceptionString(String jsonErrorString)
294   {
295     // TODO Auto-generated method stub
296     return null;
297   }
298
299   @Override
300   public String getColumnDataConfigFileName()
301   {
302     return "/fts/tdbeacons_data_columns.txt";
303   }
304   
305   public static FTSRestClientI getInstance()
306   {
307     if (instance == null)
308     {
309       instance = new TDBeaconsFTSRestClient();
310     }
311     return instance;
312   }
313   
314   private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
315
316   public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
317   {
318     if (allDefaultDisplayedStructureDataColumns == null
319             || allDefaultDisplayedStructureDataColumns.isEmpty())
320     {
321       allDefaultDisplayedStructureDataColumns = new ArrayList<>();
322       allDefaultDisplayedStructureDataColumns
323               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
324     }
325     return allDefaultDisplayedStructureDataColumns;
326   }
327   
328 }