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