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/di java #33

Open
wants to merge 8 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
11 changes: 11 additions & 0 deletions 01_web/http-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,15 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>


</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package ru.netology;

import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;

public class ConnectionHandler implements Runnable {
private final Socket socket;
private final List<String> validPaths;

public ConnectionHandler(Socket socket, List<String> validPaths) {
this.socket = socket;
this.validPaths = validPaths;
}

@Override
public void run() {
try (
final var in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final var out = new BufferedOutputStream(socket.getOutputStream());
) {
final var requestLine = in.readLine();
final var parts = requestLine.split(" ");

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

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();
return;
}

final var filePath = Path.of(".", "public", path);
final var mimeType = Files.probeContentType(filePath);

if (path.equals("/classic.html")) {
final var template = Files.readString(filePath);
final var content = template.replace(
"{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"
).getBytes());
out.write(content);
out.flush();
return;
}

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();
}
}
}
74 changes: 2 additions & 72 deletions 01_web/http-server/src/main/java/ru/netology/Main.java
Original file line number Diff line number Diff line change
@@ -1,82 +1,12 @@
package ru.netology;

import java.io.*;
import java.net.ServerSocket;
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);

// special case for classic
if (path.equals("/classic.html")) {
final var template = Files.readString(filePath);
final var content = template.replace(
"{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"
).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 server = new Server(9999, validPaths);
server.start();
}
}

Expand Down
50 changes: 50 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,50 @@
package ru.netology;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Request {
private final String path;
private final Map<String, String> queryParams;

public Request(String requestLine) {
String[] parts = requestLine.split(" ");
this.path = parts[1];
this.queryParams = parseQueryParameters(parts[1]);
}

public String getPath() {
return path;
}

public String getQueryParam(String name) {
return queryParams.get(name);
}

public Map<String, String> getQueryParams() {
return queryParams;
}

private Map<String, String> parseQueryParameters(String path) {
Map<String, String> params = new HashMap<>();
String[] parts = path.split("\\?");
if (parts.length > 1) {
String[] pairs = parts[1].split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
try {
String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name());
String value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name());
params.put(key, value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return params;
}
}

38 changes: 38 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,38 @@
package ru.netology;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
private final int port;
private final List<String> validPaths;
private final ExecutorService executorService;

public Server(int port, List<String> validPaths) {
this.port = port;
this.validPaths = validPaths;
this.executorService = Executors.newFixedThreadPool(64);
}

public void start() {
try (final var serverSocket = new ServerSocket(port)) {
while (true) {
try {
final var socket = serverSocket.accept();
executorService.submit(new ConnectionHandler(socket, validPaths));
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

public void stop() {
executorService.shutdown();
}
}
13 changes: 13 additions & 0 deletions 04_serlvets/servlets/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@
<version>2.8.6</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>ru.netology</groupId>
<artifactId>beans</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>

</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ru.netology.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.netology.controller.PostController;
import ru.netology.repository.PostRepository;
import ru.netology.repository.PostRepositoryStubImpl;
import ru.netology.service.PostService;

@Configuration
public class AppConfig {
@Bean
public PostRepository postRepository() {
return new PostRepositoryStubImpl();
}

@Bean
public PostService postService(PostRepository postRepository) {
return new PostService(postRepository);
}

@Bean
public PostController postController(PostService postService) {
return new PostController(postService);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;

public class PostController {
public static final String APPLICATION_JSON = "application/json";
Expand All @@ -23,8 +24,11 @@ public void all(HttpServletResponse response) throws IOException {
response.getWriter().print(gson.toJson(data));
}

public void getById(long id, HttpServletResponse response) {
// TODO: deserialize request & serialize response
public void getById(long id, HttpServletResponse response) throws IOException {
response.setContentType(APPLICATION_JSON);
final var gson = new Gson();
final var post = service.getById(id);
response.getWriter().print(gson.toJson(post));
}

public void save(Reader body, HttpServletResponse response) throws IOException {
Expand All @@ -35,7 +39,10 @@ public void save(Reader body, HttpServletResponse response) throws IOException {
response.getWriter().print(gson.toJson(data));
}

public void removeById(long id, HttpServletResponse response) {
// TODO: deserialize request & serialize response
public void removeById(long id, HttpServletResponse response) throws IOException {
response.setContentType(APPLICATION_JSON);
final var gson = new Gson();
service.removeById(id);
response.getWriter().print(gson.toJson(Map.of("success", true)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ public NotFoundException(Throwable cause) {
public NotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ public String getContent() {
public void setContent(String content) {
this.content = content;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ public Post save(Post post) {

public void removeById(long id) {
}
}
}
Loading