Skip to content

Commit c0edaf1

Browse files
Merge pull request #2 from xdvrx1/refactor-001
Refactor 001
2 parents 55f9d3f + 3b39775 commit c0edaf1

File tree

10 files changed

+416
-342
lines changed

10 files changed

+416
-342
lines changed

src/xdvrx1_serverProject/ClientRequest.java

Lines changed: 150 additions & 229 deletions
Large diffs are not rendered by default.
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
package xdvrx1_serverProject;
22

33
class FileNotFoundMessage {
4-
5-
String body =
6-
new StringBuilder("<html>\r\n")
7-
.append("<head><title>File Not Found</title>\r\n")
8-
.append("</head>\r\n")
9-
.append("<body>")
10-
.append("<h1>HTTP Error 404: File Not Found [Try again later]</h1>\r\n")
11-
.append("</body></html>\r\n")
12-
.toString();
13-
14-
}
4+
5+
static final String content =
6+
new StringBuilder("<html>\r\n")
7+
.append("<head><title>File Not Found</title>\r\n")
8+
.append("</head>\r\n")
9+
.append("<body>")
10+
.append("<h1>HTTP Error 404: File Not Found [Try again later]</h1>\r\n")
11+
.append("</body></html>\r\n")
12+
.toString();
13+
14+
}
Lines changed: 50 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,64 @@
11
package xdvrx1_serverProject;
22

3-
/*
3+
/**
44
* This is the actual server class.
55
* This will call the overridden
66
* method `run()` of `Runnable`.
77
*/
88

99
import java.util.concurrent.*;
10-
import java.util.logging.*;
11-
1210
import java.io.*;
1311
import java.net.*;
1412

13+
import java.util.logging.*;
14+
1515
public class FileWebServer {
16-
17-
private final File rootDirectory;
18-
private final int port;
19-
private static final int pool_count = 10000;
20-
private static final String defaultPage = "index.html";
21-
22-
private static final Logger
23-
serverLogger = Logger.getLogger(FileWebServer
24-
.class.getCanonicalName());
25-
26-
//the constructor
27-
public FileWebServer(File rootDirectory, int port)
28-
throws IOException {
29-
30-
if (!rootDirectory.isDirectory()) {
31-
throw new IOException(rootDirectory
32-
+ " is not a directory");
33-
}
34-
35-
this.rootDirectory = rootDirectory;
36-
this.port = port;
37-
38-
}
39-
40-
//void start
41-
public void start()
42-
throws IOException {
43-
44-
ExecutorService pool =
45-
Executors.newFixedThreadPool(pool_count);
46-
47-
try (ServerSocket server = new ServerSocket(port)) {
48-
49-
serverLogger.info("Listening on port " + server.getLocalPort());
50-
serverLogger.info("@DocumentRoot");
51-
52-
while (true) {
53-
try {
54-
Socket request = server.accept();
55-
Runnable r =
56-
new ClientRequest(rootDirectory, defaultPage, request);
57-
pool.submit(r);
58-
} catch (IOException ex) {
59-
serverLogger.log(Level.WARNING, "Error accepting connection", ex);
16+
17+
private final File rootDirectory;
18+
private final int port;
19+
private static final int pool_count = 1000;
20+
private static final String defaultPage = "index.html";
21+
22+
private static final Logger
23+
serverLogger = Logger.getLogger(FileWebServer
24+
.class.getCanonicalName());
25+
26+
//the constructor
27+
public FileWebServer(File rootDirectory, int port)
28+
throws IOException {
29+
30+
if (!rootDirectory.isDirectory()) {
31+
throw new IOException(rootDirectory
32+
+ " is not a directory");
33+
}
34+
35+
this.rootDirectory = rootDirectory;
36+
this.port = port;
37+
38+
}
39+
40+
//void start
41+
public void start()
42+
throws IOException {
43+
44+
ExecutorService pool =
45+
Executors.newFixedThreadPool(pool_count);
46+
47+
try (ServerSocket server = new ServerSocket(port)) {
48+
49+
serverLogger.info("Listening on port " + server.getLocalPort());
50+
serverLogger.info("@DocumentRoot");
51+
52+
while (true) {
53+
try {
54+
Socket request = server.accept();
55+
Runnable r =
56+
new ClientRequest(rootDirectory, defaultPage, request);
57+
pool.submit(r);
58+
} catch (IOException ex) {
59+
serverLogger.log(Level.WARNING, "Error accepting connection", ex);
60+
}
6061
}
61-
}
62-
}
63-
}
62+
}
63+
}
6464
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package xdvrx1_serverProject;
2+
3+
import java.nio.file.Files;
4+
import java.io.*;
5+
import java.net.*;
6+
7+
class GETMethod {
8+
9+
byte[] processGET(File rootDirectory,
10+
String[] token,
11+
String defaultPage,
12+
String http_version,
13+
Writer out) {
14+
15+
try {
16+
String fileName = token[1];
17+
18+
//add manually the default page
19+
if (fileName.endsWith("/")) {
20+
fileName = fileName + defaultPage;
21+
}
22+
23+
//get the content type for proper encoding of data
24+
String contentType =
25+
URLConnection.getFileNameMap().getContentTypeFor(fileName);
26+
27+
if (token.length > 2) {
28+
http_version = token[2];
29+
}
30+
31+
File actualFile =
32+
new File(rootDirectory,
33+
fileName.substring(1, fileName.length()));
34+
35+
String root = rootDirectory.getPath();
36+
37+
// restrict clients inside the document root
38+
if (actualFile.canRead()
39+
&& actualFile.getCanonicalPath().startsWith(root)) {
40+
41+
byte[] _data = Files.readAllBytes(actualFile.toPath());
42+
43+
if (http_version.startsWith("HTTP/")) {
44+
// send a MIME header
45+
ServerHeader
46+
.serverHeader(out,
47+
"HTTP/1.0 200 OK",
48+
contentType,
49+
_data.length);
50+
}
51+
52+
return _data;
53+
54+
} else {
55+
56+
// file not found
57+
if (http_version.startsWith("HTTP/")) {
58+
59+
// send a MIME header
60+
ServerHeader
61+
.serverHeader(out,
62+
"HTTP/1.0 404 File Not Found",
63+
"text/html; charset=utf-8",
64+
FileNotFoundMessage.content.length());
65+
}
66+
67+
out.write(FileNotFoundMessage.content);
68+
out.flush();
69+
return null;
70+
}
71+
72+
} catch (IOException ioe) {
73+
System.out.println(ioe.getMessage());
74+
return null;
75+
}
76+
77+
}
78+
79+
}

src/xdvrx1_serverProject/MainMethod.java

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,8 @@
33
import java.io.*;
44

55
class MainMethod {
6-
public static void main(String[] args) {
7-
8-
try {
9-
10-
//the relative root directory
11-
//it's up to you if you want to change this
12-
File currentDir = new File(".");
13-
14-
//create an instance of `FileWebServer`
15-
//at the current directory and using port 80
16-
//again, it is up to you when you want to change
17-
//the port
18-
FileWebServer filewebserver = new FileWebServer(currentDir, 80);
19-
20-
//call `start` method that
21-
//contains the call for the Runnable `run`
22-
//of `ClientRequest` class
23-
filewebserver.start();
24-
25-
} catch (IOException ex) {
26-
//throws an exception if `currentDir`
27-
//is not recognized as such
28-
System.out.println(ex);
29-
}
30-
}
31-
6+
public static void main(String[] args) {
7+
ServerApp serverApp = new ServerApp();
8+
serverApp.build();
9+
}
3210
}
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package xdvrx1_serverProject;
22

33
class NotSupportedMessage {
4-
5-
String body = new StringBuilder("<html>\r\n")
6-
.append("<head><title>Not Implemented</title>\r\n")
7-
.append("</head>\r\n")
8-
.append("<body>")
9-
.append("<h1>HTTP Error 501: Not Yet Supported Method</h1>\r\n")
10-
.append("</body></html>\r\n")
11-
.toString();
4+
5+
static final String content = new StringBuilder("<html>\r\n")
6+
.append("<head><title>Not Implemented</title>\r\n")
7+
.append("</head>\r\n")
8+
.append("<body>")
9+
.append("<h1>HTTP Error 501: Not Yet Supported Method</h1>\r\n")
10+
.append("</body></html>\r\n")
11+
.toString();
1212
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package xdvrx1_serverProject;
2+
3+
class POSTMethod {
4+
5+
String returnPOSTData(String userRequestToString) {
6+
7+
//get the request body for POST method
8+
//add 4, because the index that
9+
//will be returned is relative to the
10+
//very first occurence of the string
11+
String requestBody =
12+
userRequestToString
13+
.substring(userRequestToString.lastIndexOf("\r\n\r\n") + 4);
14+
15+
//just showing the input data back to the client
16+
//a lot of things can be done for the request body
17+
//it can go directly to a file or a database,
18+
//or be loaded into an XML file for further processing
19+
return requestBody;
20+
}
21+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package xdvrx1_serverProject;
2+
3+
import java.io.*;
4+
import java.net.*;
5+
6+
class ReadInputStream {
7+
8+
StringBuffer readUserRequest(BufferedInputStream bis,
9+
Reader in,
10+
Socket connection) {
11+
12+
StringBuffer userRequest = new StringBuffer();
13+
14+
try {
15+
//this will be the basis to get
16+
//all the bytes from the stream
17+
int bufferSize = bis.available();
18+
19+
while (true) {
20+
if (userRequest.length() > bufferSize-1) {
21+
//for performance, always shutdown
22+
//after breaking from this loop
23+
connection.shutdownInput();
24+
break;
25+
}
26+
27+
//read() of Reader is actually a blocking
28+
//method, and without proper algorithm
29+
//this will hang the entire program
30+
int c = in.read();
31+
userRequest.append((char) c);
32+
33+
//ignore the line endings,
34+
//the Reader will interpret this as end of buffer
35+
//we need to read the entire content of the buffer
36+
if (c == '\n' || c == '\r' || c == 1) continue;
37+
}
38+
return userRequest;
39+
} catch (IOException ioe) {
40+
System.out.println(ioe.getMessage());
41+
return null;
42+
}
43+
}
44+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package xdvrx1_serverProject;
2+
3+
import java.io.*;
4+
5+
class ServerApp {
6+
public void build() {
7+
8+
try {
9+
//the relative root directory
10+
//it's up to you if you want to change this
11+
File currentDir = new File(".");
12+
13+
//create an instance of `FileWebServer`
14+
//at the current directory and using port 80
15+
//again, it is up to you when you want to change
16+
//the port
17+
FileWebServer filewebserver = new FileWebServer(currentDir, 80);
18+
19+
//call `start` method that
20+
//contains the call for the Runnable `run`
21+
//of `ClientRequest` class
22+
filewebserver.start();
23+
24+
} catch (IOException ex) {
25+
//throws an exception if `currentDir`
26+
//is not recognized as such
27+
System.out.println(ex.getMessage());
28+
}
29+
}
30+
31+
}

0 commit comments

Comments
 (0)