JAL-1563 Further increased swing timer for search textfield to 2500ms, removed 1200ms...
[jalview.git] / src / jalview / fts / service / uniprot / UniProtFTSRestClient.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
22 package jalview.fts.service.uniprot;
23
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
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.List;
34 import java.util.Objects;
35
36 import javax.ws.rs.core.MediaType;
37
38 import com.sun.jersey.api.client.Client;
39 import com.sun.jersey.api.client.ClientResponse;
40 import com.sun.jersey.api.client.WebResource;
41 import com.sun.jersey.api.client.config.ClientConfig;
42 import com.sun.jersey.api.client.config.DefaultClientConfig;
43
44 public class UniProtFTSRestClient extends FTSRestClient
45 {
46   private static FTSRestClientI instance = null;
47
48   public static final String UNIPROT_SEARCH_ENDPOINT = "http://www.uniprot.org/uniprot/?";
49
50   @Override
51   public FTSRestResponse executeRequest(FTSRestRequest uniportRestRequest)
52   {
53     ClientConfig clientConfig = new DefaultClientConfig();
54     Client client = Client.create(clientConfig);
55
56     String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(uniportRestRequest
57             .getWantedFields());
58     int responseSize = (uniportRestRequest.getResponseSize() == 0) ? getDefaultResponsePageSize()
59             : uniportRestRequest.getResponseSize();
60
61     int offSet = (uniportRestRequest.getOffSet() == 0) ? getDefaultResponsePageSize()
62             : uniportRestRequest.getOffSet();
63
64     String query = uniportRestRequest.getFieldToSearchBy()
65             .equalsIgnoreCase("Search All") ? uniportRestRequest
66             .getSearchTerm()
67             : uniportRestRequest.getFieldToSearchBy() + ":"
68                     + uniportRestRequest.getSearchTerm();
69
70     // + (uniportRestRequest.isAllowUnpublishedEntries() ? ""
71     // : " AND status:REL");
72     // System.out.println(">>>>> Query : " + query);
73     // System.out.println(">>>>> Columns : " + wantedFields);
74     WebResource webResource = null;
75     webResource = client.resource(UNIPROT_SEARCH_ENDPOINT)
76             .queryParam("format", "tab")
77             .queryParam("columns", wantedFields)
78             .queryParam("limit", String.valueOf(responseSize))
79             .queryParam("offset", String.valueOf(offSet))
80             .queryParam("sort", "score")
81             .queryParam("query", query);
82     // Execute the REST request
83     ClientResponse clientResponse = webResource
84             .accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
85     String uniProtTabDelimittedResponseString = clientResponse
86             .getEntity(String.class);
87     // Make redundant objects eligible for garbage collection to conserve
88     // memory
89     clientResponse = null;
90     client = null;
91     // System.out.println(">>>>> response : "
92     // + uniProtTabDelimittedResponseString);
93     return parseUniprotResponse(uniProtTabDelimittedResponseString,
94             uniportRestRequest);
95
96   }
97
98   public FTSRestResponse parseUniprotResponse(
99           String uniProtTabDelimittedResponseString,
100           FTSRestRequest uniprotRestRequest)
101   {
102     FTSRestResponse searchResult = new FTSRestResponse();
103     List<FTSData> result = null;
104     String[] foundDataRow = uniProtTabDelimittedResponseString.split("\n");
105     if (foundDataRow != null && foundDataRow.length > 0)
106     {
107       result = new ArrayList<FTSData>();
108       String titleRow = getDataColumnsFieldsAsTabDelimitedString(uniprotRestRequest
109               .getWantedFields());
110       // System.out.println(">>>>Title row : " + titleRow);
111       for (String dataRow : foundDataRow)
112       {
113         if (dataRow.equalsIgnoreCase(titleRow))
114         {
115           // System.out.println(">>>>>>>>>> matched!!!");
116           continue;
117         }
118         // System.out.println(dataRow);
119         result.add(getFTSData(dataRow, uniprotRestRequest));
120       }
121       searchResult.setNumberOfItemsFound(result.size());
122       searchResult.setSearchSummary(result);
123     }
124     return searchResult;
125   }
126
127   /**
128    * Takes a collection of FTSDataColumnI and converts its 'code' values into a
129    * tab delimited string.
130    * 
131    * @param dataColumnFields
132    *          the collection of FTSDataColumnI to process
133    * @return the generated comma delimited string from the supplied
134    *         FTSDataColumnI collection
135    */
136   private String getDataColumnsFieldsAsTabDelimitedString(
137           Collection<FTSDataColumnI> dataColumnFields)
138   {
139     String result = "";
140     if (dataColumnFields != null && !dataColumnFields.isEmpty())
141     {
142       StringBuilder returnedFields = new StringBuilder();
143       for (FTSDataColumnI field : dataColumnFields)
144       {
145         if (field.getName().equalsIgnoreCase("Uniprot Id"))
146         {
147           returnedFields.append("\t").append("Entry");
148         }
149         else
150         {
151           returnedFields.append("\t").append(field.getName());
152         }
153       }
154       returnedFields.deleteCharAt(0);
155       result = returnedFields.toString();
156     }
157     return result;
158   }
159   public static FTSData getFTSData(String tabDelimittedDataStr,
160           FTSRestRequest request)
161   {
162     String primaryKey = null;
163
164     Object[] summaryRowData;
165
166     Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
167     int colCounter = 0;
168     summaryRowData = new Object[diplayFields.size()];
169     String[] columns = tabDelimittedDataStr.split("\t");
170     for (FTSDataColumnI field : diplayFields)
171     {
172       try
173       {
174         String fieldData = columns[colCounter];
175         if (field.isPrimaryKeyColumn())
176         {
177           primaryKey = fieldData;
178           summaryRowData[colCounter++] = primaryKey;
179         }
180         else if (fieldData == null || fieldData.isEmpty())
181         {
182           summaryRowData[colCounter++] = null;
183         }
184         else
185         {
186           try
187           {
188             summaryRowData[colCounter++] = (field.getDataColumnClass() == Integer.class) ? Integer
189                     .valueOf(fieldData)
190                     : (field.getDataColumnClass() == Double.class) ? Double
191                             .valueOf(fieldData) : fieldData;
192           } catch (Exception e)
193           {
194             e.printStackTrace();
195               System.out.println("offending value:" + fieldData);
196           }
197         }
198       } catch (Exception e)
199       {
200         // e.printStackTrace();
201       }
202     }
203
204     final String primaryKey1 = primaryKey;
205
206     final Object[] summaryRowData1 = summaryRowData;
207     return new FTSData()
208     {
209       @Override
210       public Object[] getSummaryData()
211       {
212         return summaryRowData1;
213       }
214
215       @Override
216       public Object getPrimaryKey()
217       {
218         return primaryKey1;
219       }
220
221       /**
222        * Returns a string representation of this object;
223        */
224       @Override
225       public String toString()
226       {
227         StringBuilder summaryFieldValues = new StringBuilder();
228         for (Object summaryField : summaryRowData1)
229         {
230           summaryFieldValues.append(
231                   summaryField == null ? " " : summaryField.toString())
232                   .append("\t");
233         }
234         return summaryFieldValues.toString();
235       }
236
237       /**
238        * Returns hash code value for this object
239        */
240       @Override
241       public int hashCode()
242       {
243         return Objects.hash(primaryKey1, this.toString());
244       }
245     };
246   }
247
248
249   public static FTSRestClientI getInstance()
250   {
251     if (instance == null)
252     {
253       instance = new UniProtFTSRestClient();
254     }
255     return instance;
256   }
257
258   @Override
259   public String getColumnDataConfigFileName()
260   {
261     return "/fts/uniprot_data_columns.txt";
262   }
263
264 }