Skip to content
This repository was archived by the owner on Jul 31, 2022. It is now read-only.

Commit 16b5abe

Browse files
committed
Fix #86
1 parent f5c2aef commit 16b5abe

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/main/java/com/kttdevelopment/simplehttpserver/SimpleHttpServerImpl.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import java.net.InetSocketAddress;
88
import java.util.*;
99
import java.util.concurrent.Executor;
10+
import java.util.function.BiConsumer;
1011

1112
/**
1213
* Implementation for {@link SimpleHttpServer}. Applications do not use this class.
@@ -147,15 +148,21 @@ public synchronized final HttpContext createContext(final String context, final
147148

148149
@Override
149150
public synchronized final HttpContext createContext(final String context, final HttpHandler handler, final Authenticator authenticator){
150-
if(!ContextUtil.getContext(context,true,false).equals("/") && handler instanceof RootHandler)
151+
final String ct = ContextUtil.getContext(context,true,false);
152+
if(!ct.equals("/") && handler instanceof RootHandler)
151153
throw new IllegalArgumentException("RootHandler can only be used at the root '/' context");
152154

153155
final HttpHandler wrapper = exchange -> {
154156
handle(exchange);
155157
handler.handle(exchange);
156158
};
157159

158-
final HttpContext hc = server.createContext(ContextUtil.getContext(context,true,false),wrapper);
160+
161+
for(final HttpContext httpContext : contexts.keySet())
162+
if(httpContext.getPath().equals(ct))
163+
throw new IllegalArgumentException("The context '" + ct + "' is already occupied");
164+
165+
final HttpContext hc = server.createContext(ct,wrapper);
159166
contexts.put(hc,handler);
160167

161168
if(authenticator != null)

src/test/java/simplehttpserver/SimpleHttpServerContextTests.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.kttdevelopment.simplehttpserver.*;
44
import com.kttdevelopment.simplehttpserver.handler.RootHandler;
55
import com.sun.net.httpserver.HttpExchange;
6+
import com.sun.net.httpserver.HttpServer;
67
import org.junit.Assert;
78
import org.junit.Test;
89

@@ -133,4 +134,14 @@ public final void createSlashedContext() throws IOException{
133134
Assert.assertEquals("Context [" + root + "] should correct to \"/\"","/",server.createContext(root).getPath());
134135
}
135136

137+
138+
@Test(expected = IllegalArgumentException.class)
139+
public final void createDuplicateContext() throws IOException{
140+
final SimpleHttpServer server = SimpleHttpServer.create();
141+
final String context = server.getRandomContext();
142+
143+
server.createContext(context);
144+
server.createContext(context,HttpExchange::close);
145+
}
146+
136147
}

0 commit comments

Comments
 (0)