PageRenderTime 53ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/jetty-client/src/test/java/org/eclipse/jetty/client/ContentExchangeTest.java

https://github.com/dekellum/jetty
Java | 384 lines | 282 code | 69 blank | 33 comment | 18 complexity | 64a647d4363cf2a7509c053c60c19afc MD5 | raw file
  1. // ========================================================================
  2. // Copyright (c) 2009-2009 Mort Bay Consulting Pty. Ltd.
  3. // ------------------------------------------------------------------------
  4. // All rights reserved. This program and the accompanying materials
  5. // are made available under the terms of the Eclipse Public License v1.0
  6. // and Apache License v2.0 which accompanies this distribution.
  7. // The Eclipse Public License is available at
  8. // http://www.eclipse.org/legal/epl-v10.html
  9. // The Apache License v2.0 is available at
  10. // http://www.opensource.org/licenses/apache2.0.php
  11. // You may elect to redistribute this code under either of these licenses.
  12. // ========================================================================
  13. package org.eclipse.jetty.client;
  14. import static org.junit.Assert.assertEquals;
  15. import static org.junit.Assert.assertTrue;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.File;
  18. import java.io.FileInputStream;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.net.URLDecoder;
  24. import javax.servlet.ServletException;
  25. import javax.servlet.ServletInputStream;
  26. import javax.servlet.http.HttpServletRequest;
  27. import javax.servlet.http.HttpServletResponse;
  28. import org.eclipse.jetty.client.security.Realm;
  29. import org.eclipse.jetty.client.security.SimpleRealmResolver;
  30. import org.eclipse.jetty.http.HttpMethods;
  31. import org.eclipse.jetty.http.HttpStatus;
  32. import org.eclipse.jetty.io.ByteArrayBuffer;
  33. import org.eclipse.jetty.io.EofException;
  34. import org.eclipse.jetty.server.Handler;
  35. import org.eclipse.jetty.server.Request;
  36. import org.eclipse.jetty.server.Server;
  37. import org.eclipse.jetty.server.handler.AbstractHandler;
  38. import org.eclipse.jetty.server.handler.HandlerCollection;
  39. import org.eclipse.jetty.server.nio.SelectChannelConnector;
  40. import org.eclipse.jetty.servlet.DefaultServlet;
  41. import org.eclipse.jetty.servlet.ServletContextHandler;
  42. import org.eclipse.jetty.servlet.ServletHolder;
  43. import org.eclipse.jetty.util.IO;
  44. import org.junit.After;
  45. import org.junit.Before;
  46. import org.junit.Test;
  47. public class ContentExchangeTest
  48. {
  49. private static String _content =
  50. "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis felis nunc. "+
  51. "Quisque suscipit mauris et ante auctor ornare rhoncus lacus aliquet. Pellentesque "+
  52. "habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. "+
  53. "Vestibulum sit amet felis augue, vel convallis dolor. Cras accumsan vehicula diam "+
  54. "at faucibus. Etiam in urna turpis, sed congue mi. Morbi et lorem eros. Donec vulputate "+
  55. "velit in risus suscipit lobortis. Aliquam id urna orci, nec sollicitudin ipsum. "+
  56. "Cras a orci turpis. Donec suscipit vulputate cursus. Mauris nunc tellus, fermentum "+
  57. "eu auctor ut, mollis at diam. Quisque porttitor ultrices metus, vitae tincidunt massa "+
  58. "sollicitudin a. Vivamus porttitor libero eget purus hendrerit cursus. Integer aliquam "+
  59. "consequat mauris quis luctus. Cras enim nibh, dignissim eu faucibus ac, mollis nec neque. "+
  60. "Aliquam purus mauris, consectetur nec convallis lacinia, porta sed ante. Suspendisse "+
  61. "et cursus magna. Donec orci enim, molestie a lobortis eu, imperdiet vitae neque.";
  62. private File _docRoot;
  63. private Server _server;
  64. private HttpClient _client;
  65. private Realm _realm;
  66. private String _protocol;
  67. private String _baseUrl;
  68. private String _requestContent;
  69. /* ------------------------------------------------------------ */
  70. @Before
  71. public void setUp()
  72. throws Exception
  73. {
  74. _docRoot = new File("target/test-output/docroot/");
  75. _docRoot.mkdirs();
  76. _docRoot.deleteOnExit();
  77. File content = new File(_docRoot,"input.txt");
  78. FileOutputStream out = new FileOutputStream(content);
  79. out.write(_content.getBytes("utf-8"));
  80. out.close();
  81. _server = new Server();
  82. configureServer(_server);
  83. _server.start();
  84. int port = _server.getConnectors()[0].getLocalPort();
  85. _baseUrl = _protocol+"://localhost:"+port+ "/";
  86. }
  87. /* ------------------------------------------------------------ */
  88. @After
  89. public void tearDown()
  90. throws Exception
  91. {
  92. if (_server != null)
  93. {
  94. _server.stop();
  95. _server = null;
  96. }
  97. }
  98. /* ------------------------------------------------------------ */
  99. @Test
  100. public void testPut() throws Exception
  101. {
  102. startClient(_realm);
  103. ContentExchange putExchange = new ContentExchange();
  104. putExchange.setURL(getBaseUrl() + "output.txt");
  105. putExchange.setMethod(HttpMethods.PUT);
  106. putExchange.setRequestContent(new ByteArrayBuffer(_content.getBytes()));
  107. _client.send(putExchange);
  108. int state = putExchange.waitForDone();
  109. int responseStatus = putExchange.getResponseStatus();
  110. stopClient();
  111. boolean statusOk = (responseStatus == 200 || responseStatus == 201);
  112. assertTrue(statusOk);
  113. String content = IO.toString(new FileInputStream(new File(_docRoot,"output.txt")));
  114. assertEquals(_content,content);
  115. }
  116. /* ------------------------------------------------------------ */
  117. @Test
  118. public void testGet() throws Exception
  119. {
  120. startClient(_realm);
  121. ContentExchange getExchange = new ContentExchange();
  122. getExchange.setURL(getBaseUrl() + "input.txt");
  123. getExchange.setMethod(HttpMethods.GET);
  124. _client.send(getExchange);
  125. int state = getExchange.waitForDone();
  126. String content = "";
  127. int responseStatus = getExchange.getResponseStatus();
  128. if (responseStatus == HttpStatus.OK_200)
  129. {
  130. content = getExchange.getResponseContent();
  131. }
  132. stopClient();
  133. assertEquals(HttpStatus.OK_200,responseStatus);
  134. assertEquals(_content,content);
  135. }
  136. /* ------------------------------------------------------------ */
  137. @Test
  138. public void testHead() throws Exception
  139. {
  140. startClient(_realm);
  141. ContentExchange getExchange = new ContentExchange();
  142. getExchange.setURL(getBaseUrl() + "input.txt");
  143. getExchange.setMethod(HttpMethods.HEAD);
  144. _client.send(getExchange);
  145. getExchange.waitForDone();
  146. int responseStatus = getExchange.getResponseStatus();
  147. stopClient();
  148. assertEquals(HttpStatus.OK_200,responseStatus);
  149. }
  150. /* ------------------------------------------------------------ */
  151. @Test
  152. public void testPost() throws Exception
  153. {
  154. startClient(_realm);
  155. ContentExchange postExchange = new ContentExchange();
  156. postExchange.setURL(getBaseUrl() + "test");
  157. postExchange.setMethod(HttpMethods.POST);
  158. postExchange.setRequestContent(new ByteArrayBuffer(_content.getBytes()));
  159. _client.send(postExchange);
  160. int state = postExchange.waitForDone();
  161. int responseStatus = postExchange.getResponseStatus();
  162. stopClient();
  163. assertEquals(HttpStatus.OK_200,responseStatus);
  164. assertEquals(_content,_requestContent);
  165. }
  166. /* ------------------------------------------------------------ */
  167. protected void configureServer(Server server)
  168. throws Exception
  169. {
  170. setProtocol("http");
  171. SelectChannelConnector connector = new SelectChannelConnector();
  172. server.addConnector(connector);
  173. Handler handler = new TestHandler(getBasePath());
  174. ServletContextHandler root = new ServletContextHandler();
  175. root.setContextPath("/");
  176. root.setResourceBase(_docRoot.getAbsolutePath());
  177. ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
  178. servletHolder.setInitParameter( "gzip", "true" );
  179. root.addServlet( servletHolder, "/*" );
  180. HandlerCollection handlers = new HandlerCollection();
  181. handlers.setHandlers(new Handler[]{handler, root});
  182. server.setHandler( handlers );
  183. }
  184. /* ------------------------------------------------------------ */
  185. protected void startClient(Realm realm)
  186. throws Exception
  187. {
  188. _client = new HttpClient();
  189. configureClient(_client);
  190. if (realm != null)
  191. _client.setRealmResolver(new SimpleRealmResolver(realm));
  192. _client.start();
  193. }
  194. /* ------------------------------------------------------------ */
  195. protected void configureClient(HttpClient client)
  196. throws Exception
  197. {
  198. client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
  199. }
  200. /* ------------------------------------------------------------ */
  201. protected void stopClient()
  202. throws Exception
  203. {
  204. if (_client != null)
  205. {
  206. _client.stop();
  207. _client = null;
  208. }
  209. }
  210. /* ------------------------------------------------------------ */
  211. protected String getBasePath()
  212. {
  213. return _docRoot.getAbsolutePath();
  214. }
  215. /* ------------------------------------------------------------ */
  216. protected String getBaseUrl()
  217. {
  218. return _baseUrl;
  219. }
  220. /* ------------------------------------------------------------ */
  221. protected HttpClient getClient()
  222. {
  223. return _client;
  224. }
  225. /* ------------------------------------------------------------ */
  226. protected Realm getRealm()
  227. {
  228. return _realm;
  229. }
  230. /* ------------------------------------------------------------ */
  231. protected String getContent()
  232. {
  233. return _content;
  234. }
  235. /* ------------------------------------------------------------ */
  236. protected void setProtocol(String protocol)
  237. {
  238. _protocol = protocol;
  239. }
  240. /* ------------------------------------------------------------ */
  241. protected void setRealm(Realm realm)
  242. {
  243. _realm = realm;
  244. }
  245. /* ------------------------------------------------------------ */
  246. public static void copyStream(InputStream in, OutputStream out)
  247. {
  248. try
  249. {
  250. byte[] buffer=new byte[1024];
  251. int len;
  252. while ((len=in.read(buffer))>=0)
  253. {
  254. out.write(buffer,0,len);
  255. }
  256. }
  257. catch (EofException e)
  258. {
  259. System.err.println(e);
  260. }
  261. catch (IOException e)
  262. {
  263. e.printStackTrace();
  264. }
  265. }
  266. /* ------------------------------------------------------------ */
  267. protected class TestHandler extends AbstractHandler {
  268. private final String resourcePath;
  269. /* ------------------------------------------------------------ */
  270. public TestHandler(String repositoryPath) {
  271. this.resourcePath = repositoryPath;
  272. }
  273. /* ------------------------------------------------------------ */
  274. public void handle(String target, Request baseRequest,
  275. HttpServletRequest request, HttpServletResponse response)
  276. throws IOException, ServletException
  277. {
  278. if (baseRequest.isHandled())
  279. {
  280. return;
  281. }
  282. OutputStream out = null;
  283. if (baseRequest.getMethod().equals("PUT"))
  284. {
  285. baseRequest.setHandled(true);
  286. File file = new File(resourcePath, URLDecoder.decode(request.getPathInfo()));
  287. file.getParentFile().mkdirs();
  288. file.deleteOnExit();
  289. out = new FileOutputStream(file);
  290. response.setStatus(HttpServletResponse.SC_CREATED);
  291. }
  292. if (baseRequest.getMethod().equals("POST"))
  293. {
  294. baseRequest.setHandled(true);
  295. out = new ByteArrayOutputStream();
  296. response.setStatus(HttpServletResponse.SC_OK);
  297. }
  298. if (out != null)
  299. {
  300. ServletInputStream in = request.getInputStream();
  301. try
  302. {
  303. copyStream( in, out );
  304. }
  305. finally
  306. {
  307. in.close();
  308. out.close();
  309. }
  310. if (!(out instanceof FileOutputStream))
  311. _requestContent = out.toString();
  312. }
  313. }
  314. }
  315. }