简体   繁体   中英

Resteasy Client keeping connection allocated after a method throws an Exception

I'm currently using TJWSEmbeddedJaxrsServer to help me with my RESTful API tests (created with Resteasy) and it works sweetly. But a problem happens when any of the called methods throws an Exception: the Reasteasy Client becomes "lost" and still holds the connection, not allowing for the other test methods to call the RESTful service. It happens even if you instanciate a Provider that can Unwrap the Exception and use it in the embedded server.

Can anyone help me, please?

To simulate the problem, it's actually easy:

  1. Download the sample provided by Mark Paluch in https://github.com/mp911de/rest-api-test
  2. Change the test class to be like this:

public class InMemoryRestTest {

@Path("/myresource")
public static class MyResource {

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.APPLICATION_XML)
    public MyModel createMyModel(int number) throws Exception {
        // supose this is a Business exception
        throw new Exception("Test");
    }

}

public static MyResource sut = new MyResource();
public static InMemoryRestServer server;

@BeforeClass
public static void beforeClass() throws Exception {
    server = InMemoryRestServer.create(sut);
}

@AfterClass
public static void afterClass() throws Exception {
    server.close();
}

@Test
public void postSimpleBody() throws Exception {
    // This one throws the "Exception" exception and passes     
    Response response = server.newRequest("/myresource").request().buildPost(Entity.text("42")).invoke();
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}

@Test
public void postAnother() throws Exception {
    // This one fails with "Invalid use of BasicClientConnManager: connection still allocated."
    Response response = server.newRequest("/myresource").request().buildPost(Entity.text("20")).invoke();
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}

}

And voilla! When the tests for "postAnother()" run, the following error will occur:

javax.ws.rs.ProcessingException: Unable to invoke request
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:287)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:407)
    at biz.paluch.rest.test.InMemoryRestTest.postSimpleBody(InMemoryRestTest.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
    at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(BasicClientConnectionManager.java:162)
    at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(BasicClientConnectionManager.java:139)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:283)
    ... 27 more

The default ResteasyClientBuilder does not use a connection pool, meaning you can have only one parallel connection at a time. Therefore you have to ensure to close your responses (ie response.close()) in order to free-up the (only) connection.

See the Response implementation here: https://github.com/resteasy/Resteasy/blob/master/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientResponse.java

public void close()
   {
      if (isClosed()) return;
      try {
         isClosed = true;
         releaseConnection(); // <= HERE!
      }
      catch (Exception e) {
         throw new ProcessingException(e);
      }
   }

So the following should fix your problem:

@Test
public void postBody() throws Exception {          
    Response response = null;
    try {
        response = server.newRequest("...").request().buildPost(Entity.text("...")).invoke();           
    } finally {
        response.close();
    }   
}

Regards,

Bernard.

You need to configure the ResteasyClientBuilder to use a connection pool. Modify the withDefaults() method of the InMemoryRestServer class the following way

//this.resteasyClient = new ResteasyrestEasyClientBuilder().build();
ResteasyrestEasyClientBuilder restEasyClientBuilder = new ResteasyrestEasyClientBuilder();
restEasyClientBuilder = restEasyClientBuilder.connectionPoolSize(20);
this.resteasyClient = restEasyClientBuilder.build();

This way both of your testcases should run without exception (both seem to throw AssertionError though)

In Java SE 7 and above, the cleaner approach would be to use try with resources. Sample snippet as follows:

try(response = server.newRequest("...").request().buildPost(Entity.text("...")).invoke())
{ 
   /* response handling logic */ 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM