1

I need to send a stub response over http to a requesting client from Jetty. It works when I run the Junit test independently, implies, I get the correct XML response .. but it fails when I run the same thing from maven. The error I see is "java.net.SocketException: Unexpected end of file from server". I have tried everything! Please help!

Here's my code -

Junit (when run as a Junit test - it works)

public class MyTest {

@Test
    public void testGetOpenLots() throws Exception {

        // create fixture
        MyService fixture = new MyService();

        // create jetty server instance
        Server server = new Server(8080);

        // set a handler
        server.setHandler(new HelloHandler());

        // set shutdown conditions
        // server.setStopAtShutdown(true);

        // start server
        server.start();

        // invoke operation
        MyResponse result = fixture.getWeather(someDummyRequest);

        assertNotNull(result);
    }

}

Somewhere down the line, inside getWeather(), I create a URL object and pass the URL http://localhost:8080 to it and send the request to that URL. At this point, I expect that the HelloHandler's handle method will get invoked and will write this dummy XML response to stream and getWeather() method will receive the response.

Here's the handler:

public class HelloHandler extends AbstractHandler {

 public void handle(String target, Request baseRequest,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("application/xml;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<result>a simple response</result>");

    }

}

When I run the same thing from maven, it throws the error mentioned above. What am I doing wrong?

Aravind Datta
  • 327
  • 4
  • 6
  • 17
  • 1
    Well.. I seemed to have fixed this problem myself. I have no clue if what I did is right or wrong.. but it works for now. What I did is, I added a servlet context like this: 'ServletContextHandler ctx = new ServletContextHandler();' ctx.setHandler(new HelloHandler()); // set a handler to the servletcontext server.setHandler(ctx); and inside handler, I made handler extend ScopedHandler instead of AbstractHandler. Handler will implement doScope and doHandle methods. – Aravind Datta May 23 '13 at 18:31

1 Answers1

3

Instead of implementing your own jetty handler you can try Jadler (http://jadler.net), an http stubbing/mocking library I've been working on for a while.

Jan Dudek
  • 245
  • 1
  • 5
  • 8