2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
22 package jalview.fts.service.uniprot;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.List;
27 import java.util.Objects;
29 import javax.ws.rs.core.MediaType;
31 import com.sun.jersey.api.client.Client;
32 import com.sun.jersey.api.client.ClientResponse;
33 import com.sun.jersey.api.client.WebResource;
34 import com.sun.jersey.api.client.config.DefaultClientConfig;
36 import jalview.bin.Cache;
37 import jalview.bin.Console;
38 import jalview.fts.api.FTSData;
39 import jalview.fts.api.FTSDataColumnI;
40 import jalview.fts.api.FTSRestClientI;
41 import jalview.fts.core.FTSRestClient;
42 import jalview.fts.core.FTSRestRequest;
43 import jalview.fts.core.FTSRestResponse;
44 import jalview.util.MessageManager;
45 import jalview.util.Platform;
47 public class UniProtFTSRestClient extends FTSRestClient
49 private static final String DEFAULT_UNIPROT_DOMAIN = "https://legacy.uniprot.org";
53 Platform.addJ2SDirectDatabaseCall(DEFAULT_UNIPROT_DOMAIN);
56 private static FTSRestClientI instance = null;
58 public final String uniprotSearchEndpoint;
60 public UniProtFTSRestClient()
63 uniprotSearchEndpoint = Cache.getDefault("UNIPROT_DOMAIN",
64 DEFAULT_UNIPROT_DOMAIN) + "/uniprot/";
67 @SuppressWarnings("unchecked")
69 public FTSRestResponse executeRequest(FTSRestRequest uniprotRestRequest)
74 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
75 uniprotRestRequest.getWantedFields());
76 int responseSize = (uniprotRestRequest.getResponseSize() == 0)
77 ? getDefaultResponsePageSize()
78 : uniprotRestRequest.getResponseSize();
80 int offSet = uniprotRestRequest.getOffSet();
82 if (isAdvancedQuery(uniprotRestRequest.getSearchTerm()))
84 query = uniprotRestRequest.getSearchTerm();
88 query = uniprotRestRequest.getFieldToSearchBy()
89 .equalsIgnoreCase("Search All")
90 ? uniprotRestRequest.getSearchTerm()
92 + uniprotRestRequest.getSearchTerm()
93 : uniprotRestRequest.getFieldToSearchBy() + ":"
94 + uniprotRestRequest.getSearchTerm();
97 // BH 2018 the trick here is to coerce the classes in Javascript to be
98 // different from the ones in Java yet still allow this to be correct for
101 Class<ClientResponse> clientResponseClass;
104 // JavaScript only -- coerce types to Java types for Java
105 client = (Client) (Object) new jalview.javascript.web.Client();
106 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
116 client = Client.create(new DefaultClientConfig());
117 clientResponseClass = ClientResponse.class;
120 WebResource webResource = null;
121 webResource = client.resource(uniprotSearchEndpoint)
122 .queryParam("format", "tab")
123 .queryParam("columns", wantedFields)
124 .queryParam("limit", String.valueOf(responseSize))
125 .queryParam("offset", String.valueOf(offSet))
126 .queryParam("sort", "score").queryParam("query", query);
127 if (Console.isDebugEnabled())
129 Console.debug("Uniprot FTS Request: " + webResource.toString());
131 // Execute the REST request
132 ClientResponse clientResponse = webResource
133 .accept(MediaType.TEXT_PLAIN).get(clientResponseClass);
134 String uniProtTabDelimittedResponseString = clientResponse
135 .getEntity(String.class);
136 // Make redundant objects eligible for garbage collection to conserve
138 // System.out.println(">>>>> response : "
139 // + uniProtTabDelimittedResponseString);
140 if (clientResponse.getStatus() != 200)
142 String errorMessage = getMessageByHTTPStatusCode(
143 clientResponse.getStatus(), "Uniprot");
144 throw new Exception(errorMessage);
147 int xTotalResults = Platform.isJS() ? 1
148 : Integer.valueOf(clientResponse.getHeaders()
149 .get("X-Total-Results").get(0));
150 clientResponse = null;
152 return parseUniprotResponse(uniProtTabDelimittedResponseString,
153 uniprotRestRequest, xTotalResults);
154 } catch (Exception e)
156 String exceptionMsg = e.getMessage();
157 if (exceptionMsg.contains("SocketException"))
159 // No internet connection
160 throw new Exception(MessageManager.getString(
161 "exception.unable_to_detect_internet_connection"));
163 else if (exceptionMsg.contains("UnknownHostException"))
165 // The server 'http://www.uniprot.org' is unreachable
166 throw new Exception(MessageManager.formatMessage(
167 "exception.fts_server_unreachable", "Uniprot"));
176 public boolean isAdvancedQuery(String query)
178 if (query.contains(" AND ") || query.contains(" OR ")
179 || query.contains(" NOT ") || query.contains(" ! ")
180 || query.contains(" || ") || query.contains(" && ")
181 || query.contains(":") || query.contains("-"))
188 public FTSRestResponse parseUniprotResponse(
189 String uniProtTabDelimittedResponseString,
190 FTSRestRequest uniprotRestRequest, int xTotalResults)
192 FTSRestResponse searchResult = new FTSRestResponse();
193 List<FTSData> result = null;
194 if (uniProtTabDelimittedResponseString == null
195 || uniProtTabDelimittedResponseString.trim().isEmpty())
197 searchResult.setNumberOfItemsFound(0);
200 String[] foundDataRow = uniProtTabDelimittedResponseString.split("\n");
201 if (foundDataRow != null && foundDataRow.length > 0)
203 result = new ArrayList<>();
204 boolean firstRow = true;
205 for (String dataRow : foundDataRow)
207 // The first data row is usually the header data. This should be
208 // filtered out from the rest of the data See: JAL-2485
214 // System.out.println(dataRow);
215 result.add(getFTSData(dataRow, uniprotRestRequest));
217 searchResult.setNumberOfItemsFound(xTotalResults);
218 searchResult.setSearchSummary(result);
224 // * Takes a collection of FTSDataColumnI and converts its 'code' values into
226 // * tab delimited string.
228 // * @param dataColumnFields
229 // * the collection of FTSDataColumnI to process
230 // * @return the generated comma delimited string from the supplied
231 // * FTSDataColumnI collection
233 // private String getDataColumnsFieldsAsTabDelimitedString(
234 // Collection<FTSDataColumnI> dataColumnFields)
236 // String result = "";
237 // if (dataColumnFields != null && !dataColumnFields.isEmpty())
239 // StringBuilder returnedFields = new StringBuilder();
240 // for (FTSDataColumnI field : dataColumnFields)
242 // if (field.getName().equalsIgnoreCase("Uniprot Id"))
244 // returnedFields.append("\t").append("Entry");
248 // returnedFields.append("\t").append(field.getName());
251 // returnedFields.deleteCharAt(0);
252 // result = returnedFields.toString();
257 public static FTSData getFTSData(String tabDelimittedDataStr,
258 FTSRestRequest request)
260 String primaryKey = null;
262 Object[] summaryRowData;
264 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
266 summaryRowData = new Object[diplayFields.size()];
267 String[] columns = tabDelimittedDataStr.split("\t");
268 for (FTSDataColumnI field : diplayFields)
272 String fieldData = columns[colCounter];
273 if (field.isPrimaryKeyColumn())
275 primaryKey = fieldData;
276 summaryRowData[colCounter++] = primaryKey;
278 else if (fieldData == null || fieldData.isEmpty())
280 summaryRowData[colCounter++] = null;
286 summaryRowData[colCounter++] = (field.getDataType()
287 .getDataTypeClass() == Integer.class)
288 ? Integer.valueOf(fieldData.replace(",", ""))
289 : (field.getDataType()
290 .getDataTypeClass() == Double.class)
291 ? Double.valueOf(fieldData)
293 } catch (Exception e)
296 System.out.println("offending value:" + fieldData);
299 } catch (Exception e)
301 // e.printStackTrace();
305 final String primaryKey1 = primaryKey;
307 final Object[] summaryRowData1 = summaryRowData;
311 public Object[] getSummaryData()
313 return summaryRowData1;
317 public Object getPrimaryKey()
323 * Returns a string representation of this object;
326 public String toString()
328 StringBuilder summaryFieldValues = new StringBuilder();
329 for (Object summaryField : summaryRowData1)
331 summaryFieldValues.append(
332 summaryField == null ? " " : summaryField.toString())
335 return summaryFieldValues.toString();
339 * Returns hash code value for this object
342 public int hashCode()
344 return Objects.hash(primaryKey1, this.toString());
348 public boolean equals(Object that)
350 return this.toString().equals(that.toString());
355 public static FTSRestClientI getInstance()
357 if (instance == null)
359 instance = new UniProtFTSRestClient();
365 public String getColumnDataConfigFileName()
367 return "/fts/uniprot_data_columns.txt";