added support for binary files

This commit is contained in:
Ziad Arafat committed 2020-09-25 12:13:15 -06:00
1 parent 62de5c6177
commit e94176036d
12 files changed
+132 -120

No files matched your search

@@ -3,110 +3,91 @@ package edu.nmsu.cs.webserver;
/**
* A simple web server: it creates a new WebWorker for each new client connection, so all the
* WebServer object does is listen on the port for incoming client connection requests.
*
* <p>
* This class contains the application "main()" (see below). At startup, main() creates an object of
* this class (WebServer) and invokes its start() method. Since servers run continually, the start()
* method never returns. It uses socket programming to listen for client network connection
* requests. When one happens, it creates a new object of the WebWorker class and hands that client
* connection off to the WebWorker object. The WebServer object then just keeps listening for new
* client connections. See the WebWorker source for more information about it.
*
*
* @author Jon Cook, Ph.D.
*
**/
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer
{
private ServerSocket socket;
public class WebServer {
private ServerSocket socket;
private boolean running;
private boolean running;
/**
* Constructor
**/
private WebServer()
{
running = false;
}
/**
* Constructor
**/
private WebServer() {
running = false;
}
/**
* Web server starting point. This method does not return until the server is finished, so perhaps
* it should be named "runServer" or something like that.
*
* @param port
* is the TCP port number to accept connections on
**/
private boolean start(int port)
{
Socket workerSocket;
WebWorker worker;
try
{
socket = new ServerSocket(port);
}
catch (Exception e)
{
System.err.println("Error binding to port " + port + ": " + e);
return false;
}
while (true)
{
try
{
// wait and listen for new client connection
workerSocket = socket.accept();
}
catch (Exception e)
{
System.err.println("No longer accepting: " + e);
break;
}
// have new client connection, so fire off a worker on it
worker = new WebWorker(workerSocket);
new Thread(worker).start();
}
return true;
} // end start
/**
* Web server starting point. This method does not return until the server is finished, so perhaps
* it should be named "runServer" or something like that.
*
* @param port
* is the TCP port number to accept connections on
**/
private boolean start(int port) {
Socket workerSocket;
WebWorker worker;
try {
socket = new ServerSocket(port);
} catch (Exception e) {
System.err.println("Error binding to port " + port + ": " + e);
return false;
}
while (true) {
try {
// wait and listen for new client connection
workerSocket = socket.accept();
} catch (Exception e) {
System.err.println("No longer accepting: " + e);
break;
}
// have new client connection, so fire off a worker on it
worker = new WebWorker(workerSocket);
new Thread(worker).start();
}
return true;
} // end start
/**
* Does not do anything, since start() never returns.
**/
private boolean stop()
{
return true;
}
/**
* Does not do anything, since start() never returns.
**/
private boolean stop() {
return true;
}
/**
* Application main: process command line and start web server; default port number is 8080 if not
* given on command line.
**/
public static void main(String args[])
{
int port = 8080;
if (args.length > 1)
{
System.err.println("Usage: java Webserver <portNumber>");
return;
}
else if (args.length == 1)
{
try
{
port = Integer.parseInt(args[0]);
}
catch (Exception e)
{
System.err.println("Argument must be an int (" + e + ")");
return;
}
}
WebServer server = new WebServer();
if (!server.start(port))
{
System.err.println("Execution failed!");
}
} // end main
/**
* Application main: process command line and start web server; default port number is 8080 if not
* given on command line.
**/
public static void main(String args[]) {
int port = 8080;
if (args.length > 1) {
System.err.println("Usage: java Webserver <portNumber>");
return;
} else if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
System.err.println("Argument must be an int (" + e + ")");
return;
}
}
WebServer server = new WebServer();
if (!server.start(port)) {
System.err.println("Execution failed!");
}
} // end main
} // end class
@@ -20,8 +20,15 @@ package edu.nmsu.cs.webserver;
* @author Jon Cook, Ph.D.
**/
import com.sun.imageio.plugins.gif.GIFImageReader;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@@ -63,6 +70,7 @@ public class WebWorker implements Runnable {
/**
* Read the HTTP request header.
*
* @return the string of the file path from the GET request if applicable
**/
private String readHTTPRequest(InputStream is) {
@@ -94,7 +102,7 @@ public class WebWorker implements Runnable {
break;
}
}
return file_path;
return "www" + file_path;
}
/**
@@ -111,10 +119,9 @@ public class WebWorker implements Runnable {
// check if it's a valid file
if (!file.isDirectory() && file.exists()) {
// System.out.println("it exists");
http_code = "200 OK";
contentType = Files.probeContentType(file.toPath());
} else {
// System.out.println("It doesn't exist.");
http_code = "404 Not Found";
}
Date d = new Date();
@@ -131,7 +138,6 @@ public class WebWorker implements Runnable {
os.write("Content-Type: ".getBytes());
os.write(contentType.getBytes());
os.write("\n\n".getBytes()); // HTTP header ends with 2 newlines
// System.out.println(file + "|||");
return http_code;
}
@@ -139,16 +145,14 @@ public class WebWorker implements Runnable {
* Write the data content to the client network connection. This MUST be done after the HTTP
* header has been written out.
*
* @param os is the OutputStream object to write to
* @param os is the OutputStream object to write to
* @param file_path is the file path string from the GET request.
* @param http_code is the http_code identified in the writeHttpHeader function
**/
private void writeContent(OutputStream os, String http_code, String file_path) throws Exception {
// System.out.println(file_path + "|" + http_code);
File file = new File("./" + file_path);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
String contentType = Files.probeContentType(file.toPath());
System.out.println(contentType.split("/")[1]);
// 404 page render
if (http_code.equals("404 Not Found")) {
@@ -156,30 +160,57 @@ public class WebWorker implements Runnable {
os.write("<h3>404 Not Found</h3>\n".getBytes());
os.write(" <img src=\"https://media1.tenor.com/images/d5d2b8703922df9d25da6aded6eaf2f3/tenor.gif?itemid=7666840\" alt=\"John Travolta\">\n".getBytes());
os.write("</body></html>\n".getBytes());
} else {
}
// render the file from the path
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"./" + file_path));
String line = reader.readLine();
while (line != null) {
// System.out.println(line);
// read next line
line = reader.readLine();
if (line == null){
break;
}
line = line.replaceAll("<cs371server>", "This is Ziad's server");
line = line.replaceAll("<cs371date>", date);
os.write(line.getBytes());
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// If it's not text lets serve it as a binary file and let the browser handle the rest.
else if (!contentType.split("/")[0].equals("text")) {
writeBinary(os, file_path);
}
// otherwise it must be a text file so let's serve it line by line as strings to bytes.
else {
writeText(os, file_path);
}
}
private void writeBinary(OutputStream os, String file_path) throws IOException {
InputStream istream = new FileInputStream(file_path);
int byteRead;
while ((byteRead = istream.read()) != -1) {
os.write(byteRead);
}
}
private void writeText(OutputStream os, String file_path) {
// Get the current date
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
// render the file from the path
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"./" + file_path));
String line = reader.readLine();
while (line != null) {
// read next line
line = reader.readLine();
if (line == null) {
break;
}
// Replace all our tags with the respective info.
line = line.replaceAll("<cs371server>", "This is Ziad's server");
line = line.replaceAll("<cs371date>", date);
os.write(line.getBytes());
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end class
File renamed without changes.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 71 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 402 KiB

After

Width:  |  Height:  |  Size: 402 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 439 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 862 B

After

Width:  |  Height:  |  Size: 862 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

File renamed without changes.