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 String sortParam = null;
90 if (pdbRestRequest.getFieldToSortBy() == null
91 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
97 if (pdbRestRequest.getFieldToSortBy()
98 .equalsIgnoreCase("Resolution"))
100 sortParam = pdbRestRequest.getFieldToSortBy()
101 + (pdbRestRequest.isAscending() ? " asc" : " desc");
105 sortParam = pdbRestRequest.getFieldToSortBy()
106 + (pdbRestRequest.isAscending() ? " desc" : " asc");
110 String facetPivot = (pdbRestRequest.getFacetPivot() == null || pdbRestRequest
111 .getFacetPivot().isEmpty()) ? "" : pdbRestRequest
113 String facetPivotMinCount = String.valueOf(pdbRestRequest
114 .getFacetPivotMinCount());
116 String query = pdbRestRequest.getFieldToSearchBy()
117 + pdbRestRequest.getSearchTerm()
118 + (pdbRestRequest.isAllowEmptySeq() ? ""
119 : " AND molecule_sequence:['' TO *]")
120 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
121 : " AND status:REL");
123 // Build request parameters for the REST Request
124 WebResource webResource = null;
125 if (pdbRestRequest.isFacet())
127 webResource = client.resource(PDB_SEARCH_ENDPOINT)
128 .queryParam("wt", "json").queryParam("fl", wantedFields)
129 .queryParam("rows", String.valueOf(responseSize))
130 .queryParam("q", query)
131 .queryParam("sort", sortParam).queryParam("facet", "true")
132 .queryParam("facet.pivot", facetPivot)
133 .queryParam("facet.pivot.mincount", facetPivotMinCount);
137 webResource = client.resource(PDB_SEARCH_ENDPOINT)
138 .queryParam("wt", "json").queryParam("fl", wantedFields)
139 .queryParam("rows", String.valueOf(responseSize))
140 .queryParam("q", query)
141 .queryParam("sort", sortParam);
143 // Execute the REST request
144 ClientResponse clientResponse = webResource.accept(
145 MediaType.APPLICATION_JSON).get(ClientResponse.class);
147 // Get the JSON string from the response object
148 String responseString = clientResponse.getEntity(String.class);
149 // System.out.println("query >>>>>>> " + pdbRestRequest.toString());
151 // Check the response status and report exception if one occurs
152 if (clientResponse.getStatus() != 200)
154 String errorMessage = "";
155 if (clientResponse.getStatus() == 400)
157 errorMessage = parseJsonExceptionString(responseString);
158 throw new Exception(errorMessage);
162 errorMessage = getMessageByHTTPStatusCode(clientResponse
164 throw new Exception(errorMessage);
168 // Make redundant objects eligible for garbage collection to conserve
170 clientResponse = null;
173 // Process the response and return the result to the caller.
174 return parsePDBJsonResponse(responseString, pdbRestRequest);
175 } catch (Exception e)
177 String exceptionMsg = e.getMessage();
178 if (exceptionMsg.contains("SocketException"))
180 // No internet connection
183 .getString("exception.unable_to_detect_internet_connection"));
185 else if (exceptionMsg.contains("UnknownHostException"))
187 // The server 'www.ebi.ac.uk' is unreachable
190 .getString("exception.pdb_server_unreachable"));
199 public String getMessageByHTTPStatusCode(int code)
205 message = MessageManager
206 .getString("exception.pdb_rest_service_no_longer_available");
210 message = MessageManager.getString("exception.resource_not_be_found");
220 message = MessageManager.getString("exception.pdb_server_error");
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 public static String parseJsonExceptionString(String jsonErrorResponse)
238 StringBuilder errorMessage = new StringBuilder(
239 "\n============= PDB Rest Client RunTime error =============\n");
243 JSONParser jsonParser = new JSONParser();
244 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
245 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
247 JSONObject responseHeader = (JSONObject) jsonObj
248 .get("responseHeader");
249 JSONObject paramsObj = (JSONObject) responseHeader.get("params");
250 String status = responseHeader.get("status").toString();
251 String message = errorResponse.get("msg").toString();
252 String query = paramsObj.get("q").toString();
253 String fl = paramsObj.get("fl").toString();
255 errorMessage.append("Status: ").append(status).append("\n");
256 errorMessage.append("Message: ").append(message).append("\n");
257 errorMessage.append("query: ").append(query).append("\n");
258 errorMessage.append("fl: ").append(fl).append("\n");
260 } catch (ParseException e)
264 return errorMessage.toString();
268 * Parses the JSON response string from PDB REST API. The response is dynamic
269 * hence, only fields specifically requested for in the 'wantedFields'
270 * parameter is fetched/processed
272 * @param pdbJsonResponseString
273 * the JSON string to be parsed
274 * @param pdbRestRequest
275 * the request object which contains parameters used to process the
279 @SuppressWarnings("unchecked")
280 public static FTSRestResponse parsePDBJsonResponse(
281 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
283 FTSRestResponse searchResult = new FTSRestResponse();
284 List<FTSData> result = null;
287 JSONParser jsonParser = new JSONParser();
288 JSONObject jsonObj = (JSONObject) jsonParser
289 .parse(pdbJsonResponseString);
291 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
292 String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
294 int numFound = Integer
295 .valueOf(pdbResponse.get("numFound").toString());
298 result = new ArrayList<FTSData>();
299 JSONArray docs = (JSONArray) pdbResponse.get("docs");
300 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
303 JSONObject doc = docIter.next();
304 result.add(getFTSData(doc, pdbRestRequest));
306 searchResult.setNumberOfItemsFound(numFound);
307 searchResult.setResponseTime(queryTime);
308 searchResult.setSearchSummary(result);
310 } catch (ParseException e)
317 public static FTSData getFTSData(JSONObject pdbJsonDoc,
318 FTSRestRequest request)
321 String primaryKey = null;
323 Object[] summaryRowData;
325 SequenceI associatedSequence;
327 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
328 SequenceI associatedSeq = request.getAssociatedSequence();
330 summaryRowData = new Object[(associatedSeq != null) ? diplayFields
331 .size() + 1 : diplayFields.size()];
332 if (associatedSeq != null)
334 associatedSequence = associatedSeq;
335 summaryRowData[0] = associatedSequence;
339 for (FTSDataColumnI field : diplayFields)
341 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
342 : pdbJsonDoc.get(field.getCode()).toString();
343 if (field.isPrimaryKeyColumn())
345 primaryKey = fieldData;
346 summaryRowData[colCounter++] = primaryKey;
348 else if (fieldData == null || fieldData.isEmpty())
350 summaryRowData[colCounter++] = null;
356 summaryRowData[colCounter++] = (field.getDataColumnClass() == Integer.class) ? Integer
358 : (field.getDataColumnClass() == Double.class) ? Double
361 } catch (Exception e)
364 System.out.println("offending value:" + fieldData);
369 final String primaryKey1 = primaryKey;
371 final Object[] summaryRowData1 = summaryRowData;
375 public Object[] getSummaryData()
377 return summaryRowData1;
381 public Object getPrimaryKey()
387 * Returns a string representation of this object;
390 public String toString()
392 StringBuilder summaryFieldValues = new StringBuilder();
393 for (Object summaryField : summaryRowData1)
395 summaryFieldValues.append(
396 summaryField == null ? " " : summaryField.toString())
399 return summaryFieldValues.toString();
403 * Returns hash code value for this object
406 public int hashCode()
408 return Objects.hash(primaryKey1, this.toString());
414 public String getColumnDataConfigFileName()
416 return getResourceFile("/fts/pdb_data_columns.conf");
420 public static FTSRestClientI getInstance()
422 if (instance == null)
424 instance = new PDBFTSRestClient();