JAL-1563 Modified Uniprot data column configurations and improved implementation...
[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   public static FTSData getFTSData(String tabDelimittedDataStr,
123           FTSRestRequest request)
124   {
125     String primaryKey = null;
126
127     Object[] summaryRowData;
128
129     Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
130     int colCounter = 0;
131     summaryRowData = new Object[diplayFields.size()];
132     String[] columns = tabDelimittedDataStr.split("\t");
133     for (FTSDataColumnI field : diplayFields)
134     {
135       try
136       {
137         String fieldData = columns[colCounter];
138         if (field.isPrimaryKeyColumn())
139         {
140           primaryKey = fieldData;
141           summaryRowData[colCounter++] = primaryKey;
142         }
143         else if (fieldData == null || fieldData.isEmpty())
144         {
145           summaryRowData[colCounter++] = null;
146         }
147         else
148         {
149           try
150           {
151             summaryRowData[colCounter++] = (field.getDataColumnClass() == Integer.class) ? Integer
152                     .valueOf(fieldData)
153                     : (field.getDataColumnClass() == Double.class) ? Double
154                             .valueOf(fieldData) : fieldData;
155           } catch (Exception e)
156           {
157             e.printStackTrace();
158               System.out.println("offending value:" + fieldData);
159           }
160         }
161       } catch (Exception e)
162       {
163         // e.printStackTrace();
164       }
165     }
166
167     final String primaryKey1 = primaryKey;
168
169     final Object[] summaryRowData1 = summaryRowData;
170     return new FTSData()
171     {
172       @Override
173       public Object[] getSummaryData()
174       {
175         return summaryRowData1;
176       }
177
178       @Override
179       public Object getPrimaryKey()
180       {
181         return primaryKey1;
182       }
183
184       /**
185        * Returns a string representation of this object;
186        */
187       @Override
188       public String toString()
189       {
190         StringBuilder summaryFieldValues = new StringBuilder();
191         for (Object summaryField : summaryRowData1)
192         {
193           summaryFieldValues.append(
194                   summaryField == null ? " " : summaryField.toString())
195                   .append("\t");
196         }
197         return summaryFieldValues.toString();
198       }
199
200       /**
201        * Returns hash code value for this object
202        */
203       @Override
204       public int hashCode()
205       {
206         return Objects.hash(primaryKey1, this.toString());
207       }
208     };
209   }
210
211
212   public static FTSRestClientI getInstance()
213   {
214     if (instance == null)
215     {
216       instance = new UniProtFTSRestClient();
217     }
218     return instance;
219   }
220
221   @Override
222   public String getColumnDataConfigFileName()
223   {
224     return "/fts/uniprot_data_columns.txt";
225   }
226
227 }