Merge branch 'lab7-dev' into develop
This commit is contained in:
commit
7e6ef47b63
4
.gitignore
vendored
4
.gitignore
vendored
@ -33,4 +33,6 @@ bin/
|
||||
### Build ###
|
||||
target
|
||||
|
||||
*.scr
|
||||
*.scr
|
||||
|
||||
DB/*
|
||||
BIN
Client.jpg
BIN
Client.jpg
Binary file not shown.
|
Before Width: | Height: | Size: 1.2 MiB |
BIN
Domain.jpg
BIN
Domain.jpg
Binary file not shown.
|
Before Width: | Height: | Size: 545 KiB |
@ -3,11 +3,11 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab6-Client</artifactId>
|
||||
<artifactId>Lab7-Client</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Lab6-Client</name>
|
||||
<name>Lab7-Client</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@ -43,8 +43,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab6-Domain</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<artifactId>Lab7-Domain</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -58,7 +58,7 @@
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>me.zinch.Lab6.Client.App</mainClass>
|
||||
<mainClass>me.zinch.Lab7.Client.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
|
||||
@ -1,32 +0,0 @@
|
||||
package me.zinch.Lab6.Client.files;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* The ScriptLoader class provides methods to load scripts from files.
|
||||
*/
|
||||
public class ScriptLoader {
|
||||
public static List<String> loadList(String path) throws IOException {
|
||||
try {
|
||||
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path));
|
||||
Scanner scanner = new Scanner(bufferedInputStream);
|
||||
List<String> list = new ArrayList<>();
|
||||
while (scanner.hasNextLine()) {
|
||||
list.add(scanner.nextLine());
|
||||
}
|
||||
bufferedInputStream.close();
|
||||
scanner.close();
|
||||
return list;
|
||||
} catch (FileNotFoundException e) {
|
||||
throw new FileNotFoundException(String.format("Файл %s не найден.", path));
|
||||
} catch (IOException e) {
|
||||
throw new IOException("Произошла неожиданная ошибка во время работы с файлом!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
package me.zinch.Lab6.Client;
|
||||
package me.zinch.Lab7.Client;
|
||||
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.console.ShutdownHook;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.console.ShutdownHook;
|
||||
|
||||
/**
|
||||
* Main class for running the application.
|
||||
@ -1,11 +1,12 @@
|
||||
package me.zinch.Lab6.Client.client;
|
||||
package me.zinch.Lab7.Client.client;
|
||||
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.ConnectionErrorException;
|
||||
import me.zinch.Lab6.Client.exceptions.ResponseException;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.Message;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.ConnectionErrorException;
|
||||
import me.zinch.Lab7.Client.exceptions.ResponseException;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.Message;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@ -17,6 +18,7 @@ import java.net.Socket;
|
||||
public class Client {
|
||||
private final String address;
|
||||
private final int port;
|
||||
private User user;
|
||||
|
||||
public Client(String address, int port) throws ConnectionErrorException, ResponseException {
|
||||
this.address = address;
|
||||
@ -37,6 +39,8 @@ public class Client {
|
||||
var byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
var objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
|
||||
|
||||
if (user != null) message.setUser(user);
|
||||
|
||||
objectOutputStream.writeObject(message);
|
||||
objectOutputStream.flush();
|
||||
bufferedSocketOutputStream.write(byteArrayOutputStream.toByteArray());
|
||||
@ -49,4 +53,12 @@ public class Client {
|
||||
throw new IOException("Сервер не доступен");
|
||||
}
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public boolean isLogin() {
|
||||
return user != null;
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -0,0 +1,28 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class CheckProductOwner extends Command {
|
||||
public CheckProductOwner() {
|
||||
super("check_product_owner", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
try {
|
||||
Long id = Long.parseLong(Console.getLastCommand().split(" ")[1]);
|
||||
var response = (BodylessMessage) client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), id));
|
||||
if (response.getType() == MessageType.ERROR) throw new CommandActionException(response.getBody().toString());
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* The Clear class represents a command to clear a collection.
|
||||
@ -1,9 +1,9 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,8 +1,8 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.files.ScriptLoader;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.files.ScriptLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@ -41,7 +41,7 @@ public class ExecuteScript extends Command {
|
||||
var commandList = ScriptLoader.loadList(scriptFile);
|
||||
for (var input : commandList) {
|
||||
input = input.trim();
|
||||
var command = CommandManager.getCommandByInput(input);
|
||||
var command = MainCommandManager.getCommandByInput(input);
|
||||
if (command.isPresent()) {
|
||||
Console.appendHistory(input);
|
||||
if (command.get() instanceof ExecuteScript) {
|
||||
@ -1,14 +1,14 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
|
||||
/**
|
||||
* A command to exit the program without saving to a file.
|
||||
*/
|
||||
public class Exit extends Command {
|
||||
public Exit() {
|
||||
super("exit", "завершить программу (без сохранения в файл)");
|
||||
super("exit", "завершить программу");
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,6 +1,6 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
|
||||
/**
|
||||
* A command to display help for available commands.
|
||||
@ -12,6 +12,6 @@ public class Help extends Command {
|
||||
|
||||
@Override
|
||||
public String action(Client client) {
|
||||
return CommandManager.getRegisteredCommand();
|
||||
return client.isLogin() ? MainCommandManager.getRegisteredCommand() : UserCommandManager.getRegisteredCommand();
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to display information about the collection (type, initialization date, number of elements, etc.) to the standard output stream.
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -0,0 +1,30 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class Login extends Command {
|
||||
|
||||
public Login() {
|
||||
super("login", "войти в систему");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
var user = Console.readUser();
|
||||
try {
|
||||
var response = client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), user));
|
||||
if (response.getType() == MessageType.OK) {
|
||||
client.setUser(user);
|
||||
}
|
||||
return response.getBody().toString();
|
||||
} catch (ClassNotFoundException | IOException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
|
||||
public class Logout extends Command {
|
||||
public Logout() {
|
||||
super("logout", "выйти из текущего пользователя");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
client.setUser(null);
|
||||
return "Успешно!";
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@ -7,7 +7,7 @@ import java.util.Optional;
|
||||
/**
|
||||
* Manages the registration and retrieval of commands.
|
||||
*/
|
||||
public class CommandManager {
|
||||
public class MainCommandManager {
|
||||
private static final List<Command> commandList = new ArrayList<>();
|
||||
|
||||
static {
|
||||
@ -25,6 +25,7 @@ public class CommandManager {
|
||||
registerCommand(new AddIfMin());
|
||||
registerCommand(new RemoveLower());
|
||||
registerCommand(new ExecuteScript());
|
||||
registerCommand(new Logout());
|
||||
|
||||
registerCommand(new Help());
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to print the elements of the collection in ascending order.
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to print the unique values of the 'manufactureCost' field of all elements in the collection.
|
||||
@ -0,0 +1,31 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class Register extends Command {
|
||||
|
||||
public Register() {
|
||||
super("register", "зарегистрироваться в системе");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
var user = Console.readUser();
|
||||
try {
|
||||
var response = client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), user));
|
||||
if (response.getType() == MessageType.OK) {
|
||||
client.setUser(new User(user.getLogin(), user.getPassword()));
|
||||
}
|
||||
return response.getBody().toString();
|
||||
} catch (ClassNotFoundException | IOException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to save the collection to a file.
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to display all elements of the collection in string representation to the standard output stream.
|
||||
@ -1,6 +1,6 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
|
||||
/**
|
||||
* Represents an unknown command.
|
||||
@ -1,12 +1,12 @@
|
||||
package me.zinch.Lab6.Client.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.console.Console;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Domain.dto.BodyfulMessage;
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.MessageBody;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.BodyfulMessage;
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageBody;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
@ -25,6 +25,10 @@ public class Update extends Command {
|
||||
var command = Console.getLastCommand();
|
||||
Long id = Long.parseLong(command.split(" ")[1]);
|
||||
|
||||
var checkProductOwner = new CheckProductOwner();
|
||||
Console.appendHistory(String.format("%s %s", checkProductOwner.getSignature(), id));
|
||||
checkProductOwner.action(client);
|
||||
|
||||
var isIdExists = new IsIdExists();
|
||||
Console.appendHistory(String.format("%s %s", isIdExists.getSignature(), id));
|
||||
isIdExists.action(client);
|
||||
@ -0,0 +1,32 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class UserCommandManager {
|
||||
private static final List<Command> commandList = new ArrayList<>();
|
||||
|
||||
static {
|
||||
registerCommand(new Login());
|
||||
registerCommand(new Register());
|
||||
registerCommand(new Exit());
|
||||
|
||||
registerCommand(new Help());
|
||||
}
|
||||
|
||||
public static void registerCommand(Command command) {
|
||||
commandList.add(command);
|
||||
}
|
||||
|
||||
public static String getRegisteredCommand() {
|
||||
return String.join("\n", commandList
|
||||
.stream()
|
||||
.map(command -> String.format("%s - %s", command.getName(), command.getDescription()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
public static Optional<Command> getCommandByInput(String input) {
|
||||
return commandList.stream().filter(command -> command.checkPattern(input)).findFirst();
|
||||
}
|
||||
}
|
||||
@ -1,22 +1,26 @@
|
||||
package me.zinch.Lab6.Client.console;
|
||||
package me.zinch.Lab7.Client.console;
|
||||
|
||||
import me.zinch.Lab6.Client.client.Client;
|
||||
import me.zinch.Lab6.Client.commands.CommandManager;
|
||||
import me.zinch.Lab6.Client.exceptions.ColorFormatException;
|
||||
import me.zinch.Lab6.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Client.exceptions.ConnectionErrorException;
|
||||
import me.zinch.Lab6.Client.exceptions.ResponseException;
|
||||
import me.zinch.Lab6.Client.exceptions.UnitOfMeasureFormatException;
|
||||
import me.zinch.Lab6.Domain.models.Color;
|
||||
import me.zinch.Lab6.Domain.models.Coordinates;
|
||||
import me.zinch.Lab6.Domain.models.Location;
|
||||
import me.zinch.Lab6.Domain.models.Person;
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab6.Domain.models.UnitOfMeasure;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
import me.zinch.Lab7.Client.commands.MainCommandManager;
|
||||
import me.zinch.Lab7.Client.commands.UserCommandManager;
|
||||
import me.zinch.Lab7.Client.exceptions.ColorFormatException;
|
||||
import me.zinch.Lab7.Client.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Client.exceptions.ConnectionErrorException;
|
||||
import me.zinch.Lab7.Client.exceptions.ResponseException;
|
||||
import me.zinch.Lab7.Client.exceptions.UnitOfMeasureFormatException;
|
||||
import me.zinch.Lab7.Domain.models.Color;
|
||||
import me.zinch.Lab7.Domain.models.Coordinates;
|
||||
import me.zinch.Lab7.Domain.models.Location;
|
||||
import me.zinch.Lab7.Domain.models.Person;
|
||||
import me.zinch.Lab7.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab7.Domain.models.UnitOfMeasure;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
@ -165,11 +169,28 @@ public class Console {
|
||||
return productDTO;
|
||||
}
|
||||
|
||||
public static String readPassword() {
|
||||
var msg = "Пароль пользователя";
|
||||
var console = System.console();
|
||||
return Objects.isNull(console) ? readField(msg) : Arrays.toString(console.readPassword(msg + ": "));
|
||||
}
|
||||
|
||||
public static User readUser() {
|
||||
var user = new User();
|
||||
log("Заполните следующие поля: ");
|
||||
|
||||
setField("Имя пользователя", () -> user.setLogin(readString()));
|
||||
setField(() -> user.setPassword(readPassword()));
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
public static void run() {
|
||||
while (client == null) {
|
||||
try {
|
||||
var address = readField("Хост");
|
||||
int port = Integer.parseInt(readField("Порт"));
|
||||
if (port > 65535 || port < 1) throw new NumberFormatException();
|
||||
client = new Client(address, port);
|
||||
} catch (NumberFormatException e) {
|
||||
log("Порт должен быть числом от 1 до 65535");
|
||||
@ -185,7 +206,7 @@ public class Console {
|
||||
|
||||
try {
|
||||
var input = scanner.nextLine().trim();
|
||||
var command = CommandManager.getCommandByInput(input);
|
||||
var command = client.isLogin() ? MainCommandManager.getCommandByInput(input) : UserCommandManager.getCommandByInput(input);
|
||||
|
||||
if (command.isPresent()) {
|
||||
appendHistory(input);
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.console;
|
||||
package me.zinch.Lab7.Client.console;
|
||||
|
||||
/**
|
||||
* Represents a shutdown hook that is executed when the application is stopped.
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
public class ColorFormatException extends IllegalArgumentException {
|
||||
public ColorFormatException() {
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs during the execution of a command action.
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Server.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs when an illegal product DTO is encountered during the creation or modification of a product.
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
public class ResponseException extends ClassNotFoundException {
|
||||
public ResponseException() {
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Client.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
public class UnitOfMeasureFormatException extends IllegalArgumentException {
|
||||
public UnitOfMeasureFormatException() {
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Server.files;
|
||||
package me.zinch.Lab7.Client.files;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.FileInputStream;
|
||||
@ -5,8 +5,8 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab6-Domain</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<artifactId>Lab7-Domain</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
|
||||
@ -1,34 +0,0 @@
|
||||
package me.zinch.Lab6.Domain.wrapper;
|
||||
|
||||
import me.zinch.Lab6.Domain.models.Product;
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IStorage {
|
||||
public Product getProductById(Long id);
|
||||
|
||||
public Product addProduct(ProductDTO productDTO);
|
||||
|
||||
public Product updateProduct(Long id, ProductDTO productDTO);
|
||||
|
||||
public Product removeProduct(Long id);
|
||||
|
||||
public String getInfo();
|
||||
|
||||
public void clear();
|
||||
|
||||
public Long getMaxPrice();
|
||||
|
||||
public Long getMinPrice();
|
||||
|
||||
public boolean isProductIdExists(Long id);
|
||||
|
||||
public Integer removeLover(Long id);
|
||||
|
||||
public String filterContainsName(String name);
|
||||
|
||||
public String getUniqueManufactureCost();
|
||||
|
||||
public List<Product> toList();
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.exceptions;
|
||||
package me.zinch.Lab7.Domain.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception related to validation errors.
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
@ -1,10 +1,10 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
@ -1,8 +1,8 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import me.zinch.Lab6.Domain.validator.NotEmpty;
|
||||
import me.zinch.Lab7.Domain.validator.NotEmpty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
@ -64,4 +64,16 @@ public class Location implements Serializable {
|
||||
public int hashCode() {
|
||||
return Objects.hash(x, y, name);
|
||||
}
|
||||
|
||||
public float getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public @NotNull(message = "Location: Координата y не может быть null") Integer getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,10 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
@ -80,4 +80,20 @@ public class Person implements Serializable {
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, passportID, hairColor, location);
|
||||
}
|
||||
|
||||
public @NotBlank(message = "Person: Имя персоны не может быть пустым или null") String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public @NotNull(message = "Person: Поле passportID не может быть null") @Size(min = 5, max = 22, message = "Длина строки passportID должна быть не меньше 5 и не должна быть больше 22") String getPassportID() {
|
||||
return passportID;
|
||||
}
|
||||
|
||||
public Color getHairColor() {
|
||||
return hairColor;
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
return location;
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,11 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import me.zinch.Lab6.Domain.validator.NotEmpty;
|
||||
import me.zinch.Lab7.Domain.validator.NotEmpty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.ZonedDateTime;
|
||||
@ -1,12 +1,12 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab6.Domain.validator.NotEmpty;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.validator.NotEmpty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.ZonedDateTime;
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.dto;
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@ -7,4 +7,10 @@ public class BodyfulMessage extends Message {
|
||||
this.setType(type);
|
||||
this.setBody(new MessageBody(command, body));
|
||||
}
|
||||
|
||||
public BodyfulMessage(MessageType type, String command, Serializable body, User user) {
|
||||
this.setType(type);
|
||||
this.setBody(new MessageBody(command, body));
|
||||
this.setUser(user);
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.dto;
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
public class BodylessMessage extends Message {
|
||||
public BodylessMessage(MessageType type) {
|
||||
@ -9,4 +9,10 @@ public class BodylessMessage extends Message {
|
||||
this.setType(type);
|
||||
this.setBody(command);
|
||||
}
|
||||
|
||||
public BodylessMessage(MessageType type, String command, User user) {
|
||||
this.setType(type);
|
||||
this.setBody(command);
|
||||
this.setUser(user);
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,11 @@
|
||||
package me.zinch.Lab6.Domain.dto;
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public abstract class Message implements Serializable {
|
||||
private MessageType type;
|
||||
private Serializable body;
|
||||
private Serializable user;
|
||||
|
||||
public final MessageType getType() {
|
||||
return type;
|
||||
@ -22,6 +23,14 @@ public abstract class Message implements Serializable {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Serializable getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(Serializable user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Message{" +
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.dto;
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.dto;
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
package me.zinch.Lab6.Domain.dto;
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab7.Domain.models.ProductDTO;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
58
Lab.Domain/src/main/java/me/zinch/Lab7/Domain/net/User.java
Normal file
58
Lab.Domain/src/main/java/me/zinch/Lab7/Domain/net/User.java
Normal file
@ -0,0 +1,58 @@
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
public class User implements Serializable {
|
||||
@NotNull
|
||||
private String login;
|
||||
@NotNull
|
||||
private String password;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String login, String password) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"login='" + login + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
User user = (User) o;
|
||||
return Objects.equals(login, user.login) && Objects.equals(password, user.password);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(login, password);
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Domain.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
@ -1,7 +1,7 @@
|
||||
package me.zinch.Lab6.Domain.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
package me.zinch.Lab6.Domain.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.Validation;
|
||||
import jakarta.validation.Validator;
|
||||
import jakarta.validation.ValidatorFactory;
|
||||
import me.zinch.Lab6.Domain.models.Product;
|
||||
import me.zinch.Lab7.Domain.models.Product;
|
||||
import org.hibernate.validator.HibernateValidator;
|
||||
|
||||
import java.util.List;
|
||||
@ -3,11 +3,11 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab6-Server</artifactId>
|
||||
<artifactId>Lab7-Server</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Lab6-Server</name>
|
||||
<name>Lab7-Server</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@ -16,11 +16,6 @@
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>2.15.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
@ -53,8 +48,8 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab6-Domain</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<artifactId>Lab7-Domain</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -68,6 +63,11 @@
|
||||
<artifactId>jline</artifactId>
|
||||
<version>3.26.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -79,7 +79,7 @@
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>me.zinch.Lab6.Server.App</mainClass>
|
||||
<mainClass>me.zinch.Lab7.Server.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
|
||||
@ -1,14 +0,0 @@
|
||||
package me.zinch.Lab6.Server;
|
||||
|
||||
import me.zinch.Lab6.Server.console.Console;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Main class for running the application.
|
||||
*/
|
||||
public class App {
|
||||
public static void main(String[] args) throws IOException {
|
||||
Console.run();
|
||||
}
|
||||
}
|
||||
@ -1,185 +0,0 @@
|
||||
package me.zinch.Lab6.Server;
|
||||
|
||||
import me.zinch.Lab6.Domain.dto.BodylessMessage;
|
||||
import me.zinch.Lab6.Domain.dto.Message;
|
||||
import me.zinch.Lab6.Domain.dto.MessageBody;
|
||||
import me.zinch.Lab6.Domain.dto.MessageType;
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.commands.CommandManager;
|
||||
import me.zinch.Lab6.Server.commands.GetCommand;
|
||||
import me.zinch.Lab6.Server.commands.PostCommand;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Server.files.DbController;
|
||||
import me.zinch.Lab6.Server.wrapper.ProductCollection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class Server {
|
||||
private static final Logger log = LoggerFactory.getLogger(Server.class);
|
||||
private final Selector selector;
|
||||
private final ServerSocketChannel serverSocketChannel;
|
||||
private final Map<SocketAddress, Message> usersMessages = new HashMap<>();
|
||||
private final IStorage storage;
|
||||
private boolean isRunning = false;
|
||||
|
||||
public Server(int port, IStorage collection) throws IOException {
|
||||
selector = Selector.open();
|
||||
serverSocketChannel = ServerSocketChannel.open();
|
||||
serverSocketChannel.bind(new InetSocketAddress(port));
|
||||
serverSocketChannel.configureBlocking(false);
|
||||
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
|
||||
isRunning = true;
|
||||
|
||||
if (collection == null) collection = new ProductCollection(new ArrayList<>());
|
||||
storage = collection;
|
||||
|
||||
log.info("The server has been assigned to port {}", port);
|
||||
}
|
||||
|
||||
public static ByteBuffer serialize(Serializable obj) throws IOException {
|
||||
try (var bOut = new ByteArrayOutputStream();
|
||||
var oOut = new ObjectOutputStream(bOut)) {
|
||||
oOut.writeObject(obj);
|
||||
oOut.flush();
|
||||
return ByteBuffer.wrap(bOut.toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
public void run() throws IOException {
|
||||
run(() -> {
|
||||
});
|
||||
}
|
||||
|
||||
public void run(Runnable middleware) throws IOException {
|
||||
log.info("The server is running");
|
||||
|
||||
while (isRunning) {
|
||||
selector.select(this::handleKey);
|
||||
middleware.run();
|
||||
}
|
||||
}
|
||||
|
||||
private void handleKey(SelectionKey key) {
|
||||
try {
|
||||
if (key.isAcceptable()) handleAccept(key);
|
||||
if (key.isReadable()) handleRead(key);
|
||||
if (key.isWritable()) handleWrite(key);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
key.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
private void handleAccept(SelectionKey key) throws IOException {
|
||||
var server = (ServerSocketChannel) key.channel();
|
||||
var client = server.accept();
|
||||
if (client != null) {
|
||||
client.configureBlocking(false);
|
||||
client.register(selector, SelectionKey.OP_READ);
|
||||
log.info("Received connection from {}", client.getRemoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
private void handleRead(SelectionKey key) throws IOException, ClassNotFoundException {
|
||||
var client = (SocketChannel) key.channel();
|
||||
var buffer = ByteBuffer.allocate(8192);
|
||||
int bytesRead = client.read(buffer);
|
||||
if (bytesRead == -1) {
|
||||
client.close();
|
||||
} else {
|
||||
buffer.flip();
|
||||
var oIn = new ObjectInputStream(new ByteArrayInputStream(buffer.array()));
|
||||
var msg = (Message) oIn.readObject();
|
||||
log.info("Received message {} from {}", msg, client.getRemoteAddress());
|
||||
usersMessages.put(client.getRemoteAddress(), msg);
|
||||
client.register(selector, SelectionKey.OP_WRITE);
|
||||
oIn.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void handleWrite(SelectionKey key) throws IOException {
|
||||
var client = (SocketChannel) key.channel();
|
||||
var message = usersMessages.get(client.getRemoteAddress());
|
||||
if (message == null) {
|
||||
log.error("Message for {} not found", client.getRemoteAddress());
|
||||
client.close();
|
||||
return;
|
||||
}
|
||||
|
||||
ByteBuffer responseBuffer = createResponse(message);
|
||||
if (responseBuffer != null) {
|
||||
client.write(responseBuffer);
|
||||
log.info("Sent message to {}", client.getRemoteAddress());
|
||||
}
|
||||
|
||||
client.close();
|
||||
}
|
||||
|
||||
private ByteBuffer createResponse(Message message) throws IOException {
|
||||
return switch (message.getType()) {
|
||||
case HELLO -> serialize(new BodylessMessage(MessageType.HELLO));
|
||||
case GET -> handleGetCommand((String) message.getBody());
|
||||
case POST -> handlePostCommand((MessageBody) message.getBody());
|
||||
default -> {
|
||||
log.error("Message type not supported");
|
||||
yield null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private ByteBuffer handleGetCommand(String inputCommand) throws IOException {
|
||||
var command = CommandManager.getCommandByInput(inputCommand);
|
||||
if (command.isEmpty()) {
|
||||
log.error("Command {} not found", inputCommand);
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, String.format("Command %s not found", inputCommand)));
|
||||
}
|
||||
try {
|
||||
var action = (GetCommand) command.get();
|
||||
return serialize(new BodylessMessage(MessageType.OK, action.action(storage)));
|
||||
} catch (CommandActionException e) {
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private ByteBuffer handlePostCommand(MessageBody request) throws IOException {
|
||||
var inputCommand = request.getCommand();
|
||||
var body = request.getBody();
|
||||
|
||||
var command = CommandManager.getCommandByInput(inputCommand);
|
||||
if (command.isEmpty()) {
|
||||
log.error("Command {} not found", inputCommand);
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, String.format("Command %s not found", inputCommand)));
|
||||
}
|
||||
|
||||
try {
|
||||
var action = (PostCommand) command.get();
|
||||
return serialize(new BodylessMessage(MessageType.OK, action.action(storage, body)));
|
||||
} catch (CommandActionException e) {
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() throws IOException {
|
||||
isRunning = false;
|
||||
serverSocketChannel.close();
|
||||
selector.close();
|
||||
DbController.saveDb(storage.toList());
|
||||
}
|
||||
}
|
||||
@ -1,37 +0,0 @@
|
||||
package me.zinch.Lab6.Server;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.configs.ServerConfig;
|
||||
import me.zinch.Lab6.Server.wrapper.ProductCollection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class ServerBuilder {
|
||||
private ServerConfig serverConfig = new ServerConfig();
|
||||
|
||||
public ServerBuilder() {
|
||||
serverConfig.setPort(3000);
|
||||
serverConfig.setCollection(new ProductCollection(new ArrayList<>()));
|
||||
}
|
||||
|
||||
public ServerBuilder(ServerConfig serverConfig) {
|
||||
this.serverConfig = serverConfig;
|
||||
}
|
||||
|
||||
public ServerBuilder setPort(int port) {
|
||||
if (port < 1 || port > 65535) throw new IllegalArgumentException("Port must be between 1 and 65535");
|
||||
serverConfig.setPort(port);
|
||||
return new ServerBuilder(serverConfig);
|
||||
}
|
||||
|
||||
public ServerBuilder setCollection(IStorage collection) {
|
||||
serverConfig.setCollection(collection);
|
||||
return new ServerBuilder(serverConfig);
|
||||
}
|
||||
|
||||
public Server build() throws IOException {
|
||||
return new Server(serverConfig.getPort(),
|
||||
serverConfig.getCollection());
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* The Clear class represents a command to clear a collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class Clear extends GetCommand {
|
||||
public Clear() {
|
||||
super("clear", "очистить коллекцию");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) {
|
||||
productCollection.clear();
|
||||
return "Коллекция была очищена";
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.console.Console;
|
||||
|
||||
/**
|
||||
* A command to exit the program without saving to a file.
|
||||
*/
|
||||
public class Exit extends GetCommand {
|
||||
public Exit() {
|
||||
super("exit", "terminate the program (without saving to a file)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) {
|
||||
Console.stopApp();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab6.Server.files.DbController;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* A command to save the collection to a file.
|
||||
*/
|
||||
public class Save extends GetCommand {
|
||||
public Save() {
|
||||
super("save", "сохранить коллекцию в файл");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) throws CommandActionException {
|
||||
try {
|
||||
DbController.saveDb(productCollection.toList());
|
||||
return "Коллекция была сохранена";
|
||||
} catch (IOException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
package me.zinch.Lab6.Server.configs;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
|
||||
public class ServerConfig {
|
||||
private Integer port;
|
||||
private IStorage collection;
|
||||
|
||||
public Integer getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(Integer port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public IStorage getCollection() {
|
||||
return collection;
|
||||
}
|
||||
|
||||
public void setCollection(IStorage collection) {
|
||||
this.collection = collection;
|
||||
}
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
package me.zinch.Lab6.Server.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs when the database initialization fails.
|
||||
*/
|
||||
public class DbInitializationException extends IOException {
|
||||
public DbInitializationException() {
|
||||
super("Ошибка! Не удалось инициализировать БД. Проверьте, что структура БД верна.");
|
||||
}
|
||||
|
||||
public DbInitializationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
package me.zinch.Lab6.Server.files;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import me.zinch.Lab6.Domain.models.Product;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The DbController class provides methods for loading and saving product data to a database file.
|
||||
*/
|
||||
public class DbController {
|
||||
private static final XmlMapper xmlMapper = XmlMapper.builder().addModule(new JavaTimeModule()).build();
|
||||
private static final String path;
|
||||
|
||||
static {
|
||||
Map<String, String> env = System.getenv();
|
||||
path = env.getOrDefault("DB_FILE", "db.xml");
|
||||
xmlMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
|
||||
}
|
||||
|
||||
public static List<Product> loadDb() {
|
||||
try {
|
||||
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path));
|
||||
List<Product> collection = xmlMapper.readValue(bufferedInputStream, Products.class).getProducts();
|
||||
bufferedInputStream.close();
|
||||
if (collection == null) return new ArrayList<>();
|
||||
return collection;
|
||||
} catch (IOException e) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveDb(List<Product> list) throws IOException {
|
||||
try {
|
||||
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(path));
|
||||
xmlMapper.writeValue(outputStreamWriter, new Products(list));
|
||||
outputStreamWriter.close();
|
||||
} catch (IOException e) {
|
||||
throw new IOException("Не удалось записать в файл");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a collection of products.
|
||||
*/
|
||||
private static class Products {
|
||||
@JacksonXmlElementWrapper(useWrapping = false)
|
||||
@JacksonXmlProperty(localName = "Product")
|
||||
private List<Product> products;
|
||||
|
||||
public Products() {
|
||||
}
|
||||
|
||||
public Products(List<Product> list) {
|
||||
this.products = list;
|
||||
}
|
||||
|
||||
public List<Product> getProducts() {
|
||||
return products;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,134 +0,0 @@
|
||||
package me.zinch.Lab6.Server.wrapper;
|
||||
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab6.Domain.models.Product;
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Represents a collection of products.
|
||||
*/
|
||||
public class ProductCollection implements IStorage {
|
||||
private final TreeSet<Product> productList;
|
||||
private Long idIncrementor;
|
||||
|
||||
public ProductCollection(List<Product> list) throws ValidationException {
|
||||
productList = new TreeSet<>((o1, o2) -> {
|
||||
var o1Length = o1.getCoordinates().getX() * o1.getCoordinates().getX() + o1.getCoordinates().getY() * o1.getCoordinates().getY();
|
||||
var o2Length = o2.getCoordinates().getX() * o2.getCoordinates().getX() + o2.getCoordinates().getY() * o2.getCoordinates().getY();
|
||||
return Math.toIntExact(o1Length - o2Length);
|
||||
});
|
||||
productList.addAll(list);
|
||||
idIncrementor = productList.isEmpty() ? 1L : productList.last().getId() + 1;
|
||||
}
|
||||
|
||||
private Long generateId() {
|
||||
return idIncrementor++;
|
||||
}
|
||||
|
||||
public Product getProductById(Long id) {
|
||||
Optional<Product> product = productList.stream().filter(i -> Objects.equals(i.getId(), id)).findFirst();
|
||||
return product.orElse(null);
|
||||
}
|
||||
|
||||
public Product addProduct(ProductDTO productDTO) {
|
||||
var product = productDTO.buildProduct(generateId(), ZonedDateTime.now());
|
||||
productList.add(product);
|
||||
return product;
|
||||
}
|
||||
|
||||
private Product addProduct(ProductDTO productDTO, Long id, ZonedDateTime creationDate) {
|
||||
var product = productDTO.buildProduct(id, creationDate);
|
||||
productList.add(product);
|
||||
return product;
|
||||
}
|
||||
|
||||
public Product updateProduct(Long id, ProductDTO productDTO) {
|
||||
var product = getProductById(id);
|
||||
productList.remove(product);
|
||||
return addProduct(productDTO, product.getId(), product.getCreationDate());
|
||||
}
|
||||
|
||||
public Product removeProduct(Long id) {
|
||||
var product = getProductById(id);
|
||||
productList.remove(product);
|
||||
return product;
|
||||
}
|
||||
|
||||
public String getInfo() {
|
||||
var optionalInitDate = productList.stream().map(Product::getCreationDate).sorted().findFirst();
|
||||
ZonedDateTime initDate = optionalInitDate.orElse(ZonedDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()));
|
||||
return String.format("Структура: TreeSet%nДата инициализации: %s%nКоличество элементов: %s", initDate, productList.size());
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
productList.clear();
|
||||
}
|
||||
|
||||
|
||||
public Long getMaxPrice() {
|
||||
return productList.stream().max(Comparator.comparingLong(Product::getPrice)).map(Product::getPrice).orElse(null);
|
||||
}
|
||||
|
||||
public Long getMinPrice() {
|
||||
return productList.stream().min(Comparator.comparingLong(Product::getPrice)).map(Product::getPrice).orElse(null);
|
||||
}
|
||||
|
||||
public boolean isProductIdExists(Long id) {
|
||||
return getProductById(id) != null;
|
||||
}
|
||||
|
||||
public Integer removeLover(Long id) {
|
||||
var size = productList.size();
|
||||
productList.headSet(getProductById(id)).stream().toList().forEach(productList::remove);
|
||||
return size - productList.size();
|
||||
}
|
||||
|
||||
public String filterContainsName(String name) {
|
||||
return String.join("\n", productList.stream()
|
||||
.filter(product -> product.getName().toLowerCase().contains(name.toLowerCase()))
|
||||
.map(Product::toString)
|
||||
.toList());
|
||||
}
|
||||
|
||||
public String getUniqueManufactureCost() {
|
||||
return String.join(", ", Set.copyOf(productList.stream()
|
||||
.map(Product::getManufactureCost)
|
||||
.toList())
|
||||
.stream()
|
||||
.map(Object::toString)
|
||||
.toList());
|
||||
}
|
||||
|
||||
public List<Product> toList() {
|
||||
return productList.stream().toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.join("\n", productList.stream().map(Product::toString).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
ProductCollection that = (ProductCollection) o;
|
||||
return Objects.equals(productList, that.productList) && Objects.equals(idIncrementor, that.idIncrementor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(productList, idIncrementor);
|
||||
}
|
||||
}
|
||||
13
Lab.Server/src/main/java/me/zinch/Lab7/Server/App.java
Normal file
13
Lab.Server/src/main/java/me/zinch/Lab7/Server/App.java
Normal file
@ -0,0 +1,13 @@
|
||||
package me.zinch.Lab7.Server;
|
||||
|
||||
import me.zinch.Lab7.Server.console.Console;
|
||||
import me.zinch.Lab7.Server.utils.SHA256;
|
||||
|
||||
/**
|
||||
* Main class for running the application.
|
||||
*/
|
||||
public class App {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Console.run();
|
||||
}
|
||||
}
|
||||
167
Lab.Server/src/main/java/me/zinch/Lab7/Server/Server/Server.java
Normal file
167
Lab.Server/src/main/java/me/zinch/Lab7/Server/Server/Server.java
Normal file
@ -0,0 +1,167 @@
|
||||
package me.zinch.Lab7.Server.Server;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.Message;
|
||||
import me.zinch.Lab7.Domain.net.MessageBody;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.utils.SHA256;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.commands.CommandManager;
|
||||
import me.zinch.Lab7.Server.commands.GetCommand;
|
||||
import me.zinch.Lab7.Server.commands.PostCommand;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.wrapper.ProductCollection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class Server {
|
||||
private static final Logger log = LoggerFactory.getLogger(Server.class);
|
||||
private final ServerSocket serverSocket;
|
||||
private final IStorage storage;
|
||||
private boolean isRunning;
|
||||
private final ExecutorService requestReadPool = Executors.newCachedThreadPool();
|
||||
private final ExecutorService requestProcessPool = Executors.newCachedThreadPool();
|
||||
private final ExecutorService responseSendPool = Executors.newFixedThreadPool(12);
|
||||
|
||||
public Server(int port, IStorage collection) throws IOException {
|
||||
serverSocket = new ServerSocket(port);
|
||||
isRunning = true;
|
||||
|
||||
if (collection == null) collection = new ProductCollection(new ArrayList<>());
|
||||
storage = collection;
|
||||
|
||||
log.info("The server has been assigned to port {}", port);
|
||||
}
|
||||
|
||||
public static byte[] serialize(Serializable obj) throws IOException {
|
||||
try (var bOut = new ByteArrayOutputStream();
|
||||
var oOut = new ObjectOutputStream(bOut)) {
|
||||
oOut.writeObject(obj);
|
||||
oOut.flush();
|
||||
return bOut.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
public void run() {
|
||||
log.info("The server is running");
|
||||
|
||||
while (isRunning) {
|
||||
try {
|
||||
var clientSocket = serverSocket.accept();
|
||||
log.info("Received connection from {}", clientSocket.getRemoteSocketAddress());
|
||||
requestReadPool.execute(() -> {
|
||||
try {
|
||||
handleClient(clientSocket);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleClient(Socket clientSocket) throws IOException, ClassNotFoundException {
|
||||
var inputStream = clientSocket.getInputStream();
|
||||
|
||||
var buffer = new byte[8192];
|
||||
inputStream.read(buffer);
|
||||
|
||||
var oIn = new ObjectInputStream(new ByteArrayInputStream(buffer));
|
||||
var msg = (Message) oIn.readObject();
|
||||
log.info("Received message {} from {}", msg, clientSocket.getRemoteSocketAddress());
|
||||
|
||||
responseSendPool.execute(() -> handleWrite(clientSocket, msg, inputStream));
|
||||
}
|
||||
|
||||
private void handleWrite(Socket clientSocket, Message msg, InputStream inputStream) {
|
||||
try {
|
||||
var response = requestProcessPool.submit(() -> createResponse(msg));
|
||||
var responseBuffer = response.get();
|
||||
if (responseBuffer != null) {
|
||||
try {
|
||||
var outputStream = clientSocket.getOutputStream();
|
||||
outputStream.write(responseBuffer);
|
||||
outputStream.flush();
|
||||
log.info("Sent message to {}", clientSocket.getRemoteSocketAddress());
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
inputStream.close();
|
||||
} catch (IOException | InterruptedException | ExecutionException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] createResponse(Message message) throws IOException {
|
||||
var user = (User) message.getUser();
|
||||
if (user != null) user.setPassword(SHA256.hash(user.getPassword()));
|
||||
return switch (message.getType()) {
|
||||
case HELLO -> serialize(new BodylessMessage(MessageType.HELLO));
|
||||
case GET -> handleGetCommand((String) message.getBody(), user);
|
||||
case POST -> handlePostCommand((MessageBody) message.getBody(), user);
|
||||
default -> {
|
||||
log.error("Message type not supported");
|
||||
yield null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private byte[] handleGetCommand(String inputCommand, User user) throws IOException {
|
||||
var command = CommandManager.getCommandByInput(inputCommand);
|
||||
if (command.isEmpty()) {
|
||||
log.error("Command {} not found", inputCommand);
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, String.format("Command %s not found", inputCommand)));
|
||||
}
|
||||
try {
|
||||
var action = (GetCommand) command.get();
|
||||
return serialize(new BodylessMessage(MessageType.OK, action.action(storage, user)));
|
||||
} catch (CommandActionException e) {
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] handlePostCommand(MessageBody request, User user) throws IOException {
|
||||
var inputCommand = request.getCommand();
|
||||
var body = request.getBody();
|
||||
|
||||
var command = CommandManager.getCommandByInput(inputCommand);
|
||||
if (command.isEmpty()) {
|
||||
log.error("Command {} not found", inputCommand);
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, String.format("Command %s not found", inputCommand)));
|
||||
}
|
||||
|
||||
try {
|
||||
var action = (PostCommand) command.get();
|
||||
return serialize(new BodylessMessage(MessageType.OK, action.action(storage, body, user)));
|
||||
} catch (CommandActionException e) {
|
||||
return serialize(new BodylessMessage(MessageType.ERROR, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() throws IOException {
|
||||
isRunning = false;
|
||||
serverSocket.close();
|
||||
requestReadPool.shutdown();
|
||||
requestProcessPool.shutdown();
|
||||
responseSendPool.shutdown();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
package me.zinch.Lab7.Server.Server;
|
||||
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.wrapper.ProductCollection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class ServerBuilder {
|
||||
private static class Config {
|
||||
private int port = 3000;
|
||||
private IStorage collection = new ProductCollection();
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public IStorage getCollection() {
|
||||
return collection;
|
||||
}
|
||||
|
||||
public void setCollection(IStorage collection) {
|
||||
this.collection = collection;
|
||||
}
|
||||
}
|
||||
|
||||
private Config config = new Config();
|
||||
|
||||
public ServerBuilder() {
|
||||
config.setPort(3000);
|
||||
config.setCollection(new ProductCollection(new ArrayList<>()));
|
||||
}
|
||||
|
||||
private ServerBuilder(Config config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public ServerBuilder setPort(int port) {
|
||||
if (port < 1 || port > 65535) throw new IllegalArgumentException("Port must be between 1 and 65535");
|
||||
config.setPort(port);
|
||||
return new ServerBuilder(config);
|
||||
}
|
||||
|
||||
public ServerBuilder setCollection(IStorage collection) {
|
||||
config.setCollection(collection);
|
||||
return new ServerBuilder(config);
|
||||
}
|
||||
|
||||
public Server build() throws IOException {
|
||||
return new Server(config.getPort(), config.getCollection());
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,13 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab6.Domain.validator.Validators;
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Domain.validator.Validators;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@ -18,13 +20,13 @@ public class Add extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object) throws CommandActionException {
|
||||
public String action(IStorage productCollection, Object object, User user) throws CommandActionException {
|
||||
var productDTO = (ProductDTO) object;
|
||||
try {
|
||||
Validators.validateObject(productDTO).throwIfNotValid();
|
||||
var product = productCollection.addProduct(productDTO);
|
||||
var product = productCollection.addProduct(productDTO, user);
|
||||
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
|
||||
} catch (ValidationException e) {
|
||||
} catch (ValidationException | SQLException e) {
|
||||
throw new CommandActionException(String.format("Произошла ошибка при добавлении%n%s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,13 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab6.Domain.validator.Validators;
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Domain.validator.Validators;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@ -18,17 +20,17 @@ public class AddIfMax extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object) throws CommandActionException {
|
||||
public String action(IStorage productCollection, Object object, User user) throws CommandActionException {
|
||||
try {
|
||||
var productDTO = (ProductDTO) object;
|
||||
try {
|
||||
Validators.validateObject(productDTO).throwIfNotValid();
|
||||
if (productCollection.getMaxPrice() == null || productCollection.getMaxPrice() < productDTO.getPrice()) {
|
||||
var product = productCollection.addProduct(productDTO);
|
||||
var product = productCollection.addProduct(productDTO, user);
|
||||
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
|
||||
}
|
||||
return "Продукт не подходит под условие";
|
||||
} catch (ValidationException e) {
|
||||
} catch (ValidationException | SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
@ -1,11 +1,13 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab6.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab6.Domain.validator.Validators;
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.models.ProductDTO;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Domain.validator.Validators;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@ -18,17 +20,17 @@ public class AddIfMin extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object) {
|
||||
public String action(IStorage productCollection, Object object, User user) {
|
||||
try {
|
||||
var productDTO = (ProductDTO) object;
|
||||
try {
|
||||
Validators.validateObject(productDTO).throwIfNotValid();
|
||||
if (productCollection.getMinPrice() == null || productCollection.getMinPrice() > productDTO.getPrice()) {
|
||||
var product = productCollection.addProduct(productDTO);
|
||||
var product = productCollection.addProduct(productDTO, user);
|
||||
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
|
||||
}
|
||||
return "Продукт не подходит под условие";
|
||||
} catch (ValidationException e) {
|
||||
} catch (ValidationException | SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
@ -0,0 +1,29 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.db.DbController;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.wrapper.DbWrapper;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class CheckProductOwner extends PostCommand {
|
||||
public CheckProductOwner() {
|
||||
super("check_product_owner", "", Pattern.compile("^check_product_owner .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object obj, User user) throws CommandActionException {
|
||||
try {
|
||||
var id = (long) obj;
|
||||
if (DbWrapper.hasAccess(id, user, DbController.getConnection())) return "Это ваш продукт";
|
||||
throw new CommandActionException("У вас нет прав на изменение данного продукта");
|
||||
} catch (ClassCastException e) {
|
||||
throw new CommandActionException(e);
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException("У вас нет прав на изменение данного продукта");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* The Clear class represents a command to clear a collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class Clear extends GetCommand {
|
||||
public Clear() {
|
||||
super("clear", "очистить коллекцию");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
try {
|
||||
productCollection.clear(user);
|
||||
return "Были удалены ваши продукты";
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException("Ошибка при отчистке коллекции");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@ -25,8 +25,10 @@ public class CommandManager {
|
||||
registerCommand(new AddIfMax());
|
||||
registerCommand(new AddIfMin());
|
||||
registerCommand(new RemoveLower());
|
||||
registerCommand(new Save());
|
||||
registerCommand(new GetProduct());
|
||||
registerCommand(new Login());
|
||||
registerCommand(new Register());
|
||||
registerCommand(new CheckProductOwner());
|
||||
|
||||
registerCommand(new Help());
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.wrapper.DbWrapper;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
public class Drop extends GetCommand{
|
||||
public Drop() {
|
||||
super("drop", "Init db");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) throws CommandActionException {
|
||||
DbWrapper.dropDb();
|
||||
return "Dropped 💀";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.console.Console;
|
||||
|
||||
/**
|
||||
* A command to exit the program without saving to a file.
|
||||
*/
|
||||
public class Exit extends GetCommand {
|
||||
public Exit() {
|
||||
super("exit", "terminate the program");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
Console.stopApp();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -13,7 +14,7 @@ public class FilterContainsName extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object) {
|
||||
public String action(IStorage productCollection, Object object, User user) {
|
||||
String name = object.toString();
|
||||
var result = productCollection.filterContainsName(name);
|
||||
return result.isEmpty() ? "Таких элементов не найдено" : result;
|
||||
@ -1,7 +1,8 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -14,5 +15,5 @@ public abstract class GetCommand extends Command {
|
||||
super(name, description);
|
||||
}
|
||||
|
||||
public abstract String action(IStorage productCollection) throws CommandActionException;
|
||||
public abstract String action(IStorage productCollection, User user) throws CommandActionException;
|
||||
}
|
||||
@ -1,7 +1,8 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -11,7 +12,7 @@ public class GetProduct extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object obj) throws CommandActionException {
|
||||
public String action(IStorage productCollection, Object obj, User user) throws CommandActionException {
|
||||
if (!productCollection.isProductIdExists((Long) obj))
|
||||
throw new CommandActionException("Продукт с таким ID не существует");
|
||||
return productCollection.getProductById((Long) obj).toString();
|
||||
@ -1,6 +1,7 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* A command to display help for available commands.
|
||||
@ -11,7 +12,7 @@ public class Help extends GetCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) {
|
||||
public String action(IStorage productCollection, User user) {
|
||||
return SystemCommandManager.getRegisteredCommand();
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* A command to display information about the collection (type, initialization date, number of elements, etc.) to the standard output stream.
|
||||
@ -11,7 +12,7 @@ public class Info extends GetCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) {
|
||||
public String action(IStorage productCollection, User user) {
|
||||
return productCollection.getInfo();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.db.DbController;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.wrapper.DbInitializer;
|
||||
import me.zinch.Lab7.Server.wrapper.DbWrapper;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class Init extends GetCommand{
|
||||
public Init() {
|
||||
super("init", "Delete all db");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) throws CommandActionException {
|
||||
try {
|
||||
DbInitializer.initializeDb(DbController.getConnection());
|
||||
return "Initialized 😇";
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,8 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -11,7 +12,7 @@ public class IsIdExists extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object obj) throws CommandActionException {
|
||||
public String action(IStorage productCollection, Object obj, User user) throws CommandActionException {
|
||||
if (!productCollection.isProductIdExists((Long) obj))
|
||||
throw new CommandActionException("Продукт с таким ID не существует");
|
||||
return "Exists";
|
||||
@ -0,0 +1,28 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.db.DbController;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.utils.SHA256;
|
||||
import me.zinch.Lab7.Server.wrapper.DbWrapper;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class Login extends PostCommand {
|
||||
public Login() {
|
||||
super("login", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object obj, User user) throws CommandActionException {
|
||||
try {
|
||||
var loginUser = (User) obj;
|
||||
if (DbWrapper.isUserExists(loginUser.getLogin(), SHA256.hash(loginUser.getPassword()), DbController.getConnection()))
|
||||
return "Здравствуйте, " + loginUser.getLogin() + "!";
|
||||
throw new CommandActionException("Ошибка в логине или пароле");
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,8 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -14,5 +15,5 @@ public abstract class PostCommand extends Command {
|
||||
super(name, description);
|
||||
}
|
||||
|
||||
public abstract String action(IStorage productCollection, Object obj) throws CommandActionException;
|
||||
public abstract String action(IStorage productCollection, Object obj, User user) throws CommandActionException;
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* A command to print the elements of the collection in ascending order.
|
||||
@ -11,7 +12,7 @@ public class PrintAscending extends GetCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) {
|
||||
public String action(IStorage productCollection, User user) {
|
||||
var result = productCollection.toString();
|
||||
return result.isEmpty() ? "Коллекция пуста" : result;
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* A command to print the unique values of the 'manufactureCost' field of all elements in the collection.
|
||||
@ -11,7 +12,7 @@ public class PrintUniqueManufactureCost extends GetCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection) {
|
||||
public String action(IStorage productCollection, User user) {
|
||||
var result = productCollection.getUniqueManufactureCost();
|
||||
return result.isEmpty() ? "Коллекция пуста" : result;
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.db.DbController;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.utils.SHA256;
|
||||
import me.zinch.Lab7.Server.wrapper.DbWrapper;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class Register extends PostCommand {
|
||||
public Register() {
|
||||
super("register", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object obj, User user) throws CommandActionException {
|
||||
try {
|
||||
var newUser = (User) obj;
|
||||
newUser.setPassword(SHA256.hash(newUser.getPassword()));
|
||||
DbWrapper.createUser(newUser, DbController.getConnection());
|
||||
return "Пользователь создан";
|
||||
} catch (ClassCastException | SQLException e) {
|
||||
throw new CommandActionException("Пользователь уже существует");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,8 +1,10 @@
|
||||
package me.zinch.Lab6.Server.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab6.Domain.wrapper.IStorage;
|
||||
import me.zinch.Lab6.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@ -14,16 +16,18 @@ public class Remove extends PostCommand {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object) throws CommandActionException {
|
||||
public String action(IStorage productCollection, Object object, User user) throws CommandActionException {
|
||||
try {
|
||||
Long id = (Long) object;
|
||||
if (productCollection.isProductIdExists(id)) {
|
||||
var product = productCollection.removeProduct(id);
|
||||
var product = productCollection.removeProduct(id, user);
|
||||
return String.format("Продукт %s был удалён", product.getName());
|
||||
}
|
||||
return "Продукта с таким id не существует";
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user