|
| 1 | +package org.restlet.test.engine; |
| 2 | + |
| 3 | +import org.restlet.Application; |
| 4 | +import org.restlet.Component; |
| 5 | +import org.restlet.Restlet; |
| 6 | +import org.restlet.data.MediaType; |
| 7 | +import org.restlet.data.Protocol; |
| 8 | +import org.restlet.representation.Representation; |
| 9 | +import org.restlet.resource.ClientResource; |
| 10 | +import org.restlet.resource.Get; |
| 11 | +import org.restlet.resource.ServerResource; |
| 12 | +import org.restlet.routing.Router; |
| 13 | +import org.restlet.test.RestletTestCase; |
| 14 | + |
| 15 | +/** |
| 16 | + * Tests that when issuing internal calls, the application context is kept intact in the caller server resource. |
| 17 | + */ |
| 18 | +public class ApplicationContextTestCase extends RestletTestCase { |
| 19 | + |
| 20 | + public static class InternalApplication extends Application { |
| 21 | + |
| 22 | + @Override |
| 23 | + public Restlet createInboundRoot() { |
| 24 | + Router router = new Router(); |
| 25 | + router.attach("/test", InternalResource.class); |
| 26 | + return router; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public static class InternalResource extends ServerResource { |
| 31 | + @Get |
| 32 | + public String hello() { |
| 33 | + return "hello, world"; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + public static class WebApiApplication extends Application { |
| 38 | + @Override |
| 39 | + public Restlet createInboundRoot() { |
| 40 | + Router router = new Router(); |
| 41 | + router.attach("/test", WebApiResource.class); |
| 42 | + return router; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public static class WebApiResource extends ServerResource { |
| 47 | + @Get |
| 48 | + public String hello() { |
| 49 | + // issuing internal calls |
| 50 | + new ClientResource("riap://component/internal/test").get(); |
| 51 | + // returns the current application |
| 52 | + return Application.getCurrent().getClass().getSimpleName(); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + private Component component; |
| 57 | + |
| 58 | + @Override |
| 59 | + protected void setUp() throws Exception { |
| 60 | + super.setUp(); |
| 61 | + this.component = new Component(); |
| 62 | + this.component.getServers().add(Protocol.HTTP, TEST_PORT); |
| 63 | + |
| 64 | + component.getDefaultHost().attach("/api", new WebApiApplication()); |
| 65 | + component.getInternalRouter().attach("/internal", new InternalApplication()); |
| 66 | + |
| 67 | + component.start(); |
| 68 | + } |
| 69 | + |
| 70 | + @Override |
| 71 | + protected void tearDown() throws Exception { |
| 72 | + component.stop(); |
| 73 | + } |
| 74 | + |
| 75 | + public void testApplicationContext() throws Exception { |
| 76 | + ClientResource res = new ClientResource("http://localhost:" + TEST_PORT + "/api/test"); |
| 77 | + Representation rep = res.get(MediaType.TEXT_PLAIN); |
| 78 | + assertEquals("WebApiApplication", rep.getText()); |
| 79 | + } |
| 80 | +} |
0 commit comments