Skip to content
This repository was archived by the owner on May 10, 2024. It is now read-only.

Commit d45e4c6

Browse files
committed
cookie, stream fixes, exchange tests except IO
1 parent dd1ab88 commit d45e4c6

File tree

8 files changed

+239
-35
lines changed

8 files changed

+239
-35
lines changed

src/main/java/dev/katsute/simplehttpserver/HttpSessionHandler.java

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,13 @@ public synchronized String assignSessionID(final HttpExchange exchange){
7474
}
7575

7676
private String getSetSession(final Headers headers){ // get session that will be set by cookie
77-
if(headers.containsKey("Set-Cookie"))
78-
for(final String value : headers.get("Set-Cookie"))
79-
if(value.startsWith(cookie + "="))
80-
return value.substring(cookie.length() + 1, value.contains(";") ? value.indexOf(";") : value.length());
77+
for(final Map.Entry<String,List<String>> entry : headers.entrySet())
78+
if(entry.getKey().equalsIgnoreCase("Set-Cookie")){
79+
for(final String value : entry.getValue())
80+
if(value.startsWith(cookie + "=\""))
81+
return value.substring(cookie.length() + 2, value.length() - 1);
82+
break;
83+
}
8184
return null;
8285
}
8386

@@ -93,15 +96,14 @@ public final HttpSession getSession(final HttpExchange exchange){
9396
final String sessionID;
9497
final HttpSession session;
9598

96-
@SuppressWarnings("SpellCheckingInspection")
97-
final String rcookies = Objects.requireNonNull(exchange).getRequestHeaders().getFirst("Cookie");
9899
final Map<String,String> cookies = new HashMap<>();
99-
100-
if(rcookies != null && !rcookies.isEmpty()){
101-
final String[] pairs = rcookies.split("; ");
102-
for(final String pair : pairs){
103-
final String[] value = pair.split("=");
104-
cookies.put(value[0], value[1]);
100+
for(final Map.Entry<String,List<String>> entry : Objects.requireNonNull(exchange).getRequestHeaders().entrySet()){
101+
if(entry.getKey().equalsIgnoreCase("Cookie")){
102+
for(final String value : entry.getValue()){
103+
final String[] pair = value.split("=");
104+
cookies.put(pair[0], pair[1]);
105+
}
106+
break;
105107
}
106108
}
107109

src/main/java/dev/katsute/simplehttpserver/SimpleHttpExchangeImpl.java

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,12 @@ private static Map<String,String> parseWwwFormEnc(final String s){
7979
getMap = rawGet == null ? new HashMap<>() : parseWwwFormEnc(rawGet);
8080

8181
String OUT;
82-
try(final InputStreamReader IN = new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8)){
83-
try(final Stream<String> lns = new BufferedReader(IN).lines()){
84-
OUT = lns.collect(Collectors.joining("\n"));
85-
}
86-
}catch(final Throwable e){
82+
try(
83+
final InputStream IN = exchange.getRequestBody();
84+
final Scanner scanner = new Scanner(IN, "UTF-8")
85+
){
86+
OUT = scanner.useDelimiter("\\A").next();
87+
}catch(final IOException | NoSuchElementException ignored){
8788
OUT = null;
8889
}
8990

@@ -155,16 +156,18 @@ private static Map<String,String> parseWwwFormEnc(final String s){
155156
multipartFormData = null;
156157
}
157158

158-
final String rawCookie = exchange.getRequestHeaders().getFirst("Cookie");
159-
final Map<String,String> cookie_buffer = new HashMap<>();
160-
if(rawCookie != null && !rawCookie.isEmpty()){
161-
final String[] cookedCookie = rawCookie.split("; "); // pair
162-
for(final String pair : cookedCookie){
163-
String[] value = pair.split("=");
164-
cookie_buffer.put(value[0], value[1]);
159+
final Map<String,String> cookies = new HashMap<>();
160+
for(final Map.Entry<String,List<String>> entry : Objects.requireNonNull(exchange).getRequestHeaders().entrySet()){
161+
if(entry.getKey().equalsIgnoreCase("Cookie")){
162+
for(final String value : entry.getValue()){
163+
final String[] pair = value.split("=");
164+
cookies.put(pair[0], pair[1]);
165+
}
166+
break;
165167
}
166168
}
167-
cookies = cookie_buffer;
169+
170+
this.cookies = cookies;
168171
}
169172

170173
//
@@ -353,7 +356,10 @@ public final void send(final byte[] response, final int responseCode, final bool
353356
exchange.getResponseHeaders().set("Content-Encoding","gzip");
354357
exchange.getResponseHeaders().set("Connection","keep-alive");
355358
sendResponseHeaders(responseCode, 0);
356-
try(GZIPOutputStream OUT = new GZIPOutputStream(exchange.getResponseBody())){
359+
try(
360+
final OutputStream OS = exchange.getResponseBody();
361+
final GZIPOutputStream OUT = new GZIPOutputStream(OS);
362+
){
357363
OUT.write(Objects.requireNonNull(response));
358364
OUT.finish();
359365
OUT.flush();

src/main/java/dev/katsute/simplehttpserver/SimpleHttpServerImpl.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ final class SimpleHttpServerImpl extends SimpleHttpServer {
3232

3333
private HttpSessionHandler sessionHandler;
3434

35-
private final Map<HttpContext, HttpHandler> contexts = Collections.synchronizedMap(new HashMap<>());
35+
private final Map<HttpContext,HttpHandler> contexts = Collections.synchronizedMap(new HashMap<>());
3636

3737
SimpleHttpServerImpl(final Integer port, final Integer backlog) throws IOException{
3838
if(port != null)

src/test/java/dev/katsute/simplehttpserver/Requests.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66

77
public class Requests {
88

9+
public static CookieManager Cookies = new CookieManager();
10+
911
static{
10-
CookieHandler.setDefault(new CookieManager());
12+
CookieHandler.setDefault(Cookies);
1113
}
1214

1315
public static HttpURLConnection openConn(final String URL){

src/test/java/dev/katsute/simplehttpserver/server/ServerTests.java renamed to src/test/java/dev/katsute/simplehttpserver/ServerTests.java

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package dev.katsute.simplehttpserver.server;
1+
package dev.katsute.simplehttpserver;
22

33
import com.sun.net.httpserver.HttpContext;
44
import com.sun.net.httpserver.HttpExchange;
@@ -10,8 +10,7 @@
1010

1111
import static org.junit.jupiter.api.Assertions.*;
1212

13-
@Disabled
14-
class ServerTests {
13+
final class ServerTests {
1514

1615
@Test
1716
final void testReference() throws IOException{
@@ -30,12 +29,21 @@ final void testProp() throws IOException{
3029
@Nested
3130
final class BindTests {
3231

32+
@BeforeEach
33+
final void beforeEach() throws InterruptedException{
34+
Thread.sleep(500);
35+
}
36+
3337
@Test
3438
final void testBind() throws IOException{
3539
final SimpleHttpServer server = SimpleHttpServer.create();
3640
assertNull(server.getAddress());
3741
assertDoesNotThrow(() -> server.bind(8080));
3842
assertTrue(server.getAddress().getAddress().isAnyLocalAddress());
43+
44+
// required to unbind
45+
server.start();
46+
server.stop();
3947
}
4048

4149
@Test
@@ -55,12 +63,16 @@ final void testOccupied() throws IOException{
5563
@Nested
5664
final class CreateTests {
5765

58-
@SuppressWarnings("SpellCheckingInspection")
66+
@BeforeEach
67+
final void beforeEach() throws InterruptedException{
68+
Thread.sleep(500);
69+
}
70+
5971
@Test
6072
final void testHttpCreate() throws IOException{
6173
final SimpleHttpServer server = SimpleHttpServer.create();
6274

63-
assertThrows(IllegalStateException.class, server::start, "Unbinded server should throw an excaption");
75+
assertThrows(IllegalStateException.class, server::start);
6476

6577
server.bind(8080);
6678
assertEquals(8080, server.getAddress().getPort());
@@ -72,12 +84,11 @@ final void testHttpCreate() throws IOException{
7284
assertDoesNotThrow(() -> server.stop(), "Second stop should not throw an exception");
7385
}
7486

75-
@SuppressWarnings("SpellCheckingInspection")
7687
@Test
7788
final void testHttpsCreate() throws IOException{
7889
final SimpleHttpsServer server = SimpleHttpsServer.create();
7990

80-
assertThrows(IllegalStateException.class, server::start, "Unbinded server should throw an excaption");
91+
assertThrows(IllegalStateException.class, server::start);
8192

8293
server.bind(8080);
8394
assertEquals(8080, server.getAddress().getPort());
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package dev.katsute.simplehttpserver.exchange;
2+
3+
import dev.katsute.simplehttpserver.*;
4+
import org.junit.jupiter.api.*;
5+
6+
import java.io.IOException;
7+
import java.util.concurrent.atomic.AtomicReference;
8+
9+
final class ExchangeGetTests {
10+
11+
private static SimpleHttpServer server;
12+
13+
private static SimpleHttpExchange exchange;
14+
15+
@BeforeAll
16+
static void beforeAll() throws IOException{
17+
server = SimpleHttpServer.create(8080);
18+
19+
AtomicReference<SimpleHttpExchange> exchangeRef = new AtomicReference<>();
20+
21+
server.createContext("exchange", (SimpleHttpHandler) e -> {
22+
exchangeRef.set(e);
23+
e.send(200);
24+
e.close();
25+
});
26+
27+
server.start();
28+
29+
Requests.getBody("http://localhost:8080/exchange?key=value&alt=a%2B%3F%26%7D");
30+
exchange = exchangeRef.get();
31+
32+
server.stop();
33+
}
34+
35+
@Test
36+
final void testGET(){
37+
Assertions.assertEquals("GET", exchange.getRequestMethod().toUpperCase());
38+
Assertions.assertTrue(exchange.hasGet());
39+
Assertions.assertEquals("value", exchange.getGetMap().get("key"));
40+
Assertions.assertEquals("a+?&}", exchange.getGetMap().get("alt"));
41+
}
42+
43+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package dev.katsute.simplehttpserver.exchange;
2+
3+
import com.sun.net.httpserver.HttpContext;
4+
import dev.katsute.simplehttpserver.*;
5+
import org.junit.jupiter.api.*;
6+
7+
import java.io.IOException;
8+
import java.util.concurrent.atomic.AtomicReference;
9+
10+
final class ExchangeTests {
11+
12+
private static SimpleHttpServer server;
13+
14+
private static SimpleHttpExchange exchange;
15+
private static HttpContext context;
16+
17+
@BeforeAll
18+
static void beforeAll() throws IOException{
19+
server = SimpleHttpServer.create(8080);
20+
21+
AtomicReference<SimpleHttpExchange> exchangeRef = new AtomicReference<>();
22+
AtomicReference<String> responseRef = new AtomicReference<>();
23+
24+
context = server.createContext("exchange", (SimpleHttpHandler) e -> {
25+
exchangeRef.set(e);
26+
responseRef.set(e.toString());
27+
e.send(responseRef.get());
28+
});
29+
30+
server.start();
31+
32+
final String res = Requests.getBody("http://localhost:8080/exchange");
33+
34+
Assertions.assertEquals(responseRef.get(), res);
35+
36+
server.stop();
37+
38+
exchange = exchangeRef.get();
39+
}
40+
41+
@Test
42+
final void testReference(){
43+
Assertions.assertNotNull(exchange);
44+
Assertions.assertSame(server.getHttpServer(), exchange.getHttpServer());
45+
Assertions.assertNotNull(exchange.getHttpExchange());
46+
}
47+
48+
@Test
49+
final void testLocation(){
50+
Assertions.assertEquals("/exchange", exchange.getRequestURI().getPath());
51+
52+
Assertions.assertNotNull(exchange.getLocalAddress());
53+
Assertions.assertNotNull(exchange.getRemoteAddress());
54+
55+
Assertions.assertSame(context, exchange.getHttpContext());
56+
57+
Assertions.assertEquals("HTTP/1.1", exchange.getProtocol());
58+
}
59+
60+
@Test
61+
final void testGetPost(){
62+
Assertions.assertFalse(exchange.hasGet());
63+
Assertions.assertNull(exchange.getRawGet());
64+
Assertions.assertTrue(exchange.getGetMap().isEmpty());
65+
66+
Assertions.assertFalse(exchange.hasPost());
67+
Assertions.assertNull(exchange.getRawPost());
68+
Assertions.assertNull(exchange.getMultipartFormData());
69+
Assertions.assertTrue(exchange.getPostMap().isEmpty());
70+
}
71+
72+
@Test
73+
final void testResponse(){
74+
Assertions.assertEquals(200, exchange.getResponseCode());
75+
Assertions.assertTrue(exchange.getCookies().isEmpty());
76+
}
77+
78+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package dev.katsute.simplehttpserver.exchange;
2+
3+
import com.sun.net.httpserver.HttpContext;
4+
import dev.katsute.simplehttpserver.*;
5+
import org.junit.jupiter.api.*;
6+
7+
import java.io.IOException;
8+
import java.net.CookieHandler;
9+
import java.net.URI;
10+
import java.util.concurrent.atomic.AtomicReference;
11+
12+
final class SessionTests {
13+
14+
private static SimpleHttpServer server;
15+
private static HttpSessionHandler sh = new HttpSessionHandler();
16+
17+
private static SimpleHttpExchange exchange;
18+
19+
@BeforeAll
20+
static void beforeAll() throws IOException{
21+
server = SimpleHttpServer.create(8080);
22+
server.setSessionHandler(sh);
23+
24+
AtomicReference<SimpleHttpExchange> exchangeRef = new AtomicReference<>();
25+
AtomicReference<String> responseRef = new AtomicReference<>();
26+
27+
server.createContext("session", (SimpleHttpHandler) e -> {
28+
exchangeRef.set(e);
29+
responseRef.set(e.toString());
30+
e.send(responseRef.get());
31+
});
32+
33+
server.start();
34+
35+
final String res = Requests.getBody("http://localhost:8080/session");
36+
37+
Assertions.assertEquals(responseRef.get(), res);
38+
39+
server.stop();
40+
41+
exchange = exchangeRef.get();
42+
}
43+
44+
@Test
45+
final void testSession() throws InterruptedException{
46+
final HttpSession session = sh.getSession(exchange);
47+
Assertions.assertNotNull(session);
48+
Assertions.assertEquals("__session-id=\"" + session.getSessionID() + '"', exchange.getResponseHeaders().getFirst("Set-Cookie"));
49+
Assertions.assertEquals(session.getSessionID(), Requests.Cookies.getCookieStore().get(URI.create("http://localhost:8080/session")).get(0).getValue());
50+
51+
long was;
52+
Assertions.assertTrue(session.getCreationTime() < System.currentTimeMillis());
53+
Assertions.assertTrue((was = session.getLastAccessed()) < System.currentTimeMillis());
54+
session.update();
55+
56+
Thread.sleep(100);
57+
58+
Assertions.assertTrue(was != session.getLastAccessed());
59+
Assertions.assertTrue(session.getLastAccessed() < System.currentTimeMillis());
60+
}
61+
62+
}

0 commit comments

Comments
 (0)