Home | History | Annotate | Download | only in integration
      1 package fi.iki.elonen.integration;
      2 
      3 import static org.junit.Assert.assertEquals;
      4 
      5 import java.io.DataInputStream;
      6 import java.io.IOException;
      7 import java.util.Map;
      8 
      9 import org.apache.http.client.ResponseHandler;
     10 import org.apache.http.client.methods.HttpPut;
     11 import org.apache.http.entity.ByteArrayEntity;
     12 import org.apache.http.impl.client.BasicResponseHandler;
     13 import org.junit.Test;
     14 
     15 import fi.iki.elonen.NanoHTTPD;
     16 
     17 public class PutStreamIntegrationTest extends IntegrationTestBase<PutStreamIntegrationTest.TestServer> {
     18 
     19     @Test
     20     public void testSimplePutRequest() throws Exception {
     21         String expected = "This HttpPut request has a content-length of 48.";
     22 
     23         HttpPut httpput = new HttpPut("http://localhost:8192/");
     24         httpput.setEntity(new ByteArrayEntity(expected.getBytes()));
     25         ResponseHandler<String> responseHandler = new BasicResponseHandler();
     26         String responseBody = httpclient.execute(httpput, responseHandler);
     27 
     28         assertEquals("PUT:" + expected, responseBody);
     29     }
     30 
     31     @Override public TestServer createTestServer() {
     32         return new TestServer();
     33     }
     34 
     35     public static class TestServer extends NanoHTTPD {
     36         public TestServer() {
     37             super(8192);
     38         }
     39 
     40         @Override
     41         public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files)
     42         {
     43             throw new UnsupportedOperationException();
     44         }
     45 
     46         @Override
     47         public Response serve(IHTTPSession session) {
     48             Method method = session.getMethod();
     49             Map<String, String> headers = session.getHeaders();
     50             int contentLength = Integer.parseInt(headers.get("content-length"));
     51 
     52             byte[] body;
     53             try {
     54                 DataInputStream dataInputStream = new DataInputStream(session.getInputStream());
     55                 body = new byte[contentLength];
     56                 dataInputStream.readFully(body, 0, contentLength);
     57             }
     58             catch(IOException e) {
     59                 return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, e.getMessage());
     60             }
     61 
     62             String response = String.valueOf(method) + ':' + new String(body);
     63             return new Response(response);
     64         }
     65     }
     66 }
     67