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