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.io.FileInputStream;
25 import java.io.FileReader;
27 import java.nio.CharBuffer;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Objects;
35 import javax.ws.rs.core.MediaType;
37 import org.json.simple.parser.ParseException;
39 import com.sun.jersey.api.client.Client;
40 import com.sun.jersey.api.client.ClientResponse;
41 import com.sun.jersey.api.client.WebResource;
42 import com.sun.jersey.api.client.config.DefaultClientConfig;
44 import jalview.datamodel.SequenceI;
45 import jalview.fts.api.FTSData;
46 import jalview.fts.api.FTSDataColumnI;
47 import jalview.fts.api.FTSRestClientI;
48 import jalview.fts.api.StructureFTSRestClientI;
49 import jalview.fts.core.FTSDataColumnPreferences;
50 import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
51 import jalview.fts.core.FTSRestClient;
52 import jalview.fts.core.FTSRestRequest;
53 import jalview.fts.core.FTSRestResponse;
54 import jalview.fts.service.alphafold.AlphafoldRestClient;
55 import jalview.util.JSONUtils;
56 import jalview.util.MessageManager;
57 import jalview.util.Platform;
60 * A rest client for querying the Search endpoint of the PDB API
64 public class PDBFTSRestClient extends FTSRestClient
65 implements StructureFTSRestClientI
68 private static FTSRestClientI instance = null;
70 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
72 protected PDBFTSRestClient()
77 * Takes a PDBRestRequest object and returns a response upon execution
79 * @param pdbRestRequest
80 * the PDBRestRequest instance to be processed
81 * @return the pdbResponse object for the given request
84 @SuppressWarnings({ "unused", "unchecked" })
86 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
91 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
92 pdbRestRequest.getWantedFields());
93 int responseSize = (pdbRestRequest.getResponseSize() == 0)
94 ? getDefaultResponsePageSize()
95 : pdbRestRequest.getResponseSize();
96 int offSet = pdbRestRequest.getOffSet();
97 String sortParam = null;
98 if (pdbRestRequest.getFieldToSortBy() == null
99 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
105 if (pdbRestRequest.getFieldToSortBy()
106 .equalsIgnoreCase("Resolution"))
108 sortParam = pdbRestRequest.getFieldToSortBy()
109 + (pdbRestRequest.isAscending() ? " asc" : " desc");
113 sortParam = pdbRestRequest.getFieldToSortBy()
114 + (pdbRestRequest.isAscending() ? " desc" : " asc");
118 String facetPivot = (pdbRestRequest.getFacetPivot() == null
119 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
120 : pdbRestRequest.getFacetPivot();
121 String facetPivotMinCount = String
122 .valueOf(pdbRestRequest.getFacetPivotMinCount());
124 String query = pdbRestRequest.getFieldToSearchBy()
125 + pdbRestRequest.getSearchTerm()
126 + (pdbRestRequest.isAllowEmptySeq() ? ""
127 : " AND molecule_sequence:['' TO *]")
128 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
129 : " AND status:REL");
131 // Build request parameters for the REST Request
133 // BH 2018 the trick here is to coerce the classes in Javascript to be
134 // different from the ones in Java yet still allow this to be correct for
137 Class<ClientResponse> clientResponseClass;
140 // JavaScript only -- coerce types to Java types for Java
141 client = (Client) (Object) new jalview.javascript.web.Client();
142 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
151 client = Client.create(new DefaultClientConfig());
152 clientResponseClass = ClientResponse.class;
155 WebResource webResource;
156 if (pdbRestRequest.isFacet())
158 webResource = client.resource(PDB_SEARCH_ENDPOINT)
159 .queryParam("wt", "json").queryParam("fl", wantedFields)
160 .queryParam("rows", String.valueOf(responseSize))
161 .queryParam("q", query)
162 .queryParam("start", String.valueOf(offSet))
163 .queryParam("sort", sortParam).queryParam("facet", "true")
164 .queryParam("facet.pivot", facetPivot)
165 .queryParam("facet.pivot.mincount", facetPivotMinCount);
169 webResource = client.resource(PDB_SEARCH_ENDPOINT)
170 .queryParam("wt", "json").queryParam("fl", wantedFields)
171 .queryParam("rows", String.valueOf(responseSize))
172 .queryParam("start", String.valueOf(offSet))
173 .queryParam("q", query).queryParam("sort", sortParam);
176 URI uri = webResource.getURI();
178 System.out.println(uri);
179 ClientResponse clientResponse = null;
180 int responseStatus = -1;
181 // Get the JSON string from the response object or directly from the
182 // client (JavaScript)
183 Map<String, Object> jsonObj = null;
184 String responseString = null;
186 System.out.println("query >>>>>>> " + pdbRestRequest.toString());
190 // Execute the REST request
191 clientResponse = webResource.accept(MediaType.APPLICATION_JSON)
192 .get(clientResponseClass);
193 responseStatus = clientResponse.getStatus();
198 if (mockQueries.containsKey(uri.toString()))
200 responseStatus = 200;
204 // FIXME - may cause unexpected exceptions for callers when mocked
205 responseStatus = 400;
209 // Check the response status and report exception if one occurs
210 switch (responseStatus)
216 responseString = mockQueries.get(uri.toString());
222 jsonObj = clientResponse.getEntity(Map.class);
226 responseString = clientResponse.getEntity(String.class);
231 throw new Exception(isMocked() ? "400 response (Mocked)"
232 : parseJsonExceptionString(responseString));
235 getMessageByHTTPStatusCode(responseStatus, "PDB"));
238 // Process the response and return the result to the caller.
239 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
240 } catch (Exception e)
242 if (e.getMessage() == null)
246 String exceptionMsg = e.getMessage();
247 if (exceptionMsg.contains("SocketException"))
249 // No internet connection
250 throw new Exception(MessageManager.getString(
251 "exception.unable_to_detect_internet_connection"));
253 else if (exceptionMsg.contains("UnknownHostException"))
255 // The server 'www.ebi.ac.uk' is unreachable
256 throw new Exception(MessageManager.formatMessage(
257 "exception.fts_server_unreachable", "PDB Solr"));
267 * Process error response from PDB server if/when one occurs.
269 * @param jsonResponse
270 * the JSON string containing error message from the server
271 * @return the processed error message from the JSON string
273 @SuppressWarnings("unchecked")
274 public static String parseJsonExceptionString(String jsonErrorResponse)
276 StringBuilder errorMessage = new StringBuilder(
277 "\n============= PDB Rest Client RunTime error =============\n");
280 // "responseHeader":{
284 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
285 // "fl":"pdb_id,title,experimental_method,resolution",
287 // "sort":"overall_quality desc",
290 // "response":{"numFound":1,"start":0,"docs":[
292 // "experimental_method":["X-ray diffraction"],
294 // "resolution":2.46,
295 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S
301 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils
302 .parse(jsonErrorResponse);
303 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj
306 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
307 .get("responseHeader");
308 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader
310 String status = responseHeader.get("status").toString();
311 String message = errorResponse.get("msg").toString();
312 String query = paramsObj.get("q").toString();
313 String fl = paramsObj.get("fl").toString();
315 errorMessage.append("Status: ").append(status).append("\n");
316 errorMessage.append("Message: ").append(message).append("\n");
317 errorMessage.append("query: ").append(query).append("\n");
318 errorMessage.append("fl: ").append(fl).append("\n");
320 } catch (ParseException e)
324 return errorMessage.toString();
328 * Parses the JSON response string from PDB REST API. The response is dynamic
329 * hence, only fields specifically requested for in the 'wantedFields'
330 * parameter is fetched/processed
332 * @param pdbJsonResponseString
333 * the JSON string to be parsed
334 * @param pdbRestRequest
335 * the request object which contains parameters used to process the
339 public static FTSRestResponse parsePDBJsonResponse(
340 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
342 return parsePDBJsonResponse(pdbJsonResponseString,
343 (Map<String, Object>) null, pdbRestRequest);
346 @SuppressWarnings("unchecked")
347 public static FTSRestResponse parsePDBJsonResponse(
348 String pdbJsonResponseString, Map<String, Object> jsonObj,
349 FTSRestRequest pdbRestRequest)
351 FTSRestResponse searchResult = new FTSRestResponse();
352 List<FTSData> result = null;
357 jsonObj = (Map<String, Object>) JSONUtils
358 .parse(pdbJsonResponseString);
360 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj
362 String queryTime = ((Map<String, Object>) jsonObj
363 .get("responseHeader")).get("QTime").toString();
364 int numFound = Integer
365 .valueOf(pdbResponse.get("numFound").toString());
366 List<Object> docs = (List<Object>) pdbResponse.get("docs");
368 result = new ArrayList<FTSData>();
372 for (Iterator<Object> docIter = docs.iterator(); docIter.hasNext();)
374 Map<String, Object> doc = (Map<String, Object>) docIter.next();
375 result.add(getFTSData(doc, pdbRestRequest));
378 // this is the total number found by the query,
379 // rather than the set returned in SearchSummary
380 searchResult.setNumberOfItemsFound(numFound);
381 searchResult.setResponseTime(queryTime);
382 searchResult.setSearchSummary(result);
384 } catch (ParseException e)
391 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
392 FTSRestRequest request)
395 String primaryKey = null;
397 Object[] summaryRowData;
399 SequenceI associatedSequence;
401 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
402 SequenceI associatedSeq = request.getAssociatedSequence();
404 summaryRowData = new Object[(associatedSeq != null)
405 ? diplayFields.size() + 1
406 : diplayFields.size()];
407 if (associatedSeq != null)
409 associatedSequence = associatedSeq;
410 summaryRowData[0] = associatedSequence;
414 for (FTSDataColumnI field : diplayFields)
416 // System.out.println("Field " + field);
417 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
418 : pdbJsonDoc.get(field.getCode()).toString();
419 // System.out.println("Field Data : " + fieldData);
420 if (field.isPrimaryKeyColumn())
422 primaryKey = fieldData;
423 summaryRowData[colCounter++] = primaryKey;
425 else if (fieldData == null || fieldData.isEmpty())
427 summaryRowData[colCounter++] = null;
433 summaryRowData[colCounter++] = (field.getDataType()
434 .getDataTypeClass() == Integer.class)
435 ? Integer.valueOf(fieldData)
436 : (field.getDataType()
437 .getDataTypeClass() == Double.class)
438 ? Double.valueOf(fieldData)
439 : sanitiseData(fieldData);
440 } catch (Exception e)
443 System.out.println("offending value:" + fieldData);
448 final String primaryKey1 = primaryKey;
450 final Object[] summaryRowData1 = summaryRowData;
454 public Object[] getSummaryData()
456 return summaryRowData1;
460 public Object getPrimaryKey()
466 * Returns a string representation of this object;
469 public String toString()
471 StringBuilder summaryFieldValues = new StringBuilder();
472 for (Object summaryField : summaryRowData1)
474 summaryFieldValues.append(
475 summaryField == null ? " " : summaryField.toString())
478 return summaryFieldValues.toString();
482 * Returns hash code value for this object
485 public int hashCode()
487 return Objects.hash(primaryKey1, this.toString());
491 public boolean equals(Object that)
493 return this.toString().equals(that.toString());
498 private static String sanitiseData(String data)
500 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
501 .replaceAll("\\[", "").replaceAll("\\]", "")
502 .replaceAll("\",\"", ", ").replaceAll("\"", "");
507 public String getColumnDataConfigFileName()
509 return "/fts/pdb_data_columns.txt";
512 public static FTSRestClientI getInstance()
514 if (instance == null)
516 instance = new PDBFTSRestClient();
521 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
524 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
526 if (allDefaultDisplayedStructureDataColumns == null
527 || allDefaultDisplayedStructureDataColumns.isEmpty())
529 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
530 allDefaultDisplayedStructureDataColumns
531 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
533 return allDefaultDisplayedStructureDataColumns;
537 public String[] getPreferencesColumnsFor(PreferenceSource source)
539 String[] columnNames = null;
543 columnNames = new String[] { "", "Display", "Group" };
545 case STRUCTURE_CHOOSER:
546 columnNames = new String[] { "", "Display", "Group" };
549 columnNames = new String[] { "PDB Field", "Show in search summary",
550 "Show in structure summary" };