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.Console;
41 import jalview.datamodel.SequenceI;
42 import jalview.fts.api.FTSData;
43 import jalview.fts.api.FTSDataColumnI;
44 import jalview.fts.api.FTSRestClientI;
45 import jalview.fts.api.StructureFTSRestClientI;
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.util.JSONUtils;
51 import jalview.util.MessageManager;
52 import jalview.util.Platform;
55 * A rest client for querying the Search endpoint of the PDB API
59 public class PDBFTSRestClient extends FTSRestClient
60 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?";
69 Platform.addJ2SDirectDatabaseCall(PDB_SEARCH_ENDPOINT);
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 ClientResponse clientResponse = null;
179 int responseStatus = -1;
180 // Get the JSON string from the response object or directly from the
181 // client (JavaScript)
182 Map<String, Object> jsonObj = null;
183 String responseString = null;
185 Console.info("REST request: " + uri.toString());
189 // Execute the REST request
190 clientResponse = webResource.accept(MediaType.APPLICATION_JSON)
191 .get(clientResponseClass);
192 responseStatus = clientResponse.getStatus();
197 if (mockQueries.containsKey(uri.toString()))
199 responseStatus = 200;
203 // FIXME - may cause unexpected exceptions for callers when mocked
204 responseStatus = 400;
208 // Check the response status and report exception if one occurs
209 switch (responseStatus)
215 responseString = mockQueries.get(uri.toString());
221 jsonObj = clientResponse.getEntity(Map.class);
225 responseString = clientResponse.getEntity(String.class);
230 throw new Exception(isMocked() ? "400 response (Mocked)"
231 : parseJsonExceptionString(responseString));
234 getMessageByHTTPStatusCode(responseStatus, "PDB"));
237 // Process the response and return the result to the caller.
238 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
239 } catch (Exception e)
241 if (e.getMessage() == null)
245 String exceptionMsg = e.getMessage();
246 if (exceptionMsg.contains("SocketException"))
248 // No internet connection
249 throw new Exception(MessageManager.getString(
250 "exception.unable_to_detect_internet_connection"));
252 else if (exceptionMsg.contains("UnknownHostException"))
254 // The server 'www.ebi.ac.uk' is unreachable
255 throw new Exception(MessageManager.formatMessage(
256 "exception.fts_server_unreachable", "PDB Solr"));
266 * Process error response from PDB server if/when one occurs.
268 * @param jsonResponse
269 * the JSON string containing error message from the server
270 * @return the processed error message from the JSON string
272 @SuppressWarnings("unchecked")
273 public static String parseJsonExceptionString(String jsonErrorResponse)
275 StringBuilder errorMessage = new StringBuilder(
276 "\n============= PDB Rest Client RunTime error =============\n");
279 // "responseHeader":{
283 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
284 // "fl":"pdb_id,title,experimental_method,resolution",
286 // "sort":"overall_quality desc",
289 // "response":{"numFound":1,"start":0,"docs":[
291 // "experimental_method":["X-ray diffraction"],
293 // "resolution":2.46,
294 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S
300 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils
301 .parse(jsonErrorResponse);
302 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj
305 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
306 .get("responseHeader");
307 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader
309 String status = responseHeader.get("status").toString();
310 String message = errorResponse.get("msg").toString();
311 String query = paramsObj.get("q").toString();
312 String fl = paramsObj.get("fl").toString();
314 errorMessage.append("Status: ").append(status).append("\n");
315 errorMessage.append("Message: ").append(message).append("\n");
316 errorMessage.append("query: ").append(query).append("\n");
317 errorMessage.append("fl: ").append(fl).append("\n");
319 } catch (ParseException e)
323 return errorMessage.toString();
327 * Parses the JSON response string from PDB REST API. The response is dynamic
328 * hence, only fields specifically requested for in the 'wantedFields'
329 * parameter is fetched/processed
331 * @param pdbJsonResponseString
332 * the JSON string to be parsed
333 * @param pdbRestRequest
334 * the request object which contains parameters used to process the
338 public static FTSRestResponse parsePDBJsonResponse(
339 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
341 return parsePDBJsonResponse(pdbJsonResponseString,
342 (Map<String, Object>) null, pdbRestRequest);
345 @SuppressWarnings("unchecked")
346 public static FTSRestResponse parsePDBJsonResponse(
347 String pdbJsonResponseString, Map<String, Object> jsonObj,
348 FTSRestRequest pdbRestRequest)
350 FTSRestResponse searchResult = new FTSRestResponse();
351 List<FTSData> result = null;
356 jsonObj = (Map<String, Object>) JSONUtils
357 .parse(pdbJsonResponseString);
359 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj
361 String queryTime = ((Map<String, Object>) jsonObj
362 .get("responseHeader")).get("QTime").toString();
363 int numFound = Integer
364 .valueOf(pdbResponse.get("numFound").toString());
365 List<Object> docs = (List<Object>) pdbResponse.get("docs");
367 result = new ArrayList<FTSData>();
371 for (Iterator<Object> docIter = docs.iterator(); docIter.hasNext();)
373 Map<String, Object> doc = (Map<String, Object>) docIter.next();
374 result.add(getFTSData(doc, pdbRestRequest));
377 // this is the total number found by the query,
378 // rather than the set returned in SearchSummary
379 searchResult.setNumberOfItemsFound(numFound);
380 searchResult.setResponseTime(queryTime);
381 searchResult.setSearchSummary(result);
383 } catch (ParseException e)
390 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
391 FTSRestRequest request)
394 String primaryKey = null;
396 Object[] summaryRowData;
398 SequenceI associatedSequence;
400 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
401 SequenceI associatedSeq = request.getAssociatedSequence();
403 summaryRowData = new Object[(associatedSeq != null)
404 ? diplayFields.size() + 1
405 : diplayFields.size()];
406 if (associatedSeq != null)
408 associatedSequence = associatedSeq;
409 summaryRowData[0] = associatedSequence;
413 for (FTSDataColumnI field : diplayFields)
415 // Console.outPrintln("Field " + field);
416 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
417 : pdbJsonDoc.get(field.getCode()).toString();
418 // Console.outPrintln("Field Data : " + fieldData);
419 if (field.isPrimaryKeyColumn())
421 primaryKey = fieldData;
422 summaryRowData[colCounter++] = primaryKey;
424 else if (fieldData == null || fieldData.isEmpty())
426 summaryRowData[colCounter++] = null;
432 summaryRowData[colCounter++] = (field.getDataType()
433 .getDataTypeClass() == Integer.class)
434 ? Integer.valueOf(fieldData)
435 : (field.getDataType()
436 .getDataTypeClass() == Double.class)
437 ? Double.valueOf(fieldData)
438 : sanitiseData(fieldData);
439 } catch (Exception e)
442 Console.warn("offending value:" + fieldData);
447 final String primaryKey1 = primaryKey;
449 final Object[] summaryRowData1 = summaryRowData;
453 public Object[] getSummaryData()
455 return summaryRowData1;
459 public Object getPrimaryKey()
465 * Returns a string representation of this object;
468 public String toString()
470 StringBuilder summaryFieldValues = new StringBuilder();
471 for (Object summaryField : summaryRowData1)
473 summaryFieldValues.append(
474 summaryField == null ? " " : summaryField.toString())
477 return summaryFieldValues.toString();
481 * Returns hash code value for this object
484 public int hashCode()
486 return Objects.hash(primaryKey1, this.toString());
490 public boolean equals(Object that)
492 return this.toString().equals(that.toString());
497 private static String sanitiseData(String data)
499 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
500 .replaceAll("\\[", "").replaceAll("\\]", "")
501 .replaceAll("\",\"", ", ").replaceAll("\"", "");
506 public String getColumnDataConfigFileName()
508 return "/fts/pdb_data_columns.txt";
511 public static FTSRestClientI getInstance()
513 if (instance == null)
515 instance = new PDBFTSRestClient();
520 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
523 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
525 if (allDefaultDisplayedStructureDataColumns == null
526 || allDefaultDisplayedStructureDataColumns.isEmpty())
528 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
529 allDefaultDisplayedStructureDataColumns
530 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
532 return allDefaultDisplayedStructureDataColumns;
536 public String[] getPreferencesColumnsFor(PreferenceSource source)
538 String[] columnNames = null;
542 columnNames = new String[] { "", "Display", "Group" };
544 case STRUCTURE_CHOOSER:
545 columnNames = new String[] { "", "Display", "Group" };
548 columnNames = new String[] { "PDB Field", "Show in search summary",
549 "Show in structure summary" };