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

Commit 0730971

Browse files
authored
Forward Compatibility (SimpleHttpExchange param can be used where HttpExchange is accepted)
Forward compatibility
2 parents fcdb2f5 + ce35f6c commit 0730971

File tree

11 files changed

+143
-99
lines changed

11 files changed

+143
-99
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ out
55
# Project ignore
66
.docs
77
src/LICENSE.txt
8-
/src/main/java/com/kttdevelopment/simplehttpserver/_ignore/
8+
/src/main/java/_ignore/
99
# Gradle
1010
.gradle
1111
# Maven

README.md

Lines changed: 9 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,37 +6,15 @@
66
[![downloads](https://img.shields.io/github/downloads/ktt-development/simplehttpserver/total?color=ff5555&style=flat-square)](https://github.com/Ktt-Development/simplehttpserver/releases)
77
[![license](https://img.shields.io/github/license/Ktt-Development/simplehttpserver?color=ff5555&style=flat-square)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html)
88

9-
Based on the java sun Http Server. Complicated features made easy.
9+
SimpleHttpServer is a simplified implementation of the [sun http server](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.httpserver/com/sun/net/httpserver/package-summary.html) for JDK11. This library simplifies complex operations for both the server, exchange, and handler.
1010

11-
## New Http Server Methods
12-
### Temporary Contexts
13-
Handlers that will process a single request before removing itself. Useful for single use download links or image hosting.
11+
### Setup
12+
- [Setting Up SimpleHttpServer](https://github.com/Ktt-Development/simplehttpserver/wiki/setup)
13+
- [Read the Wiki](https://github.com/Ktt-Development/simplehttpserver/wiki)
1414

15-
### Context Retrieval
16-
Get the contexts that the server has loaded (why wasn't this already a feature?).
15+
### Documentation
16+
- [Documentation](https://www.kttdevelopment.com/simplehttpserver/docs)
17+
- [Wiki](https://github.com/Ktt-Development/simplehttpserver/wiki)
1718

18-
## New Exchange Methods
19-
### HTTP GET
20-
Get requests are parsed into a hashmap.
21-
### HTTP POST
22-
Post requests are parsed into a hashmap (`multipart/form-data` as well!).
23-
24-
## Http Handlers
25-
### SSE Handler
26-
Sever sent event events made easy.
27-
### Redirect Handler
28-
A simple handler to redirect links without leaving a mark in the history.
29-
### Predicate Handler
30-
A simple handler to handle requests based on a predicate.
31-
### Root Handler
32-
A handler to help process homepage and 404 requests.
33-
### File Handler
34-
Host files, set their contexts, control their output, host directories and support for file walking.
35-
36-
## New Features
37-
### Constants
38-
Static variables for HTTP codes and methods.
39-
### Http Session
40-
Keep track of the user across different exchanges.
41-
### Cookies
42-
Get and set cookies.
19+
### Reporting Issues
20+
Issues or suggestions can be posted [here](https://github.com/Ktt-Development/simplehttpserver/issues).

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

Lines changed: 76 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.kttdevelopment.simplehttpserver;
22

3+
import com.sun.net.httpserver.Headers;
34
import com.sun.net.httpserver.HttpExchange;
45

56
import java.util.*;
7+
import java.util.function.Predicate;
68

79
/**
810
* This class assigns {@link HttpSession} to every client.
@@ -13,7 +15,7 @@
1315
*/
1416
public class HttpSessionHandler {
1517

16-
private final Map<String,HttpSession> sessions = new HashMap<>();
18+
private final Map<String,HttpSession> sessions = Collections.synchronizedMap(new HashMap<>());
1719

1820
private final String cookie;
1921

@@ -55,6 +57,14 @@ public synchronized String assignSessionID(final HttpExchange exchange){
5557
return id;
5658
}
5759

60+
private String getSetSession(final Headers headers){
61+
if(headers.containsKey("Set-Cookie"))
62+
for(final String value : headers.get("Set-Cookie"))
63+
if(value.startsWith(cookie + "="))
64+
return value.substring(cookie.length() + 1,value.indexOf(";"));
65+
return null;
66+
}
67+
5868
/**
5969
* Returns the session of the client or assigns one if it does not yet have one Session will only be saved client side if the exchange headers are sent using {@link HttpExchange#sendResponseHeaders(int, long)}.
6070
*
@@ -79,67 +89,71 @@ public final HttpSession getSession(final HttpExchange exchange){
7989
}
8090
}
8191

82-
if((sessionId = cookies.get(cookie)) == null || !sessions.containsKey(sessionId)){
83-
session = new HttpSession() {
84-
85-
private final String sessionID;
86-
private final long creationTime;
87-
private long lastAccessTime;
88-
89-
{
90-
sessionID = assignSessionID(exchange);
91-
creationTime = System.currentTimeMillis();
92-
lastAccessTime = creationTime;
93-
sessions.put(sessionID,this);
94-
}
95-
96-
@Override
97-
public final String getSessionID(){
98-
return sessionID;
99-
}
100-
101-
//
102-
103-
@Override
104-
public final long getCreationTime(){
105-
return creationTime;
106-
}
107-
108-
@Override
109-
public final long getLastAccessTime(){
110-
return lastAccessTime;
111-
}
112-
113-
@Override
114-
public synchronized final void updateLastAccessTime(){
115-
lastAccessTime = System.currentTimeMillis();
116-
}
117-
118-
//
119-
120-
@SuppressWarnings("StringBufferReplaceableByString")
121-
@Override
122-
public final String toString(){
123-
final StringBuilder OUT = new StringBuilder();
124-
OUT.append("HttpSession") .append('{');
125-
OUT.append("sessionID") .append('=') .append(sessionID) .append(", ");
126-
OUT.append("creationTime") .append('=') .append(creationTime) .append(", ");
127-
OUT.append("lastAccessTime").append('=') .append(lastAccessTime);
128-
OUT.append('}');
129-
return OUT.toString();
130-
}
131-
132-
};
133-
134-
final SimpleHttpCookie out =
135-
new SimpleHttpCookie.Builder(cookie,session.getSessionID())
136-
.setPath("/")
137-
.setHttpOnly(true)
138-
.build();
139-
exchange.getResponseHeaders().add("Set-Cookie",out.toCookieHeaderString());
140-
sessions.put(sessionId,session);
141-
}else{
142-
session = sessions.get(sessionId);
92+
final String setSession = getSetSession(exchange.getResponseHeaders());
93+
sessionId = setSession != null ? setSession : cookies.get(cookie);
94+
95+
synchronized(this){
96+
if(!sessions.containsKey(sessionId)){
97+
session = new HttpSession() {
98+
private final String sessionID;
99+
private final long creationTime;
100+
private long lastAccessTime;
101+
102+
{
103+
sessionID = assignSessionID(exchange);
104+
creationTime = System.currentTimeMillis();
105+
lastAccessTime = creationTime;
106+
sessions.put(sessionID, this);
107+
}
108+
109+
@Override
110+
public final String getSessionID(){
111+
return sessionID;
112+
}
113+
114+
//
115+
116+
@Override
117+
public final long getCreationTime(){
118+
return creationTime;
119+
}
120+
121+
@Override
122+
public final long getLastAccessTime(){
123+
return lastAccessTime;
124+
}
125+
126+
@Override
127+
public synchronized final void updateLastAccessTime(){
128+
lastAccessTime = System.currentTimeMillis();
129+
}
130+
131+
//
132+
133+
@SuppressWarnings("StringBufferReplaceableByString")
134+
@Override
135+
public final String toString(){
136+
final StringBuilder OUT = new StringBuilder();
137+
OUT.append("HttpSession").append('{');
138+
OUT.append("sessionID").append('=').append(sessionID).append(", ");
139+
OUT.append("creationTime").append('=').append(creationTime).append(", ");
140+
OUT.append("lastAccessTime").append('=').append(lastAccessTime);
141+
OUT.append('}');
142+
return OUT.toString();
143+
}
144+
145+
};
146+
147+
final SimpleHttpCookie out =
148+
new SimpleHttpCookie.Builder(cookie, session.getSessionID())
149+
.setPath("/")
150+
.setHttpOnly(true)
151+
.build();
152+
exchange.getResponseHeaders().add("Set-Cookie", out.toCookieHeaderString());
153+
sessions.put(session.getSessionID(), session);
154+
}else{
155+
session = sessions.get(sessionId);
156+
}
143157
}
144158
return session;
145159
}

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,18 @@ public static SimpleHttpServer create(final int port, final int backlog) throws
247247
*/
248248
public abstract HttpSession getHttpSession(final HttpExchange exchange);
249249

250+
/**
251+
* Returns the session associated with an exchange or null it no session handler exists.
252+
*
253+
* @param exchange http exchange
254+
* @return http session
255+
*
256+
* @see HttpSession
257+
* @since 03.03.00
258+
* @author Ktt Development
259+
*/
260+
public abstract HttpSession getHttpSession(final SimpleHttpExchange exchange);
261+
250262
//
251263

252264
/**

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,11 @@ public final HttpSession getHttpSession(final HttpExchange exchange){
120120
return sessionHandler != null ? sessionHandler.getSession(exchange) : null;
121121
}
122122

123+
@Override
124+
public final HttpSession getHttpSession(final SimpleHttpExchange exchange){
125+
return getHttpSession(exchange.getHttpExchange());
126+
}
127+
123128
//
124129

125130
@Override
@@ -284,16 +289,16 @@ public final Map<HttpContext, HttpHandler> getContexts(){
284289

285290
@Override
286291
public synchronized final String getRandomContext(){
287-
return getRandomContext("/");
292+
return getRandomContext("");
288293
}
289294

290295
@Override
291296
public synchronized final String getRandomContext(final String context){
292297
String targetContext;
293298

294-
final String head = getContext(context);
299+
final String head = context.isEmpty() ? "" : getContext(context);
295300

296-
do targetContext = head + '/' + UUID.randomUUID().toString();
301+
do targetContext = head + getContext(UUID.randomUUID().toString());
297302
while(getContextHandler(targetContext) != null);
298303

299304
return targetContext;

src/main/java/com/kttdevelopment/simplehttpserver/handler/FileHandler.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.kttdevelopment.simplehttpserver.var.HttpCode;
44
import com.kttdevelopment.simplehttpserver.SimpleHttpExchange;
55
import com.kttdevelopment.simplehttpserver.SimpleHttpHandler;
6+
import com.sun.net.httpserver.HttpExchange;
67

78
import java.io.*;
89
import java.nio.file.Files;
@@ -679,6 +680,11 @@ public final void handle(final SimpleHttpExchange exchange) throws IOException{
679680
exchange.close();
680681
}
681682

683+
@Override
684+
public final void handle(final HttpExchange exchange) throws IOException{
685+
SimpleHttpHandler.super.handle(exchange);
686+
}
687+
682688
/**
683689
* Handles a file and gives a response.
684690
*

src/main/java/com/kttdevelopment/simplehttpserver/handler/RedirectHandler.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.kttdevelopment.simplehttpserver.var.HttpCode;
44
import com.kttdevelopment.simplehttpserver.SimpleHttpExchange;
55
import com.kttdevelopment.simplehttpserver.SimpleHttpHandler;
6+
import com.sun.net.httpserver.HttpExchange;
67

78
import java.io.IOException;
89

@@ -31,6 +32,11 @@ public RedirectHandler(final String link){
3132
this.link = link;
3233
}
3334

35+
@Override
36+
public final void handle(final HttpExchange exchange) throws IOException{
37+
SimpleHttpHandler.super.handle(exchange);
38+
}
39+
3440
@Override
3541
public final void handle(final SimpleHttpExchange exchange) throws IOException{
3642
exchange.getResponseHeaders().set("Location", link);

src/main/java/com/kttdevelopment/simplehttpserver/handler/SSEHandler.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import com.kttdevelopment.simplehttpserver.SimpleHttpHandler;
55
import com.kttdevelopment.simplehttpserver.var.HttpCode;
66
import com.kttdevelopment.simplehttpserver.var.RequestMethod;
7+
import com.sun.net.httpserver.HttpExchange;
78

89
import java.io.IOException;
910
import java.io.OutputStream;
@@ -26,6 +27,11 @@ public class SSEHandler implements SimpleHttpHandler {
2627
private final AtomicInteger eventId = new AtomicInteger(-1);
2728
private final LinkedList<EventStreamRecord> queue = new LinkedList<>();
2829

30+
@Override
31+
public final void handle(final HttpExchange exchange) throws IOException{
32+
SimpleHttpHandler.super.handle(exchange);
33+
}
34+
2935
@Override
3036
public final void handle(final SimpleHttpExchange exchange) throws IOException{
3137
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");

src/main/java/com/kttdevelopment/simplehttpserver/handler/SessionThrottler.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,11 @@ final boolean addConnection(final HttpExchange exchange){
118118
return true;
119119
}else{
120120
synchronized(this){
121-
final AtomicInteger conn = sessions.get(session);
121+
final AtomicInteger conn;
122+
if(!sessions.containsKey(session))
123+
sessions.put(session,conn = new AtomicInteger(0));
124+
else
125+
conn = sessions.get(session);
122126
if(conn.get() + 1 <= maxConnections.get()){
123127
conn.incrementAndGet();
124128
return true;

src/main/java/com/kttdevelopment/simplehttpserver/handler/TemporaryHandler.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,10 @@ public TemporaryHandler(final HttpHandler handler, final long maxTime){
5757

5858
@Override
5959
public final void handle(final HttpExchange exchange) throws IOException{
60-
if(!hasExpiry || expiry < System.currentTimeMillis())
60+
if(!hasExpiry || System.currentTimeMillis() < expiry)
6161
handler.handle(exchange);
6262
exchange.getHttpContext().getServer().removeContext(exchange.getHttpContext());
63+
exchange.close();
6364
}
6465

6566
@Override

0 commit comments

Comments
 (0)