Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.HashMap;
- public class WebServer {
- private static WebServer instance;
- private int port;
- private ServerSocket srvr;
- private Socket skt;
- @SuppressWarnings("unused")
- private HashMap<String, User> users;
- private WebServer() {
- this.port = 8080;
- this.srvr = null;
- this.skt = null;
- this.users = new HashMap<String, User>();
- }
- public static WebServer getInstance() {
- if(instance == null) { instance = new WebServer(); }
- return instance;
- }
- public void run() throws IOException {
- this.srvr = new ServerSocket(this.port);
- while (true) {
- try {
- skt = srvr.accept();
- new WebServerThread(skt);
- skt = null;
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
- public int getPort() {
- return port;
- }
- public void setPort(int port) {
- this.port = port;
- }
- public ServerSocket getSrvr() {
- return srvr;
- }
- public void setSrvr(ServerSocket srvr) {
- this.srvr = srvr;
- }
- public Socket getSkt() {
- return skt;
- }
- public void setSkt(Socket skt) {
- this.skt = skt;
- }
- public HashMap<String, User> getUsers() {
- return users;
- }
- public void setUsers(HashMap<String, User> users) {
- this.users = users;
- }
- public static void setInstance(WebServer instance) {
- WebServer.instance = instance;
- }
- }
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintStream;
- import java.net.Socket;
- import java.util.ArrayList;
- import java.util.HashMap;
- public class WebServerThread extends Thread {
- private final String HTTP200 = "HTTP/1.0 200 OK\r\n";
- private final String HTTP201 = "HTTP/1.0 201 Created\r\n";
- private final String HTTP204 = "HTTP/1.0 204 No Content\r\n";
- private final String HTTP400 = "HTTP/1.0 400 Bad Request\r\n";
- private final String HTTP404 = "HTTP/1.0 404 File not found\r\n";
- private final String HTTPCONTENTTYPE = "Content-type: text/html; charset=UTF-8\r\n";
- private Socket sock;
- private String method;
- private String resource;
- private String firstLine;
- private HashMap<String, String> header;
- private HashMap<String, String> params;
- public WebServerThread(Socket sock) {
- this.sock = sock;
- this.method = "";
- this.firstLine = null;
- this.header = new HashMap<>();
- this.params = new HashMap<>();
- try {
- start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public void run() {
- try {
- parseHttp(sock.getInputStream());
- if (this.resource != null) {
- if (this.resource.equals("")) {
- this.resource = "index.html";
- }
- synchronized (WebServer.getInstance().getUsers()) {
- sendResponse(sock.getOutputStream());
- }
- }
- sock.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- private void sendResponse(OutputStream outputStream) throws IOException {
- if (this.resource.equals("index.html")) {
- this.fileResponse(outputStream);
- } else if (this.resource.equals("reguser.html")) {
- this.fileResponse(outputStream);
- } else if (this.resource.equals("finduser.html")) {
- this.fileResponse(outputStream);
- } else if (this.resource.startsWith("finduser?")) {
- this.onHtmlGetFindUser(outputStream);
- } else if (this.resource.equals("remuser.html")) {
- this.fileResponse(outputStream);
- } else if (this.resource.equals("listusers?")) {
- this.onHtmlGetAllUsers(outputStream);
- } else if (this.resource.equals("reguser")) {
- this.onHtmlPostRegisterUser(outputStream);
- } else if (this.resource.equals("remuser")) {
- this.onHtmlPostRemoveUser(outputStream);
- }
- }
- private void onHtmlPostRemoveUser(OutputStream outputStream) {
- String response = "";
- PrintStream ps = new PrintStream(outputStream);
- User user = WebServer.getInstance().getUsers().get(params.get("username"));
- response += HTTP200 + "\r\n";
- response += "<html><head></head><body>";
- if (user == null) {
- response += "<p> User with that username doesn't exist. "
- + "</p> <a href=\"index.html\"><button style=\"width:100px\">Home</button></a><br>";
- response += "</body></html>";
- ps.println(response);
- ps.flush();
- return;
- }
- WebServer.getInstance().getUsers().remove(user.getUsername());
- response += "<p> User deleted successfully. "
- + "</p> <a href=\"index.html\"><button style=\"width:100px\">Home</button></a><br>";
- response += "</body></html>";
- ps.println(response);
- ps.flush();
- }
- private void onHtmlGetAllUsers(OutputStream outputStream) {
- String response = "";
- PrintStream ps = new PrintStream(outputStream);
- response += HTTP200 + "\r\n";
- response += "<html><head>";
- response += "<style>table{border-collapse:collapse;}table,th,td{border:2px solid black;}"
- + ".row:nth-child(even){background:#dde;}"
- + ".row:nth-child(odd){background:white;}</style>";
- response += "</head><body>";
- response += "<fieldset><legend>Number of users is: <b>" + Integer.toString(WebServer.getInstance().getUsers().size()) + "</b></legend>";
- response += "<table style=\"border:1px solid red\">";
- response += "<tr class=\"row\"><th>eFirstname</th><th>Lastname</th><th>Username</th></tr>";
- for (String string : WebServer.getInstance().getUsers().keySet()) {
- response += "<tr class=\"row\">";
- User user = WebServer.getInstance().getUsers().get(string);
- response += "<td>" + user.getFirstName() + "</td>";
- response += "<td>" + user.getLastName() + "</td>";
- response += "<td>" + user.getUsername() + "</td>";
- response += "</tr>";
- }
- response += "</table></fieldset></body></html>";
- ps.println(response);
- ps.flush();
- }
- private void onHtmlGetFindUser(OutputStream outputStream) {
- String response = "";
- PrintStream ps = new PrintStream(outputStream);
- try {
- System.out.println(this.resource);
- String line[] = this.resource.split("\\?");
- System.out.println(line[1]);
- String[] params = line[1].split("\\=");
- System.out.println(params[1]);
- User user = WebServer.getInstance().getUsers().get(params[1]);
- if (user != null) {
- response += HTTP200 + "\r\n";
- response += "<html><head></head><body>";
- response += "<p>User <b>" + user.getUsername() + "</b> found!</p>";
- response += "<p>Password: ";
- for (int i = 0; i < (user.getPassword().length()); i++) {
- response += "*";
- }
- response += "</p>";
- response += "<p>First name: " + user.getFirstName() + "</p>";
- response += "<p>Last name: " + user.getLastName() + "</p>";
- response += "<p>" + user.getSex() + "</p>";
- } else {
- response += HTTP200 + "\r\n";
- response += "<html><head></head><body>";
- response += "<p>User <b>" + params[1] + "</b> not found!</p>";
- }
- response += "<a href=\"index.html\"><button style=\"width:100px\">Home</button></a><br>";
- response += "<a href=\"finduser.html\"><button style=\"width:100px\">Try again</button></a><br>";
- response += "</body></html>";
- } catch (Exception e) {
- response += HTTP400 + "\r\n";
- response += "<p>Invalid input data!</p>";
- }
- ps.print(response);
- ps.flush();
- }
- private void onHtmlPostRegisterUser(OutputStream outputStream) {
- String response = "";
- PrintStream ps = new PrintStream(outputStream);
- System.out.println("---");
- for (String s : this.params.keySet()) {
- System.out.println(s + " : " + this.params.get(s));
- }
- System.out.println("---");
- if (!(this.params.containsKey("username") && this.params.containsKey("password")
- && this.params.containsKey("name") && this.params.containsKey("lname")
- && this.params.containsKey("male"))) {
- return;
- }
- User user = WebServer.getInstance().getUsers().get(this.params.get("username"));
- if (user == null) {
- User newUser = new User();
- newUser.setFirstName(this.params.get("name"));
- newUser.setLastName(this.params.get("lname"));
- newUser.setUsername(this.params.get("username"));
- newUser.setPassword(this.params.get("password"));
- newUser.setSex(this.params.get("male"));
- WebServer.getInstance().getUsers().put(newUser.getUsername(), newUser);
- response += HTTP200 + "\r\n";
- response += "<html><head></head><body>";
- response += "<p>User <b>" + newUser.getUsername() + "</b> has successfully registred!</p>";
- } else {
- response += HTTP200 + "\r\n";
- response += "<html><head></head><body>";
- response += "<p>Registration failed! Username is already in use.</p>";
- }
- response += "<a href=\"reguser.html\"><button style=\"width:100px\">Try again</button></a>";
- response += "<a href=\"index.html\"><button style=\"width:100px\">Home</button></a><br>";
- response += "</body></html>";
- ps.println(response);
- ps.flush();
- }
- private void fileResponse(OutputStream os) throws IOException {
- PrintStream ps = new PrintStream(os);
- this.resource = this.resource.replace('/', File.separatorChar);
- File file = new File(this.resource);
- if (!file.exists()) {
- ps.print(HTTP404 + HTTPCONTENTTYPE + "\r\n" + "<b>404: File " + file.getName() + " not found!</b>");
- return;
- }
- ps.print(HTTP200 + "\r\n");
- FileInputStream fis = new FileInputStream(file);
- byte[] data = new byte[8192];
- int len;
- while ((len = fis.read(data)) != -1) {
- ps.write(data, 0, len);
- }
- fis.close();
- ps.flush();
- }
- private void parseHttp(InputStream is) throws IOException {
- BufferedReader dis = new BufferedReader(new InputStreamReader(is));
- System.out.println("=== HTTP REQ ===");
- this.firstLine = dis.readLine();
- System.out.println(this.firstLine);
- if (this.firstLine == null) {
- return;
- }
- String[] tokens = this.firstLine.split(" ");
- this.method = tokens[0];
- this.resource = tokens[1];
- this.resource = this.resource.substring(1);
- String s1;
- String s2[];
- while (!(s1 = dis.readLine()).equals("")) {
- System.out.println(s1);
- s2 = s1.split(": ");
- header.put(s2[0], s2[1]);
- }
- if (this.method.equals("POST")) {
- System.out.println("desilo se");
- this.extractPostParameters(dis);
- }
- System.out.println("================");
- }
- private void extractPostParameters(BufferedReader rdr) {
- try {
- String lengthStr = this.header.get("Content-Length");
- String contentType = this.header.get("Content-Type");
- if ((lengthStr != null) & (contentType != null)) {
- int len = 0;
- try {
- len = Integer.parseInt(lengthStr);
- } catch (Exception e) {
- }
- if (len > 0 && contentType.equalsIgnoreCase("application/x-www-form-urlencoded")) {
- String name, value, s1;
- char buff[] = new char[len];
- rdr.read(buff, 0, len);
- s1 = new String(buff);
- System.out.println("\n" + s1);
- putInParamMap(s1);
- }
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
- private void putInParamMap(String s) {
- String[] tokens = s.split("&");
- for (String str : tokens) {
- int idx = str.indexOf("=");
- String pName = str.substring(0, idx).trim();
- String pValue = str.substring(idx + 1).trim();
- this.params.put(pName, pValue);
- }
- }
- }
- import java.io.IOException;
- public class Main {
- public static void main(String[] args) throws IOException {
- WebServer.getInstance().run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement