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 jalview.bin.Console.outPrintln(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;
187 .outPrintln("query >>>>>>> " + pdbRestRequest.toString());
191 // Execute the REST request
192 clientResponse = webResource.accept(MediaType.APPLICATION_JSON)
193 .get(clientResponseClass);
194 responseStatus = clientResponse.getStatus();
199 if (mockQueries.containsKey(uri.toString()))
201 responseStatus = 200;
205 // FIXME - may cause unexpected exceptions for callers when mocked
206 responseStatus = 400;
210 // Check the response status and report exception if one occurs
211 switch (responseStatus)
217 responseString = mockQueries.get(uri.toString());
223 jsonObj = clientResponse.getEntity(Map.class);
227 responseString = clientResponse.getEntity(String.class);
232 throw new Exception(isMocked() ? "400 response (Mocked)"
233 : parseJsonExceptionString(responseString));
236 getMessageByHTTPStatusCode(responseStatus, "PDB"));
239 // Process the response and return the result to the caller.
240 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
241 } catch (Exception e)
243 if (e.getMessage() == null)
247 String exceptionMsg = e.getMessage();
248 if (exceptionMsg.contains("SocketException"))
250 // No internet connection
251 throw new Exception(MessageManager.getString(
252 "exception.unable_to_detect_internet_connection"));
254 else if (exceptionMsg.contains("UnknownHostException"))
256 // The server 'www.ebi.ac.uk' is unreachable
257 throw new Exception(MessageManager.formatMessage(
258 "exception.fts_server_unreachable", "PDB Solr"));
268 * Process error response from PDB server if/when one occurs.
270 * @param jsonResponse
271 * the JSON string containing error message from the server
272 * @return the processed error message from the JSON string
274 @SuppressWarnings("unchecked")
275 public static String parseJsonExceptionString(String jsonErrorResponse)
277 StringBuilder errorMessage = new StringBuilder(
278 "\n============= PDB Rest Client RunTime error =============\n");
281 // "responseHeader":{
285 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
286 // "fl":"pdb_id,title,experimental_method,resolution",
288 // "sort":"overall_quality desc",
291 // "response":{"numFound":1,"start":0,"docs":[
293 // "experimental_method":["X-ray diffraction"],
295 // "resolution":2.46,
296 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S
302 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils
303 .parse(jsonErrorResponse);
304 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj
307 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
308 .get("responseHeader");
309 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader
311 String status = responseHeader.get("status").toString();
312 String message = errorResponse.get("msg").toString();
313 String query = paramsObj.get("q").toString();
314 String fl = paramsObj.get("fl").toString();
316 errorMessage.append("Status: ").append(status).append("\n");
317 errorMessage.append("Message: ").append(message).append("\n");
318 errorMessage.append("query: ").append(query).append("\n");
319 errorMessage.append("fl: ").append(fl).append("\n");
321 } catch (ParseException e)
325 return errorMessage.toString();
329 * Parses the JSON response string from PDB REST API. The response is dynamic
330 * hence, only fields specifically requested for in the 'wantedFields'
331 * parameter is fetched/processed
333 * @param pdbJsonResponseString
334 * the JSON string to be parsed
335 * @param pdbRestRequest
336 * the request object which contains parameters used to process the
340 public static FTSRestResponse parsePDBJsonResponse(
341 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
343 return parsePDBJsonResponse(pdbJsonResponseString,
344 (Map<String, Object>) null, pdbRestRequest);
347 @SuppressWarnings("unchecked")
348 public static FTSRestResponse parsePDBJsonResponse(
349 String pdbJsonResponseString, Map<String, Object> jsonObj,
350 FTSRestRequest pdbRestRequest)
352 FTSRestResponse searchResult = new FTSRestResponse();
353 List<FTSData> result = null;
358 jsonObj = (Map<String, Object>) JSONUtils
359 .parse(pdbJsonResponseString);
361 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj
363 String queryTime = ((Map<String, Object>) jsonObj
364 .get("responseHeader")).get("QTime").toString();
365 int numFound = Integer
366 .valueOf(pdbResponse.get("numFound").toString());
367 List<Object> docs = (List<Object>) pdbResponse.get("docs");
369 result = new ArrayList<FTSData>();
373 for (Iterator<Object> docIter = docs.iterator(); docIter.hasNext();)
375 Map<String, Object> doc = (Map<String, Object>) docIter.next();
376 result.add(getFTSData(doc, pdbRestRequest));
379 // this is the total number found by the query,
380 // rather than the set returned in SearchSummary
381 searchResult.setNumberOfItemsFound(numFound);
382 searchResult.setResponseTime(queryTime);
383 searchResult.setSearchSummary(result);
385 } catch (ParseException e)
392 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
393 FTSRestRequest request)
396 String primaryKey = null;
398 Object[] summaryRowData;
400 SequenceI associatedSequence;
402 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
403 SequenceI associatedSeq = request.getAssociatedSequence();
405 summaryRowData = new Object[(associatedSeq != null)
406 ? diplayFields.size() + 1
407 : diplayFields.size()];
408 if (associatedSeq != null)
410 associatedSequence = associatedSeq;
411 summaryRowData[0] = associatedSequence;
415 for (FTSDataColumnI field : diplayFields)
417 // jalview.bin.Console.outPrintln("Field " + field);
418 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
419 : pdbJsonDoc.get(field.getCode()).toString();
420 // jalview.bin.Console.outPrintln("Field Data : " + fieldData);
421 if (field.isPrimaryKeyColumn())
423 primaryKey = fieldData;
424 summaryRowData[colCounter++] = primaryKey;
426 else if (fieldData == null || fieldData.isEmpty())
428 summaryRowData[colCounter++] = null;
434 summaryRowData[colCounter++] = (field.getDataType()
435 .getDataTypeClass() == Integer.class)
436 ? Integer.valueOf(fieldData)
437 : (field.getDataType()
438 .getDataTypeClass() == Double.class)
439 ? Double.valueOf(fieldData)
440 : sanitiseData(fieldData);
441 } catch (Exception e)
444 jalview.bin.Console.outPrintln("offending value:" + fieldData);
449 final String primaryKey1 = primaryKey;
451 final Object[] summaryRowData1 = summaryRowData;
455 public Object[] getSummaryData()
457 return summaryRowData1;
461 public Object getPrimaryKey()
467 * Returns a string representation of this object;
470 public String toString()
472 StringBuilder summaryFieldValues = new StringBuilder();
473 for (Object summaryField : summaryRowData1)
475 summaryFieldValues.append(
476 summaryField == null ? " " : summaryField.toString())
479 return summaryFieldValues.toString();
483 * Returns hash code value for this object
486 public int hashCode()
488 return Objects.hash(primaryKey1, this.toString());
492 public boolean equals(Object that)
494 return this.toString().equals(that.toString());
499 private static String sanitiseData(String data)
501 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
502 .replaceAll("\\[", "").replaceAll("\\]", "")
503 .replaceAll("\",\"", ", ").replaceAll("\"", "");
508 public String getColumnDataConfigFileName()
510 return "/fts/pdb_data_columns.txt";
513 public static FTSRestClientI getInstance()
515 if (instance == null)
517 instance = new PDBFTSRestClient();
522 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
525 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
527 if (allDefaultDisplayedStructureDataColumns == null
528 || allDefaultDisplayedStructureDataColumns.isEmpty())
530 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
531 allDefaultDisplayedStructureDataColumns
532 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
534 return allDefaultDisplayedStructureDataColumns;
538 public String[] getPreferencesColumnsFor(PreferenceSource source)
540 String[] columnNames = null;
544 columnNames = new String[] { "", "Display", "Group" };
546 case STRUCTURE_CHOOSER:
547 columnNames = new String[] { "", "Display", "Group" };
550 columnNames = new String[] { "PDB Field", "Show in search summary",
551 "Show in structure summary" };