Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

P2 #52

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/.metadata/
/bin/
1 change: 1 addition & 0 deletions Circles/build.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!-- TODO -->
1 change: 1 addition & 0 deletions Circles/src/edu/nmsu/cs/circles/build.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?>
7 changes: 7 additions & 0 deletions HelloWorld/edu/nmsu/cs/helloworld/helloworld.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package edu.nmsu.cs.helloworld;

public class helloworld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
9 changes: 9 additions & 0 deletions Questions/p1Questions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
1. Estimate the time it will take you to do the assignment, to within a quarter-hour: 2 hours

2.
Thought/Design: 1 hours
Programming: 2 hours
Debugging: 4 hours
TOTAL: 7 hours

3. To within what percent accuracy was your original estimate: Roughly underestimated the amount of time needed by 71.5%
10 changes: 10 additions & 0 deletions Questions/p2Questions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
1. Estimate the time it will take you to do the assignment, to within a quarter-hour: 2 hours

2.
Thought/Design: 1 hours
Programming: 2 hours
Debugging: 4 hours
TOTAL: 7 hours


3. To within what percent accuracy was your original estimate: Roughly underestimated the amount of time needed by 71.5%
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ This assignment relies on the Coverage programs.

## Program 4
This assignment relies on the Circles programs.

## Lab 1 (L1)
Github User ID: 91238639
Github Username: jcengstrom
27 changes: 27 additions & 0 deletions SimpleWebServer/build.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<project name="WebServer" default="default" basedir=".">
<property name="src.dir" value="src"/>
<property name="bin.dir" value="bin"/>

<target name="clean">
<delete dir="${bin.dir}"/>
</target>

<target name="compile">
<mkdir dir="${bin.dir}"/>
<javac srcdir="${src.dir}" destdir="${bin.dir}" includeantruntime="false"/>
</target>

<target name="build" depends="clean, compile"/>

<target name="run" depends="build" description="Run WebServer">
<java classname="edu.nmsu.cs.webserver.WebServer" fork="true">
<arg value="8080" />
<classpath>
<pathelement location="bin" />
</classpath>
<jvmarg value="-Duser.dir=${basedir}/www" />
</java>
</target>

<target name="default" depends="build, run"/>
</project>
221 changes: 132 additions & 89 deletions SimpleWebServer/src/edu/nmsu/cs/webserver/WebWorker.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
package edu.nmsu.cs.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
* Web worker: an object of this class executes in its own new thread to receive and respond to a
* single HTTP request. After the constructor the object executes on its "run" method, and leaves
* single HTTP request. After the constructor, the object executes on its "run" method, and leaves
* when it is done.
*
* One WebWorker object is only responsible for one client connection. This code uses Java threads
Expand All @@ -18,81 +33,88 @@
* particular format).
*
**/

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;

public class WebWorker implements Runnable
{

private Socket socket;

public class WebWorker implements Runnable {
private Socket socket;
private String requestedFile;

/**
* Constructor: must have a valid open socket
**/
public WebWorker(Socket s)
{
socket = s;
}
public WebWorker(Socket s) {
socket = s;
}

/**
* Worker thread starting point. Each worker handles just one HTTP request and then returns, which
* destroys the thread. This method assumes that whoever created the worker created it with a
* valid open socket object.
**/
public void run()
{
System.err.println("Handling connection...");
try
{
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
readHTTPRequest(is);
writeHTTPHeader(os, "text/html");
writeContent(os);
os.flush();
socket.close();
}
catch (Exception e)
{
System.err.println("Output error: " + e);
}
System.err.println("Done handling connection.");
return;
}
public void run() {
System.err.println("Handling connection...");
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
readHTTPRequest(is); // Read HTTP request
if (requestedFile != null) { // Check if the requested file exists
File file = new File(requestedFile);
if (file.exists() && !file.isDirectory()) { // Checks if requested file exists and isn't a directory
String contentType = Files.probeContentType(Paths.get(requestedFile)); // Get content type of requested file
writeHTTPHeader(os, contentType); // Call writeHTTPHeader
writeContent(os, file, contentType); // Call writeContent
}
else { // Else return a not found error
writeHTTPHeader(os, "text/html");
os.write("<html><head></head><body>\n".getBytes());
os.write("<h3>404 Not Found</h3>\n".getBytes());
os.write("</body></html>\n".getBytes());
}
}
else { // Write HTTP header for a bad request
writeHTTPHeader(os, "text/html");
os.write("<html><head></head><body>\n".getBytes());
os.write("<h3>Bad Request</h3>\n".getBytes());
os.write("</body></html>\n".getBytes());
}
os.flush(); // Flush the output stream and close the socket connection
socket.close();
}
catch (Exception e) {
System.err.println("Output error: " + e);
}
System.err.println("Done handling connection.");
return;
}

/**
* Read the HTTP request header.
**/
private void readHTTPRequest(InputStream is)
{
String line;
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while (true)
{
try
{
while (!r.ready())
Thread.sleep(1);
line = r.readLine();
System.err.println("Request line: (" + line + ")");
if (line.length() == 0)
break;
}
catch (Exception e)
{
System.err.println("Request error: " + e);
break;
}
}
return;
}
private void readHTTPRequest(InputStream is) { // Begin method to read HTTP request
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is)); // Create BufferedReader to read input stream (HTTP request)
while (true) { // Read all lines of request
try {
while (!br.ready()) { // Wait for BufferedReader
Thread.sleep(1);
}
line = br.readLine(); // Read line from input
System.err.println("Request line: (" + line + ")");
if (line.startsWith("GET")) { // Check if line starts with GET request
String[] pieces = line.split(" ");
if (pieces.length >= 2) { // Check if there are at least two pieces (GET request and requested file path)
requestedFile = "www/" + pieces[1].substring(1); // Updated requested file path to include "www/" prefix
}
}
if (line.length() == 0) { // If an empty line is encountered, exit loop
break;
}
} catch (Exception e) {
System.err.println("Request error: " + e);
break;
}
}
return;
}


/**
* Write the HTTP header lines to the client network connection.
Expand All @@ -102,37 +124,58 @@ private void readHTTPRequest(InputStream is)
* @param contentType
* is the string MIME content type (e.g. "text/html")
**/
private void writeHTTPHeader(OutputStream os, String contentType) throws Exception
{
Date d = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("GMT"));
os.write("HTTP/1.1 200 OK\n".getBytes());
os.write("Date: ".getBytes());
os.write((df.format(d)).getBytes());
os.write("\n".getBytes());
os.write("Server: Jon's very own server\n".getBytes());
// os.write("Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\n".getBytes());
// os.write("Content-Length: 438\n".getBytes());
os.write("Connection: close\n".getBytes());
os.write("Content-Type: ".getBytes());
os.write(contentType.getBytes());
os.write("\n\n".getBytes()); // HTTP header ends with 2 newlines
return;
}
private void writeHTTPHeader(OutputStream os, String contentType) throws Exception {
Date d = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("MST"));
os.write("HTTP/1.1 200 OK\n".getBytes());
os.write("Date: ".getBytes());
os.write((df.format(d)).getBytes());
os.write("\n".getBytes());
os.write("Server: Jonas' very own server\n".getBytes());
os.write("Connection: close\n".getBytes());
os.write("Content-Type: ".getBytes());
os.write(contentType.getBytes());
os.write("\n\n".getBytes());

return;
}

/**
* 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
**/
private void writeContent(OutputStream os) throws Exception
{
os.write("<html><head></head><body>\n".getBytes());
os.write("<h3>My web server works!</h3>\n".getBytes());
os.write("</body></html>\n".getBytes());
}

} // end class
private void writeContent(OutputStream os, File file, String contentType) throws Exception {
try (FileInputStream fis = new FileInputStream(file)) {
if (contentType.startsWith("text/")) { // Check if content type starts with "text/"
BufferedReader br = new BufferedReader(new InputStreamReader(fis)); // Create BufferedReader to read file
String line;
while ((line = br.readLine()) != null) { // Read each line of file
if (line.contains("<cs371date>")) {
SimpleDateFormat date = new SimpleDateFormat("MMMM dd, yyyy");
date.setTimeZone(TimeZone.getTimeZone("MST"));
String todaysDate = date.format(new Date());
line = line.replace("<cs371date>", todaysDate);
}
if (line.contains("<cs371server>")) {
line = line.replace("<cs371server>", "Jonas' server");
}
os.write(line.getBytes()); // Write modified line to output stream
}
}
else if (contentType.startsWith("image/")) { // Check if content type starts with "image/"
byte[] buffer = new byte[4096]; // Create buffer to read binary data from image file
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) { // Read binary data and write it to output
os.write(buffer, 0, bytesRead);
}
}
}
catch (IOException e) {
System.err.println("Error reading file: " + e);
}
}
}
Binary file added SimpleWebServer/www/cat.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added SimpleWebServer/www/earth.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added SimpleWebServer/www/flower.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions SimpleWebServer/www/hello.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<html>
<head>
</head>
<body>
<p>Hello world, the current date is: <cs371date>. The server is: <cs371server>.</p>
</body>
</html>
Binary file added SimpleWebServer/www/pointing.ico
Binary file not shown.
11 changes: 11 additions & 0 deletions SimpleWebServer/www/test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h1>Flower</h1>
<p>Flower image</p>
<img src="flower.jpg" alt="Test Image" />
</body>
</html>