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.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 implements StructureFTSRestClientI
62 private static FTSRestClientI instance = null;
64 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
66 protected PDBFTSRestClient()
71 * Takes a PDBRestRequest object and returns a response upon execution
73 * @param pdbRestRequest
74 * the PDBRestRequest instance to be processed
75 * @return the pdbResponse object for the given request
78 @SuppressWarnings({ "unused", "unchecked" })
80 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
85 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
86 pdbRestRequest.getWantedFields());
87 int responseSize = (pdbRestRequest.getResponseSize() == 0)
88 ? getDefaultResponsePageSize()
89 : pdbRestRequest.getResponseSize();
90 int offSet = pdbRestRequest.getOffSet();
91 String sortParam = null;
92 if (pdbRestRequest.getFieldToSortBy() == null
93 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
99 if (pdbRestRequest.getFieldToSortBy()
100 .equalsIgnoreCase("Resolution"))
102 sortParam = pdbRestRequest.getFieldToSortBy()
103 + (pdbRestRequest.isAscending() ? " asc" : " desc");
107 sortParam = pdbRestRequest.getFieldToSortBy()
108 + (pdbRestRequest.isAscending() ? " desc" : " asc");
112 String facetPivot = (pdbRestRequest.getFacetPivot() == null
113 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
114 : pdbRestRequest.getFacetPivot();
115 String facetPivotMinCount = String
116 .valueOf(pdbRestRequest.getFacetPivotMinCount());
118 String query = pdbRestRequest.getFieldToSearchBy()
119 + pdbRestRequest.getSearchTerm()
120 + (pdbRestRequest.isAllowEmptySeq() ? ""
121 : " AND molecule_sequence:['' TO *]")
122 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
123 : " AND status:REL");
125 // Build request parameters for the REST Request
127 // BH 2018 the trick here is to coerce the classes in Javascript to be
128 // different from the ones in Java yet still allow this to be correct for Java
130 Class<ClientResponse> clientResponseClass;
133 // JavaScript only -- coerce types to Java types for Java
134 client = (Client) (Object) new jalview.javascript.web.Client();
135 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
144 client = Client.create(new DefaultClientConfig());
145 clientResponseClass = ClientResponse.class;
148 WebResource webResource;
149 if (pdbRestRequest.isFacet())
151 webResource = client.resource(PDB_SEARCH_ENDPOINT)
152 .queryParam("wt", "json").queryParam("fl", wantedFields)
153 .queryParam("rows", String.valueOf(responseSize))
154 .queryParam("q", query)
155 .queryParam("start", String.valueOf(offSet))
156 .queryParam("sort", sortParam).queryParam("facet", "true")
157 .queryParam("facet.pivot", facetPivot)
158 .queryParam("facet.pivot.mincount", facetPivotMinCount);
162 webResource = client.resource(PDB_SEARCH_ENDPOINT)
163 .queryParam("wt", "json").queryParam("fl", wantedFields)
164 .queryParam("rows", String.valueOf(responseSize))
165 .queryParam("start", String.valueOf(offSet))
166 .queryParam("q", query).queryParam("sort", sortParam);
169 URI uri = webResource.getURI();
171 System.out.println(uri);
173 // Execute the REST request
174 ClientResponse clientResponse = webResource
175 .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
177 // Get the JSON string from the response object or directly from the
178 // client (JavaScript)
179 Map<String, Object> jsonObj = null;
180 String responseString = null;
182 System.out.println("query >>>>>>> " + pdbRestRequest.toString());
184 // Check the response status and report exception if one occurs
185 int responseStatus = clientResponse.getStatus();
186 switch (responseStatus)
191 jsonObj = clientResponse.getEntity(Map.class);
195 responseString = clientResponse.getEntity(String.class);
199 throw new Exception(parseJsonExceptionString(responseString));
202 getMessageByHTTPStatusCode(responseStatus, "PDB"));
205 // Process the response and return the result to the caller.
206 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
207 } catch (Exception e)
209 String exceptionMsg = e.getMessage();
210 if (exceptionMsg.contains("SocketException"))
212 // No internet connection
213 throw new Exception(MessageManager.getString(
214 "exception.unable_to_detect_internet_connection"));
216 else if (exceptionMsg.contains("UnknownHostException"))
218 // The server 'www.ebi.ac.uk' is unreachable
219 throw new Exception(MessageManager.formatMessage(
220 "exception.fts_server_unreachable", "PDB Solr"));
230 * Process error response from PDB server if/when one occurs.
232 * @param jsonResponse
233 * the JSON string containing error message from the server
234 * @return the processed error message from the JSON string
236 @SuppressWarnings("unchecked")
237 public static String parseJsonExceptionString(String jsonErrorResponse)
239 StringBuilder errorMessage = new StringBuilder(
240 "\n============= PDB Rest Client RunTime error =============\n");
244 // "responseHeader":{
248 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
249 // "fl":"pdb_id,title,experimental_method,resolution",
251 // "sort":"overall_quality desc",
254 // "response":{"numFound":1,"start":0,"docs":[
256 // "experimental_method":["X-ray diffraction"],
258 // "resolution":2.46,
259 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
264 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
265 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
267 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
268 .get("responseHeader");
269 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
270 String status = responseHeader.get("status").toString();
271 String message = errorResponse.get("msg").toString();
272 String query = paramsObj.get("q").toString();
273 String fl = paramsObj.get("fl").toString();
275 errorMessage.append("Status: ").append(status).append("\n");
276 errorMessage.append("Message: ").append(message).append("\n");
277 errorMessage.append("query: ").append(query).append("\n");
278 errorMessage.append("fl: ").append(fl).append("\n");
280 } catch (ParseException e)
284 return errorMessage.toString();
288 * Parses the JSON response string from PDB REST API. The response is dynamic
289 * hence, only fields specifically requested for in the 'wantedFields'
290 * parameter is fetched/processed
292 * @param pdbJsonResponseString
293 * the JSON string to be parsed
294 * @param pdbRestRequest
295 * the request object which contains parameters used to process the
299 public static FTSRestResponse parsePDBJsonResponse(
300 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
302 return parsePDBJsonResponse(pdbJsonResponseString,
303 (Map<String, Object>) null, pdbRestRequest);
306 @SuppressWarnings("unchecked")
307 public static FTSRestResponse parsePDBJsonResponse(
308 String pdbJsonResponseString, Map<String, Object> jsonObj,
309 FTSRestRequest pdbRestRequest)
311 FTSRestResponse searchResult = new FTSRestResponse();
312 List<FTSData> result = null;
317 jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
319 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
320 String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
321 .get("QTime").toString();
322 int numFound = Integer
323 .valueOf(pdbResponse.get("numFound").toString());
326 result = new ArrayList<>();
327 List<Object> docs = (List<Object>) pdbResponse.get("docs");
328 for (Iterator<Object> docIter = docs.iterator(); docIter
331 Map<String, Object> doc = (Map<String, Object>) docIter.next();
332 result.add(getFTSData(doc, pdbRestRequest));
334 searchResult.setNumberOfItemsFound(numFound);
335 searchResult.setResponseTime(queryTime);
336 searchResult.setSearchSummary(result);
338 } catch (ParseException e)
345 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
346 FTSRestRequest request)
349 String primaryKey = null;
351 Object[] summaryRowData;
353 SequenceI associatedSequence;
355 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
356 SequenceI associatedSeq = request.getAssociatedSequence();
358 summaryRowData = new Object[(associatedSeq != null)
359 ? diplayFields.size() + 1
360 : diplayFields.size()];
361 if (associatedSeq != null)
363 associatedSequence = associatedSeq;
364 summaryRowData[0] = associatedSequence;
368 for (FTSDataColumnI field : diplayFields)
370 //System.out.println("Field " + field);
371 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
372 : pdbJsonDoc.get(field.getCode()).toString();
373 //System.out.println("Field Data : " + fieldData);
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 public static FTSRestClientI getInstance()
468 if (instance == null)
470 instance = new PDBFTSRestClient();
475 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
477 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
479 if (allDefaultDisplayedStructureDataColumns == null
480 || allDefaultDisplayedStructureDataColumns.isEmpty())
482 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
483 allDefaultDisplayedStructureDataColumns
484 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
486 return allDefaultDisplayedStructureDataColumns;
489 public String[] getPreferencesColumnsFor(PreferenceSource source) {
490 String[] columnNames = null;
494 columnNames = new String[] { "", "Display", "Group" };
496 case STRUCTURE_CHOOSER:
497 columnNames = new String[] { "", "Display", "Group" };
500 columnNames = new String[] { "PDB Field", "Show in search summary",
501 "Show in structure summary" };