39ae75d5ede59f2107634920c7347e8c30b13ce1
[jalview.git] / test / jalview / fts / service / pdb / PDBFTSRestClientTest.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.fts.service.pdb;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertTrue;
25
26 import jalview.fts.api.FTSDataColumnI;
27 import jalview.fts.core.FTSRestRequest;
28 import jalview.fts.core.FTSRestResponse;
29 import jalview.gui.JvOptionPane;
30
31 import java.io.BufferedReader;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.Iterator;
36 import java.util.List;
37
38 import javax.ws.rs.core.MediaType;
39
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;
44 import org.testng.Assert;
45 import org.testng.annotations.AfterMethod;
46 import org.testng.annotations.BeforeClass;
47 import org.testng.annotations.BeforeMethod;
48 import org.testng.annotations.Test;
49
50 import com.sun.jersey.api.client.Client;
51 import com.sun.jersey.api.client.ClientResponse;
52 import com.sun.jersey.api.client.WebResource;
53 import com.sun.jersey.api.client.config.ClientConfig;
54 import com.sun.jersey.api.client.config.DefaultClientConfig;
55
56 public class PDBFTSRestClientTest
57 {
58
59   @BeforeClass(alwaysRun = true)
60   public void setUpJvOptionPane()
61   {
62     JvOptionPane.setInteractiveMode(false);
63     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
64   }
65
66   @BeforeMethod(alwaysRun = true)
67   public void setUp() throws Exception
68   {
69   }
70
71   @AfterMethod(alwaysRun = true)
72   public void tearDown() throws Exception
73   {
74   }
75
76   @Test(groups = { "External", "Network" })
77   public void executeRequestTest()
78   {
79     List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
80     try
81     {
82       wantedFields.add(PDBFTSRestClient.getInstance()
83               .getDataColumnByNameOrCode("molecule_type"));
84       wantedFields.add(PDBFTSRestClient.getInstance()
85               .getDataColumnByNameOrCode("pdb_id"));
86       wantedFields.add(PDBFTSRestClient.getInstance()
87               .getDataColumnByNameOrCode("genus"));
88       wantedFields.add(PDBFTSRestClient.getInstance()
89               .getDataColumnByNameOrCode("gene_name"));
90       wantedFields.add(PDBFTSRestClient.getInstance()
91               .getDataColumnByNameOrCode("title"));
92     } catch (Exception e1)
93     {
94       e1.printStackTrace();
95     }
96     System.out.println("wantedFields >>" + wantedFields);
97
98
99     FTSRestRequest request = new FTSRestRequest();
100     request.setAllowEmptySeq(false);
101     request.setResponseSize(100);
102     request.setFieldToSearchBy("text:");
103     request.setSearchTerm("abc");
104     request.setWantedFields(wantedFields);
105
106     FTSRestResponse response;
107     try
108     {
109       response = PDBFTSRestClient.getInstance().executeRequest(request);
110     } catch (Exception e)
111     {
112       e.printStackTrace();
113       Assert.fail("Couldn't execute webservice call!");
114       return;
115     }
116     assertTrue(response.getNumberOfItemsFound() > 99);
117     assertTrue(response.getSearchSummary() != null);
118     assertTrue(response.getSearchSummary().size() > 99);
119   }
120
121   @Test(groups = { "Functional" })
122   public void getPDBDocFieldsAsCommaDelimitedStringTest()
123   {
124     List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
125     try
126     {
127       wantedFields.add(PDBFTSRestClient.getInstance()
128               .getDataColumnByNameOrCode("molecule_type"));
129       wantedFields.add(PDBFTSRestClient.getInstance()
130               .getDataColumnByNameOrCode("pdb_id"));
131       wantedFields.add(PDBFTSRestClient.getInstance()
132               .getDataColumnByNameOrCode("genus"));
133       wantedFields.add(PDBFTSRestClient.getInstance()
134               .getDataColumnByNameOrCode("gene_name"));
135       wantedFields.add(PDBFTSRestClient.getInstance()
136               .getDataColumnByNameOrCode("title"));
137     } catch (Exception e)
138     {
139       e.printStackTrace();
140     }
141
142     String expectedResult = "molecule_type,pdb_id,genus,gene_name,title";
143     String actualResult = PDBFTSRestClient.getInstance()
144             .getDataColumnsFieldsAsCommaDelimitedString(wantedFields);
145
146     assertEquals("", expectedResult, actualResult);
147   }
148
149   @Test(groups = { "External, Network" })
150   public void parsePDBJsonExceptionStringTest()
151   {
152     List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
153     try
154     {
155       wantedFields.add(PDBFTSRestClient.getInstance()
156               .getDataColumnByNameOrCode("molecule_type"));
157       wantedFields.add(PDBFTSRestClient.getInstance()
158               .getDataColumnByNameOrCode("pdb_id"));
159       wantedFields.add(PDBFTSRestClient.getInstance()
160               .getDataColumnByNameOrCode("genus"));
161       wantedFields.add(PDBFTSRestClient.getInstance()
162               .getDataColumnByNameOrCode("gene_name"));
163       wantedFields.add(PDBFTSRestClient.getInstance()
164               .getDataColumnByNameOrCode("title"));
165     } catch (Exception e1)
166     {
167       e1.printStackTrace();
168     }
169
170     FTSRestRequest request = new FTSRestRequest();
171     request.setAllowEmptySeq(false);
172     request.setResponseSize(100);
173     request.setFieldToSearchBy("text:");
174     request.setSearchTerm("abc");
175     request.setWantedFields(wantedFields);
176
177     String jsonErrorResponse = "";
178     try
179     {
180       jsonErrorResponse = readJsonStringFromFile("test/jalview/io/pdb_request_json_error.txt");
181     } catch (IOException e)
182     {
183       e.printStackTrace();
184     }
185
186     String parsedErrorResponse = PDBFTSRestClient
187             .parseJsonExceptionString(jsonErrorResponse);
188
189     String expectedErrorMsg = "\n============= PDB Rest Client RunTime error =============\n"
190             + "Status: 400\n"
191             + "Message: org.apache.solr.search.SyntaxError: Cannot parse 'text:abc OR text:go:abc AND molecule_sequence:['' TO *]': Encountered \" \":\" \": \"\" at line 1, column 19.\n"
192             + "query: text:abc OR text:go:abc AND molecule_sequence:['' TO *]\n"
193             + "fl: pdb_id\n";
194
195     assertEquals(expectedErrorMsg, parsedErrorResponse);
196   }
197
198   @Test(groups = { "External" }, expectedExceptions = Exception.class)
199   public void testForExpectedRuntimeException() throws Exception
200   {
201     // JBPNote: looks like this test fails for no good reason - what exception was supposed to be raised ?
202     List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
203     wantedFields.add(PDBFTSRestClient.getInstance()
204             .getDataColumnByNameOrCode("pdb_id"));
205
206     FTSRestRequest request = new FTSRestRequest();
207     request.setFieldToSearchBy("text:");
208     request.setSearchTerm("abc OR text:go:abc");
209     request.setWantedFields(wantedFields);
210     PDBFTSRestClient.getInstance().executeRequest(request);
211   }
212
213   // JBP: Is this actually external ? Looks like it is mocked
214   @Test(groups = { "External" })
215   public void parsePDBJsonResponseTest()
216   {
217     List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
218     try
219     {
220       wantedFields.add(PDBFTSRestClient.getInstance()
221               .getDataColumnByNameOrCode("molecule_type"));
222       wantedFields.add(PDBFTSRestClient.getInstance()
223               .getDataColumnByNameOrCode("pdb_id"));
224       wantedFields.add(PDBFTSRestClient.getInstance()
225               .getDataColumnByNameOrCode("genus"));
226       wantedFields.add(PDBFTSRestClient.getInstance()
227               .getDataColumnByNameOrCode("gene_name"));
228       wantedFields.add(PDBFTSRestClient.getInstance()
229               .getDataColumnByNameOrCode("title"));
230     } catch (Exception e1)
231     {
232       e1.printStackTrace();
233     }
234
235     FTSRestRequest request = new FTSRestRequest();
236     request.setAllowEmptySeq(false);
237     request.setWantedFields(wantedFields);
238
239     String jsonString = "";
240     try
241     {
242       jsonString = readJsonStringFromFile("test/jalview/io/pdb_response_json.txt");
243     } catch (IOException e)
244     {
245       e.printStackTrace();
246     }
247     FTSRestResponse response = PDBFTSRestClient.parsePDBJsonResponse(
248             jsonString, request);
249     assertTrue(response.getSearchSummary() != null);
250     assertTrue(response.getNumberOfItemsFound() == 931);
251     assertTrue(response.getSearchSummary().size() == 14);
252     System.out.println("Search summary : " + response.getSearchSummary());
253   }
254
255   @Test(groups = { "Functional" })
256   public void getPDBIdColumIndexTest()
257   {
258     List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
259     try
260     {
261       wantedFields.add(PDBFTSRestClient.getInstance()
262               .getDataColumnByNameOrCode("molecule_type"));
263       wantedFields.add(PDBFTSRestClient.getInstance()
264               .getDataColumnByNameOrCode("genus"));
265       wantedFields.add(PDBFTSRestClient.getInstance()
266               .getDataColumnByNameOrCode("gene_name"));
267       wantedFields.add(PDBFTSRestClient.getInstance()
268               .getDataColumnByNameOrCode("title"));
269       wantedFields.add(PDBFTSRestClient.getInstance()
270               .getDataColumnByNameOrCode("pdb_id"));
271     } catch (Exception e)
272     {
273       e.printStackTrace();
274     }
275     try
276     {
277       assertEquals(5, PDBFTSRestClient.getInstance()
278               .getPrimaryKeyColumIndex(wantedFields, true));
279       assertEquals(4, PDBFTSRestClient.getInstance()
280               .getPrimaryKeyColumIndex(wantedFields, false));
281     } catch (Exception e)
282     {
283       // TODO Auto-generated catch block
284       e.printStackTrace();
285     }
286   }
287
288   @Test(groups = { "External" })
289   public void externalServiceIntegrationTest()
290   {
291     ClientConfig clientConfig = new DefaultClientConfig();
292     Client client = Client.create(clientConfig);
293
294     // Build request parameters for the REST Request
295     WebResource webResource = client
296             .resource(PDBFTSRestClient.PDB_SEARCH_ENDPOINT)
297             .queryParam("wt", "json").queryParam("rows", String.valueOf(1))
298             .queryParam("q", "text:abc AND molecule_sequence:['' TO *]");
299
300     // Execute the REST request
301     ClientResponse clientResponse = webResource.accept(
302             MediaType.APPLICATION_JSON).get(ClientResponse.class);
303
304     // Get the JSON string from the response object
305     String pdbJsonResponseString = clientResponse.getEntity(String.class);
306
307     // Check the response status and report exception if one occurs
308     if (clientResponse.getStatus() != 200)
309     {
310       Assert.fail("Webservice call failed!!!");
311     }
312     else
313     {
314       try
315       {
316         JSONParser jsonParser = new JSONParser();
317         JSONObject jsonObj = (JSONObject) jsonParser
318                 .parse(pdbJsonResponseString);
319         JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
320         String queryTime = ((JSONObject) jsonObj.get("responseHeader"))
321                 .get("QTime").toString();
322         String numFound = pdbResponse.get("numFound").toString();
323         JSONArray docs = (JSONArray) pdbResponse.get("docs");
324         Iterator<JSONObject> docIter = docs.iterator();
325
326         assertTrue("Couldn't Retrieve 'response' object",
327                 pdbResponse != null);
328         assertTrue("Couldn't Retrieve 'QTime' value", queryTime != null);
329         assertTrue("Couldn't Retrieve 'numFound' value", numFound != null);
330         assertTrue("Couldn't Retrieve 'docs' object", docs != null
331                 || !docIter.hasNext());
332
333         JSONObject pdbJsonDoc = docIter.next();
334
335         for (FTSDataColumnI field : PDBFTSRestClient.getInstance()
336                 .getAllFTSDataColumns())
337         {
338           if (field.getName().equalsIgnoreCase("ALL"))
339           {
340             continue;
341           }
342           if (pdbJsonDoc.get(field.getCode()) == null)
343           {
344             // System.out.println(">>>\t" + field.getCode());
345             assertTrue(field.getCode()
346                     + " has been removed from PDB doc Entity",
347                     !pdbJsonResponseString.contains(field.getCode()));
348           }
349         }
350       } catch (ParseException e)
351       {
352         Assert.fail(">>>  Test failed due to exception while parsing pdb response json !!!");
353         e.printStackTrace();
354       }
355     }
356   }
357
358   public String readJsonStringFromFile(String filePath) throws IOException
359   {
360     String fileContent;
361     BufferedReader br = new BufferedReader(new FileReader(filePath));
362     try
363     {
364       StringBuilder sb = new StringBuilder();
365       String line = br.readLine();
366
367       while (line != null)
368       {
369         sb.append(line);
370         sb.append(System.lineSeparator());
371         line = br.readLine();
372       }
373       fileContent = sb.toString();
374     } finally
375     {
376       br.close();
377     }
378     return fileContent;
379   }
380
381 }