KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > atomapi > AtomServletTest


1 package org.roller.presentation.atomapi;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileInputStream JavaDoc;
6 import java.io.StringReader JavaDoc;
7 import java.io.StringWriter JavaDoc;
8 import java.text.SimpleDateFormat JavaDoc;
9 import java.util.ArrayList JavaDoc;
10 import java.util.Calendar JavaDoc;
11 import java.util.Date JavaDoc;
12 import java.util.List JavaDoc;
13
14 import javax.servlet.http.HttpServletResponse JavaDoc;
15
16 import junit.framework.Test;
17 import junit.framework.TestSuite;
18
19 import org.jdom.Document;
20 import org.jdom.input.SAXBuilder;
21 import org.roller.RollerTestBase;
22 import org.roller.model.WeblogManager;
23 import org.roller.pojos.UserData;
24 import org.roller.pojos.WeblogEntryData;
25 import org.roller.pojos.WebsiteData;
26 import org.roller.presentation.MockRollerContext;
27 import org.roller.util.Utilities;
28
29 import com.mockrunner.mock.web.ActionMockObjectFactory;
30 import com.mockrunner.mock.web.MockHttpServletRequest;
31 import com.mockrunner.mock.web.MockHttpServletResponse;
32 import com.mockrunner.mock.web.MockServletContext;
33 import com.mockrunner.mock.web.WebMockObjectFactory;
34 import com.mockrunner.servlet.ServletTestModule;
35 import com.mockrunner.struts.ActionTestModule;
36 import com.sun.syndication.feed.atom.Content;
37 import com.sun.syndication.feed.atom.Entry;
38
39 /**
40  * Test new Rome based Atom API implementation.
41  * @author David M Johnson
42  */

43 public class AtomServletTest extends RollerTestBase
44 {
45     private ActionMockObjectFactory mockFactory;
46     protected MockRollerContext rollerContext;
47     protected ActionTestModule strutsModule;
48     private ServletTestModule servletModule;
49     private static SimpleDateFormat JavaDoc df =
50         new SimpleDateFormat JavaDoc( "yyyy-MM-dd'T'HH:mm:ssZ" );
51
52     protected WebMockObjectFactory getMockFactory()
53     {
54         if (mockFactory == null)
55         {
56             mockFactory = new ActionMockObjectFactory();
57         }
58         return mockFactory;
59     }
60     
61     //------------------------------------------------------------------------------
62
/**
63      * Test get of introspection URI
64      */

65     public void testGetIntrospection() throws Exception JavaDoc
66     {
67         UserData user = (UserData)mUsersCreated.get(0);
68                 
69         MockHttpServletRequest mockRequest = getMockFactory().getMockRequest();
70         mockRequest.addHeader("X-WSSE",
71                 generateWSSEHeader(user.getUserName(), user.getPassword()));
72         mockRequest.setContextPath("/atom");
73         mockRequest.setPathInfo("/" + user.getUserName());
74         getServletModule().doGet();
75
76         String JavaDoc output = getServletModule().getOutput();
77         SAXBuilder builder = new SAXBuilder();
78         Document doc = builder.build(new StringReader JavaDoc(output));
79         
80         AtomService service = AtomService.documentToService(doc);
81         assertEquals(1, service.getWorkspaces().size());
82     }
83
84     //------------------------------------------------------------------------------
85
/**
86      * Test get of entries collection URI
87      */

88     public void testGetEntriesCollection() throws Exception JavaDoc
89     {
90         UserData user = (UserData)mUsersCreated.get(0);
91                 
92         // get entries collection
93
MockHttpServletRequest mockRequest = getMockFactory().getMockRequest();
94         mockRequest.addHeader("X-WSSE",
95                 generateWSSEHeader(user.getUserName(), user.getPassword()));
96         mockRequest.setContextPath("/atom");
97         mockRequest.setPathInfo("/" + user.getUserName() + "/entries");
98         getServletModule().doGet();
99         
100         // assert that we got 20 entries
101
String JavaDoc output = getServletModule().getOutput();
102         SAXBuilder builder = new SAXBuilder();
103         Document doc = builder.build(new StringReader JavaDoc(output));
104         AtomCollection col = AtomCollection.documentToCollection(doc);
105         assertEquals(20, col.getMembers().size());
106         
107         // use collection next URI to get next batch of entries
108
resetMocks();
109         String JavaDoc[] next = Utilities.stringToStringArray(col.getNext(), "/");
110         
111         mockRequest = getMockFactory().getMockRequest();
112         mockRequest.addHeader("X-WSSE",
113             generateWSSEHeader(user.getUserName(), user.getPassword()));
114         mockRequest.setContextPath("/atom");
115         mockRequest.setPathInfo(
116             "/" + user.getUserName() + "/entries/" + next[next.length-1]);
117         getServletModule().doGet();
118
119         // assert that we got another 20 entries
120
output = getServletModule().getOutput();
121         doc = builder.build(new StringReader JavaDoc(output));
122         col = AtomCollection.documentToCollection(doc);
123         assertEquals(10, col.getMembers().size());
124     }
125
126     //------------------------------------------------------------------------------
127
/**
128      * Test get of entries collection URI with a range
129      */

130     public void testGetEntriesCollectionRange() throws Exception JavaDoc
131     {
132         UserData user = (UserData)mUsersCreated.get(0);
133         
134         Date JavaDoc end = new Date JavaDoc(); // now
135
Calendar JavaDoc cal = Calendar.getInstance();
136         cal.setTime(end);
137         cal.add(Calendar.DATE, -30);
138         Date JavaDoc start = cal.getTime(); // one day ago
139
String JavaDoc startString = df.format(start);
140         String JavaDoc endString = df.format(end);
141         
142         // get entries collection
143
MockHttpServletRequest mockRequest = getMockFactory().getMockRequest();
144         mockRequest.addHeader("X-WSSE",
145             generateWSSEHeader(user.getUserName(), user.getPassword()));
146         mockRequest.addHeader("Range",
147             "updated=" + startString + "/" + endString);
148         mockRequest.setContextPath("/atom");
149         mockRequest.setPathInfo("/" + user.getUserName() + "/entries");
150         getServletModule().doGet();
151         
152         // assert that we got 20 entries
153
String JavaDoc output = getServletModule().getOutput();
154         SAXBuilder builder = new SAXBuilder();
155         Document doc = builder.build(new StringReader JavaDoc(output));
156         AtomCollection col = AtomCollection.documentToCollection(doc);
157         assertEquals(20, col.getMembers().size());
158         
159         // use collection next URI to get next batch of entries
160
resetMocks();
161         String JavaDoc[] next = Utilities.stringToStringArray(col.getNext(), "/");
162         
163         mockRequest = getMockFactory().getMockRequest();
164         mockRequest.addHeader("X-WSSE",
165             generateWSSEHeader(user.getUserName(), user.getPassword()));
166         mockRequest.setContextPath("/atom");
167         mockRequest.setPathInfo("/" + user.getUserName() + "/entries");
168         mockRequest.setQueryString("Range=updated="+startString+"/"+endString);
169         getServletModule().doGet();
170
171         // assert that we got another 20 entries
172
output = getServletModule().getOutput();
173         doc = builder.build(new StringReader JavaDoc(output));
174         col = AtomCollection.documentToCollection(doc);
175         assertEquals(20, col.getMembers().size());
176     }
177
178     //------------------------------------------------------------------------------
179
/**
180      * Test that GET on the EditURI returns an entry.
181      */

182     public void testGetEntry() throws Exception JavaDoc
183     {
184         UserData user = (UserData)mUsersCreated.get(0);
185         WebsiteData website =
186             getRoller().getUserManager().getWebsite(user.getUserName());
187         WeblogEntryData entry = (WeblogEntryData)
188             getRoller().getWeblogManager().getWeblogEntries(
189                 website, null, null, null, WeblogManager.ALL, new Integer JavaDoc(1)).get(0);
190
191         Entry fetchedEntry = getEntry(user, entry.getId());
192         assertEquals(entry.getId(), fetchedEntry.getId());
193     }
194     
195     //------------------------------------------------------------------------------
196
/**
197      * Test that POST to the PostURI returns an entry.
198      */

199     public void testPostEntry() throws Exception JavaDoc
200     {
201         UserData user = (UserData)mUsersCreated.get(0);
202         
203         // Create an entry in a feed, so Rome can handle it
204
Content content = new Content();
205         content.setMode(Content.ESCAPED);
206         content.setValue("test entry text");
207         List JavaDoc contents = new ArrayList JavaDoc();
208         contents.add(content);
209
210         Entry entry = new Entry();
211         entry.setTitle("test entry title");
212         entry.setContents(contents);
213         
214         StringWriter JavaDoc entryWriter = new StringWriter JavaDoc();
215         AtomServlet.serializeEntry(entry, entryWriter);
216         
217         MockHttpServletRequest mockRequest = getMockFactory().getMockRequest();
218         mockRequest.setContextPath("/atom");
219         mockRequest.setPathInfo(user.getUserName() + "/entries/");
220         mockRequest.addHeader("X-WSSE",
221                 generateWSSEHeader(user.getUserName(), user.getPassword()));
222         mockRequest.setBodyContent(entryWriter.toString());
223         getServletModule().doPost();
224
225         String JavaDoc output = getServletModule().getOutput();
226         Entry returnedEntry = AtomServlet.parseEntry(new StringReader JavaDoc(output));
227         assertEquals(returnedEntry.getTitle(), entry.getTitle());
228         
229         MockHttpServletResponse mockResponse = getMockFactory().getMockResponse();
230         assertEquals(HttpServletResponse.SC_CREATED, mockResponse.getStatusCode());
231         assertTrue(mockResponse.containsHeader("Location"));
232        
233         getRoller().release();
234         resetMocks();
235
236         Entry fetchedEntry = getEntry(user, returnedEntry.getId());
237         assertEquals(returnedEntry.getId(), fetchedEntry.getId());
238     }
239     
240     //------------------------------------------------------------------------------
241
/**
242      * Test that PUT on the EditURI updates an entry.
243      */

244     public void testPutEntry() throws Exception JavaDoc
245     {
246         UserData user = (UserData)mUsersCreated.get(0);
247
248         WebsiteData website =
249             getRoller().getUserManager().getWebsite(user.getUserName());
250         WeblogEntryData entry = (WeblogEntryData)
251             getRoller().getWeblogManager().getWeblogEntries(
252                 website, null, null, null, WeblogManager.ALL, new Integer JavaDoc(1)).get(0);
253         
254         // Fetch that entry using Atom
255
Entry fetchedEntry = getEntry(user, entry.getId());
256         assertEquals(entry.getId(), fetchedEntry.getId());
257         
258         // Make a change to the fetched entry
259
fetchedEntry.setTitle("TEST TITLE");
260         
261         // Use Atom PUT to update the entry
262
StringWriter JavaDoc entryWriter = new StringWriter JavaDoc();
263         AtomServlet.serializeEntry(fetchedEntry, entryWriter);
264         MockHttpServletRequest mockRequest2 = getMockFactory().getMockRequest();
265         mockRequest2.setContextPath("/atom");
266         mockRequest2.setPathInfo(user.getUserName() + "/entry/" + entry.getId());
267         mockRequest2.addHeader("X-WSSE",
268            generateWSSEHeader(user.getUserName(), user.getPassword()));
269         mockRequest2.setBodyContent(entryWriter.toString());
270         getServletModule().doPut();
271         
272         getRoller().release();
273         resetMocks();
274
275         // Get the entry again to make sure the update was made
276
Entry fetchedEntry2 = getEntry(user, entry.getId());
277         assertEquals(fetchedEntry.getTitle(), fetchedEntry2.getTitle());
278     }
279     
280     //------------------------------------------------------------------------------
281
/**
282      * Test that DELETE on EditURI deletes entry.
283      */

284     public void testDeleteEntry() throws Exception JavaDoc
285     {
286         UserData user = (UserData)mUsersCreated.get(0);
287         WebsiteData website =
288             getRoller().getUserManager().getWebsite(user.getUserName());
289         WeblogEntryData entry = (WeblogEntryData)
290             getRoller().getWeblogManager().getWeblogEntries(
291                 website, null, null, null, WeblogManager.ALL, new Integer JavaDoc(1)).get(0);
292
293         Entry fetchedEntry = getEntry(user, entry.getId());
294         assertEquals(entry.getId(), fetchedEntry.getId());
295
296         // Use Atom DELETE to delete the entry
297
MockHttpServletRequest mockRequest2 = getMockFactory().getMockRequest();
298         mockRequest2.setContextPath("/atom");
299         mockRequest2.setPathInfo(user.getUserName() + "/entry/" + entry.getId());
300         mockRequest2.addHeader("X-WSSE",
301                 generateWSSEHeader(user.getUserName(), user.getPassword()));
302         getServletModule().doDelete();
303         getRoller().release();
304         resetMocks();
305         try
306         {
307             getEntry(user, entry.getId()).getId();
308             fail(); // no exception was thrown!
309
}
310         catch (Exception JavaDoc expected) {}
311     }
312
313      //------------------------------------------------------------------------------
314
private Entry getEntry(UserData user, String JavaDoc id) throws Exception JavaDoc
315     {
316         MockHttpServletRequest mockRequest = getMockFactory().getMockRequest();
317         mockRequest.setContextPath("/atom");
318         mockRequest.setPathInfo(user.getUserName() + "/entry/" + id);
319         mockRequest.addHeader("X-WSSE",
320                 generateWSSEHeader(user.getUserName(), user.getPassword()));
321         getServletModule().doGet();
322
323         String JavaDoc output = getServletModule().getOutput();
324         return AtomServlet.parseEntry(new StringReader JavaDoc(output));
325     }
326     
327     //------------------------------------------------------------------------------
328
public void testPostResource() throws Exception JavaDoc
329     {
330         UserData user = (UserData)mUsersCreated.get(0);
331         
332         // read test file into byte array
333
String JavaDoc fileName = "rssbadge.gif";
334         File JavaDoc testFile = new File JavaDoc(fileName);
335         FileInputStream JavaDoc fis = new FileInputStream JavaDoc(testFile);
336         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
337         Utilities.copyInputToOutput(fis, baos);
338         
339         // post file as resource
340
MockHttpServletRequest mockRequest = getMockFactory().getMockRequest();
341         mockRequest.setContextPath("/atom");
342         mockRequest.setPathInfo(user.getUserName() + "/resources/");
343         mockRequest.addHeader("Name", fileName);
344         mockRequest.addHeader("X-WSSE",
345                 generateWSSEHeader(user.getUserName(), user.getPassword()));
346         mockRequest.setBodyContent(baos.toByteArray());
347         getServletModule().doPost();
348         
349         MockHttpServletResponse mockResponse = getMockFactory().getMockResponse();
350         assertEquals(HttpServletResponse.SC_CREATED, mockResponse.getStatusCode());
351         assertTrue(mockResponse.containsHeader("Location"));
352         
353         getRoller().release();
354         resetMocks();
355     }
356
357     //------------------------------------------------------------------------------
358
public void setUp() throws Exception JavaDoc
359     {
360         super.setUp();
361         super.setUpTestWeblogs();
362         resetMocks();
363         MockServletContext ctx = getMockFactory().getMockServletContext();
364         ctx.setRealPath("/", "");
365         rollerContext = new MockRollerContext();
366         rollerContext.init(ctx);
367     }
368
369     //------------------------------------------------------------------------------
370
/**
371      * Really really reset mocks.
372      */

373     private void resetMocks()
374     {
375         mockFactory = null;
376         getMockFactory().refresh();
377         getMockFactory().getMockRequest().clearParameters();
378         getMockFactory().getMockRequest().clearAttributes();
379         setServletModule(new ServletTestModule(getMockFactory()));
380         getServletModule().setServlet(
381             getServletModule().createServlet(AtomServlet.class));
382         getServletModule().clearOutput();
383     }
384     
385     //------------------------------------------------------------------------------
386
/**
387      * @param servletModule The servletModule to set.
388      */

389     protected void setServletModule(ServletTestModule servletModule)
390     {
391         this.servletModule = servletModule;
392     }
393
394     //------------------------------------------------------------------------------
395
/**
396      * @return Returns the servletModule.
397      */

398     protected ServletTestModule getServletModule()
399     {
400         return servletModule;
401     }
402
403     //------------------------------------------------------------------------------
404
public void tearDown() throws Exception JavaDoc
405     {
406         super.tearDown();
407         super.tearDownTestWeblogs();
408     }
409     
410     //------------------------------------------------------------------------
411
public static Test suite()
412     {
413         return new TestSuite(AtomServletTest.class);
414     }
415
416     //------------------------------------------------------------------------------
417
public static String JavaDoc generateWSSEHeader(String JavaDoc username, String JavaDoc password)
418         throws Exception JavaDoc
419     {
420         byte[] nonceBytes = Long.toString(new Date JavaDoc().getTime()).getBytes();
421         String JavaDoc nonce = new String JavaDoc(WSSEUtilities.base64Encode(nonceBytes));
422         
423         SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc("yyyy-MM-dd'T'HH:mm:ss'Z'");
424         String JavaDoc created = sdf.format(new Date JavaDoc());
425         
426         String JavaDoc digest = WSSEUtilities.generateDigest(
427                 nonceBytes, created.getBytes("UTF-8"), password.getBytes("UTF-8"));
428         
429         StringBuffer JavaDoc header = new StringBuffer JavaDoc("UsernameToken Username=\"");
430         header.append(username);
431         header.append("\", ");
432         header.append("PasswordDigest=\"");
433         header.append(digest);
434         header.append("\", ");
435         header.append("Nonce=\"");
436         header.append(nonce);
437         header.append("\", ");
438         header.append("Created=\"");
439         header.append(created);
440         header.append("\"");
441         return header.toString();
442     }
443 }
444
Popular Tags