JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / test / jalview / ws / dbsources / PDBRestClientTest.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
3  * Copyright (C) 2015 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.ws.dbsources;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertTrue;
25
26 import jalview.ws.dbsources.PDBRestClient.PDBDocField;
27 import jalview.ws.uimodel.PDBRestRequest;
28 import jalview.ws.uimodel.PDBRestResponse;
29
30 import java.io.BufferedReader;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.Iterator;
35 import java.util.List;
36
37 import javax.ws.rs.core.MediaType;
38
39 import org.json.simple.JSONArray;
40 import org.json.simple.JSONObject;
41 import org.json.simple.parser.JSONParser;
42 import org.json.simple.parser.ParseException;
43 import org.testng.Assert;
44 import org.testng.annotations.AfterMethod;
45 import org.testng.annotations.BeforeMethod;
46 import org.testng.annotations.Test;
47
48 import com.sun.jersey.api.client.Client;
49 import com.sun.jersey.api.client.ClientResponse;
50 import com.sun.jersey.api.client.WebResource;
51 import com.sun.jersey.api.client.config.ClientConfig;
52 import com.sun.jersey.api.client.config.DefaultClientConfig;
53
54 public class PDBRestClientTest
55 {
56
57   @BeforeMethod(alwaysRun = true)
58   public void setUp() throws Exception
59   {
60   }
61
62   @AfterMethod
63   public void tearDown() throws Exception
64   {
65   }
66
67   @Test(groups = { "External", "Network" })
68   public void executeRequestTest()
69   {
70     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
71     wantedFields.add(PDBDocField.MOLECULE_TYPE);
72     wantedFields.add(PDBDocField.PDB_ID);
73     wantedFields.add(PDBDocField.GENUS);
74     wantedFields.add(PDBDocField.GENE_NAME);
75     wantedFields.add(PDBDocField.TITLE);
76
77     PDBRestRequest request = new PDBRestRequest();
78     request.setAllowEmptySeq(false);
79     request.setResponseSize(100);
80     request.setFieldToSearchBy("text:");
81     request.setSearchTerm("abc");
82     request.setWantedFields(wantedFields);
83
84     PDBRestResponse response;
85     try
86     {
87       response = new PDBRestClient().executeRequest(request);
88     } catch (Exception e)
89     {
90       e.printStackTrace();
91       Assert.fail("Couldn't execute webservice call!");
92       return;
93     }
94     assertTrue(response.getNumberOfItemsFound() > 99);
95     assertTrue(response.getSearchSummary() != null);
96     assertTrue(response.getSearchSummary().size() > 99);
97   }
98
99   @Test(groups = { "Functional" })
100   public void getPDBDocFieldsAsCommaDelimitedStringTest()
101   {
102     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
103     wantedFields.add(PDBDocField.MOLECULE_TYPE);
104     wantedFields.add(PDBDocField.PDB_ID);
105     wantedFields.add(PDBDocField.GENUS);
106     wantedFields.add(PDBDocField.GENE_NAME);
107     wantedFields.add(PDBDocField.TITLE);
108
109     String expectedResult = "molecule_type,pdb_id,genus,gene_name,title";
110     String actualResult = PDBRestClient
111             .getPDBDocFieldsAsCommaDelimitedString(wantedFields);
112
113     assertEquals("", expectedResult, actualResult);
114   }
115
116   @Test(groups = { "External, Network" })
117   public void parsePDBJsonExceptionStringTest()
118   {
119     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
120     wantedFields.add(PDBDocField.MOLECULE_TYPE);
121     wantedFields.add(PDBDocField.PDB_ID);
122     wantedFields.add(PDBDocField.GENUS);
123     wantedFields.add(PDBDocField.GENE_NAME);
124     wantedFields.add(PDBDocField.TITLE);
125
126     PDBRestRequest request = new PDBRestRequest();
127     request.setAllowEmptySeq(false);
128     request.setResponseSize(100);
129     request.setFieldToSearchBy("text:");
130     request.setSearchTerm("abc");
131     request.setWantedFields(wantedFields);
132
133     String jsonErrorResponse = "";
134     try
135     {
136       jsonErrorResponse = readJsonStringFromFile("test/jalview/io/pdb_request_json_error.txt");
137     } catch (IOException e)
138     {
139       e.printStackTrace();
140     }
141
142     String parsedErrorResponse = PDBRestClient
143             .parseJsonExceptionString(jsonErrorResponse);
144
145     String expectedErrorMsg = "\n============= PDB Rest Client RunTime error =============\n"
146             + "Status: 400\n"
147             + "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"
148             + "query: text:abc OR text:go:abc AND molecule_sequence:['' TO *]\n"
149             + "fl: pdb_id\n";
150
151     assertEquals(expectedErrorMsg, parsedErrorResponse);
152   }
153
154   @Test(
155     groups = { "External", "Network" },
156     expectedExceptions = Exception.class)
157   public void testForExpectedRuntimeException() throws Exception
158   {
159     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
160     wantedFields.add(PDBDocField.PDB_ID);
161
162     PDBRestRequest request = new PDBRestRequest();
163     request.setFieldToSearchBy("text:");
164     request.setSearchTerm("abc OR text:go:abc");
165     request.setWantedFields(wantedFields);
166     new PDBRestClient().executeRequest(request);
167   }
168
169   @Test(groups = { "External" })
170   public void parsePDBJsonResponseTest()
171   {
172     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
173     wantedFields.add(PDBDocField.MOLECULE_TYPE);
174     wantedFields.add(PDBDocField.PDB_ID);
175     wantedFields.add(PDBDocField.GENUS);
176     wantedFields.add(PDBDocField.GENE_NAME);
177     wantedFields.add(PDBDocField.TITLE);
178
179     PDBRestRequest request = new PDBRestRequest();
180     request.setAllowEmptySeq(false);
181     request.setWantedFields(wantedFields);
182
183     String jsonString = "";
184     try
185     {
186       jsonString = readJsonStringFromFile("test/jalview/io/pdb_response_json.txt");
187     } catch (IOException e)
188     {
189       e.printStackTrace();
190     }
191     PDBRestResponse response = PDBRestClient.parsePDBJsonResponse(
192             jsonString, request);
193     assertTrue(response.getSearchSummary() != null);
194     assertTrue(response.getNumberOfItemsFound() == 931);
195     assertTrue(response.getSearchSummary().size() == 14);
196   }
197
198   @Test(groups = { "Functional" })
199   public void getPDBIdColumIndexTest()
200   {
201     List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
202     wantedFields.add(PDBDocField.MOLECULE_TYPE);
203     wantedFields.add(PDBDocField.GENUS);
204     wantedFields.add(PDBDocField.GENE_NAME);
205     wantedFields.add(PDBDocField.TITLE);
206     wantedFields.add(PDBDocField.PDB_ID);
207     assertEquals(5, PDBRestClient.getPDBIdColumIndex(wantedFields, true));
208     assertEquals(4, PDBRestClient.getPDBIdColumIndex(wantedFields, false));
209   }
210
211   @Test(groups = { "External" })
212   public void externalServiceIntegrationTest()
213   {
214     ClientConfig clientConfig = new DefaultClientConfig();
215     Client client = Client.create(clientConfig);
216
217     // Build request parameters for the REST Request
218     WebResource webResource = client
219             .resource(PDBRestClient.PDB_SEARCH_ENDPOINT)
220             .queryParam("wt", "json").queryParam("rows", String.valueOf(1))
221             .queryParam("q", "text:abc AND molecule_sequence:['' TO *]");
222
223     // Execute the REST request
224     ClientResponse clientResponse = webResource.accept(
225             MediaType.APPLICATION_JSON).get(ClientResponse.class);
226
227     // Get the JSON string from the response object
228     String pdbJsonResponseString = clientResponse.getEntity(String.class);
229
230     // Check the response status and report exception if one occurs
231     if (clientResponse.getStatus() != 200)
232     {
233       Assert.fail("Webservice call failed!!!");
234     }
235     else
236     {
237       try
238       {
239         JSONParser jsonParser = new JSONParser();
240         JSONObject jsonObj = (JSONObject) jsonParser
241                 .parse(pdbJsonResponseString);
242         JSONObject pdbResponse = (JSONObject) jsonObj.get("response");
243         String queryTime = ((JSONObject) jsonObj.get("responseHeader"))
244                 .get("QTime").toString();
245         String numFound = pdbResponse.get("numFound").toString();
246         JSONArray docs = (JSONArray) pdbResponse.get("docs");
247         Iterator<JSONObject> docIter = docs.iterator();
248
249         assertTrue("Couldn't Retrieve 'response' object",
250                 pdbResponse != null);
251         assertTrue("Couldn't Retrieve 'QTime' value", queryTime != null);
252         assertTrue("Couldn't Retrieve 'numFound' value", numFound != null);
253         assertTrue("Couldn't Retrieve 'docs' object", docs != null
254                 || !docIter.hasNext());
255
256         JSONObject pdbJsonDoc = docIter.next();
257
258         for (PDBDocField field : PDBDocField.values())
259         {
260           if (field == PDBDocField.ALL)
261           {
262             continue;
263           }
264           if (pdbJsonDoc.get(field.getCode()) == null)
265           {
266             // System.out.println(">>>\t" + field.getCode());
267             assertTrue(field.getClass()
268                     + " has been removed from PDB doc Entity",
269                     !pdbJsonResponseString.contains(field.getCode()));
270           }
271         }
272       } catch (ParseException e)
273       {
274         Assert.fail(">>>  Test failed due to exception while parsing pdb response json !!!");
275         e.printStackTrace();
276       }
277     }
278   }
279
280   public String readJsonStringFromFile(String filePath) throws IOException
281   {
282     String fileContent;
283     BufferedReader br = new BufferedReader(new FileReader(filePath));
284     try
285     {
286       StringBuilder sb = new StringBuilder();
287       String line = br.readLine();
288
289       while (line != null)
290       {
291         sb.append(line);
292         sb.append(System.lineSeparator());
293         line = br.readLine();
294       }
295       fileContent = sb.toString();
296     } finally
297     {
298       br.close();
299     }
300     return fileContent;
301   }
302
303 }