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

Feature/query #25

Open
wants to merge 5 commits into
base: master
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
17 changes: 17 additions & 0 deletions 01_web/http-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,22 @@
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>

</project>
2 changes: 1 addition & 1 deletion 01_web/http-server/public/forms.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
</head>
<body>
<h1>Forms Demo</h1>
<form>
<form action="http://localhost:9999">
<input name="login" placeholder="Login">
<input name="password" type="password" placeholder="Password">
<button>Login</button>
Expand Down
8 changes: 8 additions & 0 deletions 01_web/http-server/src/main/java/ru/netology/Handler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ru.netology;

import java.io.BufferedOutputStream;
import java.io.IOException;

public interface Handler {
void handle(Request request, BufferedOutputStream out) throws IOException;
}
103 changes: 39 additions & 64 deletions 01_web/http-server/src/main/java/ru/netology/Main.java
Original file line number Diff line number Diff line change
@@ -1,83 +1,58 @@
package ru.netology;

import java.io.*;
import java.net.ServerSocket;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;

public class Main {
public static void main(String[] args) {
final var validPaths = List.of("/index.html", "/spring.svg", "/spring.png", "/resources.html", "/styles.css", "/app.js", "/links.html", "/forms.html", "/classic.html", "/events.html", "/events.js");

try (final var serverSocket = new ServerSocket(9999)) {
while (true) {
try (
final var socket = serverSocket.accept();
final var in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final var out = new BufferedOutputStream(socket.getOutputStream());
) {
// read only request line for simplicity
// must be in form GET /path HTTP/1.1
final var requestLine = in.readLine();
final var parts = requestLine.split(" ");

if (parts.length != 3) {
// just close socket
continue;
}

final var path = parts[1];
if (!validPaths.contains(path)) {
out.write((
"HTTP/1.1 404 Not Found\r\n" +
"Content-Length: 0\r\n" +
"Connection: close\r\n" +
"\r\n"
).getBytes());
out.flush();
continue;
}

final var filePath = Path.of(".", "public", path);
final var mimeType = Files.probeContentType(filePath);
public static void main(String[] args) {
Server server = new Server(64, 9999);
server.addHandler("GET", "/classic.html", Main::processFile);
server.addHandler("GET", "/events.html", Main::processFile);
server.addHandler("GET", "/forms.html", Main::processFile);
server.addHandler("GET", "/index.html", Main::processFile);
server.addHandler("GET", "/links.html", Main::processFile);
server.addHandler("GET", "/resources.html", Main::processFile);
server.addHandler("GET", "/events.js", Main::processFile);
server.addHandler("GET", "/spring.png", Main::processFile);
server.addHandler("GET", "/spring.svg", Main::processFile);
server.addHandler("GET", "/styles.css", Main::processFile);
server.addHandler("GET", "/app.js", Main::processFile);
server.start(9999);
}

// special case for classic
if (path.equals("/classic.html")) {
public static void processFile(Request request, BufferedOutputStream out) throws IOException {
final var filePath = Path.of(".", "public", request.getPath());
final var mimeType = Files.probeContentType(filePath);
// special case for classic
if (request.getPath().equals("/classic.html")) {
final var template = Files.readString(filePath);
final var content = template.replace(
"{time}",
LocalDateTime.now().toString()
"{time}",
LocalDateTime.now().toString()
).getBytes();
out.write((
"HTTP/1.1 200 OK\r\n" +
"Content-Type: " + mimeType + "\r\n" +
"Content-Length: " + content.length + "\r\n" +
"Connection: close\r\n" +
"\r\n"
"HTTP/1.1 200 OK\r\n" +
"Content-Type: " + mimeType + "\r\n" +
"Content-Length: " + content.length + "\r\n" +
"Connection: close\r\n" +
"\r\n"
).getBytes());
out.write(content);
out.flush();
continue;
}

final var length = Files.size(filePath);
out.write((
"HTTP/1.1 200 OK\r\n" +
"Content-Type: " + mimeType + "\r\n" +
"Content-Length: " + length + "\r\n" +
"Connection: close\r\n" +
"\r\n"
).getBytes());
Files.copy(filePath, out);
out.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
final var length = Files.size(filePath);
out.write((
"HTTP/1.1 200 OK\r\n" +
"Content-Type: " + mimeType + "\r\n" +
"Content-Length: " + length + "\r\n" +
"Connection: close\r\n" +
"\r\n"
).getBytes());
Files.copy(filePath, out);
out.flush();
}
}
}


42 changes: 42 additions & 0 deletions 01_web/http-server/src/main/java/ru/netology/Request.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package ru.netology;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class Request {
private final String method;
private final String path;
private final List<NameValuePair> queryParams;

public Request(String method, String path) throws URISyntaxException {
this.method = method;
URI uri = new URI(path);
this.path = uri.getPath();
this.queryParams = URLEncodedUtils.parse(uri, Charset.defaultCharset());
}

public String getMethod() {
return method;
}

public String getPath() {
return path;
}

public List<NameValuePair> getQueryParam(String name) {
return queryParams.stream()
.filter(x -> Objects.equals(x.getName(), name))
.collect(Collectors.toList());
}

public List<NameValuePair> getQueryParams() {
return queryParams;
}
}
95 changes: 95 additions & 0 deletions 01_web/http-server/src/main/java/ru/netology/Server.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package ru.netology;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
Map<String, Map<String, Handler>> handlers = new ConcurrentHashMap<>();
private final ExecutorService executorService;
private final int poolSize;
private final int port;

public Server(int poolSize, int port) {
this.poolSize = poolSize;
this.port = port;
this.executorService = Executors.newFixedThreadPool(poolSize);
}

public void start(int port) {
try (final var serverSocket = new ServerSocket(port)) {
while (true) {
final var socket = serverSocket.accept();
executorService.submit(() -> connect(socket));
}
} catch (IOException e) {
throw new RuntimeException();
}
}

private void connect(Socket socket) {
try (socket;
var in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
var out = new BufferedOutputStream(socket.getOutputStream());
) {
// read only request line for simplicity
// must be in form GET /path HTTP/1.1
final var requestLine = in.readLine();
final var parts = requestLine.split(" ");
if (parts.length != 3) {
// just close socket
return;
}
final var request = new Request(parts[0], parts[1]);
if (!handlers.containsKey(request.getMethod())) {
notFoundMessage(out);
}
var methodHandlers = handlers.get(request.getMethod());
if (!methodHandlers.containsKey(request.getPath())) {
notFoundMessage(out);
}
var handler = methodHandlers.get(request.getPath());
if (handler == null) {
notFoundMessage(out);
}
var getQueryParams = request.getQueryParams();
var path = request.getPath();
var method = request.getMethod();
System.out.println();
System.out.println("Метод запроса: " + method);
System.out.println("Ресурс: " + path);
System.out.println("Параметры запроса: " + getQueryParams);
System.out.println("Версия протокола: " + parts[2]);
handler.handle(request, out);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}

public void addHandler(String method, String path, Handler handler) {
if (handlers.get(method) == null) {
handlers.put(method, new ConcurrentHashMap<>());
}
handlers.get(method).put(path, handler);
}

public void notFoundMessage(BufferedOutputStream out) throws IOException {
out.write((
"HTTP/1.1 404 Not Found\r\n" +
"Content-Length: 0\r\n" +
"Connection: close\r\n" +
"\r\n"
).getBytes());
out.flush();
}
}