Skip to content

Commit

Permalink
Return -1 port for non-listening WebServers
Browse files Browse the repository at this point in the history
Update `WebServer` implementations to return -1 from `getPort()` if
the server  isn't listening on a port. This aligns the implementations
with the interface Javadoc.

See gh-24606
  • Loading branch information
spartusch authored and philwebb committed Jan 5, 2021
1 parent 2ad9a47 commit 5c61df3
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 6 deletions.
Expand Up @@ -275,11 +275,13 @@ public void stop() {
@Override
public int getPort() {
Connector[] connectors = this.server.getConnectors();
Integer localPort = -1;
for (Connector connector : connectors) {
// Probably only one...
return getLocalPort(connector);
localPort = getLocalPort(connector);
break;
}
return 0;
return (localPort > 0) ? localPort : -1;
}

@Override
Expand Down
Expand Up @@ -192,7 +192,7 @@ public int getPort() {
if (this.disposableServer != null) {
return this.disposableServer.port();
}
return 0;
return -1;
}

}
Expand Up @@ -364,7 +364,7 @@ public int getPort() {
if (connector != null) {
return connector.getLocalPort();
}
return 0;
return -1;
}

private String getContextPath() {
Expand Down
Expand Up @@ -295,7 +295,7 @@ public void stop() throws WebServerException {
public int getPort() {
List<Port> ports = getActualPorts();
if (ports.isEmpty()) {
return 0;
return -1;
}
return ports.get(0).getNumber();
}
Expand Down
Expand Up @@ -115,6 +115,16 @@ void specificPort() throws Exception {
assertThat(this.webServer.getPort()).isEqualTo(specificPort);
}

@Test
void portIsMinusOneWhenConnectionIsClosed() {
AbstractReactiveWebServerFactory factory = getFactory();
this.webServer = factory.getWebServer(new EchoHandler());
this.webServer.start();
assertThat(this.webServer.getPort()).isGreaterThan(0);
this.webServer.stop();
assertThat(this.webServer.getPort()).isEqualTo(-1);
}

@Test
void basicSslFromClassPath() {
testBasicSslWithKeyStore("classpath:test.jks", "password");
Expand Down
Expand Up @@ -250,7 +250,7 @@ void emptyServerWhenPortIsMinusOne() {
factory.setPort(-1);
this.webServer = factory.getWebServer(exampleServletRegistration());
this.webServer.start();
assertThat(this.webServer.getPort()).isLessThan(0); // Jetty is -2
assertThat(this.webServer.getPort()).isEqualTo(-1);
}

@Test
Expand Down Expand Up @@ -300,6 +300,16 @@ void loadOnStartAfterContextIsInitialized() {
assertThat(servlet.getInitCount()).isEqualTo(1);
}

@Test
void portIsMinusOneWhenConnectionIsClosed() {
AbstractServletWebServerFactory factory = getFactory();
this.webServer = factory.getWebServer();
this.webServer.start();
assertThat(this.webServer.getPort()).isGreaterThan(0);
this.webServer.stop();
assertThat(this.webServer.getPort()).isEqualTo(-1);
}

@Test
void specificPort() throws Exception {
AbstractServletWebServerFactory factory = getFactory();
Expand Down

0 comments on commit 5c61df3

Please sign in to comment.