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;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Objects;
38 import javax.ws.rs.core.MediaType;
40 import org.json.simple.JSONArray;
41 import org.json.simple.JSONObject;
42 import org.json.simple.parser.JSONParser;
43 import org.json.simple.parser.ParseException;
45 import com.sun.jersey.api.client.Client;
46 import com.sun.jersey.api.client.ClientResponse;
47 import com.sun.jersey.api.client.WebResource;
48 import com.sun.jersey.api.client.config.ClientConfig;
49 import com.sun.jersey.api.client.config.DefaultClientConfig;
52 * A rest client for querying the Search endpoint of the PDB API
57 public class PDBFTSRestClient extends FTSRestClient
60 private static FTSRestClientI instance = null;
62 public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?";
64 protected PDBFTSRestClient()
69 * Takes a PDBRestRequest object and returns a response upon execution
71 * @param pdbRestRequest
72 * the PDBRestRequest instance to be processed
73 * @return the pdbResponse object for the given request
77 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
82 ClientConfig clientConfig = new DefaultClientConfig();
83 Client client = Client.create(clientConfig);
85 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(pdbRestRequest
87 int responseSize = (pdbRestRequest.getResponseSize() == 0) ? getDefaultResponsePageSize()
88 : pdbRestRequest.getResponseSize();
89 int offSet = pdbRestRequest.getOffSet();
90 String sortParam = null;
91 if (pdbRestRequest.getFieldToSortBy() == null
92 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
98 if (pdbRestRequest.getFieldToSortBy()
99 .equalsIgnoreCase("Resolution"))
101 sortParam = pdbRestRequest.getFieldToSortBy()
102 + (pdbRestRequest.isAscending() ? " asc" : " desc");
106 sortParam = pdbRestRequest.getFieldToSortBy()
107 + (pdbRestRequest.isAscending() ? " desc" : " asc");
111 String facetPivot = (pdbRestRequest.getFacetPivot() == null || pdbRestRequest
112 .getFacetPivot().isEmpty()) ? "" : pdbRestRequest
114 String facetPivotMinCount = String.valueOf(pdbRestRequest
115 .getFacetPivotMinCount());
117 String query = pdbRestRequest.getFieldToSearchBy()
118 + pdbRestRequest.getSearchTerm()
119 + (pdbRestRequest.isAllowEmptySeq() ? ""
120 : " AND molecule_sequence:['' TO *]")
121 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
122 : " AND status:REL");
124 // Build request parameters for the REST Request
125 WebResource webResource = null;
126 if (pdbRestRequest.isFacet())
128 webResource = client.resource(PDB_SEARCH_ENDPOINT)
129 .queryParam("wt", "json").queryParam("fl", wantedFields)
130 .queryParam("rows", String.valueOf(responseSize))
131 .queryParam("q", query)
132 .queryParam("start", String.valueOf(offSet))
133 .queryParam("sort", sortParam).queryParam("facet", "true")
134 .queryParam("facet.pivot", facetPivot)
135 .queryParam("facet.pivot.mincount", facetPivotMinCount);
139 webResource = client.resource(PDB_SEARCH_ENDPOINT)
140 .queryParam("wt", "json").queryParam("fl", wantedFields)
141 .queryParam("rows", String.valueOf(responseSize))
142 .queryParam("start", String.valueOf(offSet))
143 .queryParam("q", query).queryParam("sort", sortParam);
145 // Execute the REST request
146 ClientResponse clientResponse = webResource.accept(
147 MediaType.APPLICATION_JSON).get(ClientResponse.class);
149 // Get the JSON string from the response object
150 String responseString = clientResponse.getEntity(String.class);
151 // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
153 // Check the response status and report exception if one occurs
154 if (clientResponse.getStatus() != 200)
156 String errorMessage = "";
157 if (clientResponse.getStatus() == 400)
159 errorMessage = parseJsonExceptionString(responseString);
160 throw new Exception(errorMessage);
164 errorMessage = getMessageByHTTPStatusCode(
165 clientResponse.getStatus(), "PDB");
166 throw new Exception(errorMessage);
170 // Make redundant objects eligible for garbage collection to conserve
172 clientResponse = null;
175 // Process the response and return the result to the caller.
176 return parsePDBJsonResponse(responseString, pdbRestRequest);
177 } catch (Exception e)
179 String exceptionMsg = e.getMessage();
180 if (exceptionMsg.contains("SocketException"))
182 // No internet connection
185 .getString("exception.unable_to_detect_internet_connection"));
187 else if (exceptionMsg.contains("UnknownHostException"))
189 // The server 'www.ebi.ac.uk' is unreachable
190 throw new Exception(MessageManager.formatMessage(
191 "exception.fts_server_unreachable", "PDB Solr"));
201 * Process error response from PDB server if/when one occurs.
203 * @param jsonResponse
204 * the JSON string containing error message from the server
205 * @return the processed error message from the JSON string
207 public static String parseJsonExceptionString(String jsonErrorResponse)
209 StringBuilder errorMessage = new StringBuilder(
210 "\n============= PDB Rest Client RunTime error =============\n");
214 JSONParser jsonParser = new JSONParser();
215 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
216 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
218 JSONObject responseHeader = (JSONObject) jsonObj
219 .get("responseHeader");
220 JSONObject paramsObj = (JSONObject) responseHeader.get("params");
221 String status = responseHeader.get("status").toString();
222 String message = errorResponse.get("msg").toString();
223 String query = paramsObj.get("q").toString();
224 String fl = paramsObj.get("fl").toString();
226 errorMessage.append("Status: ").append(status).append("\n");
227 errorMessage.append("Message: ").append(message).append("\n");
228 errorMessage.append("query: ").append(query).append("\n");
229 errorMessage.append("fl: ").append(fl).append("\n");
231 } catch (ParseException e)
235 return errorMessage.toString();
239 * Parses the JSON response string from PDB REST API. The response is dynamic
240 * hence, only fields specifically requested for in the 'wantedFields'
241 * parameter is fetched/processed
243 * @param pdbJsonResponseString
244 * the JSON string to be parsed
245 * @param pdbRestRequest
246 * the request object which contains parameters used to process the
250 @SuppressWarnings("unchecked")
251 public static FTSRestResponse parsePDBJsonResponse(
252 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
254 FTSRestResponse searchResult = new FTSRestResponse();
255 List<FTSData> result = null;
258 JSONParser jsonParser = new JSONParser();
259 JSONObject jsonObj = (JSONObject) jsonParser
260 .parse(pdbJsonResponseString);
262 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
263 String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
265 int numFound = Integer
266 .valueOf(pdbResponse.get("numFound").toString());
269 result = new ArrayList<FTSData>();
270 JSONArray docs = (JSONArray) pdbResponse.get("docs");
271 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
274 JSONObject doc = docIter.next();
275 result.add(getFTSData(doc, pdbRestRequest));
277 searchResult.setNumberOfItemsFound(numFound);
278 searchResult.setResponseTime(queryTime);
279 searchResult.setSearchSummary(result);
281 } catch (ParseException e)
288 public static FTSData getFTSData(JSONObject pdbJsonDoc,
289 FTSRestRequest request)
292 String primaryKey = null;
294 Object[] summaryRowData;
296 SequenceI associatedSequence;
298 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
299 SequenceI associatedSeq = request.getAssociatedSequence();
301 summaryRowData = new Object[(associatedSeq != null) ? diplayFields
302 .size() + 1 : diplayFields.size()];
303 if (associatedSeq != null)
305 associatedSequence = associatedSeq;
306 summaryRowData[0] = associatedSequence;
310 for (FTSDataColumnI field : diplayFields)
312 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
313 : pdbJsonDoc.get(field.getCode()).toString();
314 if (field.isPrimaryKeyColumn())
316 primaryKey = fieldData;
317 summaryRowData[colCounter++] = primaryKey;
319 else if (fieldData == null || fieldData.isEmpty())
321 summaryRowData[colCounter++] = null;
327 summaryRowData[colCounter++] = (field.getDataType()
328 .getDataTypeClass() == Integer.class) ? Integer
329 .valueOf(fieldData) : (field.getDataType()
330 .getDataTypeClass() == Double.class) ? Double
331 .valueOf(fieldData) : sanitiseData(fieldData);
332 } catch (Exception e)
335 System.out.println("offending value:" + fieldData);
340 final String primaryKey1 = primaryKey;
342 final Object[] summaryRowData1 = summaryRowData;
346 public Object[] getSummaryData()
348 return summaryRowData1;
352 public Object getPrimaryKey()
358 * Returns a string representation of this object;
361 public String toString()
363 StringBuilder summaryFieldValues = new StringBuilder();
364 for (Object summaryField : summaryRowData1)
366 summaryFieldValues.append(
367 summaryField == null ? " " : summaryField.toString())
370 return summaryFieldValues.toString();
374 * Returns hash code value for this object
377 public int hashCode()
379 return Objects.hash(primaryKey1, this.toString());
383 public boolean equals(Object that)
385 return this.toString().equals(that.toString());
390 private static String sanitiseData(String data)
392 String cleanData = data.replaceAll("\\[\"", "").replaceAll("\\]\"", "")
393 .replaceAll("\\[", "").replaceAll("\\]", "")
394 .replaceAll("\",\"", ", ").replaceAll("\"", "");
399 public String getColumnDataConfigFileName()
401 return "/fts/pdb_data_columns.txt";
404 public static FTSRestClientI getInstance()
406 if (instance == null)
408 instance = new PDBFTSRestClient();
413 private Collection<FTSDataColumnI> allDefaultDisplayedStructureDataColumns;
415 public Collection<FTSDataColumnI> getAllDefaultDisplayedStructureDataColumns()
417 if (allDefaultDisplayedStructureDataColumns == null
418 || allDefaultDisplayedStructureDataColumns.isEmpty())
420 allDefaultDisplayedStructureDataColumns = new ArrayList<FTSDataColumnI>();
421 allDefaultDisplayedStructureDataColumns.addAll(super
422 .getAllDefaultDisplayedFTSDataColumns());
424 return allDefaultDisplayedStructureDataColumns;