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