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 REST 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 private static int DEFAULT_RESPONSE_SIZE = 200;
66 protected PDBFTSRestClient()
71 * Takes a PDBRestRequest object and returns a response upon execution
73 * @param pdbRestRequest
74 * the PDBRestRequest instance to be processed
75 * @return the pdbResponse object for the given request
79 public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest)
84 ClientConfig clientConfig = new DefaultClientConfig();
85 Client client = Client.create(clientConfig);
87 String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(pdbRestRequest
89 int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE
90 : pdbRestRequest.getResponseSize();
91 String sortParam = null;
92 if (pdbRestRequest.getFieldToSortBy() == null
93 || pdbRestRequest.getFieldToSortBy().trim().isEmpty())
99 if (pdbRestRequest.getFieldToSortBy()
100 .equalsIgnoreCase("Resolution"))
102 sortParam = pdbRestRequest.getFieldToSortBy()
103 + (pdbRestRequest.isAscending() ? " asc" : " desc");
107 sortParam = pdbRestRequest.getFieldToSortBy()
108 + (pdbRestRequest.isAscending() ? " desc" : " asc");
112 String facetPivot = (pdbRestRequest.getFacetPivot() == null || pdbRestRequest
113 .getFacetPivot().isEmpty()) ? "" : pdbRestRequest
115 String facetPivotMinCount = String.valueOf(pdbRestRequest
116 .getFacetPivotMinCount());
118 String query = pdbRestRequest.getFieldToSearchBy()
119 + pdbRestRequest.getSearchTerm()
120 + (pdbRestRequest.isAllowEmptySeq() ? ""
121 : " AND molecule_sequence:['' TO *]")
122 + (pdbRestRequest.isAllowUnpublishedEntries() ? ""
123 : " AND status:REL");
125 // Build request parameters for the REST Request
126 WebResource webResource = null;
127 if (pdbRestRequest.isFacet())
129 webResource = client.resource(PDB_SEARCH_ENDPOINT)
130 .queryParam("wt", "json").queryParam("fl", wantedFields)
131 .queryParam("rows", String.valueOf(responseSize))
132 .queryParam("q", query)
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("q", query)
143 .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(clientResponse
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
192 .getString("exception.pdb_server_unreachable"));
201 public String getMessageByHTTPStatusCode(int code)
207 message = MessageManager
208 .getString("exception.pdb_rest_service_no_longer_available");
212 message = MessageManager.getString("exception.resource_not_be_found");
222 message = MessageManager.getString("exception.pdb_server_error");
232 * Process error response from PDB server if/when one occurs.
234 * @param jsonResponse
235 * the JSON string containing error message from the server
236 * @return the processed error message from the JSON string
238 public static String parseJsonExceptionString(String jsonErrorResponse)
240 StringBuilder errorMessage = new StringBuilder(
241 "\n============= PDB Rest Client RunTime error =============\n");
245 JSONParser jsonParser = new JSONParser();
246 JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse);
247 JSONObject errorResponse = (JSONObject) jsonObj.get("error");
249 JSONObject responseHeader = (JSONObject) jsonObj
250 .get("responseHeader");
251 JSONObject paramsObj = (JSONObject) responseHeader.get("params");
252 String status = responseHeader.get("status").toString();
253 String message = errorResponse.get("msg").toString();
254 String query = paramsObj.get("q").toString();
255 String fl = paramsObj.get("fl").toString();
257 errorMessage.append("Status: ").append(status).append("\n");
258 errorMessage.append("Message: ").append(message).append("\n");
259 errorMessage.append("query: ").append(query).append("\n");
260 errorMessage.append("fl: ").append(fl).append("\n");
262 } catch (ParseException e)
266 return errorMessage.toString();
270 * Parses the JSON response string from PDB REST API. The response is dynamic
271 * hence, only fields specifically requested for in the 'wantedFields'
272 * parameter is fetched/processed
274 * @param pdbJsonResponseString
275 * the JSON string to be parsed
276 * @param pdbRestRequest
277 * the request object which contains parameters used to process the
281 @SuppressWarnings("unchecked")
282 public static FTSRestResponse parsePDBJsonResponse(
283 String pdbJsonResponseString, FTSRestRequest pdbRestRequest)
285 FTSRestResponse searchResult = new FTSRestResponse();
286 List<FTSData> result = null;
289 JSONParser jsonParser = new JSONParser();
290 JSONObject jsonObj = (JSONObject) jsonParser
291 .parse(pdbJsonResponseString);
293 JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
294 String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get(
296 int numFound = Integer
297 .valueOf(pdbResponse.get("numFound").toString());
300 result = new ArrayList<FTSData>();
301 JSONArray docs = (JSONArray) pdbResponse.get("docs");
302 for (Iterator<JSONObject> docIter = docs.iterator(); docIter
305 JSONObject doc = docIter.next();
306 result.add(getFTSData(doc, pdbRestRequest));
308 searchResult.setNumberOfItemsFound(numFound);
309 searchResult.setResponseTime(queryTime);
310 searchResult.setSearchSummary(result);
312 } catch (ParseException e)
319 public static FTSData getFTSData(JSONObject pdbJsonDoc,
320 FTSRestRequest request)
323 String primaryKey = null;
325 Object[] summaryRowData;
327 SequenceI associatedSequence;
329 Collection<FTSDataColumnI> diplayFields = request.getWantedFields();
330 SequenceI associatedSeq = request.getAssociatedSequence();
332 summaryRowData = new Object[(associatedSeq != null) ? diplayFields
333 .size() + 1 : diplayFields.size()];
334 if (associatedSeq != null)
336 associatedSequence = associatedSeq;
337 summaryRowData[0] = associatedSequence;
341 for (FTSDataColumnI field : diplayFields)
343 String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? ""
344 : pdbJsonDoc.get(field.getCode()).toString();
345 if (field.isPrimaryKeyColumn())
347 primaryKey = fieldData;
348 summaryRowData[colCounter++] = primaryKey;
352 if (field.getGroup().getName().equals("Quality Measures"))
356 if (fieldData == null || fieldData.isEmpty())
358 summaryRowData[colCounter++] = null;
362 Double value = Double.valueOf(fieldData);
363 summaryRowData[colCounter++] = value;
365 } catch (Exception e)
368 System.out.println("offending value:" + fieldData);
369 summaryRowData[colCounter++] = 0.0;
374 summaryRowData[colCounter++] = (fieldData == null || fieldData
375 .isEmpty()) ? null : fieldData;
380 final String primaryKey1 = primaryKey;
382 final Object[] summaryRowData1 = summaryRowData;
386 public Object[] getSummaryData()
388 return summaryRowData1;
392 public Object getPrimaryKey()
398 * Returns a string representation of this object;
401 public String toString()
403 StringBuilder summaryFieldValues = new StringBuilder();
404 for (Object summaryField : summaryRowData1)
406 summaryFieldValues.append(
407 summaryField == null ? " " : summaryField.toString())
410 return summaryFieldValues.toString();
414 * Returns hash code value for this object
417 public int hashCode()
419 return Objects.hash(primaryKey1, this.toString());
425 public String getColumnDataConfigFile()
427 return getFile("fts/pdb_data_columns.conf");
431 public static FTSRestClientI getInstance()
433 if (instance == null)
435 instance = new PDBFTSRestClient();