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.MessageManager;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Objects;
39 import javax.ws.rs.core.MediaType;
41 import org.json.simple.JSONArray;
42 import org.json.simple.JSONObject;
43 import org.json.simple.parser.JSONParser;
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 final String PDB_SEARCH_ENDPOINT = "https://www.ebi.ac.uk/pdbe/search/pdb/select?";
63 protected PDBFTSRestClient()
68 * Takes a PDBRestRequest object and returns a response upon execution
70 * @param pdbRestRequest
71 * the PDBRestRequest instance to be processed
72 * @return the pdbResponse object for the given request
75 @SuppressWarnings({ "unused", "unchecked" })
77 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
82 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(
83 pdbRestRequest.getWantedFields());
84 int responseSize = (pdbRestRequest.getResponseSize() == 0)
85 ? getDefaultResponsePageSize()
86 : pdbRestRequest.getResponseSize();
87 int offSet = pdbRestRequest.getOffSet();
88 String sortParam = null;
89 if (pdbRestRequest.getFieldToSortBy() == null
90 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
96 if (pdbRestRequest.getFieldToSortBy()
97 .equalsIgnoreCase("Resolution"))
99 sortParam = pdbRestRequest.getFieldToSortBy()
100 + (pdbRestRequest.isAscending() ? " asc" : " desc");
104 sortParam = pdbRestRequest.getFieldToSortBy()
105 + (pdbRestRequest.isAscending() ? " desc" : " asc");
109 String facetPivot = (pdbRestRequest.getFacetPivot() == null
110 || pdbRestRequest.getFacetPivot().isEmpty()) ? ""
111 : pdbRestRequest.getFacetPivot();
112 String facetPivotMinCount = String
113 .valueOf(pdbRestRequest.getFacetPivotMinCount());
115 String query = pdbRestRequest.getFieldToSearchBy()
116 + pdbRestRequest.getSearchTerm()
117 + (pdbRestRequest.isAllowEmptySeq() ? ""
118 : " AND molecule_sequence:['' TO *]")
119 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
120 : " AND status:REL");
122 // Build request parameters for the REST Request
124 // BH 2018 the trick here is to coerce the classes in Javascript to be
125 // different from the ones in Java yet still allow this to be correct for Java
127 Class<ClientResponse> clientResponseClass;
128 if (/** @j2sNative true || */
131 // JavaScript only -- coerce types to Java types for Java
132 client = (Client) (Object) new jalview.javascript.web.Client();
133 clientResponseClass = (Class<ClientResponse>) (Object) jalview.javascript.web.ClientResponse.class;
138 client = Client.create(new DefaultClientConfig());
139 clientResponseClass = ClientResponse.class;
142 WebResource webResource;
143 if (pdbRestRequest.isFacet())
145 webResource = client.resource(PDB_SEARCH_ENDPOINT)
146 .queryParam("wt", "json").queryParam("fl", wantedFields)
147 .queryParam("rows", String.valueOf(responseSize))
148 .queryParam("q", query)
149 .queryParam("start", String.valueOf(offSet))
150 .queryParam("sort", sortParam).queryParam("facet", "true")
151 .queryParam("facet.pivot", facetPivot)
152 .queryParam("facet.pivot.mincount", facetPivotMinCount);
156 webResource = client.resource(PDB_SEARCH_ENDPOINT)
157 .queryParam("wt", "json").queryParam("fl", wantedFields)
158 .queryParam("rows", String.valueOf(responseSize))
159 .queryParam("start", String.valueOf(offSet))
160 .queryParam("q", query).queryParam("sort", sortParam);
163 URI uri = webResource.getURI();
165 // Execute the REST request
166 ClientResponse clientResponse = webResource
167 .accept(MediaType.APPLICATION_JSON).get(clientResponseClass );
169 // Get the JSON string from the response object
170 String responseString = clientResponse.getEntity(String.class);
171 // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
173 // Check the response status and report exception if one occurs
174 if (clientResponse.getStatus() != 200)
176 String errorMessage = "";
177 if (clientResponse.getStatus() == 400)
179 errorMessage = parseJsonExceptionString(responseString);
180 throw new Exception(errorMessage);
184 errorMessage = getMessageByHTTPStatusCode(
185 clientResponse.getStatus(), "PDB");
186 throw new Exception(errorMessage);
190 // Make redundant objects eligible for garbage collection to conserve
192 clientResponse = null;
195 // Process the response and return the result to the caller.
196 return parsePDBJsonResponse(responseString, pdbRestRequest);
197 } catch (Exception e)
199 String exceptionMsg = e.getMessage();
200 if (exceptionMsg.contains("SocketException"))
202 // No internet connection
203 throw new Exception(MessageManager.getString(
204 "exception.unable_to_detect_internet_connection"));
206 else if (exceptionMsg.contains("UnknownHostException"))
208 // The server 'www.ebi.ac.uk' is unreachable
209 throw new Exception(MessageManager.formatMessage(
210 "exception.fts_server_unreachable", "PDB Solr"));
220 * Process error response from PDB server if/when one occurs.
222 * @param jsonResponse
223 * the JSON string containing error message from the server
224 * @return the processed error message from the JSON string
226 public static String parseJsonExceptionString(String jsonErrorResponse)
228 StringBuilder errorMessage = new StringBuilder(
229 "\n============= PDB Rest Client RunTime error =============\n");
233 // "responseHeader":{
237 // "q":"(text:q93xj9_soltu) AND molecule_sequence:['' TO *] AND status:REL",
238 // "fl":"pdb_id,title,experimental_method,resolution",
240 // "sort":"overall_quality desc",
243 // "response":{"numFound":1,"start":0,"docs":[
245 // "experimental_method":["X-ray diffraction"],
247 // "resolution":2.46,
248 // "title":"The crystal structure of Potato ferredoxin I with 2Fe-2S cluster"}]
253 JSONParser jsonParser = new JSONParser();
254 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
255 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
257 JSONObject responseHeader = (JSONObject) jsonObj
258 .get("responseHeader");
259 JSONObject paramsObj = (JSONObject) responseHeader.get("params");
260 String status = responseHeader.get("status").toString();
261 String message = errorResponse.get("msg").toString();
262 String query = paramsObj.get("q").toString();
263 String fl = paramsObj.get("fl").toString();
265 errorMessage.append("Status: ").append(status).append("\n");
266 errorMessage.append("Message: ").append(message).append("\n");
267 errorMessage.append("query: ").append(query).append("\n");
268 errorMessage.append("fl: ").append(fl).append("\n");
270 } catch (ParseException e)
274 return errorMessage.toString();
278 * Parses the JSON response string from PDB REST API. The response is dynamic
279 * hence, only fields specifically requested for in the 'wantedFields'
280 * parameter is fetched/processed
282 * @param pdbJsonResponseString
283 * the JSON string to be parsed
284 * @param pdbRestRequest
285 * the request object which contains parameters used to process the
289 @SuppressWarnings("unchecked")
290 public static FTSRestResponse parsePDBJsonResponse(
291 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
293 FTSRestResponse searchResult = new FTSRestResponse();
294 List<FTSData> result = null;
297 JSONParser jsonParser = new JSONParser();
298 JSONObject jsonObj = (JSONObject) jsonParser
299 .parse(pdbJsonResponseString);
301 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
302 String queryTime = ((JSONObject) jsonObj.get("responseHeader"))
303 .get("QTime").toString();
304 int numFound = Integer
305 .valueOf(pdbResponse.get("numFound").toString());
308 result = new ArrayList<FTSData>();
309 JSONArray docs = (JSONArray) pdbResponse.get("docs");
310 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
313 JSONObject doc = docIter.next();
314 result.add(getFTSData(doc, pdbRestRequest));
316 searchResult.setNumberOfItemsFound(numFound);
317 searchResult.setResponseTime(queryTime);
318 searchResult.setSearchSummary(result);
320 } catch (ParseException e)
327 public static FTSData getFTSData(JSONObject pdbJsonDoc,
328 FTSRestRequest request)
331 String primaryKey = null;
333 Object[] summaryRowData;
335 SequenceI associatedSequence;
337 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
338 SequenceI associatedSeq = request.getAssociatedSequence();
340 summaryRowData = new Object[(associatedSeq != null)
341 ? diplayFields.size() + 1
342 : diplayFields.size()];
343 if (associatedSeq != null)
345 associatedSequence = associatedSeq;
346 summaryRowData[0] = associatedSequence;
350 for (FTSDataColumnI field : diplayFields)
352 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
353 : pdbJsonDoc.get(field.getCode()).toString();
354 if (field.isPrimaryKeyColumn())
356 primaryKey = fieldData;
357 summaryRowData[colCounter++] = primaryKey;
359 else if (fieldData == null || fieldData.isEmpty())
361 summaryRowData[colCounter++] = null;
367 summaryRowData[colCounter++] = (field.getDataType()
368 .getDataTypeClass() == Integer.class)
369 ? Integer.valueOf(fieldData)
370 : (field.getDataType()
371 .getDataTypeClass() == Double.class)
372 ? Double.valueOf(fieldData)
373 : sanitiseData(fieldData);
374 } catch (Exception e)
377 System.out.println("offending value:" + fieldData);
382 final String primaryKey1 = primaryKey;
384 final Object[] summaryRowData1 = summaryRowData;
388 public Object[] getSummaryData()
390 return summaryRowData1;
394 public Object getPrimaryKey()
400 * Returns a string representation of this object;
403 public String toString()
405 StringBuilder summaryFieldValues = new StringBuilder();
406 for (Object summaryField : summaryRowData1)
408 summaryFieldValues.append(
409 summaryField == null ? " " : summaryField.toString())
412 return summaryFieldValues.toString();
416 * Returns hash code value for this object
419 public int hashCode()
421 return Objects.hash(primaryKey1, this.toString());
425 public boolean equals(Object that)
427 return this.toString().equals(that.toString());
432 private static String sanitiseData(String data)
434 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
435 .replaceAll("\\[", "").replaceAll("\\]", "")
436 .replaceAll("\",\"", ", ").replaceAll("\"", "");
441 public String getColumnDataConfigFileName()
443 return "/fts/pdb_data_columns.txt";
446 public static FTSRestClientI getInstance()
448 if (instance == null)
450 instance = new PDBFTSRestClient();
455 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
457 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
459 if (allDefaultDisplayedStructureDataColumns == null
460 || allDefaultDisplayedStructureDataColumns.isEmpty())
462 allDefaultDisplayedStructureDataColumns = new ArrayList<FTSDataColumnI>();
463 allDefaultDisplayedStructureDataColumns
464 .addAll(super.getAllDefaultDisplayedFTSDataColumns());
466 return allDefaultDisplayedStructureDataColumns;
469 public static void main(String[] args) {
472 // check for transpiler fix associated with JSONParser yylex.java use of charAt()
473 // instead of codePointAt()
482 String result = s +x + y + z;
483 assert (result == "e103982102");
484 JSONParser jsonParser = new JSONParser();
487 JSONObject jsonObj = (JSONObject) jsonParser.parse("{\"a\":3}");
488 System.out.println(jsonObj);
489 } catch (ParseException e)