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

P1,L1 #55

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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/
Empty file added Circles/build.xml
Empty file.
7 changes: 7 additions & 0 deletions HelloWorld/src/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");
}
}
6 changes: 6 additions & 0 deletions Questions/p1Questions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
1.4 hours
2.Thought/Design: 3 hours
Programming: 2 hours
Debugging: 2 hours
TOTAL: 7 hours
3.10% accuracy
Empty file added Questions/p2Questions.txt
Empty file.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ This assignment relies on the Coverage programs.

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

## user ID
Anishmod
16 changes: 16 additions & 0 deletions SimpleWebServer/build.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<project>
<target name="clean">
<delete dir="bin"/>
</target>
<target name="compile">
<mkdir dir="bin" />
<javac srcdir="src" destdir="bin" fork="true" includeantruntime="false"/>
<copy todir="bin">
<fileset dir="resources"/>
</copy>
</target>
<target name="run" depends="compile" description="run the project">
<mkdir dir="bin" />
<java classname="edu.nmsu.cs.webserver.WebServer" dir="bin" fork="true"/>
</target>
</project>
7 changes: 7 additions & 0 deletions SimpleWebServer/resources/res/acc/test.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>
64 changes: 22 additions & 42 deletions SimpleWebServer/src/edu/nmsu/cs/webserver/WebServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,49 +15,38 @@
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()
{
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.
* 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
* @param port is the TCP port number to accept connections on
**/
private boolean start(int port)
{
private boolean start(int port) {
Socket workerSocket;
WebWorker worker;
try
{
try {
socket = new ServerSocket(port);
}
catch (Exception e)
{
} catch (Exception e) {
System.err.println("Error binding to port " + port + ": " + e);
return false;
}
while (true)
{
try
{
while (true) {
try {
// wait and listen for new client connection
workerSocket = socket.accept();
}
catch (Exception e)
{
} catch (Exception e) {
System.err.println("No longer accepting: " + e);
break;
}
Expand All @@ -71,38 +60,29 @@ private boolean start(int port)
/**
* Does not do anything, since start() never returns.
**/
private boolean stop()
{
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.
* 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[])
{
public static void main(String args[]) {
int port = 8080;
if (args.length > 1)
{
if (args.length > 1) {
System.err.println("Usage: java Webserver <portNumber>");
return;
}
else if (args.length == 1)
{
try
{
} else if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e)
{
} catch (Exception e) {
System.err.println("Argument must be an int (" + e + ")");
return;
}
}
WebServer server = new WebServer();
if (!server.start(port))
{
if (!server.start(port)) {
System.err.println("Execution failed!");
}
} // end main
Expand Down
144 changes: 91 additions & 53 deletions SimpleWebServer/src/edu/nmsu/cs/webserver/WebWorker.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,73 +20,89 @@
**/

import java.io.BufferedReader;
import java.io.FileInputStream;
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.StringTokenizer;
import java.util.TimeZone;

public class WebWorker implements Runnable
{
public class WebWorker implements Runnable {

private Socket socket;
private boolean exist = false;
private FileInputStream in;
private String fileName;

/**
* Constructor: must have a valid open socket
**/
public WebWorker(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.
* 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();
public void run() {
System.err.println("Handling connection..."); // prints to command line when run
try {
InputStream is = socket.getInputStream(); // used for Input
OutputStream os = socket.getOutputStream(); // used for output
readHTTPRequest(is);
writeHTTPHeader(os, "text/html");
writeContent(os);
os.flush();
socket.close();
socket.close(); // closes socket
in.close(); // closes File Input Stream
} catch (Exception e) {
System.err.println("Output error: " + e); // prints to command line when there is an error
}
catch (Exception e)
{
System.err.println("Output error: " + e);
}
System.err.println("Done handling connection.");
System.err.println("Done handling connection."); // prints to command line before program is closed
return;
}

/**
* Read the HTTP request header.
**/
private void readHTTPRequest(InputStream is)
{
String line;
private void readHTTPRequest(InputStream is) {
String line = "";
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while (true)
{
try
{
int fileCheck = 1;
// while running this is constantly checking for new http request headers
while (line.length() == 0) {
try {
while (!r.ready())
Thread.sleep(1);
// saves the HTTP path into string variable line
line = r.readLine();
// checks for a filepath
if (fileCheck > 0) {
// seperates the line into tokens
StringTokenizer token = new StringTokenizer(line);
token.nextToken();
// goes through tokens to build the file name that will be accessed saves to
// fileName
fileName = token.nextToken();
fileName = "." + fileName;
in = null;
exist = true;
// open the html file that was built
try {
in = new FileInputStream(fileName);
} catch (Exception fileNotFound) {
exist = false;
}
fileCheck--;
}
System.err.println("Request line: (" + line + ")");
if (line.length() == 0)
break;
}
catch (Exception e)
{
} // end try
catch (Exception e) {
System.err.println("Request error: " + e);
break;
}
Expand All @@ -97,42 +113,64 @@ private void readHTTPRequest(InputStream is)
/**
* Write the HTTP header lines to the client network connection.
*
* @param os
* is the OutputStream object to write to
* @param contentType
* is the string MIME content type (e.g. "text/html")
* @param os is the OutputStream object to write to
* @param contentType is the string MIME content type (e.g. "text/html")
**/
private void writeHTTPHeader(OutputStream os, String contentType) throws Exception
{
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());
if (exist) {
os.write("HTTP/1.1 200 OK\n".getBytes());
} else {
os.write("HTTP/1.1 404 File Not Found\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("Server: Anish's 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()); // HTTP header ends with 2 newlines
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.
* 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
**/
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());
private void writeContent(OutputStream os) throws Exception {
System.out.println("writeContent");
if (exist) {
System.out.println("writeContent: File exists");
byte[] buffer = new byte[1024];
int bytes = 0;
Date date = new Date();
// file is used for the html file that will be opened in the browser
String file = "";
String server = "Anish's Server!";

while ((bytes = in.read(buffer)) != -1) {
file = new String(buffer, 0, bytes);
// prints date when date tag is used
if (file.contains("<cs371date>")) {
file = file.replace("<cs371date>", date.toString());
}
// prints server name when server tag is used
if (file.contains("<cs371server>")) {
file = file.replace("<cs371server>", server);
}
}

os.write(file.getBytes());
} else { // if file cannot be open/does not exist this html is opened
os.write("<html><head></head><body>\n".getBytes());
os.write("<h3>404: File not found.</h3>\n".getBytes());
os.write("</body></html>\n".getBytes());
}
}

} // end class
} // end class
2 changes: 1 addition & 1 deletion meta/code_formatter-ecologylab-tabs.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml version="1.0" encoding="UTF-8" standalone="no"? >
<profiles version="18">
<profile kind="CodeFormatterProfile" name="ecologylab tabs" version="18">
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
Expand Down