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.datamodel.SequenceI;
41 import jalview.fts.api.FTSData;
42 import jalview.fts.api.FTSDataColumnI;
43 import jalview.fts.api.FTSRestClientI;
44 import jalview.fts.api.StructureFTSRestClientI;
45 import jalview.fts.core.FTSDataColumnPreferences;
46 import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
47 import jalview.fts.core.FTSRestClient;
48 import jalview.fts.core.FTSRestRequest;
49 import jalview.fts.core.FTSRestResponse;
50 import jalview.fts.service.alphafold.AlphafoldRestClient;
51 import jalview.util.JSONUtils;
52 import jalview.util.MessageManager;
53 import jalview.util.Platform;
56 * A rest client for querying the Search endpoint of the PDB API
60 public class PDBFTSRestClient extends FTSRestClient implements StructureFTSRestClientI
63 private static FTSRestClientI instance = null;
65 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
67 protected PDBFTSRestClient()
72 * Takes a PDBRestRequest object and returns a response upon execution
74 * @param pdbRestRequest
75 * the PDBRestRequest instance to be processed
76 * @return the pdbResponse object for the given request
79 @SuppressWarnings({ "unused", "unchecked" })
81 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
86 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
87 pdbRestRequest.getWantedFields());
88 int responseSize = (pdbRestRequest.getResponseSize() == 0)
89 ? getDefaultResponsePageSize()
90 : pdbRestRequest.getResponseSize();
91 int offSet = pdbRestRequest.getOffSet();
92 String sortParam = null;
93 if (pdbRestRequest.getFieldToSortBy() == null
94 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
100 if (pdbRestRequest.getFieldToSortBy()
101 .equalsIgnoreCase("Resolution"))
103 sortParam = pdbRestRequest.getFieldToSortBy()
104 + (pdbRestRequest.isAscending() ? " asc" : " desc");
108 sortParam = pdbRestRequest.getFieldToSortBy()
109 + (pdbRestRequest.isAscending() ? " desc" : " asc");
113 String facetPivot = (pdbRestRequest.getFacetPivot() == null
114 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
115 : pdbRestRequest.getFacetPivot();
116 String facetPivotMinCount = String
117 .valueOf(pdbRestRequest.getFacetPivotMinCount());
119 String query = pdbRestRequest.getFieldToSearchBy()
120 + pdbRestRequest.getSearchTerm()
121 + (pdbRestRequest.isAllowEmptySeq() ? ""
122 : " AND molecule_sequence:['' TO *]")
123 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
124 : " AND status:REL");
126 // Build request parameters for the REST Request
128 // BH 2018 the trick here is to coerce the classes in Javascript to be
129 // different from the ones in Java yet still allow this to be correct for Java
131 Class<ClientResponse> clientResponseClass;
134 // JavaScript only -- coerce types to Java types for Java
135 client = (Client) (Object) new jalview.javascript.web.Client();
136 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
145 client = Client.create(new DefaultClientConfig());
146 clientResponseClass = ClientResponse.class;
149 WebResource webResource;
150 if (pdbRestRequest.isFacet())
152 webResource = client.resource(PDB_SEARCH_ENDPOINT)
153 .queryParam("wt", "json").queryParam("fl", wantedFields)
154 .queryParam("rows", String.valueOf(responseSize))
155 .queryParam("q", query)
156 .queryParam("start", String.valueOf(offSet))
157 .queryParam("sort", sortParam).queryParam("facet", "true")
158 .queryParam("facet.pivot", facetPivot)
159 .queryParam("facet.pivot.mincount", facetPivotMinCount);
163 webResource = client.resource(PDB_SEARCH_ENDPOINT)
164 .queryParam("wt", "json").queryParam("fl", wantedFields)
165 .queryParam("rows", String.valueOf(responseSize))
166 .queryParam("start", String.valueOf(offSet))
167 .queryParam("q", query).queryParam("sort", sortParam);
170 URI uri = webResource.getURI();
172 System.out.println(uri);
174 // Execute the REST request
175 ClientResponse clientResponse = webResource
176 .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
178 // Get the JSON string from the response object or directly from the
179 // client (JavaScript)
180 Map<String, Object> jsonObj = null;
181 String responseString = null;
183 System.out.println("query >>>>>>> " + pdbRestRequest.toString());
185 // Check the response status and report exception if one occurs
186 int responseStatus = clientResponse.getStatus();
187 switch (responseStatus)
192 jsonObj = clientResponse.getEntity(Map.class);
196 responseString = clientResponse.getEntity(String.class);
200 throw new Exception(parseJsonExceptionString(responseString));
203 getMessageByHTTPStatusCode(responseStatus, "PDB"));
206 // Process the response and return the result to the caller.
207 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
208 } catch (Exception e)
210 String exceptionMsg = e.getMessage();
211 if (exceptionMsg.contains("SocketException"))
213 // No internet connection
214 throw new Exception(MessageManager.getString(
215 "exception.unable_to_detect_internet_connection"));
217 else if (exceptionMsg.contains("UnknownHostException"))
219 // The server 'www.ebi.ac.uk' is unreachable
220 throw new Exception(MessageManager.formatMessage(
221 "exception.fts_server_unreachable", "PDB Solr"));
231 * Process error response from PDB server if/when one occurs.
233 * @param jsonResponse
234 * the JSON string containing error message from the server
235 * @return the processed error message from the JSON string
237 @SuppressWarnings("unchecked")
238 public static String parseJsonExceptionString(String jsonErrorResponse)
240 StringBuilder errorMessage = new StringBuilder(
241 "\n============= PDB Rest Client RunTime error =============\n");
245 // "responseHeader":{
249 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
250 // "fl":"pdb_id,title,experimental_method,resolution",
252 // "sort":"overall_quality desc",
255 // "response":{"numFound":1,"start":0,"docs":[
257 // "experimental_method":["X-ray diffraction"],
259 // "resolution":2.46,
260 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
265 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
266 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
268 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
269 .get("responseHeader");
270 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
271 String status = responseHeader.get("status").toString();
272 String message = errorResponse.get("msg").toString();
273 String query = paramsObj.get("q").toString();
274 String fl = paramsObj.get("fl").toString();
276 errorMessage.append("Status: ").append(status).append("\n");
277 errorMessage.append("Message: ").append(message).append("\n");
278 errorMessage.append("query: ").append(query).append("\n");
279 errorMessage.append("fl: ").append(fl).append("\n");
281 } catch (ParseException e)
285 return errorMessage.toString();
289 * Parses the JSON response string from PDB REST API. The response is dynamic
290 * hence, only fields specifically requested for in the 'wantedFields'
291 * parameter is fetched/processed
293 * @param pdbJsonResponseString
294 * the JSON string to be parsed
295 * @param pdbRestRequest
296 * the request object which contains parameters used to process the
300 public static FTSRestResponse parsePDBJsonResponse(
301 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
303 return parsePDBJsonResponse(pdbJsonResponseString,
304 (Map<String, Object>) null, pdbRestRequest);
307 @SuppressWarnings("unchecked")
308 public static FTSRestResponse parsePDBJsonResponse(
309 String pdbJsonResponseString, Map<String, Object> jsonObj,
310 FTSRestRequest pdbRestRequest)
312 FTSRestResponse searchResult = new FTSRestResponse();
313 List<FTSData> result = null;
318 jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
320 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
321 String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
322 .get("QTime").toString();
323 int numFound = Integer
324 .valueOf(pdbResponse.get("numFound").toString());
325 List<Object> docs = (List<Object>) pdbResponse.get("docs");
326 // add in any alphafold bits at the top
327 result = AlphafoldRestClient.getFTSData(pdbRestRequest);
331 for (Iterator<Object> docIter = docs.iterator(); docIter
334 Map<String, Object> doc = (Map<String, Object>) docIter.next();
335 result.add(getFTSData(doc, pdbRestRequest));
338 searchResult.setNumberOfItemsFound(result.size());
339 searchResult.setResponseTime(queryTime);
340 searchResult.setSearchSummary(result);
342 } catch (ParseException e)
349 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
350 FTSRestRequest request)
353 String primaryKey = null;
355 Object[] summaryRowData;
357 SequenceI associatedSequence;
359 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
360 SequenceI associatedSeq = request.getAssociatedSequence();
362 summaryRowData = new Object[(associatedSeq != null)
363 ? diplayFields.size() + 1
364 : diplayFields.size()];
365 if (associatedSeq != null)
367 associatedSequence = associatedSeq;
368 summaryRowData[0] = associatedSequence;
372 for (FTSDataColumnI field : diplayFields)
374 //System.out.println("Field " + field);
375 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
376 : pdbJsonDoc.get(field.getCode()).toString();
377 //System.out.println("Field Data : " + fieldData);
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 public static FTSRestClientI getInstance()
472 if (instance == null)
474 instance = new PDBFTSRestClient();
479 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
481 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
483 if (allDefaultDisplayedStructureDataColumns == null
484 || allDefaultDisplayedStructureDataColumns.isEmpty())
486 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
487 allDefaultDisplayedStructureDataColumns
488 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
490 return allDefaultDisplayedStructureDataColumns;
493 public String[] getPreferencesColumnsFor(PreferenceSource source) {
494 String[] columnNames = null;
498 columnNames = new String[] { "", "Display", "Group" };
500 case STRUCTURE_CHOOSER:
501 columnNames = new String[] { "", "Display", "Group" };
504 columnNames = new String[] { "PDB Field", "Show in search summary",
505 "Show in structure summary" };