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;
23 import jalview.datamodel.SequenceI;
24 import jalview.fts.api.FTSData;
25 import jalview.fts.api.FTSDataColumnI;
26 import jalview.fts.api.FTSRestClientI;
27 import jalview.fts.core.FTSRestClient;
28 import jalview.fts.core.FTSRestRequest;
29 import jalview.fts.core.FTSRestResponse;
30 import jalview.util.JSONUtils;
31 import jalview.util.MessageManager;
32 import jalview.util.Platform;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Objects;
42 import javax.ws.rs.core.MediaType;
44 import org.json.simple.parser.ParseException;
46 import com.sun.jersey.api.client.Client;
47 import com.sun.jersey.api.client.ClientResponse;
48 import com.sun.jersey.api.client.WebResource;
49 import com.sun.jersey.api.client.config.DefaultClientConfig;
52 * A rest client for querying the Search endpoint of the PDB API
56 public class PDBFTSRestClient extends FTSRestClient
59 private static FTSRestClientI instance = null;
61 public static FTSRestClientI getInstance()
64 // BH 2019.05.08 need to isolate static fields in JavaScript
66 FTSRestClientI i = instance;
67 @SuppressWarnings("unused")
71 g = Thread.currentThread().getThreadGroup();
73 * @j2sNative i = g._jalviewPDBFTSRestClientInstance;
79 i = new PDBFTSRestClient();
84 * @j2sNative g._jalviewPDBFTSRestClientInstance = i;
96 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
98 protected PDBFTSRestClient()
103 * Takes a PDBRestRequest object and returns a response upon execution
105 * @param pdbRestRequest
106 * the PDBRestRequest instance to be processed
107 * @return the pdbResponse object for the given request
110 @SuppressWarnings({ "unused", "unchecked" })
112 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
117 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
118 pdbRestRequest.getWantedFields());
119 int responseSize = (pdbRestRequest.getResponseSize() == 0)
120 ? getDefaultResponsePageSize()
121 : pdbRestRequest.getResponseSize();
122 int offSet = pdbRestRequest.getOffSet();
123 String sortParam = null;
124 if (pdbRestRequest.getFieldToSortBy() == null
125 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
131 if (pdbRestRequest.getFieldToSortBy()
132 .equalsIgnoreCase("Resolution"))
134 sortParam = pdbRestRequest.getFieldToSortBy()
135 + (pdbRestRequest.isAscending() ? " asc" : " desc");
139 sortParam = pdbRestRequest.getFieldToSortBy()
140 + (pdbRestRequest.isAscending() ? " desc" : " asc");
144 String facetPivot = (pdbRestRequest.getFacetPivot() == null
145 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
146 : pdbRestRequest.getFacetPivot();
147 String facetPivotMinCount = String
148 .valueOf(pdbRestRequest.getFacetPivotMinCount());
150 String query = pdbRestRequest.getFieldToSearchBy()
151 + pdbRestRequest.getSearchTerm()
152 + (pdbRestRequest.isAllowEmptySeq() ? ""
153 : " AND molecule_sequence:['' TO *]")
154 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
155 : " AND status:REL");
157 // Build request parameters for the REST Request
159 // BH 2018 the trick here is to coerce the classes in Javascript to be
160 // different from the ones in Java yet still allow this to be correct for Java
162 Class<ClientResponse> clientResponseClass;
165 // JavaScript only -- coerce types to Java types for Java
166 client = (Client) (Object) new jalview.javascript.web.Client();
167 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
176 client = Client.create(new DefaultClientConfig());
177 clientResponseClass = ClientResponse.class;
180 WebResource webResource;
181 if (pdbRestRequest.isFacet())
183 webResource = client.resource(PDB_SEARCH_ENDPOINT)
184 .queryParam("wt", "json").queryParam("fl", wantedFields)
185 .queryParam("rows", String.valueOf(responseSize))
186 .queryParam("q", query)
187 .queryParam("start", String.valueOf(offSet))
188 .queryParam("sort", sortParam).queryParam("facet", "true")
189 .queryParam("facet.pivot", facetPivot)
190 .queryParam("facet.pivot.mincount", facetPivotMinCount);
194 webResource = client.resource(PDB_SEARCH_ENDPOINT)
195 .queryParam("wt", "json").queryParam("fl", wantedFields)
196 .queryParam("rows", String.valueOf(responseSize))
197 .queryParam("start", String.valueOf(offSet))
198 .queryParam("q", query).queryParam("sort", sortParam);
201 URI uri = webResource.getURI();
203 System.out.println(uri);
205 // Execute the REST request
206 ClientResponse clientResponse = webResource
207 .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
209 int status = clientResponse.getStatus();
211 // Get the JSON string from the response object or directly from the
212 // client (JavaScript)
213 Map<String, Object> jsonObj = (Platform.isJS() && status == 200
214 ? clientResponse.getEntity(Map.class)
216 String responseString = (jsonObj == null
217 ? clientResponse.getEntity(String.class)
220 // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
222 // Check the response status and report exception if one occurs
228 throw new Exception(parseJsonExceptionString(responseString));
230 throw new Exception(getMessageByHTTPStatusCode(status, "PDB"));
233 // Make redundant objects eligible for garbage collection to conserve
235 clientResponse = null;
238 // Process the response and return the result to the caller.
239 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
240 } catch (Exception e)
242 String exceptionMsg = e.getMessage();
243 if (exceptionMsg.contains("SocketException"))
245 // No internet connection
246 throw new Exception(MessageManager.getString(
247 "exception.unable_to_detect_internet_connection"));
249 else if (exceptionMsg.contains("UnknownHostException"))
251 // The server 'www.ebi.ac.uk' is unreachable
252 throw new Exception(MessageManager.formatMessage(
253 "exception.fts_server_unreachable", "PDB Solr"));
263 * Process error response from PDB server if/when one occurs.
265 * @param jsonResponse
266 * the JSON string containing error message from the server
267 * @return the processed error message from the JSON string
269 @SuppressWarnings("unchecked")
270 public static String parseJsonExceptionString(String jsonErrorResponse)
272 StringBuilder errorMessage = new StringBuilder(
273 "\n============= PDB Rest Client RunTime error =============\n");
277 // "responseHeader":{
281 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
282 // "fl":"pdb_id,title,experimental_method,resolution",
284 // "sort":"overall_quality desc",
287 // "response":{"numFound":1,"start":0,"docs":[
289 // "experimental_method":["X-ray diffraction"],
291 // "resolution":2.46,
292 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
297 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils.parse(jsonErrorResponse);
298 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj.get("error");
300 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
301 .get("responseHeader");
302 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader.get("params");
303 String status = responseHeader.get("status").toString();
304 String message = errorResponse.get("msg").toString();
305 String query = paramsObj.get("q").toString();
306 String fl = paramsObj.get("fl").toString();
308 errorMessage.append("Status: ").append(status).append("\n");
309 errorMessage.append("Message: ").append(message).append("\n");
310 errorMessage.append("query: ").append(query).append("\n");
311 errorMessage.append("fl: ").append(fl).append("\n");
313 } catch (ParseException e)
317 return errorMessage.toString();
321 * Parses the JSON response string from PDB REST API. The response is dynamic
322 * hence, only fields specifically requested for in the 'wantedFields'
323 * parameter is fetched/processed
325 * @param pdbJsonResponseString
326 * the JSON string to be parsed
327 * @param pdbRestRequest
328 * the request object which contains parameters used to process the
332 public static FTSRestResponse parsePDBJsonResponse(
333 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
335 return parsePDBJsonResponse(pdbJsonResponseString,
336 (Map<String, Object>) null, pdbRestRequest);
339 @SuppressWarnings("unchecked")
340 public static FTSRestResponse parsePDBJsonResponse(
341 String pdbJsonResponseString, Map<String, Object> jsonObj,
342 FTSRestRequest pdbRestRequest)
344 FTSRestResponse searchResult = new FTSRestResponse();
345 List<FTSData> result = null;
350 jsonObj = (Map<String, Object>) JSONUtils.parse(pdbJsonResponseString);
352 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj.get("response");
353 String queryTime = ((Map<String, Object>) jsonObj.get("responseHeader"))
354 .get("QTime").toString();
355 int numFound = Integer
356 .valueOf(pdbResponse.get("numFound").toString());
359 result = new ArrayList<>();
360 List<Object> docs = (List<Object>) pdbResponse.get("docs");
361 for (Iterator<Object> docIter = docs.iterator(); docIter
364 Map<String, Object> doc = (Map<String, Object>) docIter.next();
365 result.add(getFTSData(doc, pdbRestRequest));
367 searchResult.setNumberOfItemsFound(numFound);
368 searchResult.setResponseTime(queryTime);
369 searchResult.setSearchSummary(result);
371 } catch (ParseException e)
378 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
379 FTSRestRequest request)
382 String primaryKey = null;
384 Object[] summaryRowData;
386 SequenceI associatedSequence;
388 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
389 SequenceI associatedSeq = request.getAssociatedSequence();
391 summaryRowData = new Object[(associatedSeq != null)
392 ? diplayFields.size() + 1
393 : diplayFields.size()];
394 if (associatedSeq != null)
396 associatedSequence = associatedSeq;
397 summaryRowData[0] = associatedSequence;
401 for (FTSDataColumnI field : diplayFields)
403 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
404 : pdbJsonDoc.get(field.getCode()).toString();
405 if (field.isPrimaryKeyColumn())
407 primaryKey = fieldData;
408 summaryRowData[colCounter++] = primaryKey;
410 else if (fieldData == null || fieldData.isEmpty())
412 summaryRowData[colCounter++] = null;
418 summaryRowData[colCounter++] = (field.getDataType()
419 .getDataTypeClass() == Integer.class)
420 ? Integer.valueOf(fieldData)
421 : (field.getDataType()
422 .getDataTypeClass() == Double.class)
423 ? Double.valueOf(fieldData)
424 : sanitiseData(fieldData);
425 } catch (Exception e)
428 System.out.println("offending value:" + fieldData);
433 final String primaryKey1 = primaryKey;
435 final Object[] summaryRowData1 = summaryRowData;
439 public Object[] getSummaryData()
441 return summaryRowData1;
445 public Object getPrimaryKey()
451 * Returns a string representation of this object;
454 public String toString()
456 StringBuilder summaryFieldValues = new StringBuilder();
457 for (Object summaryField : summaryRowData1)
459 summaryFieldValues.append(
460 summaryField == null ? " " : summaryField.toString())
463 return summaryFieldValues.toString();
467 * Returns hash code value for this object
470 public int hashCode()
472 return Objects.hash(primaryKey1, this.toString());
476 public boolean equals(Object that)
478 return this.toString().equals(that.toString());
483 private static String sanitiseData(String data)
485 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
486 .replaceAll("\\[", "").replaceAll("\\]", "")
487 .replaceAll("\",\"", ", ").replaceAll("\"", "");
492 public String getColumnDataConfigFileName()
494 return "/fts/pdb_data_columns.txt";
497 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
499 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
501 if (allDefaultDisplayedStructureDataColumns == null
502 || allDefaultDisplayedStructureDataColumns.isEmpty())
504 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
505 allDefaultDisplayedStructureDataColumns
506 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
508 return allDefaultDisplayedStructureDataColumns;