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