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 #27

Open
wants to merge 3 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
78 changes: 4 additions & 74 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;
}
int poolSize = 64;
int port = 9999;
Server server = new Server(poolSize);
server.start(port);

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

Expand Down
102 changes: 102 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,102 @@
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.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {


final List<String> 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");

ExecutorService executorService;

public Server(int poolSize) {
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) {
e.printStackTrace();
}
}

private void connect(Socket socket) {
try (socket;
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
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);

// 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();
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();
}
}
}
5 changes: 5 additions & 0 deletions 04_serlvets/servlets/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@
<version>2.8.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.15</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
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.service.PostService;

@Configuration
public class JavaConfig {
@Bean
public PostController postController(PostService service) {
return new PostController(service);
}

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

@Bean
public PostRepository postRepository() {
return new PostRepository();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ru.netology.controller;

import com.google.gson.Gson;
import ru.netology.exception.NotFoundException;
import ru.netology.model.Post;
import ru.netology.service.PostService;

Expand All @@ -11,31 +12,38 @@
public class PostController {
public static final String APPLICATION_JSON = "application/json";
private final PostService service;
private final Gson gson;

public PostController(PostService service) {
this.service = service;
gson = new Gson();
}

public void all(HttpServletResponse response) throws IOException {
response.setContentType(APPLICATION_JSON);
final var data = service.all();
final var gson = new Gson();
//final var gson = new Gson();
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, NotFoundException {
response.setContentType(APPLICATION_JSON);
final var post = service.getById(id);
response.getWriter().println(gson.toJson(post));
}

public void save(Reader body, HttpServletResponse response) throws IOException {
response.setContentType(APPLICATION_JSON);
final var gson = new Gson();
//final var gson = new Gson();
final var post = gson.fromJson(body, Post.class);
final var data = service.save(post);
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 data = service.getById(id);
service.removeById(id);
response.getWriter().print(gson.toJson(data));
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
package ru.netology.repository;

import ru.netology.exception.NotFoundException;
import ru.netology.model.Post;

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

// Stub
public class PostRepository {
public List<Post> all() {
return Collections.emptyList();
}
private final ConcurrentHashMap<Long, Post> posts;
private final AtomicLong idCounter = new AtomicLong(0L);

public Optional<Post> getById(long id) {
return Optional.empty();
}
public PostRepository() {
this.posts = new ConcurrentHashMap<>();
}

public Post save(Post post) {
return post;
}
public List<Post> all() {
return new ArrayList<>(posts.values());
}

public void removeById(long id) {
}
public Optional<Post> getById(long id) {
return Optional.ofNullable(posts.get(id));
}

public Post save(Post post) {
if (post.getId() == 0) {
long id = idCounter.incrementAndGet();
post.setId(id);
posts.put(id, post);
} else if (post.getId() != 0) {
Long currentId = post.getId();
posts.put(currentId, post);
}
return post;
}

public void removeById(long id) {
if (posts.containsKey(id)) {
posts.remove(id);
} else {
throw new NotFoundException("Удаление поста номер " + id + " не выполнено");
}
}
}
Loading