Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f7f8e03d25 | |||
| d6f8da7106 | |||
| d92cc8d71b | |||
| 5555786417 | |||
| ae519be5c6 | |||
| c23b171b5f | |||
| 9555d61966 | |||
| 8ea371d33b | |||
| 7e6ef47b63 | |||
| 0f170b8691 | |||
| bac5ed4dc1 | |||
| e3b4bcac17 | |||
| a513663505 | |||
| 9220ff44a5 | |||
| c4ef680acf | |||
| 5c8f333478 | |||
| 2ffcca7eeb | |||
| d3cb180b12 | |||
| bd939c9bc5 | |||
| 5b95fff14d | |||
| 10d21a6789 | |||
| db490ed5ec | |||
| b114a45cd8 | |||
| 723aceb374 | |||
| ad354595d1 | |||
| 3ac2784373 | |||
| cd428e532b | |||
| f3e6257e8e | |||
| afc63b0772 | |||
| ca28cbab7d | |||
| 96a055a29d | |||
| f00ba84c10 | |||
| a630bf28f8 | |||
| d33c983dbb | |||
| d4fe517eb8 | |||
| 722b9f4d8c |
2
.gitignore
vendored
2
.gitignore
vendored
@ -34,3 +34,5 @@ bin/
|
||||
target
|
||||
|
||||
*.scr
|
||||
|
||||
DB/*
|
||||
85
Lab.Client/pom.xml
Normal file
85
Lab.Client/pom.xml
Normal file
@ -0,0 +1,85 @@
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab7-Client</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Lab7-Client</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
</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>
|
||||
<version>2.17.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>8.0.1.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
<artifactId>jakarta.el</artifactId>
|
||||
<version>5.0.0-M1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.23.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab7-Domain</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<version>3.7.1</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>me.zinch.Lab7.Client.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
14
Lab.Client/src/main/java/me/zinch/Lab7/Client/App.java
Normal file
14
Lab.Client/src/main/java/me/zinch/Lab7/Client/App.java
Normal file
@ -0,0 +1,14 @@
|
||||
package me.zinch.Lab7.Client;
|
||||
|
||||
import me.zinch.Lab7.Client.console.Console;
|
||||
import me.zinch.Lab7.Client.console.ShutdownHook;
|
||||
|
||||
/**
|
||||
* Main class for running the application.
|
||||
*/
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
|
||||
Console.run();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
package me.zinch.Lab7.Client.client;
|
||||
|
||||
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;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
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;
|
||||
this.port = port;
|
||||
|
||||
try {
|
||||
if (sendMessage(new BodylessMessage(MessageType.HELLO)).getType() == MessageType.HELLO) {
|
||||
Console.log(String.format("Соединение с сервером %s:%s установлено", address, port));
|
||||
}
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new ResponseException();
|
||||
}
|
||||
}
|
||||
|
||||
public Message sendMessage(Message message) throws ClassNotFoundException, IOException {
|
||||
try (var socket = new Socket(address, port);
|
||||
var bufferedSocketOutputStream = new BufferedOutputStream(socket.getOutputStream());
|
||||
var byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
var objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
|
||||
|
||||
if (user != null) message.setUser(user);
|
||||
|
||||
objectOutputStream.writeObject(message);
|
||||
objectOutputStream.flush();
|
||||
bufferedSocketOutputStream.write(byteArrayOutputStream.toByteArray());
|
||||
bufferedSocketOutputStream.flush();
|
||||
|
||||
try (var objectInputStream = new ObjectInputStream(socket.getInputStream())) {
|
||||
return (Message) objectInputStream.readObject();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IOException("Сервер не доступен");
|
||||
}
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public boolean isLogin() {
|
||||
return user != null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The Add class represents a command to add a new element to a collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class Add extends Command {
|
||||
public Add() {
|
||||
super("add {element}", "добавить новый элемент в коллекцию", Pattern.compile("^add"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
try {
|
||||
var productDTO = Console.readProductDTO();
|
||||
var request = new BodyfulMessage(MessageType.POST, Console.getLastCommand(), productDTO);
|
||||
var response = (BodylessMessage) client.sendMessage(request);
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The AddIfMax class represents a command to add a new element to a collection if its price value exceeds the maximum price value in the collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class AddIfMax extends Command {
|
||||
public AddIfMax() {
|
||||
super("add_if_max {element}", "добавить новый элемент в коллекцию, если его значение цены превышает значение наибольшей цены этой коллекции", Pattern.compile("^add_if_max"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
try {
|
||||
var productDTO = Console.readProductDTO();
|
||||
var response = (BodylessMessage) client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), productDTO));
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The AddIfMin class represents a command to add a new element to a collection if its price is lower than the lowest price in the collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class AddIfMin extends Command {
|
||||
public AddIfMin() {
|
||||
super("add_if_min {element}", "добавить новый элемент в коллекцию, если его значение цены меньше, чем у наименьшей цены этой коллекции", Pattern.compile("^add_if_min"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) {
|
||||
try {
|
||||
var productDTO = Console.readProductDTO();
|
||||
var response = (BodylessMessage) client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), productDTO));
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* The Clear class represents a command to clear a collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class Clear extends Command {
|
||||
public Clear() {
|
||||
super("clear", "очистить коллекцию");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Represents a command that can be executed.
|
||||
*/
|
||||
public abstract class Command {
|
||||
private final String name;
|
||||
private final String description;
|
||||
private final Pattern pattern;
|
||||
|
||||
public Command(String name, String description, Pattern pattern) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
public Command(String name, String description) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.pattern = Pattern.compile("^" + name);
|
||||
}
|
||||
|
||||
public final String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public final String getSignature() {
|
||||
return name.split(" ")[0];
|
||||
}
|
||||
|
||||
public final String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public final Pattern getPattern() {
|
||||
return pattern;
|
||||
}
|
||||
|
||||
public final boolean checkPattern(String input) {
|
||||
return pattern.matcher(input).matches();
|
||||
}
|
||||
|
||||
public String action(Client client) throws CommandActionException {
|
||||
try {
|
||||
var response = (BodylessMessage) client.sendMessage(new BodylessMessage(MessageType.GET, this.getName()));
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,8 +1,8 @@
|
||||
package me.zinch.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.console.Console;
|
||||
import me.zinch.files.ScriptLoader;
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
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;
|
||||
@ -15,6 +15,10 @@ import java.util.regex.Pattern;
|
||||
public class ExecuteScript extends Command {
|
||||
private static final List<String> executeStack = new ArrayList<>();
|
||||
|
||||
public ExecuteScript() {
|
||||
super("execute_script file_name", "считать и исполнить скрипт из указанного файла. В скрипте содержатся команды в таком же виде, в котором их вводит пользователь в интерактивном режиме", Pattern.compile("^execute_script .+"));
|
||||
}
|
||||
|
||||
private void addFileToStack(String filePath) {
|
||||
executeStack.add(filePath);
|
||||
}
|
||||
@ -27,19 +31,17 @@ public class ExecuteScript extends Command {
|
||||
return executeStack.contains(filePath);
|
||||
}
|
||||
|
||||
public ExecuteScript() {
|
||||
super("execute_script file_name", "считать и исполнить скрипт из указанного файла. В скрипте содержатся команды в таком же виде, в котором их вводит пользователь в интерактивном режиме", Pattern.compile("^execute_script .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(ProductCollection productCollection) {
|
||||
public String action(Client client) {
|
||||
try {
|
||||
var result = new StringBuilder();
|
||||
var scriptFile = Console.getLastCommand().split(" ")[1];
|
||||
result.append(String.format("Скрипт %s начинает работу.", scriptFile)).append("\n");
|
||||
addFileToStack(scriptFile);
|
||||
var commandList = ScriptLoader.loadList(scriptFile);
|
||||
for (var input: commandList) {
|
||||
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) {
|
||||
@ -47,13 +49,14 @@ public class ExecuteScript extends Command {
|
||||
if (checkFileInStack(nextFile)) continue;
|
||||
addFileToStack(nextFile);
|
||||
}
|
||||
command.get().action(productCollection);
|
||||
result.append(command.get().action(client)).append("\n");
|
||||
} else {
|
||||
new UnknownCommand().action(productCollection);
|
||||
new UnknownCommand().action(client);
|
||||
}
|
||||
}
|
||||
clearStack();
|
||||
return String.format("Скрипт %s завершил работу.%n", scriptFile);
|
||||
result.append(String.format("Скрипт %s завершил работу.", scriptFile)).append("\n");
|
||||
return result.toString();
|
||||
} catch (IOException e) {
|
||||
return e.getMessage();
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
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", "завершить программу");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) {
|
||||
Console.stopAppWithoutSaving();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@ -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.BodylessMessage;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to filter elements whose 'name' field contains the specified substring.
|
||||
*/
|
||||
public class FilterContainsName extends Command {
|
||||
public FilterContainsName() {
|
||||
super("filter_contains_name name", "вывести элементы, значение поля name которых содержит заданную подстроку", Pattern.compile("^filter_contains_name \\w+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
try {
|
||||
String name = Console.getLastCommand().split(" ")[1];
|
||||
var response = (BodylessMessage) client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), name));
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class GetProductById extends Command {
|
||||
public GetProductById() {
|
||||
super("get_product_by_id {element}", "", Pattern.compile("^get_product_by_id +."));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
|
||||
/**
|
||||
* A command to display help for available commands.
|
||||
*/
|
||||
public class Help extends Command {
|
||||
public Help() {
|
||||
super("help", "вывести справку по доступным командам");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) {
|
||||
return client.isLogin() ? MainCommandManager.getRegisteredCommand() : UserCommandManager.getRegisteredCommand();
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,4 @@
|
||||
package me.zinch.commands;
|
||||
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
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.
|
||||
@ -9,9 +7,4 @@ public class Info extends Command {
|
||||
public Info() {
|
||||
super("info", "вывести в стандартный поток вывода информацию о коллекции (тип, дата инициализации, количество элементов и т.д.)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(ProductCollection productCollection) {
|
||||
return productCollection.getInfo();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class IsIdExists extends Command {
|
||||
public IsIdExists() {
|
||||
super("is_id_exists {element}", "", Pattern.compile("^is_id_exists +."));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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 "Успешно!";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Manages the registration and retrieval of commands.
|
||||
*/
|
||||
public class MainCommandManager {
|
||||
private static final List<Command> commandList = new ArrayList<>();
|
||||
|
||||
static {
|
||||
registerCommand(new Show());
|
||||
registerCommand(new Exit());
|
||||
registerCommand(new Info());
|
||||
registerCommand(new Clear());
|
||||
registerCommand(new PrintAscending());
|
||||
registerCommand(new PrintUniqueManufactureCost());
|
||||
registerCommand(new FilterContainsName());
|
||||
registerCommand(new Add());
|
||||
registerCommand(new Update());
|
||||
registerCommand(new Remove());
|
||||
registerCommand(new AddIfMax());
|
||||
registerCommand(new AddIfMin());
|
||||
registerCommand(new RemoveLower());
|
||||
registerCommand(new ExecuteScript());
|
||||
registerCommand(new Logout());
|
||||
|
||||
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,6 +1,4 @@
|
||||
package me.zinch.commands;
|
||||
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to print the elements of the collection in ascending order.
|
||||
@ -9,9 +7,4 @@ public class PrintAscending extends Command {
|
||||
public PrintAscending() {
|
||||
super("print_ascending", "вывести элементы коллекции в порядке возрастания");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(ProductCollection productCollection) {
|
||||
return productCollection.toString();
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,4 @@
|
||||
package me.zinch.commands;
|
||||
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to print the unique values of the 'manufactureCost' field of all elements in the collection.
|
||||
@ -9,9 +7,4 @@ public class PrintUniqueManufactureCost extends Command {
|
||||
public PrintUniqueManufactureCost() {
|
||||
super("print_unique_manufacture_cost", "вывести уникальные значения поля manufactureCost всех элементов в коллекции");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(ProductCollection productCollection) {
|
||||
return productCollection.getUniqueManufactureCost();
|
||||
}
|
||||
}
|
||||
@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to remove an element from the collection by its id.
|
||||
*/
|
||||
public class Remove extends Command {
|
||||
public Remove() {
|
||||
super("remove_by_id id", "удалить элемент из коллекции по его id", Pattern.compile("^remove_by_id .+"));
|
||||
}
|
||||
|
||||
@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));
|
||||
return response.getBody().toString();
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to remove all elements from the collection that have ids lower than the specified id.
|
||||
*/
|
||||
public class RemoveLower extends Command {
|
||||
public RemoveLower() {
|
||||
super("remove_lower id", "удалить из коллекции все элементы, меньшие, чем заданный по id", Pattern.compile("^remove_lower .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) {
|
||||
try {
|
||||
Long id = Long.parseLong(Console.getLastCommand().split(" ")[1]);
|
||||
var response = (BodylessMessage) client.sendMessage(new BodyfulMessage(MessageType.POST, Console.getLastCommand(), id));
|
||||
return response.getBody().toString();
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to save the collection to a file.
|
||||
*/
|
||||
public class Save extends Command {
|
||||
public Save() {
|
||||
super("save", "save the collection to a file");
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,4 @@
|
||||
package me.zinch.commands;
|
||||
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
/**
|
||||
* A command to display all elements of the collection in string representation to the standard output stream.
|
||||
@ -9,9 +7,4 @@ public class Show extends Command {
|
||||
public Show() {
|
||||
super("show", "вывести в стандартный поток вывода все элементы коллекции в строковом представлении");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(ProductCollection productCollection) {
|
||||
return productCollection.toString();
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
package me.zinch.commands;
|
||||
package me.zinch.Lab7.Client.commands;
|
||||
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
import me.zinch.Lab7.Client.client.Client;
|
||||
|
||||
/**
|
||||
* Represents an unknown command.
|
||||
@ -11,7 +11,7 @@ public class UnknownCommand extends Command {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(ProductCollection productCollection) {
|
||||
public String action(Client client) {
|
||||
return "Команда не распознана.";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
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.MessageBody;
|
||||
import me.zinch.Lab7.Domain.net.MessageType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to update the value of an element in the collection, whose id is specified.
|
||||
*/
|
||||
public class Update extends Command {
|
||||
public Update() {
|
||||
super("update id {element}", "обновить значение элемента коллекции, id которого равен заданному", Pattern.compile("^update .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(Client client) throws CommandActionException {
|
||||
try {
|
||||
var command = Console.getLastCommand();
|
||||
Long id = Long.parseLong(command.split(" ")[1]);
|
||||
|
||||
var isIdExists = new IsIdExists();
|
||||
Console.appendHistory(String.format("%s %s", isIdExists.getSignature(), id));
|
||||
isIdExists.action(client);
|
||||
|
||||
var checkProductOwner = new CheckProductOwner();
|
||||
Console.appendHistory(String.format("%s %s", checkProductOwner.getSignature(), id));
|
||||
checkProductOwner.action(client);
|
||||
|
||||
var getProductById = new GetProductById();
|
||||
Console.appendHistory(String.format("%s %s", getProductById.getSignature(), id));
|
||||
var product = getProductById.action(client);
|
||||
|
||||
Console.log("Вы собираетесь обновить следующий продукт");
|
||||
Console.log(product);
|
||||
|
||||
var productDTO = Console.readProductDTO();
|
||||
var response = (BodylessMessage) client.sendMessage(
|
||||
new BodyfulMessage(MessageType.POST, command,
|
||||
new MessageBody(String.format("%s %s", command, id), productDTO)));
|
||||
return response.getBody().toString();
|
||||
} catch (IOException | ClassNotFoundException | NumberFormatException e) {
|
||||
throw new CommandActionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,229 @@
|
||||
package me.zinch.Lab7.Client.console;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Console class provides methods for interacting with the console, reading user input, and managing application flow.
|
||||
* This class includes methods for appending input history, stopping the application, reading product DTO from the console, and running the application loop.
|
||||
*/
|
||||
public class Console {
|
||||
private static final Scanner scanner = new Scanner(System.in);
|
||||
private static final List<String> history = new ArrayList<>();
|
||||
private static boolean isRunning = true;
|
||||
private static boolean isExitMessageShowed = false;
|
||||
private static Client client;
|
||||
|
||||
public static void appendHistory(String input) {
|
||||
history.add(input);
|
||||
}
|
||||
|
||||
public static void log(Object msg) {
|
||||
if (isRunning) System.out.println(msg.toString());
|
||||
}
|
||||
|
||||
public static void log() {
|
||||
log("");
|
||||
}
|
||||
|
||||
public static void stopAppWithoutSaving() {
|
||||
showExitMessage();
|
||||
isRunning = false;
|
||||
}
|
||||
|
||||
public static void stopAppWithSaving() {
|
||||
stopAppWithoutSaving();
|
||||
}
|
||||
|
||||
public static void showExitMessage() {
|
||||
if (!isExitMessageShowed) log("\nВсего хорошего!");
|
||||
isExitMessageShowed = true;
|
||||
}
|
||||
|
||||
public static String getLastCommand() {
|
||||
return history.get(history.size() - 1);
|
||||
}
|
||||
|
||||
|
||||
private static String readString() {
|
||||
if (!scanner.hasNextLine()) Console.stopAppWithSaving();
|
||||
var input = scanner.nextLine().trim();
|
||||
return input.isEmpty() ? null : input;
|
||||
}
|
||||
|
||||
private static Long readLong() {
|
||||
var input = readString();
|
||||
if (input == null || input.isEmpty()) return null;
|
||||
try {
|
||||
return Long.parseLong(input);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new NumberFormatException(String.format("Не могу распознать %s как число", input));
|
||||
}
|
||||
}
|
||||
|
||||
private static Color readColor() throws ColorFormatException {
|
||||
System.out.format("Цвет волос(%s): ", Color.getColorsString());
|
||||
var input = readString();
|
||||
if (input == null || input.isEmpty()) return null;
|
||||
try {
|
||||
return Color.create(Integer.parseInt(input));
|
||||
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
|
||||
try {
|
||||
return Color.create(input);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
throw new ColorFormatException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static UnitOfMeasure readUnitOfMeasure() throws UnitOfMeasureFormatException {
|
||||
System.out.format("Единица измерения(%s): ", UnitOfMeasure.getUnitOfMeasuerString());
|
||||
var input = readString();
|
||||
try {
|
||||
return UnitOfMeasure.create(Integer.parseInt(input));
|
||||
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
|
||||
try {
|
||||
return UnitOfMeasure.create(input);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
throw new ColorFormatException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Location readLocation() throws NumberFormatException {
|
||||
System.out.print("Создать поле Location? (Y/n): ");
|
||||
var input = readString();
|
||||
if (input != null && input.equalsIgnoreCase("n")) return null;
|
||||
System.out.print("Координата x локации: ");
|
||||
var locationX = Float.parseFloat(readString());
|
||||
System.out.print("Координата y локации: ");
|
||||
var locationY = Integer.parseInt(readString());
|
||||
System.out.print("Название: ");
|
||||
var locationName = readString();
|
||||
return new Location(locationX, locationY, locationName);
|
||||
}
|
||||
|
||||
private static void setField(String fieldName, Runnable function) {
|
||||
while (isRunning) {
|
||||
if (fieldName != null) System.out.format("%s: ", fieldName);
|
||||
try {
|
||||
function.run();
|
||||
return;
|
||||
} catch (NullPointerException e) {
|
||||
log("Произошла ошибка при заполнении поля\nПоле не может быть пустым");
|
||||
} catch (Exception e) {
|
||||
System.out.format("Произошла ошибка при заполнении поля%n%s%n", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void setField(Runnable function) {
|
||||
setField(null, function);
|
||||
}
|
||||
|
||||
private static String readField(String message) {
|
||||
System.out.print(message + ": ");
|
||||
return readString();
|
||||
}
|
||||
|
||||
public static ProductDTO readProductDTO() {
|
||||
var productDTO = new ProductDTO();
|
||||
var coordinates = new Coordinates();
|
||||
var owner = new Person();
|
||||
log("Заполните следующие поля: ");
|
||||
|
||||
setField("Название [не может быть пустым]", () -> productDTO.setName(readString()));
|
||||
setField("Координата x [должна быть меньше 884]", () -> coordinates.setX(readLong()));
|
||||
setField("Координата y [должна быть больше -427, не может быть пустой]", () -> coordinates.setY(readLong()));
|
||||
setField("Цена [должна быть больше 0, не может быть пустой]", () -> productDTO.setPrice(readLong()));
|
||||
setField("Номер части [не больше 82 символов, должен быть уникальным]", () -> productDTO.setPartNumber(readString()));
|
||||
setField("Себестоимость [не может быть пустым]", () -> productDTO.setManufactureCost(readLong()));
|
||||
setField(() -> productDTO.setUnitOfMeasure(readUnitOfMeasure()));
|
||||
setField("Имя владельца [не может быть пустым]", () -> owner.setName(readString()));
|
||||
setField("Данные паспорта [длина строки от 5 до 22, не может быть пустым]", () -> owner.setPassportID(readString()));
|
||||
setField(() -> owner.setHairColor(readColor()));
|
||||
setField(() -> owner.setLocation(readLocation()));
|
||||
|
||||
productDTO.setCoordinates(coordinates);
|
||||
productDTO.setOwner(owner);
|
||||
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");
|
||||
} catch (ResponseException | ConnectionErrorException e) {
|
||||
log("Ошибка при подключении\nПопробуйте ещё раз");
|
||||
}
|
||||
}
|
||||
|
||||
log("Добро пожаловать! Для просмотра команд введите help");
|
||||
|
||||
while (isRunning) {
|
||||
System.out.print(":");
|
||||
|
||||
try {
|
||||
var input = scanner.nextLine().trim();
|
||||
var command = client.isLogin() ? MainCommandManager.getCommandByInput(input) : UserCommandManager.getCommandByInput(input);
|
||||
|
||||
if (command.isPresent()) {
|
||||
appendHistory(input);
|
||||
|
||||
try {
|
||||
log(command.get().action(client));
|
||||
} catch (CommandActionException e) {
|
||||
log(e.getMessage());
|
||||
}
|
||||
} else {
|
||||
log("Такой команды не существует. Напишите help, чтобы посмотреть список доступных команд.");
|
||||
}
|
||||
} catch (NoSuchElementException e) {
|
||||
stopAppWithoutSaving();
|
||||
}
|
||||
log();
|
||||
}
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package me.zinch.Lab7.Client.console;
|
||||
|
||||
/**
|
||||
* Represents a shutdown hook that is executed when the application is stopped.
|
||||
*/
|
||||
public class ShutdownHook extends Thread {
|
||||
public ShutdownHook() {
|
||||
super(new Thread(Console::stopAppWithSaving));
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
public class ColorFormatException extends IllegalArgumentException {
|
||||
public ColorFormatException() {
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs during the execution of a command action.
|
||||
@ -0,0 +1,9 @@
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class ConnectionErrorException extends IOException {
|
||||
public ConnectionErrorException() {
|
||||
super("Произошла ошибка при подключении, сервер не доступен");
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@ -9,4 +9,8 @@ public class DbInitializationException extends IOException {
|
||||
public DbInitializationException() {
|
||||
super("Ошибка! Не удалось инициализировать БД. Проверьте, что структура БД верна.");
|
||||
}
|
||||
|
||||
public DbInitializationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.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.
|
||||
@ -0,0 +1,7 @@
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
public class ResponseException extends ClassNotFoundException {
|
||||
public ResponseException() {
|
||||
super("Ошибка при обработке данных от сервера.");
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.exceptions;
|
||||
package me.zinch.Lab7.Client.exceptions;
|
||||
|
||||
public class UnitOfMeasureFormatException extends IllegalArgumentException {
|
||||
public UnitOfMeasureFormatException() {
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.files;
|
||||
package me.zinch.Lab7.Client.files;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.FileInputStream;
|
||||
37
Lab.Domain/pom.xml
Normal file
37
Lab.Domain/pom.xml
Normal file
@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab7-Domain</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.validation</groupId>
|
||||
<artifactId>jakarta.validation-api</artifactId>
|
||||
<version>3.0.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>8.0.1.Final</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@ -1,10 +1,11 @@
|
||||
package me.zinch.exceptions;
|
||||
package me.zinch.Lab7.Domain.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception related to validation errors.
|
||||
*/
|
||||
public class ValidationException extends jakarta.validation.ValidationException {
|
||||
public ValidationException() {}
|
||||
public ValidationException() {
|
||||
}
|
||||
|
||||
public ValidationException(String message) {
|
||||
super(message);
|
||||
@ -1,5 +1,6 @@
|
||||
package me.zinch.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
@ -7,7 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
/**
|
||||
* Represents a color enumeration.
|
||||
*/
|
||||
public enum Color {
|
||||
public enum Color implements Serializable {
|
||||
GREEN("Зелёный"),
|
||||
BLACK("Чёрный"),
|
||||
BLUE("Синий"),
|
||||
@ -20,10 +21,6 @@ public enum Color {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
private String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public static Color create(String input) throws IllegalArgumentException {
|
||||
for (var unit : List.of(Color.values())) {
|
||||
if (unit.getColor().equalsIgnoreCase(input)) return unit;
|
||||
@ -42,6 +39,10 @@ public enum Color {
|
||||
.toList());
|
||||
}
|
||||
|
||||
private String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Color{" +
|
||||
@ -1,32 +1,54 @@
|
||||
package me.zinch.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.Lab7.Domain.exceptions.ValidationException;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Represents coordinates with x and y values.
|
||||
*/
|
||||
public class Coordinates {
|
||||
public class Coordinates implements Serializable {
|
||||
@Max(value = 883, message = "Coordinates: Максимальное значение координаты x: 883")
|
||||
@JsonProperty("x")
|
||||
private long x; //Максимальное значение поля: 883
|
||||
|
||||
@NotNull(message = "Coordinates: Поле не может быть null")
|
||||
@NotNull(message = "Coordinates: Поле y не может быть null")
|
||||
@Min(value = -427, message = "Значение координаты y должно быть больше -427")
|
||||
@JsonProperty("y")
|
||||
private Long y; //Значение поля должно быть больше -427, Поле не может быть null
|
||||
|
||||
public Coordinates() {}
|
||||
public Coordinates() {
|
||||
}
|
||||
|
||||
public Coordinates(long x, Long y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public long getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(long x) {
|
||||
if (x > 883) throw new ValidationException("Максимальное значение координаты x: 883");
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public Long getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(Long y) {
|
||||
if (y == null) throw new ValidationException("Поле y не может быть null");
|
||||
if (y < -427) throw new ValidationException("Значение координаты y должно быть больше -427");
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Coordinates{" +
|
||||
@ -1,15 +1,16 @@
|
||||
package me.zinch.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import me.zinch.validator.NotEmpty;
|
||||
import me.zinch.Lab7.Domain.validator.NotEmpty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Represents a location with x and y coordinates and a name.
|
||||
*/
|
||||
public class Location {
|
||||
public class Location implements Serializable {
|
||||
@JsonProperty("x")
|
||||
private float x;
|
||||
|
||||
@ -21,7 +22,8 @@ public class Location {
|
||||
@JsonProperty("name")
|
||||
private String name; //Строка не может быть пустой, Поле может быть null
|
||||
|
||||
public Location() {}
|
||||
public Location() {
|
||||
}
|
||||
|
||||
public Location(float x, Integer y, String name) {
|
||||
this.x = x;
|
||||
@ -62,4 +64,16 @@ public class Location {
|
||||
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,16 +1,18 @@
|
||||
package me.zinch.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.Lab7.Domain.exceptions.ValidationException;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Represents a person with a name, passport ID, hair color, and location.
|
||||
*/
|
||||
public class Person {
|
||||
public class Person implements Serializable {
|
||||
@NotBlank(message = "Person: Имя персоны не может быть пустым или null")
|
||||
@JsonProperty("name")
|
||||
private String name; //Поле не может быть null, Строка не может быть пустой
|
||||
@ -26,7 +28,8 @@ public class Person {
|
||||
@JsonProperty("location")
|
||||
private Location location; //Поле может быть null
|
||||
|
||||
public Person() {}
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String name, String passportID, Color hairColor, Location location) {
|
||||
this.name = name;
|
||||
@ -36,10 +39,14 @@ public class Person {
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
if (name == null || name.isEmpty()) throw new ValidationException("Имя персоны не может быть пустым или null");
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setPassportID(String passportID) {
|
||||
if (passportID == null) throw new ValidationException("Поле passportID не может быть null");
|
||||
if (passportID.length() < 5 || passportID.length() > 22)
|
||||
throw new ValidationException("Длина строки passportID должна быть не меньше 5 и не должна быть больше 22");
|
||||
this.passportID = passportID;
|
||||
}
|
||||
|
||||
@ -73,4 +80,20 @@ public class Person {
|
||||
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,19 +1,20 @@
|
||||
package me.zinch.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.validator.NotEmpty;
|
||||
import me.zinch.Lab7.Domain.validator.NotEmpty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Represents a product with various attributes such as ID, name, coordinates, creation date, price, part number, manufacture cost, unit of measure, and owner.
|
||||
*/
|
||||
public class Product {
|
||||
public class Product implements Serializable {
|
||||
@NotNull(message = "Product: Поле id не может быть null")
|
||||
@Min(value = 1, message = "Product: Значение поля id должно быть больше 0")
|
||||
@JsonProperty("id")
|
||||
@ -52,18 +53,19 @@ public class Product {
|
||||
@JsonProperty("owner")
|
||||
private Person owner; //Поле не может быть null
|
||||
|
||||
public Product() {}
|
||||
public Product() {
|
||||
}
|
||||
|
||||
public Product (Long id,
|
||||
String name,
|
||||
Coordinates coordinates,
|
||||
ZonedDateTime creationDate,
|
||||
Long price,
|
||||
String partNumber,
|
||||
long manufactureCost,
|
||||
UnitOfMeasure unitOfMeasure,
|
||||
Person owner
|
||||
) {
|
||||
public Product(Long id,
|
||||
String name,
|
||||
Coordinates coordinates,
|
||||
ZonedDateTime creationDate,
|
||||
Long price,
|
||||
String partNumber,
|
||||
long manufactureCost,
|
||||
UnitOfMeasure unitOfMeasure,
|
||||
Person owner
|
||||
) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.coordinates = coordinates;
|
||||
@ -1,20 +1,20 @@
|
||||
package me.zinch.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.Lab7.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Domain.validator.NotEmpty;
|
||||
|
||||
import me.zinch.validator.NotEmpty;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/**
|
||||
* Represents a Data Transfer Object (DTO) for a product with attributes such as name, coordinates, price, part number, manufacture cost, unit of measure, and owner.
|
||||
*/
|
||||
public class ProductDTO {
|
||||
public class ProductDTO implements Serializable {
|
||||
@NotBlank(message = "ProductDTO: Строка name не может быть пустой или null")
|
||||
@JsonProperty("name")
|
||||
private String name; //Поле не может быть null, Строка не может быть пустой
|
||||
@ -24,7 +24,7 @@ public class ProductDTO {
|
||||
private Coordinates coordinates; //Поле не может быть null
|
||||
|
||||
@NotNull(message = "ProductDTO: Поле price не может быть null")
|
||||
@Min(value = 1, message = "Поле price не может быть null")
|
||||
@Min(value = 1, message = "ProductDTO: Значение поля price должно быть больше 0")
|
||||
@JsonProperty("price")
|
||||
private Long price; //Поле не может быть null, Значение поля должно быть больше 0
|
||||
|
||||
@ -44,7 +44,8 @@ public class ProductDTO {
|
||||
@JsonProperty("owner")
|
||||
private Person owner; //Поле не может быть null
|
||||
|
||||
public ProductDTO() {}
|
||||
public ProductDTO() {
|
||||
}
|
||||
|
||||
public ProductDTO(String name, Coordinates coordinates, Long price, String partNumber, long manufactureCost, UnitOfMeasure unitOfMeasure, Person owner) {
|
||||
this.name = name;
|
||||
@ -72,55 +73,63 @@ public class ProductDTO {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
if (name == null || name.isEmpty()) throw new ValidationException("Строка name не может быть пустой или null");
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Coordinates getCoordinates() {
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
public void setCoordinates(Coordinates coordinates) {
|
||||
if (coordinates == null) throw new ValidationException("Поле coordinates не может быть null");
|
||||
this.coordinates = coordinates;
|
||||
}
|
||||
|
||||
public Long getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Long price) {
|
||||
if (price == null) throw new ValidationException("Поле price не может быть null");
|
||||
if (price <= 0) throw new ValidationException("Поле price не может быть null");
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getPartNumber() {
|
||||
return partNumber;
|
||||
}
|
||||
|
||||
public void setPartNumber(String partNumber) {
|
||||
if (partNumber.isEmpty()) throw new ValidationException("Строка partNumber не может быть пустой");
|
||||
if (partNumber.length() > 82) throw new ValidationException("Длина строки partNumber не должна быть больше 82");
|
||||
this.partNumber = partNumber;
|
||||
}
|
||||
|
||||
public long getManufactureCost() {
|
||||
return manufactureCost;
|
||||
}
|
||||
|
||||
public void setManufactureCost(long manufactureCost) {
|
||||
this.manufactureCost = manufactureCost;
|
||||
}
|
||||
|
||||
public UnitOfMeasure getUnitOfMeasure() {
|
||||
return unitOfMeasure;
|
||||
}
|
||||
|
||||
public void setUnitOfMeasure(UnitOfMeasure unitOfMeasure) {
|
||||
if (unitOfMeasure == null) throw new ValidationException("Поле unitOfMeasure не может быть null");
|
||||
this.unitOfMeasure = unitOfMeasure;
|
||||
}
|
||||
|
||||
public Person getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setCoordinates(Coordinates coordinates) {
|
||||
this.coordinates = coordinates;
|
||||
}
|
||||
|
||||
public void setPrice(Long price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public void setPartNumber(String partNumber) {
|
||||
this.partNumber = partNumber;
|
||||
}
|
||||
|
||||
public void setManufactureCost(long manufactureCost) {
|
||||
this.manufactureCost = manufactureCost;
|
||||
}
|
||||
|
||||
public void setUnitOfMeasure(UnitOfMeasure unitOfMeasure) {
|
||||
this.unitOfMeasure = unitOfMeasure;
|
||||
}
|
||||
|
||||
public void setOwner(Person owner) {
|
||||
if (owner == null) throw new ValidationException("Поле owner не может быть null");
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
package me.zinch.models;
|
||||
package me.zinch.Lab7.Domain.models;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
@ -7,7 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
/**
|
||||
* Represents a unit of measure enumeration.
|
||||
*/
|
||||
public enum UnitOfMeasure {
|
||||
public enum UnitOfMeasure implements Serializable {
|
||||
KILOGRAMS("Килограммы"),
|
||||
CENTIMETERS("Сантиметры"),
|
||||
GRAMS("Граммы");
|
||||
@ -18,10 +19,6 @@ public enum UnitOfMeasure {
|
||||
this.unitOfMeasure = unitOfMeasure;
|
||||
}
|
||||
|
||||
public String getUnitOfMeasure() {
|
||||
return unitOfMeasure;
|
||||
}
|
||||
|
||||
public static UnitOfMeasure create(String input) throws IllegalArgumentException {
|
||||
for (var unit : List.of(UnitOfMeasure.values())) {
|
||||
if (unit.getUnitOfMeasure().equalsIgnoreCase(input)) return unit;
|
||||
@ -40,6 +37,9 @@ public enum UnitOfMeasure {
|
||||
.toList());
|
||||
}
|
||||
|
||||
public String getUnitOfMeasure() {
|
||||
return unitOfMeasure;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
@ -0,0 +1,16 @@
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class BodyfulMessage extends Message {
|
||||
public BodyfulMessage(MessageType type, String command, Serializable body) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
public class BodylessMessage extends Message {
|
||||
public BodylessMessage(MessageType type) {
|
||||
this.setType(type);
|
||||
}
|
||||
|
||||
public BodylessMessage(MessageType type, String command) {
|
||||
this.setType(type);
|
||||
this.setBody(command);
|
||||
}
|
||||
|
||||
public BodylessMessage(MessageType type, String command, User user) {
|
||||
this.setType(type);
|
||||
this.setBody(command);
|
||||
this.setUser(user);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
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;
|
||||
}
|
||||
|
||||
public final void setType(MessageType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public final Object getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public final void setBody(Serializable body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Serializable getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(Serializable user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Message{" +
|
||||
"type=" + type +
|
||||
", body=" + body +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class MessageBody implements Serializable {
|
||||
private String command;
|
||||
private Serializable body;
|
||||
|
||||
public MessageBody(String command, Serializable body) {
|
||||
this.command = command;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public String getCommand() {
|
||||
return command;
|
||||
}
|
||||
|
||||
public void setCommand(String command) {
|
||||
this.command = command;
|
||||
}
|
||||
|
||||
public Serializable getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(Serializable body) {
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public enum MessageType implements Serializable {
|
||||
GET,
|
||||
POST,
|
||||
ERROR,
|
||||
OK,
|
||||
HELLO
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package me.zinch.Lab7.Domain.net;
|
||||
|
||||
import me.zinch.Lab7.Domain.models.ProductDTO;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class UpdateBody implements Serializable {
|
||||
private Long id;
|
||||
private ProductDTO productDTO;
|
||||
|
||||
public UpdateBody(Long id, ProductDTO productDTO) {
|
||||
this.id = id;
|
||||
this.productDTO = productDTO;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public ProductDTO getProductDTO() {
|
||||
return productDTO;
|
||||
}
|
||||
|
||||
public void setProductDTO(ProductDTO productDTO) {
|
||||
this.productDTO = productDTO;
|
||||
}
|
||||
}
|
||||
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.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
@ -16,6 +16,8 @@ import java.lang.annotation.Target;
|
||||
@Constraint(validatedBy = NotEmptyValidator.class)
|
||||
public @interface NotEmpty {
|
||||
String message() default "Value must not be blank";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
@ -1,12 +1,13 @@
|
||||
package me.zinch.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.ValidationException;
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Represents the result of a validation process.
|
||||
*
|
||||
* @param <T> the type of object being validated
|
||||
*/
|
||||
public class ValidateResult<T> {
|
||||
@ -1,12 +1,13 @@
|
||||
package me.zinch.validator;
|
||||
package me.zinch.Lab7.Domain.validator;
|
||||
|
||||
import jakarta.validation.Validation;
|
||||
import jakarta.validation.Validator;
|
||||
import jakarta.validation.ValidatorFactory;
|
||||
import me.zinch.models.Product;
|
||||
import me.zinch.Lab7.Domain.models.Product;
|
||||
import org.hibernate.validator.HibernateValidator;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
@ -30,7 +31,7 @@ public class Validators {
|
||||
|
||||
public static List<ValidateResult<Product>> validateProductList(List<Product> db) {
|
||||
var ids = db.stream().map(Product::getId).toList();
|
||||
var partNumbers = db.stream().map(Product::getPartNumber).toList();
|
||||
var partNumbers = db.stream().map(Product::getPartNumber).filter(Objects::nonNull).toList();
|
||||
var validations = new java.util.ArrayList<>(db.stream().map(Validators::validateObject).toList());
|
||||
if (ids.size() != Set.copyOf(ids).size()) {
|
||||
validations.add(new ValidateResult<>("Поле id должно быть уникальным"));
|
||||
106
Lab.Server/pom.xml
Normal file
106
Lab.Server/pom.xml
Normal file
@ -0,0 +1,106 @@
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab7-Server</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Lab7-Server</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>2.17.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>8.0.1.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
<artifactId>jakarta.el</artifactId>
|
||||
<version>5.0.0-M1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.5.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-core</artifactId>
|
||||
<version>1.5.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>2.0.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.zinch</groupId>
|
||||
<artifactId>Lab7-Domain</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jline</groupId>
|
||||
<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>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<version>3.7.1</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>me.zinch.Lab7.Server.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
23
Lab.Server/src/main/java/me/zinch/Lab7/Server/App.java
Normal file
23
Lab.Server/src/main/java/me/zinch/Lab7/Server/App.java
Normal file
@ -0,0 +1,23 @@
|
||||
package me.zinch.Lab7.Server;
|
||||
|
||||
import me.zinch.Lab7.Server.console.Console;
|
||||
import me.zinch.Lab7.Server.exceptions.DbConnectionException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Main class for running the application.
|
||||
*/
|
||||
public class App {
|
||||
private static final Logger log = LoggerFactory.getLogger(App.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
Console.run();
|
||||
} catch (IOException | DbConnectionException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* The Add class represents a command to add a new element to a collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class Add extends PostCommand {
|
||||
public Add() {
|
||||
super("add {element}", "добавить новый элемент в коллекцию", Pattern.compile("^add"));
|
||||
}
|
||||
|
||||
@Override
|
||||
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, user);
|
||||
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
|
||||
} catch (ValidationException | SQLException e) {
|
||||
throw new CommandActionException(String.format("Произошла ошибка при добавлении%n%s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* The AddIfMax class represents a command to add a new element to a collection if its price value exceeds the maximum price value in the collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class AddIfMax extends PostCommand {
|
||||
public AddIfMax() {
|
||||
super("add_if_max {element}", "добавить новый элемент в коллекцию, если его значение цены превышает значение наибольшей цены этой коллекции", Pattern.compile("^add_if_max"));
|
||||
}
|
||||
|
||||
@Override
|
||||
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, user);
|
||||
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
|
||||
}
|
||||
return "Продукт не подходит под условие";
|
||||
} catch (ValidationException | SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* The AddIfMin class represents a command to add a new element to a collection if its price is lower than the lowest price in the collection.
|
||||
* It extends the Command class.
|
||||
*/
|
||||
public class AddIfMin extends PostCommand {
|
||||
public AddIfMin() {
|
||||
super("add_if_min {element}", "добавить новый элемент в коллекцию, если его значение цены меньше, чем у наименьшей цены этой коллекции", Pattern.compile("^add_if_min"));
|
||||
}
|
||||
|
||||
@Override
|
||||
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, user);
|
||||
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
|
||||
}
|
||||
return "Продукт не подходит под условие";
|
||||
} catch (ValidationException | SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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,7 +1,4 @@
|
||||
package me.zinch.commands;
|
||||
|
||||
import me.zinch.exceptions.CommandActionException;
|
||||
import me.zinch.wrapper.ProductCollection;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -40,6 +37,4 @@ public abstract class Command {
|
||||
public final boolean checkPattern(String input) {
|
||||
return pattern.matcher(input).matches();
|
||||
}
|
||||
|
||||
public abstract String action(ProductCollection productCollection) throws CommandActionException;
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package me.zinch.commands;
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@ -10,21 +10,6 @@ import java.util.Optional;
|
||||
public class CommandManager {
|
||||
private static final List<Command> commandList = new ArrayList<>();
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
static {
|
||||
registerCommand(new Show());
|
||||
registerCommand(new Exit());
|
||||
@ -34,14 +19,25 @@ public class CommandManager {
|
||||
registerCommand(new PrintUniqueManufactureCost());
|
||||
registerCommand(new FilterContainsName());
|
||||
registerCommand(new Add());
|
||||
registerCommand(new IsIdExists());
|
||||
registerCommand(new Update());
|
||||
registerCommand(new Remove());
|
||||
registerCommand(new AddIfMax());
|
||||
registerCommand(new AddIfMin());
|
||||
registerCommand(new RemoveLower());
|
||||
registerCommand(new Save());
|
||||
registerCommand(new ExecuteScript());
|
||||
registerCommand(new GetProduct());
|
||||
registerCommand(new Login());
|
||||
registerCommand(new Register());
|
||||
registerCommand(new CheckProductOwner());
|
||||
|
||||
registerCommand(new Help());
|
||||
}
|
||||
|
||||
public static void registerCommand(Command command) {
|
||||
commandList.add(command);
|
||||
}
|
||||
|
||||
public static Optional<Command> getCommandByInput(String input) {
|
||||
return commandList.stream().filter(command -> command.checkPattern(input)).findFirst();
|
||||
}
|
||||
}
|
||||
@ -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 "";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to filter elements whose 'name' field contains the specified substring.
|
||||
*/
|
||||
public class FilterContainsName extends PostCommand {
|
||||
public FilterContainsName() {
|
||||
super("filter_contains_name name", "вывести элементы, значение поля name которых содержит заданную подстроку", Pattern.compile("^filter_contains_name .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object, User user) {
|
||||
String name = object.toString();
|
||||
var result = productCollection.filterContainsName(name);
|
||||
return result.isEmpty() ? "Таких элементов не найдено" : result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
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.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public abstract class GetCommand extends Command {
|
||||
public GetCommand(String name, String description, Pattern pattern) {
|
||||
super(name, description, pattern);
|
||||
}
|
||||
|
||||
public GetCommand(String name, String description) {
|
||||
super(name, description);
|
||||
}
|
||||
|
||||
public abstract String action(IStorage productCollection, User user) throws CommandActionException;
|
||||
}
|
||||
@ -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.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class GetProduct extends PostCommand {
|
||||
public GetProduct() {
|
||||
super("get_product_by_id", "", Pattern.compile("^get_product_by_id +."));
|
||||
}
|
||||
|
||||
@Override
|
||||
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();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* A command to display help for available commands.
|
||||
*/
|
||||
public class Help extends GetCommand {
|
||||
public Help() {
|
||||
super("help", "display help for available commands");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
return SystemCommandManager.getRegisteredCommand();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
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.
|
||||
*/
|
||||
public class Info extends GetCommand {
|
||||
public Info() {
|
||||
super("info", "вывести в стандартный поток вывода информацию о коллекции (тип, дата инициализации, количество элементов и т.д.)");
|
||||
}
|
||||
|
||||
@Override
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class IsIdExists extends PostCommand {
|
||||
public IsIdExists() {
|
||||
super("is_id_exists", "", Pattern.compile("^is_id_exists +."));
|
||||
}
|
||||
|
||||
@Override
|
||||
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 UnauthorizedCommand {
|
||||
public Login() {
|
||||
super("login", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action( Object obj) 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
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.exceptions.CommandActionException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public abstract class PostCommand extends Command {
|
||||
public PostCommand(String name, String description, Pattern pattern) {
|
||||
super(name, description, pattern);
|
||||
}
|
||||
|
||||
public PostCommand(String name, String description) {
|
||||
super(name, description);
|
||||
}
|
||||
|
||||
public abstract String action(IStorage productCollection, Object obj, User user) throws CommandActionException;
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
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.
|
||||
*/
|
||||
public class PrintAscending extends GetCommand {
|
||||
public PrintAscending() {
|
||||
super("print_ascending", "вывести элементы коллекции в порядке возрастания");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
var result = productCollection.toString();
|
||||
return result.isEmpty() ? "Коллекция пуста" : result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
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.
|
||||
*/
|
||||
public class PrintUniqueManufactureCost extends GetCommand {
|
||||
public PrintUniqueManufactureCost() {
|
||||
super("print_unique_manufacture_cost", "вывести уникальные значения поля manufactureCost всех элементов в коллекции");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
var result = productCollection.getUniqueManufactureCost();
|
||||
return result.isEmpty() ? "Коллекция пуста" : result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
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 UnauthorizedCommand {
|
||||
public Register() {
|
||||
super("register", "");
|
||||
}
|
||||
|
||||
public String action(Object obj) 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("Пользователь уже существует");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
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.exceptions.CommandActionException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to remove an element from the collection by its id.
|
||||
*/
|
||||
public class Remove extends PostCommand {
|
||||
public Remove() {
|
||||
super("remove_by_id id", "удалить элемент из коллекции по его id", Pattern.compile("^remove_by_id .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
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, user);
|
||||
return String.format("Продукт %s был удалён", product.getName());
|
||||
}
|
||||
return "Продукта с таким id не существует";
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
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;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A command to remove all elements from the collection that have ids lower than the specified id.
|
||||
*/
|
||||
public class RemoveLower extends PostCommand {
|
||||
public RemoveLower() {
|
||||
super("remove_lower id", "удалить из коллекции все элементы, меньшие, чем заданный по id", Pattern.compile("^remove_lower .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object, User user) {
|
||||
try {
|
||||
Long id = (Long) object;
|
||||
var size = productCollection.removeLover(id, user);
|
||||
return String.format("Было удалено %d продуктов", size);
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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 Seed extends GetCommand{
|
||||
public Seed() {
|
||||
super("seed", "Seed data");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) throws CommandActionException {
|
||||
DbWrapper.seedDb();
|
||||
return "Seeded 🌿";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* A command to display all elements of the collection in string representation to the standard output stream.
|
||||
*/
|
||||
public class Show extends GetCommand {
|
||||
public Show() {
|
||||
super("show", "вывести в стандартный поток вывода все элементы коллекции в строковом представлении");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
var result = productCollection.toString();
|
||||
return result.isEmpty() ? "Коллекция пуста" : result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Manages the registration and retrieval of commands.
|
||||
*/
|
||||
public class SystemCommandManager {
|
||||
private static final List<Command> commandList = new ArrayList<>();
|
||||
|
||||
static {
|
||||
registerCommand(new Exit());
|
||||
registerCommand(new Drop());
|
||||
registerCommand(new Init());
|
||||
registerCommand(new Seed());
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
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.util.regex.Pattern;
|
||||
|
||||
public abstract class UnauthorizedCommand extends Command {
|
||||
public UnauthorizedCommand(String name, String description, Pattern pattern) {
|
||||
super(name, description, pattern);
|
||||
}
|
||||
|
||||
public UnauthorizedCommand(String name, String description) {
|
||||
super(name, description);
|
||||
}
|
||||
|
||||
public abstract String action(Object obj) throws CommandActionException;
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.User;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
|
||||
/**
|
||||
* Represents an unknown command.
|
||||
*/
|
||||
public class UnknownCommand extends GetCommand {
|
||||
public UnknownCommand() {
|
||||
super("", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, User user) {
|
||||
return "Команда не распознана.";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package me.zinch.Lab7.Server.commands;
|
||||
|
||||
import me.zinch.Lab7.Domain.net.MessageBody;
|
||||
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;
|
||||
|
||||
/**
|
||||
* A command to update the value of an element in the collection, whose id is specified.
|
||||
*/
|
||||
public class Update extends PostCommand {
|
||||
public Update() {
|
||||
super("update id {element}", "обновить значение элемента коллекции, id которого равен заданному", Pattern.compile("^update .+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String action(IStorage productCollection, Object object, User user) throws CommandActionException {
|
||||
try {
|
||||
var body = (MessageBody) object;
|
||||
var id = Long.parseLong(body.getCommand().split(" ")[1]);
|
||||
if (productCollection.isProductIdExists(id)) {
|
||||
var productDTO = (ProductDTO) body.getBody();
|
||||
try {
|
||||
Validators.validateObject(productDTO).throwIfNotValid();
|
||||
var product = productCollection.updateProduct(id, productDTO, user);
|
||||
return String.format("Продукт %s был изменён", product.getName());
|
||||
} catch (ValidationException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
return "Продукта с таким id не существует";
|
||||
} catch (NumberFormatException e) {
|
||||
return "Неверный аргумент, id может быть только число";
|
||||
} catch (SQLException e) {
|
||||
throw new CommandActionException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
package me.zinch.Lab7.Server.configs;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
public class ServerConfig {
|
||||
private static final Logger log = LoggerFactory.getLogger(ServerConfig.class);
|
||||
private static final Properties properties = new Properties();
|
||||
|
||||
static {
|
||||
var settingsFile = new File("server.properties");
|
||||
if (settingsFile.isFile() && settingsFile.exists()) {
|
||||
try {
|
||||
properties.load(new FileReader(settingsFile));
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
} else {
|
||||
var classLoader = ServerConfig.class.getClassLoader();
|
||||
try (var inputStream = classLoader.getResourceAsStream("server.properties")) {
|
||||
properties.load(inputStream);
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int getPort() {
|
||||
return Integer.parseInt(properties.getProperty("server-port", "3000"));
|
||||
}
|
||||
|
||||
public static String getDbHost() {
|
||||
return properties.getProperty("db-host", "localhost");
|
||||
}
|
||||
|
||||
public static int getDbPort() {
|
||||
return Integer.parseInt(properties.getProperty("db-port", "5432"));
|
||||
}
|
||||
|
||||
public static String getDbName() {
|
||||
return properties.getProperty("db-name", "studs");
|
||||
}
|
||||
|
||||
public static String getDbScheme() {
|
||||
return properties.getProperty("db-scheme", "s408657");
|
||||
}
|
||||
|
||||
public static String getDbUsername() {
|
||||
return properties.getProperty("db-username", "postgres");
|
||||
}
|
||||
|
||||
public static String getDbPassword() {
|
||||
return properties.getProperty("db-password", "postgres");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,92 @@
|
||||
package me.zinch.Lab7.Server.console;
|
||||
|
||||
import me.zinch.Lab7.Domain.exceptions.ValidationException;
|
||||
import me.zinch.Lab7.Server.wrapper.IStorage;
|
||||
import me.zinch.Lab7.Server.server.ServerBuilder;
|
||||
import me.zinch.Lab7.Server.commands.GetCommand;
|
||||
import me.zinch.Lab7.Server.commands.SystemCommandManager;
|
||||
import me.zinch.Lab7.Server.configs.ServerConfig;
|
||||
import me.zinch.Lab7.Server.exceptions.CommandActionException;
|
||||
import me.zinch.Lab7.Server.db.DbController;
|
||||
import me.zinch.Lab7.Server.exceptions.DbConnectionException;
|
||||
import me.zinch.Lab7.Server.wrapper.DbInitializer;
|
||||
import me.zinch.Lab7.Server.wrapper.ProductCollection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Console class provides methods for interacting with the console, reading user input, and managing application flow.
|
||||
* This class includes methods for appending input history, stopping the application, reading product DTO from the console, and running the application loop.
|
||||
*/
|
||||
public class Console {
|
||||
private static final Scanner scanner = new Scanner(System.in);
|
||||
private static final Logger log = LoggerFactory.getLogger(Console.class);
|
||||
private static boolean isRunning = true;
|
||||
private static boolean isExitMessageShowed = false;
|
||||
private static IStorage collection;
|
||||
|
||||
public static void stopApp() {
|
||||
showExitMessage();
|
||||
isRunning = false;
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
public static void showExitMessage() {
|
||||
if (!isExitMessageShowed) log.info("Have a nice day!");
|
||||
isExitMessageShowed = true;
|
||||
}
|
||||
|
||||
public static void run() throws IOException, ValidationException, DbConnectionException {
|
||||
DbController.initConnection();
|
||||
DbInitializer.initializeDb(DbController.getConnection());
|
||||
|
||||
collection = new ProductCollection(DbController.getConnection());
|
||||
|
||||
var server = new ServerBuilder()
|
||||
.setPort(ServerConfig.getPort())
|
||||
.setCollection(collection)
|
||||
.build();
|
||||
|
||||
Console.handleInput();
|
||||
|
||||
server.run();
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
Console.stopApp();
|
||||
try {
|
||||
server.stop();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public static void handleInput() {
|
||||
new Thread(() -> {
|
||||
while (isRunning) {
|
||||
try {
|
||||
var input = scanner.nextLine().trim();
|
||||
var command = SystemCommandManager.getCommandByInput(input);
|
||||
|
||||
if (command.isPresent()) {
|
||||
var action = (GetCommand) command.get();
|
||||
try {
|
||||
System.out.println(action.action(collection, null));
|
||||
} catch (CommandActionException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
} else {
|
||||
System.out.println("This command does not exist. Write help to see a list of available commands.");
|
||||
}
|
||||
} catch (NoSuchElementException e) {
|
||||
stopApp();
|
||||
}
|
||||
}
|
||||
scanner.close();
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,10 @@
|
||||
package me.zinch.console;
|
||||
package me.zinch.Lab7.Server.console;
|
||||
|
||||
/**
|
||||
* Represents a shutdown hook that is executed when the application is stopped.
|
||||
*/
|
||||
public class ShutdownHook extends Thread {
|
||||
public ShutdownHook() {
|
||||
super(new Thread(Console::stopApp));
|
||||
super();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
package me.zinch.Lab7.Server.db;
|
||||
|
||||
import me.zinch.Lab7.Server.configs.ServerConfig;
|
||||
import me.zinch.Lab7.Server.exceptions.DbConnectionException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* The DbController class provides methods for loading and saving product data to a database file.
|
||||
*/
|
||||
public class DbController {
|
||||
private static final Logger log = LoggerFactory.getLogger(DbController.class);
|
||||
private static Connection connection;
|
||||
|
||||
public static void initConnection() throws DbConnectionException {
|
||||
var url = String.format("jdbc:postgresql://%s:%s/%s?currentSchema=%s",
|
||||
ServerConfig.getDbHost(),
|
||||
ServerConfig.getDbPort(),
|
||||
ServerConfig.getDbName(),
|
||||
ServerConfig.getDbScheme());
|
||||
var props = new Properties();
|
||||
props.setProperty("user", ServerConfig.getDbUsername());
|
||||
props.setProperty("password", ServerConfig.getDbPassword());
|
||||
try {
|
||||
connection = DriverManager.getConnection(url, props);
|
||||
log.info("Connection to the database has been successfully established");
|
||||
} catch (SQLException e) {
|
||||
log.error(e.getMessage());
|
||||
throw new DbConnectionException("Failed to connect to the database");
|
||||
}
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws DbConnectionException {
|
||||
if (connection == null) initConnection();
|
||||
return connection;
|
||||
}
|
||||
|
||||
public static void closeConnection() throws DbConnectionException {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException e) {
|
||||
log.error(e.getMessage());
|
||||
throw new DbConnectionException("Failed to close the connection to the database");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package me.zinch.Lab7.Server.exceptions;
|
||||
|
||||
public class ColorFormatException extends IllegalArgumentException {
|
||||
public ColorFormatException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ColorFormatException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Server.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs during the execution of a command action.
|
||||
*/
|
||||
public class CommandActionException extends RuntimeException {
|
||||
public CommandActionException() {
|
||||
super("Ошибка во время выполнения команды");
|
||||
}
|
||||
|
||||
public CommandActionException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public CommandActionException(Throwable e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package me.zinch.Lab7.Server.exceptions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs when the database initialization fails.
|
||||
*/
|
||||
public class DbConnectionException extends SQLException {
|
||||
public DbConnectionException() {
|
||||
super("Failed to connect to the database");
|
||||
}
|
||||
|
||||
public DbConnectionException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package me.zinch.Lab7.Server.exceptions;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DbExecuteException extends SQLException {
|
||||
public DbExecuteException() {
|
||||
super("Error during sql command execution");
|
||||
}
|
||||
|
||||
public DbExecuteException(String reason) {
|
||||
super(reason);
|
||||
}
|
||||
|
||||
public DbExecuteException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package me.zinch.Lab7.Server.exceptions;
|
||||
|
||||
/**
|
||||
* Represents an exception that occurs when an illegal product DTO is encountered during the creation or modification of a product.
|
||||
*/
|
||||
public class IllegalProductDtoException extends CommandActionException {
|
||||
public IllegalProductDtoException() {
|
||||
super("Ошибка при создании или изменении продукта. Были введены некорректные значения.");
|
||||
}
|
||||
|
||||
public IllegalProductDtoException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public IllegalProductDtoException(Throwable e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user