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.
21 package jalview.fts.service.pdb;
23 import jalview.bin.Instance;
24 import jalview.datamodel.SequenceI;
25 import jalview.fts.api.FTSData;
26 import jalview.fts.api.FTSDataColumnI;
27 import jalview.fts.api.FTSRestClientI;
28 import jalview.fts.core.FTSRestClient;
29 import jalview.fts.core.FTSRestRequest;
30 import jalview.fts.core.FTSRestResponse;
31 import jalview.util.JSONUtils;
32 import jalview.util.MessageManager;
33 import jalview.util.Platform;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Iterator;
39 import java.util.List;
41 import java.util.Objects;
43 import javax.ws.rs.core.MediaType;
45 import org.json.simple.parser.ParseException;
47 import com.sun.jersey.api.client.Client;
48 import com.sun.jersey.api.client.ClientResponse;
49 import com.sun.jersey.api.client.WebResource;
50 import com.sun.jersey.api.client.config.DefaultClientConfig;
53 * A rest client for querying the Search endpoint of the PDB API
57 public class PDBFTSRestClient extends FTSRestClient
60 public static FTSRestClientI getInstance()
62 Instance j = Instance.getInstance();
63 return (j.pdbFTSRestClient == null
64 ? j.pdbFTSRestClient = new PDBFTSRestClient()
65 : j.pdbFTSRestClient);
68 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
70 private PDBFTSRestClient()
72 // singleton -- use getInstance()
76 * Takes a PDBRestRequest object and returns a response upon execution
78 * @param pdbRestRequest
79 * the PDBRestRequest instance to be processed
80 * @return the pdbResponse object for the given request
83 @SuppressWarnings({ "unused", "unchecked" })
85 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
90 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
91 pdbRestRequest.getWantedFields());
92 int responseSize = (pdbRestRequest.getResponseSize() == 0)
93 ? getDefaultResponsePageSize()
94 : pdbRestRequest.getResponseSize();
95 int offSet = pdbRestRequest.getOffSet();
96 String sortParam = null;
97 if (pdbRestRequest.getFieldToSortBy() == null
98 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
104 if (pdbRestRequest.getFieldToSortBy()
105 .equalsIgnoreCase("Resolution"))
107 sortParam = pdbRestRequest.getFieldToSortBy()
108 + (pdbRestRequest.isAscending() ? " asc" : " desc");
112 sortParam = pdbRestRequest.getFieldToSortBy()
113 + (pdbRestRequest.isAscending() ? " desc" : " asc");
117 String facetPivot = (pdbRestRequest.getFacetPivot() == null
118 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
119 : pdbRestRequest.getFacetPivot();
120 String facetPivotMinCount = String
121 .valueOf(pdbRestRequest.getFacetPivotMinCount());
123 String query = pdbRestRequest.getFieldToSearchBy()
124 + pdbRestRequest.getSearchTerm()
125 + (pdbRestRequest.isAllowEmptySeq() ? ""
126 : " AND molecule_sequence:['' TO *]")
127 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
128 : " AND status:REL");
130 // Build request parameters for the REST Request
132 // BH 2018 the trick here is to coerce the classes in Javascript to be
133 // different from the ones in Java yet still allow this to be correct for Java
135 Class<ClientResponse> clientResponseClass;
138 // JavaScript only -- coerce types to Java types for Java
139 client = (Client) (Object) new jalview.javascript.web.Client();
140 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
149 client = Client.create(new DefaultClientConfig());
150 clientResponseClass = ClientResponse.class;
153 WebResource webResource;
154 if (pdbRestRequest.isFacet())
156 webResource = client.resource(PDB_SEARCH_ENDPOINT)
157 .queryParam("wt", "json").queryParam("fl", wantedFields)
158 .queryParam("rows", String.valueOf(responseSize))
159 .queryParam("q", query)
160 .queryParam("start", String.valueOf(offSet))
161 .queryParam("sort", sortParam).queryParam("facet", "true")
162 .queryParam("facet.pivot", facetPivot)
163 .queryParam("facet.pivot.mincount", facetPivotMinCount);
167 webResource = client.resource(PDB_SEARCH_ENDPOINT)
168 .queryParam("wt", "json").queryParam("fl", wantedFields)
169 .queryParam("rows", String.valueOf(responseSize))
170 .queryParam("start", String.valueOf(offSet))
171 .queryParam("q", query).queryParam("sort", sortParam);
174 URI uri = webResource.getURI();
176 System.out.println(uri);
178 // Execute the REST request
179 ClientResponse clientResponse = webResource
180 .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
182 int status = clientResponse.getStatus();
184 // Get the JSON string from the response object or directly from the
185 // client (JavaScript)
186 Map<String, Object> jsonObj = (Platform.isJS() && status == 200
187 ? clientResponse.getEntity(Map.class)
189 String responseString = (jsonObj == null
190 ? clientResponse.getEntity(String.class)
193 // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
195 // Check the response status and report exception if one occurs
201 throw new Exception(parseJsonExceptionString(responseString));
203 throw new Exception(getMessageByHTTPStatusCode(status, "PDB"));
206 // Make redundant objects eligible for garbage collection to conserve
208 clientResponse = null;
211 // Process the response and return the result to the caller.
212 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
213 } catch (Exception e)
215 String exceptionMsg = e.getMessage();
216 if (exceptionMsg.contains("SocketException"))
218 // No internet connection
219 throw new Exception(MessageManager.getString(
220 "exception.unable_to_detect_internet_connection"));
222 else if (exceptionMsg.contains("UnknownHostException"))
224 // The server 'www.ebi.ac.uk' is unreachable
225 throw new Exception(MessageManager.formatMessage(
226 "exception.fts_server_unreachable", "PDB Solr"));
236 * Process error response from PDB server if/when one occurs.
238 * @param jsonResponse
239 * the JSON string containing error message from the server
240 * @return the processed error message from the JSON string
242 @SuppressWarnings("unchecked")
243 public static String parseJsonExceptionString(String jsonErrorResponse)
245 StringBuilder errorMessage = new StringBuilder(
246 "\n============= PDB Rest Client RunTime error =============\n");
250 // "responseHeader":{
254 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
255 // "fl":"pdb_id,title,experimental_method,resolution",
257 // "sort":"overall_quality desc",
260 // "response":{"numFound":1,"start":0,"docs":[
262 // "experimental_method":["X-ray diffraction"],
264 // "resolution":2.46,
265 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
270 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
271 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
273 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
274 .get("responseHeader");
275 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
276 String status = responseHeader.get("status").toString();
277 String message = errorResponse.get("msg").toString();
278 String query = paramsObj.get("q").toString();
279 String fl = paramsObj.get("fl").toString();
281 errorMessage.append("Status: ").append(status).append("\n");
282 errorMessage.append("Message: ").append(message).append("\n");
283 errorMessage.append("query: ").append(query).append("\n");
284 errorMessage.append("fl: ").append(fl).append("\n");
286 } catch (ParseException e)
290 return errorMessage.toString();
294 * Parses the JSON response string from PDB REST API. The response is dynamic
295 * hence, only fields specifically requested for in the 'wantedFields'
296 * parameter is fetched/processed
298 * @param pdbJsonResponseString
299 * the JSON string to be parsed
300 * @param pdbRestRequest
301 * the request object which contains parameters used to process the
305 public static FTSRestResponse parsePDBJsonResponse(
306 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
308 return parsePDBJsonResponse(pdbJsonResponseString,
309 (Map<String, Object>) null, pdbRestRequest);
312 @SuppressWarnings("unchecked")
313 public static FTSRestResponse parsePDBJsonResponse(
314 String pdbJsonResponseString, Map<String, Object> jsonObj,
315 FTSRestRequest pdbRestRequest)
317 FTSRestResponse searchResult = new FTSRestResponse();
318 List<FTSData> result = null;
323 jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
325 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
326 String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
327 .get("QTime").toString();
328 int numFound = Integer
329 .valueOf(pdbResponse.get("numFound").toString());
332 result = new ArrayList<>();
333 List<Object> docs = (List<Object>) pdbResponse.get("docs");
334 for (Iterator<Object> docIter = docs.iterator(); docIter
337 Map<String, Object> doc = (Map<String, Object>) docIter.next();
338 result.add(getFTSData(doc, pdbRestRequest));
340 searchResult.setNumberOfItemsFound(numFound);
341 searchResult.setResponseTime(queryTime);
342 searchResult.setSearchSummary(result);
344 } catch (ParseException e)
351 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
352 FTSRestRequest request)
355 String primaryKey = null;
357 Object[] summaryRowData;
359 SequenceI associatedSequence;
361 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
362 SequenceI associatedSeq = request.getAssociatedSequence();
364 summaryRowData = new Object[(associatedSeq != null)
365 ? diplayFields.size() + 1
366 : diplayFields.size()];
367 if (associatedSeq != null)
369 associatedSequence = associatedSeq;
370 summaryRowData[0] = associatedSequence;
374 for (FTSDataColumnI field : diplayFields)
376 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
377 : pdbJsonDoc.get(field.getCode()).toString();
378 if (field.isPrimaryKeyColumn())
380 primaryKey = fieldData;
381 summaryRowData[colCounter++] = primaryKey;
383 else if (fieldData == null || fieldData.isEmpty())
385 summaryRowData[colCounter++] = null;
391 summaryRowData[colCounter++] = (field.getDataType()
392 .getDataTypeClass() == Integer.class)
393 ? Integer.valueOf(fieldData)
394 : (field.getDataType()
395 .getDataTypeClass() == Double.class)
396 ? Double.valueOf(fieldData)
397 : sanitiseData(fieldData);
398 } catch (Exception e)
401 System.out.println("offending value:" + fieldData);
406 final String primaryKey1 = primaryKey;
408 final Object[] summaryRowData1 = summaryRowData;
412 public Object[] getSummaryData()
414 return summaryRowData1;
418 public Object getPrimaryKey()
424 * Returns a string representation of this object;
427 public String toString()
429 StringBuilder summaryFieldValues = new StringBuilder();
430 for (Object summaryField : summaryRowData1)
432 summaryFieldValues.append(
433 summaryField == null ? " " : summaryField.toString())
436 return summaryFieldValues.toString();
440 * Returns hash code value for this object
443 public int hashCode()
445 return Objects.hash(primaryKey1, this.toString());
449 public boolean equals(Object that)
451 return this.toString().equals(that.toString());
456 private static String sanitiseData(String data)
458 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
459 .replaceAll("\\[", "").replaceAll("\\]", "")
460 .replaceAll("\",\"", ", ").replaceAll("\"", "");
465 public String getColumnDataConfigFileName()
467 return "/fts/pdb_data_columns.txt";
470 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
472 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
474 if (allDefaultDisplayedStructureDataColumns == null
475 || allDefaultDisplayedStructureDataColumns.isEmpty())
477 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
478 allDefaultDisplayedStructureDataColumns
479 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
481 return allDefaultDisplayedStructureDataColumns;