Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http.maxConnections tests #4751

Open
wants to merge 1 commit into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
Expand Down Expand Up @@ -37,6 +37,17 @@ public final class ExternalProperties {
*/
public static final String HTTP_NON_PROXY_HOSTS = "http.nonProxyHosts";

/**
* Property used to indicates if persistent connections should be supported.
*/
public static final String HTTP_KEEPALIVE = "http.keepAlive";

/**
* If HTTP keepalive is enabled this value determines the maximum number
* of idle connections that will be simultaneously kept alive, per destination.
*/
public static final String HTTP_MAX_CONNECTIONS = "http.maxConnections";

/**
* Prevent instantiation.
*/
Expand Down
12 changes: 11 additions & 1 deletion tests/integration/externalproperties/pom.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
Copyright (c) 2020, 2021 Oracle and/or its affiliates. All rights reserved.

This program and the accompanying materials are made available under the
terms of the Eclipse Public License v. 2.0, which is available at
Expand Down Expand Up @@ -42,6 +42,16 @@
<artifactId>jersey-test-framework-provider-jetty</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-jdk-connector</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
/*
* Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/

package org.glassfish.jersey.tests.externalproperties;

import org.glassfish.jersey.ExternalProperties;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jdk.connector.JdkConnectorProperties;
import org.glassfish.jersey.jdk.connector.JdkConnectorProvider;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import javax.net.ServerSocketFactory;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.core.Application;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@RunWith(Parameterized.class)
public class HttpMaxConnectionTest extends JerseyTest {

private final Client client;

@Parameterized.Parameters(name = "{index}: {0}")
public static List<Object[]> configurations() {
return Arrays.asList(new Object[][]{
{createApacheConfig()},
{createJdkConfig()},
});
}

private static ClientConfig createApacheConfig() {
System.setProperty(ExternalProperties.HTTP_MAX_CONNECTIONS, "1");
System.setProperty(ExternalProperties.HTTP_KEEPALIVE, "true");
ClientConfig config = new ClientConfig();
config.connectorProvider(new ApacheConnectorProvider());
config.property(ApacheClientProperties.USE_SYSTEM_PROPERTIES, true);
return config;
}

private static ClientConfig createJdkConfig() {
ClientConfig config = new ClientConfig();
config.connectorProvider(new JdkConnectorProvider());
config.property(JdkConnectorProperties.MAX_CONNECTIONS_PER_DESTINATION, 1);
config.property(JdkConnectorProperties.CONNECTION_IDLE_TIMEOUT, 10_000);
return config;
}

public HttpMaxConnectionTest(ClientConfig clientConfigClass) {
this.client = ClientBuilder.newClient(clientConfigClass);
}

@Test
public void testPersistentConnection() throws IOException, InterruptedException {
TestServer testServer = new TestServer(true);

try {
testServer.start();
CountDownLatch latch = new CountDownLatch(2);
AtomicInteger result1 = new AtomicInteger(-1);
sendGetToTestServer(result1, latch);
AtomicInteger result2 = new AtomicInteger(-1);
sendGetToTestServer(result2, latch);

assertTrue(latch.await(5, TimeUnit.SECONDS));

assertEquals(1, result1.get());
assertEquals(1, result2.get());
} finally {
testServer.stop();
}
}

@Test
public void testNonPersistentConnection() throws IOException, InterruptedException {
TestServer testServer = new TestServer(false);

try {
testServer.start();
CountDownLatch latch1 = new CountDownLatch(1);
AtomicInteger result1 = new AtomicInteger(-1);
sendGetToTestServer(result1, latch1);
assertTrue(latch1.await(5, TimeUnit.SECONDS));
CountDownLatch latch2 = new CountDownLatch(1);

AtomicInteger result2 = new AtomicInteger(-1);
sendGetToTestServer(result2, latch2);

assertTrue(latch2.await(5, TimeUnit.SECONDS));

assertEquals(1, result1.get());
assertEquals(2, result2.get());
} finally {
testServer.stop();
}
}

private void sendGetToTestServer(final AtomicInteger result, final CountDownLatch latch) {
client.target("http://localhost:" + TestServer.PORT).request().async().get(new InvocationCallback<Integer>() {
@Override
public void completed(Integer response) {
System.out.println("#Received: " + response);
result.set(response);
latch.countDown();
}

@Override
public void failed(Throwable throwable) {
throwable.printStackTrace();
}
});
}

@Override
protected Application configure() {
return new ResourceConfig(EchoResource.class);
}

@Path("/echo")
public static class EchoResource {

@POST
public String post(String entity) {
return entity;
}
}

private static class TestServer {

static final int PORT = 8321;

private final boolean persistentConnection;
private final ServerSocket serverSocket;
private final ExecutorService executorService = Executors.newCachedThreadPool();
private final AtomicInteger connectionsCount = new AtomicInteger(0);

private volatile boolean stopped = false;

TestServer(boolean persistentConnection) throws IOException {
this.persistentConnection = persistentConnection;
ServerSocketFactory socketFactory = ServerSocketFactory.getDefault();
serverSocket = socketFactory.createServerSocket(PORT);
}

void start() {
executorService.execute(() -> {
try {
while (!stopped) {
final Socket socket = serverSocket.accept();
connectionsCount.incrementAndGet();
executorService.submit(() -> handleConnection(socket));

}
} catch (IOException e) {
//do nothing
}
});
}

private void handleConnection(Socket socket) {

try {
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream receivedMessage = new ByteArrayOutputStream();

while (!stopped && !socket.isClosed()) {
int result = inputStream.read();
if (result == -1) {
return;
}

receivedMessage.write((byte) result);
String msg = new String(receivedMessage.toByteArray(), "ASCII");
if (msg.contains("\r\n\r\n")) {
receivedMessage = new ByteArrayOutputStream();
OutputStream outputStream = socket.getOutputStream();
String response = "HTTP/1.1 200 OK\r\nContent-Length: 1\r\nContent-Type: text/plain\r\n";
if (!persistentConnection) {
response += "Connection: Close\r\n";
}
response += "\r\n" + connectionsCount.get();
outputStream.write(response.getBytes("ASCII"));
outputStream.flush();
}
}
} catch (IOException e) {
if (!e.getClass().equals(SocketException.class)) {
e.printStackTrace();
}
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

void stop() throws IOException {
executorService.shutdown();
serverSocket.close();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
Expand All @@ -22,6 +22,7 @@
import org.glassfish.jersey.ExternalProperties;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
Expand All @@ -38,6 +39,7 @@ public class HttpProxyTest extends JerseyTest {
private static final String PROXY_HOST = "localhost";
private static final String PROXY_PORT = "9997";
private static boolean proxyHit = false;
private Server server;

@Path("resource")
public static class ProxyTestResource {
Expand All @@ -58,7 +60,7 @@ protected Application configure() {
public void startFakeProxy() {
System.setProperty(ExternalProperties.HTTP_PROXY_HOST, PROXY_HOST);
System.setProperty(ExternalProperties.HTTP_PROXY_PORT, PROXY_PORT);
Server server = new Server(Integer.parseInt(PROXY_PORT));
server = new Server(Integer.parseInt(PROXY_PORT));
server.setHandler(new ProxyHandler(false));
try {
server.start();
Expand All @@ -67,6 +69,11 @@ public void startFakeProxy() {
}
}

@After
public void stopFakeProxy() throws Exception {
server.stop();
}

@Test
public void testProxy() {
System.setProperty(ExternalProperties.HTTP_NON_PROXY_HOSTS, "");
Expand Down