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;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.List;
29 import java.util.Objects;
31 import javax.ws.rs.core.MediaType;
33 import org.json.simple.parser.ParseException;
35 import com.sun.jersey.api.client.Client;
36 import com.sun.jersey.api.client.ClientResponse;
37 import com.sun.jersey.api.client.WebResource;
38 import com.sun.jersey.api.client.config.DefaultClientConfig;
40 import jalview.bin.ApplicationSingletonProvider;
41 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
42 import jalview.datamodel.SequenceI;
43 import jalview.fts.api.FTSData;
44 import jalview.fts.api.FTSDataColumnI;
45 import jalview.fts.api.FTSRestClientI;
46 import jalview.fts.core.FTSRestClient;
47 import jalview.fts.core.FTSRestRequest;
48 import jalview.fts.core.FTSRestResponse;
49 import jalview.util.JSONUtils;
50 import jalview.util.MessageManager;
51 import jalview.util.Platform;
54 * A rest client for querying the Search endpoint of the PDB API
58 public class PDBFTSRestClient extends FTSRestClient implements ApplicationSingletonI
60 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
62 public static FTSRestClientI getInstance()
64 return (FTSRestClientI) ApplicationSingletonProvider
65 .getInstance(PDBFTSRestClient.class);
68 protected PDBFTSRestClient()
73 * Takes a PDBRestRequest object and returns a response upon execution
75 * @param pdbRestRequest
76 * the PDBRestRequest instance to be processed
77 * @return the pdbResponse object for the given request
80 @SuppressWarnings({ "unused", "unchecked" })
82 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
87 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
88 pdbRestRequest.getWantedFields());
89 int responseSize = (pdbRestRequest.getResponseSize() == 0)
90 ? getDefaultResponsePageSize()
91 : pdbRestRequest.getResponseSize();
92 int offSet = pdbRestRequest.getOffSet();
93 String sortParam = null;
94 if (pdbRestRequest.getFieldToSortBy() == null
95 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
101 if (pdbRestRequest.getFieldToSortBy()
102 .equalsIgnoreCase("Resolution"))
104 sortParam = pdbRestRequest.getFieldToSortBy()
105 + (pdbRestRequest.isAscending() ? " asc" : " desc");
109 sortParam = pdbRestRequest.getFieldToSortBy()
110 + (pdbRestRequest.isAscending() ? " desc" : " asc");
114 String facetPivot = (pdbRestRequest.getFacetPivot() == null
115 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
116 : pdbRestRequest.getFacetPivot();
117 String facetPivotMinCount = String
118 .valueOf(pdbRestRequest.getFacetPivotMinCount());
120 String query = pdbRestRequest.getFieldToSearchBy()
121 + pdbRestRequest.getSearchTerm()
122 + (pdbRestRequest.isAllowEmptySeq() ? ""
123 : " AND molecule_sequence:['' TO *]")
124 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
125 : " AND status:REL");
127 // Build request parameters for the REST Request
129 // BH 2018 the trick here is to coerce the classes in Javascript to be
130 // different from the ones in Java yet still allow this to be correct for Java
132 Class<ClientResponse> clientResponseClass;
135 // JavaScript only -- coerce types to Java types for Java
136 client = (Client) (Object) new jalview.javascript.web.Client();
137 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
146 client = Client.create(new DefaultClientConfig());
147 clientResponseClass = ClientResponse.class;
150 WebResource webResource;
151 if (pdbRestRequest.isFacet())
153 webResource = client.resource(PDB_SEARCH_ENDPOINT)
154 .queryParam("wt", "json").queryParam("fl", wantedFields)
155 .queryParam("rows", String.valueOf(responseSize))
156 .queryParam("q", query)
157 .queryParam("start", String.valueOf(offSet))
158 .queryParam("sort", sortParam).queryParam("facet", "true")
159 .queryParam("facet.pivot", facetPivot)
160 .queryParam("facet.pivot.mincount", facetPivotMinCount);
164 webResource = client.resource(PDB_SEARCH_ENDPOINT)
165 .queryParam("wt", "json").queryParam("fl", wantedFields)
166 .queryParam("rows", String.valueOf(responseSize))
167 .queryParam("start", String.valueOf(offSet))
168 .queryParam("q", query).queryParam("sort", sortParam);
171 URI uri = webResource.getURI();
173 // System.out.println(uri);
175 // Execute the REST request
176 ClientResponse clientResponse = webResource
177 .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
179 // Get the JSON string from the response object or directly from the
180 // client (JavaScript)
181 Map<String, Object> jsonObj = null;
182 String responseString = null;
184 // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
186 // Check the response status and report exception if one occurs
187 int responseStatus = clientResponse.getStatus();
188 switch (responseStatus)
193 jsonObj = clientResponse.getEntity(Map.class);
197 responseString = clientResponse.getEntity(String.class);
201 throw new Exception(parseJsonExceptionString(responseString));
204 getMessageByHTTPStatusCode(responseStatus, "PDB"));
207 // Process the response and return the result to the caller.
208 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
209 } catch (Exception e)
211 String exceptionMsg = e.getMessage();
212 if (exceptionMsg.contains("SocketException"))
214 // No internet connection
215 throw new Exception(MessageManager.getString(
216 "exception.unable_to_detect_internet_connection"));
218 else if (exceptionMsg.contains("UnknownHostException"))
220 // The server 'www.ebi.ac.uk' is unreachable
221 throw new Exception(MessageManager.formatMessage(
222 "exception.fts_server_unreachable", "PDB Solr"));
232 * Process error response from PDB server if/when one occurs.
234 * @param jsonResponse
235 * the JSON string containing error message from the server
236 * @return the processed error message from the JSON string
238 @SuppressWarnings("unchecked")
239 public static String parseJsonExceptionString(String jsonErrorResponse)
241 StringBuilder errorMessage = new StringBuilder(
242 "\n============= PDB Rest Client RunTime error =============\n");
246 // "responseHeader":{
250 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
251 // "fl":"pdb_id,title,experimental_method,resolution",
253 // "sort":"overall_quality desc",
256 // "response":{"numFound":1,"start":0,"docs":[
258 // "experimental_method":["X-ray diffraction"],
260 // "resolution":2.46,
261 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
266 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
267 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
269 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
270 .get("responseHeader");
271 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
272 String status = responseHeader.get("status").toString();
273 String message = errorResponse.get("msg").toString();
274 String query = paramsObj.get("q").toString();
275 String fl = paramsObj.get("fl").toString();
277 errorMessage.append("Status: ").append(status).append("\n");
278 errorMessage.append("Message: ").append(message).append("\n");
279 errorMessage.append("query: ").append(query).append("\n");
280 errorMessage.append("fl: ").append(fl).append("\n");
282 } catch (ParseException e)
286 return errorMessage.toString();
290 * Parses the JSON response string from PDB REST API. The response is dynamic
291 * hence, only fields specifically requested for in the 'wantedFields'
292 * parameter is fetched/processed
294 * @param pdbJsonResponseString
295 * the JSON string to be parsed
296 * @param pdbRestRequest
297 * the request object which contains parameters used to process the
301 public static FTSRestResponse parsePDBJsonResponse(
302 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
304 return parsePDBJsonResponse(pdbJsonResponseString,
305 (Map<String, Object>) null, pdbRestRequest);
308 @SuppressWarnings("unchecked")
309 public static FTSRestResponse parsePDBJsonResponse(
310 String pdbJsonResponseString, Map<String, Object> jsonObj,
311 FTSRestRequest pdbRestRequest)
313 FTSRestResponse searchResult = new FTSRestResponse();
314 List<FTSData> result = null;
319 jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
321 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
322 String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
323 .get("QTime").toString();
324 int numFound = Integer
325 .valueOf(pdbResponse.get("numFound").toString());
328 result = new ArrayList<>();
329 List<Object> docs = (List<Object>) pdbResponse.get("docs");
330 for (Iterator<Object> docIter = docs.iterator(); docIter
333 Map<String, Object> doc = (Map<String, Object>) docIter.next();
334 result.add(getFTSData(doc, pdbRestRequest));
336 searchResult.setNumberOfItemsFound(numFound);
337 searchResult.setResponseTime(queryTime);
338 searchResult.setSearchSummary(result);
340 } catch (ParseException e)
347 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
348 FTSRestRequest request)
351 String primaryKey = null;
353 Object[] summaryRowData;
355 SequenceI associatedSequence;
357 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
358 SequenceI associatedSeq = request.getAssociatedSequence();
360 summaryRowData = new Object[(associatedSeq != null)
361 ? diplayFields.size() + 1
362 : diplayFields.size()];
363 if (associatedSeq != null)
365 associatedSequence = associatedSeq;
366 summaryRowData[0] = associatedSequence;
370 for (FTSDataColumnI field : diplayFields)
372 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
373 : pdbJsonDoc.get(field.getCode()).toString();
374 if (field.isPrimaryKeyColumn())
376 primaryKey = fieldData;
377 summaryRowData[colCounter++] = primaryKey;
379 else if (fieldData == null || fieldData.isEmpty())
381 summaryRowData[colCounter++] = null;
387 summaryRowData[colCounter++] = (field.getDataType()
388 .getDataTypeClass() == Integer.class)
389 ? Integer.valueOf(fieldData)
390 : (field.getDataType()
391 .getDataTypeClass() == Double.class)
392 ? Double.valueOf(fieldData)
393 : sanitiseData(fieldData);
394 } catch (Exception e)
397 System.out.println("offending value:" + fieldData);
402 final String primaryKey1 = primaryKey;
404 final Object[] summaryRowData1 = summaryRowData;
408 public Object[] getSummaryData()
410 return summaryRowData1;
414 public Object getPrimaryKey()
420 * Returns a string representation of this object;
423 public String toString()
425 StringBuilder summaryFieldValues = new StringBuilder();
426 for (Object summaryField : summaryRowData1)
428 summaryFieldValues.append(
429 summaryField == null ? " " : summaryField.toString())
432 return summaryFieldValues.toString();
436 * Returns hash code value for this object
439 public int hashCode()
441 return Objects.hash(primaryKey1, this.toString());
445 public boolean equals(Object that)
447 return this.toString().equals(that.toString());
452 private static String sanitiseData(String data)
454 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
455 .replaceAll("\\[", "").replaceAll("\\]", "")
456 .replaceAll("\",\"", ", ").replaceAll("\"", "");
461 public String getColumnDataConfigFileName()
463 return "/fts/pdb_data_columns.txt";
466 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
468 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
470 if (allDefaultDisplayedStructureDataColumns == null
471 || allDefaultDisplayedStructureDataColumns.isEmpty())
473 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
474 allDefaultDisplayedStructureDataColumns
475 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
477 return allDefaultDisplayedStructureDataColumns;