1ee7f372f745b820f4a9c7e0657b1acc19c56188
[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
10 import javax.ws.rs.core.MediaType;
11
12 import org.json.simple.parser.ParseException;
13
14 import com.sun.jersey.api.client.Client;
15 import com.sun.jersey.api.client.ClientResponse;
16 import com.sun.jersey.api.client.WebResource;
17 import com.sun.jersey.api.client.config.DefaultClientConfig;
18
19 import jalview.datamodel.SequenceI;
20 import jalview.fts.api.FTSData;
21 import jalview.fts.api.FTSDataColumnI;
22 import jalview.fts.api.FTSRestClientI;
23 import jalview.fts.core.FTSRestClient;
24 import jalview.fts.core.FTSRestRequest;
25 import jalview.fts.core.FTSRestResponse;
26 import jalview.fts.service.pdb.PDBFTSRestClient;
27 import jalview.util.JSONUtils;
28 import jalview.util.MessageManager;
29 import jalview.util.Platform;
30
31 public class TDBeaconsFTSRestClient extends FTSRestClient
32 {
33   private static final String DEFAULT_THREEDBEACONS_DOMAIN = 
34           "https://wwwdev.ebi.ac.uk/pdbe/pdbe-kb/3dbeacons-hub-api/uniprot/";
35   
36   private static FTSRestClientI instance = null;
37   
38   @SuppressWarnings("unchecked")
39   @Override
40   public FTSRestResponse executeRequest(FTSRestRequest tdbRestRequest)
41           throws Exception
42   {
43     try
44     {
45       // Removed wantedFields, sortParam & facetPivot from PDBFTSRClient
46       String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
47               tdbRestRequest.getWantedFields());
48       int responseSize = (tdbRestRequest.getResponseSize() == 0)
49               ? getDefaultResponsePageSize()
50               : tdbRestRequest.getResponseSize();
51       
52       String query = tdbRestRequest.getFieldToSearchBy()
53               + tdbRestRequest.getSearchTerm();
54       Client client;
55       Class<ClientResponse> clientResponseClass;
56       if (Platform.isJS())
57       {
58         // JavaScript only
59         client = (Client) (Object) new jalview.javascript.web.Client();
60         clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
61       }
62       else
63       /**
64        * Java only
65        * @j2sIgnore
66        */
67       {
68         client = Client.create(new DefaultClientConfig());
69         clientResponseClass = ClientResponse.class;
70       }
71       WebResource webResource;
72       webResource = client.resource(DEFAULT_THREEDBEACONS_DOMAIN)
73               .queryParam("P",query);
74       URI uri = webResource.getURI();
75         
76       System.out.println(uri);
77         
78       // Execute the REST request
79       ClientResponse clientResponse = webResource
80               .accept(MediaType.APPLICATION_JSON).get(clientResponseClass);
81   
82       // Get the JSON string from the response object or directly from the
83       // client (JavaScript)
84       Map<String, Object> jsonObj = null;
85       String responseString = null;
86   
87       System.out.println("query >>>>>>> " + tdbRestRequest.toString());
88         
89       // Check the response status and report exception if one occurs
90       int responseStatus = clientResponse.getStatus();
91       switch (responseStatus)
92       {
93       // if succesful
94       case 200:
95         if (Platform.isJS())
96         {
97           jsonObj = clientResponse.getEntity(Map.class);
98         }
99         else
100         {
101           responseString = clientResponse.getEntity(String.class);
102         }
103         break;
104       case 400:
105         throw new Exception(parseJsonExceptionString(responseString));
106       default:
107         throw new Exception(
108                 getMessageByHTTPStatusCode(responseStatus, "3DBeacons"));
109       }
110       // Process the response and return the result to the caller.
111       return parseTDBeaconsJsonResponse(responseString, jsonObj, tdbRestRequest);
112     } catch (Exception e)
113     {
114       String exceptionMsg = e.getMessage();
115       if (exceptionMsg.contains("SocketException"))
116       {
117         // No internet connection
118         throw new Exception(MessageManager.getString(
119                 "exception.unable_to_detect_internet_connection"));
120       }
121       else if (exceptionMsg.contains("UnknownHostException"))
122       {
123         // The server is unreachable
124         throw new Exception(MessageManager.formatMessage(
125                 "exception.fts_server_unreachable", "3DB Hub"));
126       }
127       else
128       {
129         throw e;
130       }
131     }
132       
133   }
134   
135   public static FTSRestResponse parseTDBeaconsJsonResponse(
136           String tdbJsonResponseString, FTSRestRequest tdbRestRequest)
137   {
138     return parseTDBeaconsJsonResponse(tdbJsonResponseString,
139             (Map<String, Object>) null, tdbRestRequest);
140   }
141   
142   @SuppressWarnings("unchecked")
143   public static FTSRestResponse parseTDBeaconsJsonResponse(String tdbJsonResponseString,
144           Map<String, Object> jsonObj, FTSRestRequest tdbRestRequest)
145   {
146     FTSRestResponse searchResult = new FTSRestResponse();
147     //searchResult.setNumberOfItemsFound(1);
148     List<FTSData> result = null;
149     
150     try
151     {
152       if (jsonObj == null)
153       {
154         jsonObj = (Map<String, Object>) JSONUtils.parse(tdbJsonResponseString);
155       }
156       Map<String, Object> tdbEntry = (Map<String, Object>) jsonObj.get("uniprot_entry");
157       //String seqLength = tdbEntry.get("sequence_length").toString();
158       int seqLength = Integer.valueOf(tdbEntry.get("sequence_length").toString());
159       
160       // tdbStructures is the list of found structures
161 //      Map<String, Object> tdbStructures = (Map<String, Object>) jsonObj.get("structures");
162       Object[] structures = (Object[]) jsonObj.get("structures");
163       String accessName = ((Map<String, Object>) jsonObj.get("uniprot_entry"))
164               .get("ac").toString();
165       // this is to be modified
166       int numFound = structures.length;
167 //      if (numFound > 0)
168 //      {
169 //        
170 //        result = new ArrayList<>();
171 //        List<String> models;
172 //        //= ((Map<String, Object>) jsonObj.get("structures"))
173 //                //.get("model_identifier").toString();
174 //        for (Iterator<String> modelsIter = models.iterator(); modelsIter.hasNext();)
175 //                .hasNext();)
176 //        {
177 //          Map<String, Object> doc = (Map<String, Object>) docIter.next();
178 //          result.add(getFTSData(doc, tdbRestRequest));
179 //        }
180         searchResult.setNumberOfItemsFound(numFound); 
181         // searchResult.setAccessionName(accessName); ?usefulness?       
182 //        searchResult.setSearchSummary(result);
183 //        
184 //      }
185     } catch (ParseException e)
186     {
187       e.printStackTrace();
188     }
189     return searchResult;
190   }
191
192 //  private static FTSData getFTSData(Map<String, Object> doc,
193 //          FTSRestRequest tdbRestRequest)
194 //  {
195 //    String primaryKey = null;
196 //
197 //    Object[] summaryRowData;
198 //
199 //    Collection<FTSDataColumnI> displayFields = tdbRestRequest.getWantedFields();
200 //    int colCounter = 0;
201 //    summaryRowData = new Object[displayFields.size() + 1];
202 // 
203 //    return null;
204 //  }
205
206   private String parseJsonExceptionString(String jsonErrorString)
207   {
208     // TODO Auto-generated method stub
209     return null;
210   }
211
212   @Override
213   public String getColumnDataConfigFileName()
214   {
215     // TODO Auto-generated method stub
216     return null;
217   }
218   
219   public static FTSRestClientI getInstance()
220   {
221     if (instance == null)
222     {
223       instance = new TDBeaconsFTSRestClient();
224     }
225     return instance;
226   }
227   
228   private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
229
230   public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
231   {
232     if (allDefaultDisplayedStructureDataColumns == null
233             || allDefaultDisplayedStructureDataColumns.isEmpty())
234     {
235       allDefaultDisplayedStructureDataColumns = new ArrayList<>();
236       allDefaultDisplayedStructureDataColumns
237               .addAll(super.getAllDefaultDisplayedFTSDataColumns());
238     }
239     return allDefaultDisplayedStructureDataColumns;
240   }
241   
242 }