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.bin.ApplicationSingletonProvider;
45 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
46 import jalview.datamodel.SequenceI;
47 import jalview.fts.api.FTSData;
48 import jalview.fts.api.FTSDataColumnI;
49 import jalview.fts.api.FTSRestClientI;
50 import jalview.fts.api.StructureFTSRestClientI;
51 import jalview.fts.core.FTSDataColumnPreferences;
52 import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
53 import jalview.fts.core.FTSRestClient;
54 import jalview.fts.core.FTSRestRequest;
55 import jalview.fts.core.FTSRestResponse;
56 import jalview.fts.service.alphafold.AlphafoldRestClient;
57 import jalview.util.JSONUtils;
58 import jalview.util.MessageManager;
59 import jalview.util.Platform;
62 * A rest client for querying the Search endpoint of the PDB API
66 public class PDBFTSRestClient extends FTSRestClient
67 implements StructureFTSRestClientI,ApplicationSingletonI
70 private static FTSRestClientI instance = null;
72 public static final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
74 public static FTSRestClientI getInstance()
76 return ApplicationSingletonProvider.getInstance(PDBFTSRestClient.class);
78 protected PDBFTSRestClient()
83 * Takes a PDBRestRequest object and returns a response upon execution
85 * @param pdbRestRequest
86 * the PDBRestRequest instance to be processed
87 * @return the pdbResponse object for the given request
90 @SuppressWarnings({ "unused", "unchecked" })
92 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
97 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
98 pdbRestRequest.getWantedFields());
99 int responseSize = (pdbRestRequest.getResponseSize() == 0)
100 ? getDefaultResponsePageSize()
101 : pdbRestRequest.getResponseSize();
102 int offSet = pdbRestRequest.getOffSet();
103 String sortParam = null;
104 if (pdbRestRequest.getFieldToSortBy() == null
105 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
111 if (pdbRestRequest.getFieldToSortBy()
112 .equalsIgnoreCase("Resolution"))
114 sortParam = pdbRestRequest.getFieldToSortBy()
115 + (pdbRestRequest.isAscending() ? " asc" : " desc");
119 sortParam = pdbRestRequest.getFieldToSortBy()
120 + (pdbRestRequest.isAscending() ? " desc" : " asc");
124 String facetPivot = (pdbRestRequest.getFacetPivot() == null
125 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
126 : pdbRestRequest.getFacetPivot();
127 String facetPivotMinCount = String
128 .valueOf(pdbRestRequest.getFacetPivotMinCount());
130 String query = pdbRestRequest.getFieldToSearchBy()
131 + pdbRestRequest.getSearchTerm()
132 + (pdbRestRequest.isAllowEmptySeq() ? ""
133 : " AND molecule_sequence:['' TO *]")
134 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
135 : " AND status:REL");
137 // Build request parameters for the REST Request
139 // BH 2018 the trick here is to coerce the classes in Javascript to be
140 // different from the ones in Java yet still allow this to be correct for
143 Class<ClientResponse> clientResponseClass;
146 // JavaScript only -- coerce types to Java types for Java
147 client = (Client) (Object) new jalview.javascript.web.Client();
148 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
157 client = Client.create(new DefaultClientConfig());
158 clientResponseClass = ClientResponse.class;
161 WebResource webResource;
162 if (pdbRestRequest.isFacet())
164 webResource = client.resource(PDB_SEARCH_ENDPOINT)
165 .queryParam("wt", "json").queryParam("fl", wantedFields)
166 .queryParam("rows", String.valueOf(responseSize))
167 .queryParam("q", query)
168 .queryParam("start", String.valueOf(offSet))
169 .queryParam("sort", sortParam).queryParam("facet", "true")
170 .queryParam("facet.pivot", facetPivot)
171 .queryParam("facet.pivot.mincount", facetPivotMinCount);
175 webResource = client.resource(PDB_SEARCH_ENDPOINT)
176 .queryParam("wt", "json").queryParam("fl", wantedFields)
177 .queryParam("rows", String.valueOf(responseSize))
178 .queryParam("start", String.valueOf(offSet))
179 .queryParam("q", query).queryParam("sort", sortParam);
182 URI uri = webResource.getURI();
184 System.out.println(uri);
185 ClientResponse clientResponse = null;
186 int responseStatus = -1;
188 // Get the JSON string from the response object or directly from the
189 // client (JavaScript)
190 Map<String, Object> jsonObj = null;
191 String responseString = null;
193 System.out.println("query >>>>>>> " + pdbRestRequest.toString());
197 // Execute the REST request
198 clientResponse = webResource.accept(MediaType.APPLICATION_JSON)
199 .get(clientResponseClass);
200 responseStatus = clientResponse.getStatus();
205 if (mockQueries.containsKey(uri.toString()))
207 responseStatus = 200;
211 // FIXME - may cause unexpected exceptions for callers when mocked
212 responseStatus = 400;
216 // Check the response status and report exception if one occurs
217 switch (responseStatus)
222 responseString = mockQueries.get(uri.toString());
228 jsonObj = clientResponse.getEntity(Map.class);
232 responseString = clientResponse.getEntity(String.class);
237 throw new Exception(isMocked() ? "400 response (Mocked)"
238 : parseJsonExceptionString(responseString));
241 getMessageByHTTPStatusCode(responseStatus, "PDB"));
244 // Process the response and return the result to the caller.
245 return parsePDBJsonResponse(responseString, jsonObj, pdbRestRequest);
246 } catch (Exception e)
248 if (e.getMessage() == null)
252 String exceptionMsg = e.getMessage();
253 if (exceptionMsg.contains("SocketException"))
255 // No internet connection
256 throw new Exception(MessageManager.getString(
257 "exception.unable_to_detect_internet_connection"));
259 else if (exceptionMsg.contains("UnknownHostException"))
261 // The server 'www.ebi.ac.uk' is unreachable
262 throw new Exception(MessageManager.formatMessage(
263 "exception.fts_server_unreachable", "PDB Solr"));
273 * Process error response from PDB server if/when one occurs.
275 * @param jsonResponse
276 * the JSON string containing error message from the server
277 * @return the processed error message from the JSON string
279 @SuppressWarnings("unchecked")
280 public static String parseJsonExceptionString(String jsonErrorResponse)
282 StringBuilder errorMessage = new StringBuilder(
283 "\n============= PDB Rest Client RunTime error =============\n");
286 // "responseHeader":{
290 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
291 // "fl":"pdb_id,title,experimental_method,resolution",
293 // "sort":"overall_quality desc",
296 // "response":{"numFound":1,"start":0,"docs":[
298 // "experimental_method":["X-ray diffraction"],
300 // "resolution":2.46,
301 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S
307 Map<String, Object> jsonObj = (Map<String, Object>) JSONUtils
308 .parse(jsonErrorResponse);
309 Map<String, Object> errorResponse = (Map<String, Object>) jsonObj
312 Map<String, Object> responseHeader = (Map<String, Object>) jsonObj
313 .get("responseHeader");
314 Map<String, Object> paramsObj = (Map<String, Object>) responseHeader
316 String status = responseHeader.get("status").toString();
317 String message = errorResponse.get("msg").toString();
318 String query = paramsObj.get("q").toString();
319 String fl = paramsObj.get("fl").toString();
321 errorMessage.append("Status: ").append(status).append("\n");
322 errorMessage.append("Message: ").append(message).append("\n");
323 errorMessage.append("query: ").append(query).append("\n");
324 errorMessage.append("fl: ").append(fl).append("\n");
326 } catch (ParseException e)
330 return errorMessage.toString();
334 * Parses the JSON response string from PDB REST API. The response is dynamic
335 * hence, only fields specifically requested for in the 'wantedFields'
336 * parameter is fetched/processed
338 * @param pdbJsonResponseString
339 * the JSON string to be parsed
340 * @param pdbRestRequest
341 * the request object which contains parameters used to process the
345 public static FTSRestResponse parsePDBJsonResponse(
346 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
348 return parsePDBJsonResponse(pdbJsonResponseString,
349 (Map<String, Object>) null, pdbRestRequest);
352 @SuppressWarnings("unchecked")
353 public static FTSRestResponse parsePDBJsonResponse(
354 String pdbJsonResponseString, Map<String, Object> jsonObj,
355 FTSRestRequest pdbRestRequest)
357 FTSRestResponse searchResult = new FTSRestResponse();
358 List<FTSData> result = null;
363 jsonObj = (Map<String, Object>) JSONUtils
364 .parse(pdbJsonResponseString);
366 Map<String, Object> pdbResponse = (Map<String, Object>) jsonObj
368 String queryTime = ((Map<String, Object>) jsonObj
369 .get("responseHeader")).get("QTime").toString();
370 int numFound = Integer
371 .valueOf(pdbResponse.get("numFound").toString());
372 List<Object> docs = (List<Object>) pdbResponse.get("docs");
374 result = new ArrayList<FTSData>();
377 for (Iterator<Object> docIter = docs.iterator(); docIter.hasNext();)
379 Map<String, Object> doc = (Map<String, Object>) docIter.next();
380 result.add(getFTSData(doc, pdbRestRequest));
383 // this is the total number found by the query,
384 // rather than the set returned in SearchSummary
385 searchResult.setNumberOfItemsFound(numFound);
386 searchResult.setResponseTime(queryTime);
387 searchResult.setSearchSummary(result);
388 } catch (ParseException e)
395 public static FTSData getFTSData(Map<String, Object> pdbJsonDoc,
396 FTSRestRequest request)
399 String primaryKey = null;
401 Object[] summaryRowData;
403 SequenceI associatedSequence;
405 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
406 SequenceI associatedSeq = request.getAssociatedSequence();
408 summaryRowData = new Object[(associatedSeq != null)
409 ? diplayFields.size() + 1
410 : diplayFields.size()];
411 if (associatedSeq != null)
413 associatedSequence = associatedSeq;
414 summaryRowData[0] = associatedSequence;
418 for (FTSDataColumnI field : diplayFields)
420 // System.out.println("Field " + field);
421 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
422 : pdbJsonDoc.get(field.getCode()).toString();
423 // System.out.println("Field Data : " + fieldData);
424 if (field.isPrimaryKeyColumn())
426 primaryKey = fieldData;
427 summaryRowData[colCounter++] = primaryKey;
429 else if (fieldData == null || fieldData.isEmpty())
431 summaryRowData[colCounter++] = null;
437 summaryRowData[colCounter++] = (field.getDataType()
438 .getDataTypeClass() == Integer.class)
439 ? Integer.valueOf(fieldData)
440 : (field.getDataType()
441 .getDataTypeClass() == Double.class)
442 ? Double.valueOf(fieldData)
443 : sanitiseData(fieldData);
444 } catch (Exception e)
447 System.out.println("offending value:" + fieldData);
452 final String primaryKey1 = primaryKey;
454 final Object[] summaryRowData1 = summaryRowData;
458 public Object[] getSummaryData()
460 return summaryRowData1;
464 public Object getPrimaryKey()
470 * Returns a string representation of this object;
473 public String toString()
475 StringBuilder summaryFieldValues = new StringBuilder();
476 for (Object summaryField : summaryRowData1)
478 summaryFieldValues.append(
479 summaryField == null ? " " : summaryField.toString())
482 return summaryFieldValues.toString();
486 * Returns hash code value for this object
489 public int hashCode()
491 return Objects.hash(primaryKey1, this.toString());
495 public boolean equals(Object that)
497 return this.toString().equals(that.toString());
502 private static String sanitiseData(String data)
504 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
505 .replaceAll("\\[", "").replaceAll("\\]", "")
506 .replaceAll("\",\"", ", ").replaceAll("\"", "");
511 public String getColumnDataConfigFileName()
513 return "/fts/pdb_data_columns.txt";
517 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
520 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
522 if (allDefaultDisplayedStructureDataColumns == null
523 || allDefaultDisplayedStructureDataColumns.isEmpty())
525 allDefaultDisplayedStructureDataColumns = new ArrayList<>();
526 allDefaultDisplayedStructureDataColumns
527 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
529 return allDefaultDisplayedStructureDataColumns;
532 public String[] getPreferencesColumnsFor(PreferenceSource source)
534 String[] columnNames = null;
538 columnNames = new String[] { "", "Display", "Group" };
540 case STRUCTURE_CHOOSER:
541 columnNames = new String[] { "", "Display", "Group" };
544 columnNames = new String[] { "PDB Field", "Show in search summary",
545 "Show in structure summary" };