Ah shit. Here we go again.
This commit is contained in:
+45
@@ -0,0 +1,45 @@
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/modules.xml
|
||||
.idea/jarRepositories.xml
|
||||
.idea/compiler.xml
|
||||
.idea/libraries/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Kotlin ###
|
||||
.kotlin
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
Generated
+10
@@ -0,0 +1,10 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Environment-dependent path to Maven home directory
|
||||
/mavenHomeManager.xml
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
+20
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleHome" value="" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/client" />
|
||||
<option value="$PROJECT_DIR$/common" />
|
||||
<option value="$PROJECT_DIR$/server" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="2.2.0" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="FrameworkDetectionExcludesConfiguration">
|
||||
<file type="web" url="file://$PROJECT_DIR$" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="corretto-17" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,22 @@
|
||||
plugins {
|
||||
id 'org.jetbrains.kotlin.jvm' version '2.2.0'
|
||||
id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.0'
|
||||
id 'com.gradleup.shadow' version '9.3.1'
|
||||
id 'org.jetbrains.dokka' version '2.2.0'
|
||||
}
|
||||
|
||||
group = 'lab6.prog'
|
||||
version = '1.0'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation 'org.jetbrains.kotlin:kotlin-test'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0'
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
plugins {
|
||||
id 'org.jetbrains.kotlin.jvm' version '2.2.0'
|
||||
id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.0'
|
||||
id 'com.gradleup.shadow' version '9.3.1'
|
||||
id 'org.jetbrains.dokka' version '2.2.0'
|
||||
}
|
||||
|
||||
group = 'lab6.prog'
|
||||
version = '1.0'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
shadowJar {
|
||||
archiveBaseName.set('Lab6-client')
|
||||
archiveVersion.set('1.0')
|
||||
manifest {
|
||||
attributes 'Main-Class': 'MainKt'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation 'org.jetbrains.kotlin:kotlin-test'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0'
|
||||
implementation "io.ktor:ktor-network:3.4.2"
|
||||
implementation project(':common')
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import network.NetworkManager
|
||||
import input.HumanBeingBuilder
|
||||
import input.IOManager
|
||||
import network.Request
|
||||
|
||||
|
||||
// BEGIN ---- Move it to CommandValidator
|
||||
|
||||
// Команды, которые требуют ввода HumanBeing
|
||||
private val HUMAN_BEING_COMMANDS = setOf("add", "add_if_max", "add_if_min")
|
||||
|
||||
// Команды с аргументом (UUID) в строке команды
|
||||
private val ARG_COMMANDS = setOf("update", "remove_by_id", "execute_script")
|
||||
|
||||
// Все команды, доступные клиенту (save — только серверная)
|
||||
private val KNOWN_COMMANDS = setOf(
|
||||
"help", "info", "show", "add", "update",
|
||||
"remove_by_id", "clear", "execute_script",
|
||||
"add_if_max", "add_if_min", "history",
|
||||
"sum_of_minutes_of_waiting", "min_by_name",
|
||||
"print_field_descending_minutes_of_waiting",
|
||||
"exit"
|
||||
)
|
||||
|
||||
// END ---- Move it to CommandValidator
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val host = if (args.isNotEmpty()) args[0] else "localhost"
|
||||
val port = if (args.size >= 2) args[1].toIntOrNull() ?: 8080 else 8080
|
||||
|
||||
val io = IOManager()
|
||||
val client = NetworkManager(host, port)
|
||||
|
||||
io.print("""
|
||||
|╔══════════════════════════════════════╗
|
||||
|║ Lab6 Client — подключение к $host:$port
|
||||
|╚══════════════════════════════════════╝
|
||||
|Введите 'help' для справки.
|
||||
""".trimMargin())
|
||||
|
||||
// Shutdown hook — закрыть канал при выходе
|
||||
Runtime.getRuntime().addShutdownHook(Thread {
|
||||
client.close()
|
||||
})
|
||||
|
||||
runClientRepl(io, client)
|
||||
}
|
||||
|
||||
fun runClientRepl(io: IOManager, client: NetworkManager) {
|
||||
while (true) {
|
||||
val line = io.readLine(" ☭ ") ?: break
|
||||
if (line.isBlank()) continue
|
||||
|
||||
val parts = line.trim().split(" ")
|
||||
val commandName = parts[0].lowercase()
|
||||
val args = parts.drop(1)
|
||||
|
||||
// Move to CommandValidate
|
||||
if (commandName !in KNOWN_COMMANDS) {
|
||||
io.print("Неизвестная команда: '$commandName'. Введите 'help' для справки.")
|
||||
continue
|
||||
}
|
||||
|
||||
if (commandName == "exit") {
|
||||
io.print("До свидания!")
|
||||
break
|
||||
}
|
||||
|
||||
// In the event of using fucking script (don't)
|
||||
if (commandName == "execute_script") {
|
||||
if (args.isEmpty()) {
|
||||
io.print("[Ошибка] Укажите путь к файлу. Пример: execute_script script.txt")
|
||||
continue
|
||||
}
|
||||
io.addScriptScanner(args[0])
|
||||
continue
|
||||
}
|
||||
|
||||
// MOVE TO FUCKING VALIDATE
|
||||
// 4. Для update — нужен UUID аргумент ДО ввода HumanBeing
|
||||
if (commandName == "update" && args.isEmpty()) {
|
||||
io.print("[Ошибка] Укажите id элемента. Пример: update <uuid>")
|
||||
continue
|
||||
}
|
||||
|
||||
// 5. Строим HumanBeing если нужно
|
||||
val humanBeing = if (commandName in HUMAN_BEING_COMMANDS ||
|
||||
commandName == "update") {
|
||||
try {
|
||||
HumanBeingBuilder(io).build()
|
||||
} catch (e: IllegalStateException) {
|
||||
io.print("[Ошибка] Ввод прерван: ${e.message}")
|
||||
continue
|
||||
}
|
||||
} else null
|
||||
|
||||
// 6. Формируем запрос и отправляем
|
||||
val request = Request(
|
||||
commandName = commandName,
|
||||
args = args,
|
||||
humanBeing = humanBeing
|
||||
)
|
||||
|
||||
val response = client.sendRequest(request)
|
||||
|
||||
// 7. Обрабатываем ответ
|
||||
if (response == null) {
|
||||
io.print("[!] Сервер недоступен. Попробуйте позже.")
|
||||
} else {
|
||||
io.print(response.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package input
|
||||
|
||||
import models.Car
|
||||
import models.Coordinates
|
||||
import models.HumanBeing
|
||||
import models.WeaponType
|
||||
|
||||
/**
|
||||
* Интерактивный построитель объекта [HumanBeing].
|
||||
*
|
||||
* Читает поля по одному из [inputManager], показывает приглашения,
|
||||
* валидирует ввод и повторяет запрос при ошибке.
|
||||
*
|
||||
* Поля [HumanBeing.id] и [HumanBeing.creationDate] генерируются
|
||||
* автоматически и не запрашиваются у пользователя.
|
||||
*
|
||||
* @property inputManager источник ввода
|
||||
*/
|
||||
class HumanBeingBuilder(private val inputManager: IOManager) {
|
||||
|
||||
/**
|
||||
* Запускает интерактивный ввод всех полей и возвращает готовый [HumanBeing].
|
||||
*
|
||||
* @throws IllegalStateException если EOF
|
||||
*/
|
||||
fun build(): HumanBeing {
|
||||
val name = readNonBlankString("Введите имя:")
|
||||
val coordinates = readCoordinates()
|
||||
val realHero = readBoolean("Герой? (true/false):")
|
||||
val hasToothpick = readBoolean("Есть зубочистка? (true/false):")
|
||||
val impactSpeed = readDouble("Введите скорость удара (impactSpeed):")
|
||||
val soundtrackName = readNonBlankString("Введите название саундтрека:")
|
||||
val minutesOfWaiting = readFloat("Введите минуты ожидания (minutesOfWaiting):")
|
||||
val weaponType = readNullableWeaponType()
|
||||
val car = readCar()
|
||||
|
||||
return HumanBeing(
|
||||
name = name, coordinates = coordinates, realHero = realHero,
|
||||
hasToothpick = hasToothpick, impactSpeed = impactSpeed,
|
||||
soundtrackName = soundtrackName, minutesOfWaiting = minutesOfWaiting,
|
||||
weaponType = weaponType, car = car
|
||||
)
|
||||
}
|
||||
|
||||
private fun readCoordinates(): Coordinates {
|
||||
val x = readLong("Введите координату X (тип Long):")
|
||||
val y = readInt("Введите координату Y (тип Int):")
|
||||
return Coordinates(x, y)
|
||||
}
|
||||
|
||||
private fun readCar(): Car {
|
||||
val cool = readBoolean("Крутой автомобиль ? (true/false):")
|
||||
return Car(cool)
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает непустую строку. Повторяет запрос при пустом вводе.
|
||||
*/
|
||||
private fun readNonBlankString(prompt: String): String {
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > $prompt")
|
||||
?: throw IllegalStateException("EOF")
|
||||
if (input.isNotBlank()) return input.trim()
|
||||
inputManager.print("[Ошибка] Строка не может быть пустой.")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает Long. Повторяет запрос при некорректном вводе.
|
||||
*/
|
||||
private fun readLong(prompt: String): Long {
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > $prompt")
|
||||
?: throw IllegalStateException("EOF")
|
||||
try {
|
||||
return input.trim().toLong()
|
||||
} catch (e: NumberFormatException) {
|
||||
inputManager.print("[Ошибка] Ожидается целое число (Long). Попробуйте снова.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает Int. Повторяет запрос при некорректном вводе.
|
||||
*/
|
||||
private fun readInt(prompt: String): Int {
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > $prompt")
|
||||
?: throw IllegalStateException("EOF")
|
||||
try {
|
||||
return input.trim().toInt()
|
||||
} catch (e: NumberFormatException) {
|
||||
inputManager.print("[Ошибка] Ожидается целое число (Int). Попробуйте снова.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает Double. Повторяет запрос при некорректном вводе.
|
||||
*/
|
||||
private fun readDouble(prompt: String): Double {
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > $prompt")
|
||||
?: throw IllegalStateException("EOF")
|
||||
try {
|
||||
return input.trim().toDouble()
|
||||
} catch (e: NumberFormatException) {
|
||||
inputManager.print("[Ошибка] Ожидается число с плавающей точкой (Double). Попробуйте снова.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает Float. Повторяет запрос при некорректном вводе.
|
||||
*/
|
||||
private fun readFloat(prompt: String): Float {
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > $prompt")
|
||||
?: throw IllegalStateException("EOF")
|
||||
try {
|
||||
return input.trim().toFloat()
|
||||
} catch (e: NumberFormatException) {
|
||||
inputManager.print("[Ошибка] Ожидается число (Float). Попробуйте снова.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает Boolean (true/false). Повторяет запрос при некорректном вводе.
|
||||
*/
|
||||
private fun readBoolean(prompt: String): Boolean {
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > $prompt")
|
||||
?: throw IllegalStateException("EOF")
|
||||
when (input.trim().lowercase()) {
|
||||
"true" -> return true
|
||||
"false" -> return false
|
||||
else -> inputManager.print("[Ошибка] Ожидается 'true' или 'false'. Попробуйте снова.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает [WeaponType] или null (пустая строка).
|
||||
* Перед вводом выводит список допустимых констант.
|
||||
*/
|
||||
private fun readNullableWeaponType(): WeaponType? {
|
||||
val constants = WeaponType.entries.joinToString(", ")
|
||||
while (true) {
|
||||
val input = inputManager.readLine(" > Введите тип оружия (доступные: $constants) или оставьте пустым для null:")
|
||||
?: throw IllegalStateException("EOF")
|
||||
if (input.isBlank()) return null
|
||||
try {
|
||||
return WeaponType.valueOf(input.trim().uppercase())
|
||||
} catch (e: IllegalArgumentException) {
|
||||
inputManager.print("[Ошибка] Неизвестный тип оружия '$input'. Допустимые значения: $constants")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выводит приглашение к вводу только в интерактивном режиме.
|
||||
* В режиме скрипта приглашения не выводятся.
|
||||
*/
|
||||
private fun printPrompt(message: String) {
|
||||
if (inputManager.isInteractive) inputManager.print(" > $message ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package input
|
||||
|
||||
import java.io.File
|
||||
import java.io.FileNotFoundException
|
||||
import java.util.ArrayDeque
|
||||
import java.util.Scanner
|
||||
|
||||
/**
|
||||
* Реализация [input.IOManager] для чтения потока ввода/файла.
|
||||
* Поддерживает корректную обработку Ctrl+C и Ctrl+D.
|
||||
*/
|
||||
class IOManager() {
|
||||
val isInteractive = true
|
||||
val inputQueue = ArrayDeque<Scanner>()
|
||||
val fileHistory = ArrayDeque<String>()
|
||||
|
||||
init {
|
||||
inputQueue.push(Scanner(System.`in`))
|
||||
}
|
||||
|
||||
fun addScriptScanner(filePath: String) {
|
||||
if (fileHistory.contains(filePath)) {
|
||||
printErrConsole("Скрипт уже был выполнен: $filePath")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
fileHistory.push(filePath)
|
||||
inputQueue.push(Scanner(File(filePath), Charsets.UTF_8))
|
||||
} catch (e: FileNotFoundException) {
|
||||
printErrConsole("Файл не найден: $filePath")
|
||||
}
|
||||
}
|
||||
|
||||
// сделать основной Scanner
|
||||
// при инициализации стандартный сканер добавляется
|
||||
// стек input, один (console) открыт постоянно
|
||||
// если файл - в стек кидается Scanner
|
||||
|
||||
/**
|
||||
* Читает строку с промптом ☭.
|
||||
*/
|
||||
fun readLine(prompt: String): String? {
|
||||
while (inputQueue.isNotEmpty()) {
|
||||
if (inputQueue.size == 1) kotlin.io.print(prompt)
|
||||
val topInDeque = inputQueue.peek()
|
||||
if (topInDeque.hasNextLine()) {
|
||||
|
||||
return topInDeque.nextLine().toString()
|
||||
}
|
||||
if (inputQueue.size > 1) {
|
||||
topInDeque.close()
|
||||
inputQueue.pop()
|
||||
fileHistory.pop()
|
||||
|
||||
// snap back to reality
|
||||
continue
|
||||
}
|
||||
inputQueue.pop()
|
||||
print("Ввод закончен.")
|
||||
break
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun print(text: String) {
|
||||
println(text)
|
||||
}
|
||||
|
||||
fun printErrConsole(text: String) {
|
||||
System.err.println(text)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package network
|
||||
|
||||
import kotlinx.serialization.SerializationException
|
||||
import lab6.prog.network.AppJson
|
||||
import java.net.InetSocketAddress
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.DatagramChannel
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* UDP-клиент на основе DatagramChannel в неблокирующем режиме.
|
||||
*
|
||||
* При недоступности сервера уведомляет пользователя и повторяет
|
||||
* попытку каждые [retryDelayMS] мс, не более [maxRetries] раз.
|
||||
*
|
||||
* @property host адрес сервера
|
||||
* @property port порт сервера
|
||||
*/
|
||||
class NetworkManager(
|
||||
private val host: String,
|
||||
private val port: Int,
|
||||
private val bufferSize: Int = 65507,
|
||||
private val timeoutMS: Long = 3000,
|
||||
private val retryDelayMS: Long = 5000,
|
||||
private val maxRetries: Int = 3
|
||||
) {
|
||||
private val channel: DatagramChannel = DatagramChannel.open().also {
|
||||
it.configureBlocking(false)
|
||||
it.connect(InetSocketAddress(host, port))
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправляет [Request] и возвращает [Response].
|
||||
* При недоступности сервера возвращает null.
|
||||
*/
|
||||
fun sendRequest(request: Request): Response? {
|
||||
val requestBytes = AppJson.encodeToString(Request.serializer(), request).toByteArray(Charsets.UTF_8)
|
||||
|
||||
repeat(maxRetries) { attempt ->
|
||||
|
||||
channel.write(ByteBuffer.wrap(requestBytes))
|
||||
|
||||
val response = waitForResponse()
|
||||
if (response != null) return response
|
||||
|
||||
println(
|
||||
"[Client] Сервер не отвечает " +
|
||||
"(попытка ${attempt + 1}/$maxRetries). " +
|
||||
"Повтор через ${retryDelayMS / 1000} сек..."
|
||||
)
|
||||
Thread.sleep(retryDelayMS)
|
||||
}
|
||||
|
||||
println("[Client] Сервер недоступен. Команда не выполнена.")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Опрашивает канал до [timeoutMS] мс, возвращает ответ или null.
|
||||
*/
|
||||
// catch java.net.PortUnreachableException if server is no more reachable
|
||||
private fun waitForResponse(): Response? {
|
||||
val buf = ByteBuffer.allocate(bufferSize)
|
||||
val deadline = System.currentTimeMillis() + timeoutMS
|
||||
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
buf.clear()
|
||||
if (channel.read(buf) > 0) {
|
||||
buf.flip()
|
||||
return try {
|
||||
AppJson.decodeFromString<Response>(Charsets.UTF_8.decode(buf).toString())
|
||||
} catch (e: SerializationException) {
|
||||
System.err.println("[Client] Некорректный ответ сервера: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
Thread.sleep(50)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun close() = channel.close()
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package runner
|
||||
|
||||
class CommandValidator {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
plugins {
|
||||
id 'org.jetbrains.kotlin.jvm' version '2.2.0'
|
||||
id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.0'
|
||||
id 'org.jetbrains.dokka' version '2.2.0'
|
||||
}
|
||||
|
||||
group = 'lab6.prog'
|
||||
version = '1.0'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation 'org.jetbrains.kotlin:kotlin-test'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0'
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package models
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Автомобиль, которым владеет [HumanBeing].
|
||||
*
|
||||
* @property cool признак того, что автомобиль крутой
|
||||
*/
|
||||
@Serializable
|
||||
data class Car(
|
||||
val cool: Boolean
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Координаты местоположения [HumanBeing].
|
||||
*
|
||||
* @property x координата X
|
||||
* @property y координата Y
|
||||
*/
|
||||
|
||||
@Serializable
|
||||
data class Coordinates(
|
||||
val x: Long,
|
||||
val y: Int
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
package models
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import lab6.prog.network.utils.LocalDateSerializer
|
||||
import lab6.prog.network.utils.UUIDSerializer
|
||||
import java.time.LocalDate
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Основная сущность коллекции — Райан Гослинг.
|
||||
*
|
||||
* @property id уникальный идентификатор, генерируется автоматически
|
||||
* @property name имя героя (Райан Гослинг), не может быть null или пустой строкой
|
||||
* @property coordinates координаты героя, не может быть null
|
||||
* @property creationDate дата создания записи, генерируется автоматически
|
||||
* @property realHero является ли настоящим героем (конечно)
|
||||
* @property hasToothpick есть ли зубочистка (естественно)
|
||||
* @property impactSpeed скорость удара, не может быть null
|
||||
* @property soundtrackName название саундтрека, не может быть null (Nightcall - Kavinsky)
|
||||
* @property minutesOfWaiting количество минут ожидания
|
||||
* @property weaponType тип оружия, может быть null
|
||||
* @property car автомобиль героя, не может быть null
|
||||
*/
|
||||
@Serializable
|
||||
data class HumanBeing(
|
||||
@Serializable(with = UUIDSerializer::class)
|
||||
val id: UUID = UUID.randomUUID(),
|
||||
val name: String,
|
||||
val coordinates: Coordinates,
|
||||
@Serializable(with = LocalDateSerializer::class)
|
||||
val creationDate: LocalDate = LocalDate.now(),
|
||||
val realHero: Boolean,
|
||||
val hasToothpick: Boolean,
|
||||
val impactSpeed: Double,
|
||||
val soundtrackName: String,
|
||||
val minutesOfWaiting: Float,
|
||||
val weaponType: WeaponType?,
|
||||
val car: Car
|
||||
) : Comparable<HumanBeing> {
|
||||
|
||||
init {
|
||||
require(name.isNotBlank()) { "Имя не может быть пустым" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Сравниваем по имени и id
|
||||
*/
|
||||
override fun compareTo(other: HumanBeing): Int {
|
||||
val byName = this.name.compareTo(other.name)
|
||||
if (byName != 0) return byName
|
||||
return this.id.toString().compareTo(other.id.toString())
|
||||
}
|
||||
|
||||
/**
|
||||
* Два объекта считаются одинаковыми, если совпадают их [id].
|
||||
*/
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is HumanBeing) return false
|
||||
return id == other.id
|
||||
}
|
||||
|
||||
override fun hashCode(): Int = id.hashCode()
|
||||
|
||||
/**
|
||||
* Красивое строковое представление для команды [show].
|
||||
*/
|
||||
override fun toString(): String =
|
||||
"""
|
||||
|HumanBeing (It Drives) {
|
||||
| id = $id
|
||||
| name = $name (a.k.a. Ryan Gosling)
|
||||
| coordinates = (x=${coordinates.x}, y=${coordinates.y})
|
||||
| creationDate = $creationDate
|
||||
| realHero = $realHero
|
||||
| hasToothpick = $hasToothpick
|
||||
| impactSpeed = $impactSpeed
|
||||
| soundtrackName = $soundtrackName
|
||||
| minutesOfWait = $minutesOfWaiting
|
||||
| weaponType = ${weaponType ?: "null"}
|
||||
| car.cool = ${car.cool}
|
||||
|}
|
||||
""".trimMargin()
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package models
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Перечисление типов оружия, которым может владеть [HumanBeing].
|
||||
* Поле [weaponType] в [HumanBeing] может быть null.
|
||||
*/
|
||||
@Serializable
|
||||
enum class WeaponType {
|
||||
HAMMER,
|
||||
SHOTGUN,
|
||||
BAT;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package lab6.prog.network
|
||||
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/**
|
||||
* Общий экземпляр Json для всего приложения.
|
||||
* ignoreUnknownKeys — устойчивость к добавлению новых полей в протокол.
|
||||
*/
|
||||
val AppJson = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package network
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import models.HumanBeing
|
||||
|
||||
/**
|
||||
* Запрос от клиента к серверу.
|
||||
*
|
||||
* @property commandName имя команды ("add", "show", "remove_by_id" ...)
|
||||
* @property args строковые аргументы (UUID для update/remove_by_id и т.п.)
|
||||
* @property humanBeing объект для команд: add, update, add_if_max, add_if_min
|
||||
*/
|
||||
@Serializable
|
||||
data class Request(
|
||||
val commandName: String,
|
||||
val args: List<String> = emptyList(),
|
||||
val humanBeing: HumanBeing? = null
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
package network
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Ответ сервера клиенту.
|
||||
*
|
||||
* @property success true — команда выполнена, false — ошибка
|
||||
* @property message текст для вывода пользователю
|
||||
*/
|
||||
@Serializable
|
||||
data class Response(
|
||||
val success: Boolean,
|
||||
val message: String
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package lab6.prog.network.utils
|
||||
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.descriptors.*
|
||||
import kotlinx.serialization.encoding.*
|
||||
import java.time.LocalDate
|
||||
|
||||
/**
|
||||
* Кастомный KSerializer для LocalDate.
|
||||
* Сериализует как ISO строку: "2025-04-12"
|
||||
*/
|
||||
object LocalDateSerializer : KSerializer<LocalDate> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING)
|
||||
|
||||
override fun serialize(encoder: Encoder, value: LocalDate) =
|
||||
encoder.encodeString(value.toString())
|
||||
|
||||
override fun deserialize(decoder: Decoder): LocalDate =
|
||||
LocalDate.parse(decoder.decodeString())
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package lab6.prog.network.utils
|
||||
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.descriptors.*
|
||||
import kotlinx.serialization.encoding.*
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Кастомный KSerializer для UUID.
|
||||
* UUID не поддерживается kotlinx.serialization из коробки.
|
||||
*/
|
||||
object UUIDSerializer : KSerializer<UUID> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING)
|
||||
|
||||
override fun serialize(encoder: Encoder, value: UUID) =
|
||||
encoder.encodeString(value.toString())
|
||||
|
||||
override fun deserialize(decoder: Decoder): UUID =
|
||||
UUID.fromString(decoder.decodeString())
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
# Техническое задание к программе
|
||||
|
||||
**Необходимо выполнить следующие требования:**
|
||||
|
||||
- Операции обработки объектов коллекции должны быть реализованы с помощью Stream API с использованием лямбда-выражений.
|
||||
- Объекты между клиентом и сервером должны передаваться в сериализованном виде.
|
||||
- Объекты в коллекции, передаваемой клиенту, должны быть отсортированы по названию
|
||||
- Клиент должен корректно обрабатывать временную недоступность сервера.
|
||||
- Обмен данными между клиентом и сервером должен осуществляться по протоколу UDP
|
||||
- Для обмена данными на сервере необходимо использовать **датаграммы**
|
||||
- Для обмена данными на клиенте необходимо использовать **сетевой канал**
|
||||
- Сетевые каналы должны использоваться в неблокирующем режиме.
|
||||
|
||||
**Обязанности серверного приложения:**
|
||||
|
||||
- Работа с файлом, хранящим коллекцию.
|
||||
- Управление коллекцией объектов.
|
||||
- Назначение автоматически генерируемых полей объектов в коллекции.
|
||||
- Ожидание подключений и запросов от клиента.
|
||||
- Обработка полученных запросов (команд).
|
||||
- Сохранение коллекции в файл при завершении работы приложения.
|
||||
- Сохранение коллекции в файл при исполнении специальной команды, доступной только серверу (клиент такую команду отправить не может).
|
||||
|
||||
**Серверное приложение должно состоять из следующих модулей (реализованных в виде одного или нескольких классов):**
|
||||
|
||||
- Модуль приёма подключений.
|
||||
- Модуль чтения запроса.
|
||||
- Модуль обработки полученных команд.
|
||||
- Модуль отправки ответов клиенту.
|
||||
|
||||
Сервер должен работать в **однопоточном** режиме.
|
||||
|
||||
**Обязанности клиентского приложения:**
|
||||
|
||||
- Чтение команд из консоли.
|
||||
- Валидация вводимых данных.
|
||||
- Сериализация введённой команды и её аргументов.
|
||||
- Отправка полученной команды и её аргументов на сервер.
|
||||
- Обработка ответа от сервера (вывод результата исполнения команды в консоль).
|
||||
- Команду `save` из клиентского приложения необходимо убрать.
|
||||
- Команда `exit` завершает работу клиентского приложения.
|
||||
|
||||
**Важно!** Команды и их аргументы должны представлять из себя объекты классов. Недопустим обмен "простыми" строками. Так, для команды add или её аналога необходимо сформировать объект, содержащий тип команды и объект, который должен храниться в вашей коллекции.
|
||||
|
||||
**Принцип работы клиентской части**
|
||||
|
||||
1. ввод команды
|
||||
2. валидация команды (без запроса на сервер, у клиента должна быть информация о доступных командах)
|
||||
3. ввод аргументов
|
||||
4. запрос на сервер
|
||||
5. обработка ответа от сервера
|
||||
6. вывод информации
|
||||
|
||||
**Принцип работы серверного приложения**
|
||||
|
||||
1. подключение
|
||||
3. получение запроса
|
||||
4. выполнение команды
|
||||
5. отправка ответа
|
||||
|
||||
**Примечания**
|
||||
|
||||
1. сервер может работать сразу с несколькими клиентами, но не параллельно
|
||||
2. клиент продолжает работать даже если сервер -- нет (должно быть информирование пользователя о том, что сервер умер + попытки подключения раз в N секунд)
|
||||
3. Общение между клиентом и сервером должно быть в виде json строк
|
||||
@@ -0,0 +1 @@
|
||||
kotlin.code.style=official
|
||||
Vendored
BIN
Binary file not shown.
+6
@@ -0,0 +1,6 @@
|
||||
#Sat Apr 11 18:48:17 MSK 2026
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,33 @@
|
||||
plugins {
|
||||
id 'org.jetbrains.kotlin.jvm' version '2.2.0'
|
||||
id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.0'
|
||||
id 'com.gradleup.shadow' version '9.3.1'
|
||||
id 'org.jetbrains.dokka' version '2.2.0'
|
||||
}
|
||||
|
||||
group = 'lab6.prog'
|
||||
version = '1.0'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
shadowJar {
|
||||
archiveBaseName.set('Lab6-server')
|
||||
archiveVersion.set('1.0')
|
||||
manifest {
|
||||
attributes 'Main-Class': 'MainKt'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation 'org.jetbrains.kotlin:kotlin-test'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0'
|
||||
implementation 'io.github.microutils:kotlin-logging-jvm:3.0.5'
|
||||
implementation "io.ktor:ktor-network:3.4.2"
|
||||
implementation project(':common')
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import collection.CollectionManager
|
||||
import commands.*
|
||||
import file.FileManager
|
||||
import network.NetworkManager
|
||||
import runner.CommandInvoker
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
System.setProperty("slf4j.internal.verbosity", "WARN")
|
||||
|
||||
val filePath = if (args.isNotEmpty()) args[0] else "data.csv"
|
||||
|
||||
val fileManager = FileManager(filePath)
|
||||
val manager = CollectionManager()
|
||||
val invoker = CommandInvoker()
|
||||
|
||||
// Загружаем коллекцию из файла
|
||||
manager.loadFromFile(fileManager.read())
|
||||
|
||||
// Регистрируем команды
|
||||
registerServerCommands(invoker, manager, fileManager)
|
||||
|
||||
// Сохранение при завершении (Ctrl+C или kill)
|
||||
val server = NetworkManager(port = 8080, invoker = invoker)
|
||||
Runtime.getRuntime().addShutdownHook(Thread {
|
||||
println("[Server] Сохранение коллекции перед выходом...")
|
||||
fileManager.write(manager.getAll())
|
||||
server.stop()
|
||||
})
|
||||
|
||||
// Консоль на сервере
|
||||
Thread {
|
||||
val scanner = java.util.Scanner(System.`in`)
|
||||
println("[Server] Серверные команды: save, exit")
|
||||
while (scanner.hasNextLine()) {
|
||||
when (scanner.nextLine().trim().lowercase()) {
|
||||
"save" -> {
|
||||
fileManager.write(manager.getAll())
|
||||
println("[Server] Коллекция сохранена.")
|
||||
}
|
||||
"exit" -> {
|
||||
println("[Server] Завершение работы...")
|
||||
exitProcess(0)
|
||||
}
|
||||
else -> println("[Server] Доступные команды: save, exit")
|
||||
}
|
||||
}
|
||||
}.also { it.isDaemon = true }.start()
|
||||
|
||||
server.start()
|
||||
}
|
||||
|
||||
fun registerServerCommands(
|
||||
invoker: CommandInvoker,
|
||||
manager: CollectionManager,
|
||||
fileManager: FileManager
|
||||
) {
|
||||
listOf(
|
||||
HelpCommand(invoker),
|
||||
InfoCommand(manager),
|
||||
ShowCommand(manager),
|
||||
AddCommand(manager),
|
||||
UpdateCommand(manager),
|
||||
RemoveByIdCommand(manager),
|
||||
ClearCommand(manager),
|
||||
SaveCommand(manager, fileManager), // только на сервере
|
||||
AddIfMaxCommand(manager),
|
||||
AddIfMinCommand(manager),
|
||||
HistoryCommand(invoker),
|
||||
SumOfMinutesCommand(manager),
|
||||
MinByNameCommand(manager),
|
||||
PrintDescendingMinutesCommand(manager),
|
||||
ExitCommand()
|
||||
).forEach { invoker.register(it) }
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package collection
|
||||
|
||||
import models.HumanBeing
|
||||
import mu.KotlinLogging
|
||||
import java.time.LocalDate
|
||||
import java.util.TreeSet
|
||||
import java.util.UUID
|
||||
|
||||
private val logger = KotlinLogging.logger {}
|
||||
|
||||
class CollectionManager {
|
||||
|
||||
private val collection: TreeSet<HumanBeing> = TreeSet()
|
||||
val initDate: LocalDate = LocalDate.now()
|
||||
|
||||
fun add(humanBeing: HumanBeing): Boolean {
|
||||
logger.info { "[ADD] Создан элемент ${humanBeing.id}" }
|
||||
return collection.add(humanBeing)
|
||||
}
|
||||
|
||||
fun update(id: UUID, updated: HumanBeing): Boolean {
|
||||
val old = getById(id) ?: return false
|
||||
collection.remove(old)
|
||||
val replaced = updated.copy(id = old.id, creationDate = old.creationDate)
|
||||
logger.info { "[UPDATE] Обновлён элемент ${old.id}" }
|
||||
return collection.add(replaced)
|
||||
}
|
||||
|
||||
fun removeById(id: UUID): Boolean {
|
||||
val target = getById(id) ?: return false
|
||||
logger.info { "[REMOVE] Удалён элемент ${target.id}" }
|
||||
return collection.remove(target)
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
collection.clear()
|
||||
logger.info { "[CLEAR] Коллекция очищена" }
|
||||
}
|
||||
|
||||
fun getAll(): TreeSet<HumanBeing> = TreeSet(collection)
|
||||
|
||||
fun getById(id: UUID): HumanBeing? =
|
||||
collection.stream()
|
||||
.filter { it.id == id }
|
||||
.findFirst()
|
||||
.orElse(null)
|
||||
|
||||
fun size(): Int = collection.size
|
||||
|
||||
fun isEmpty(): Boolean = collection.isEmpty()
|
||||
|
||||
fun getMax(): HumanBeing? =
|
||||
collection.stream()
|
||||
.max(Comparator.naturalOrder())
|
||||
.orElse(null)
|
||||
|
||||
fun getMin(): HumanBeing? =
|
||||
collection.stream()
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElse(null)
|
||||
|
||||
fun sumOfMinutesOfWaiting(): Double =
|
||||
collection.stream()
|
||||
.mapToDouble { it.minutesOfWaiting.toDouble() }
|
||||
.sum()
|
||||
|
||||
fun minByName(): HumanBeing? =
|
||||
collection.stream()
|
||||
.min(Comparator.comparing { it.name })
|
||||
.orElse(null)
|
||||
|
||||
fun getMinutesOfWaitingDescending(): List<Float> =
|
||||
collection.stream()
|
||||
.map { it.minutesOfWaiting }
|
||||
.sorted(Comparator.reverseOrder())
|
||||
.toList()
|
||||
|
||||
fun loadFromFile(items: List<HumanBeing>) {
|
||||
collection.clear()
|
||||
items.stream().forEach { collection.add(it) }
|
||||
logger.info { "[LOAD] Загружено ${items.size} элементов" }
|
||||
}
|
||||
|
||||
fun getInfo(): String =
|
||||
"""
|
||||
|Тип коллекции : ${collection::class.simpleName}
|
||||
|Тип элементов : ${HumanBeing::class.simpleName}
|
||||
|Дата инициал. : $initDate
|
||||
|Кол-во элемен.: ${collection.size}
|
||||
""".trimMargin()
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
class AddCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "add"
|
||||
override val description = "добавить новый элемент в коллекцию"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
humanBeing ?: return "[Ошибка] Объект HumanBeing не передан."
|
||||
return if (manager.add(humanBeing))
|
||||
"Элемент добавлен: ${humanBeing.name} [${humanBeing.id}]"
|
||||
else
|
||||
"Элемент уже существует в коллекции."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
class AddIfMaxCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "add_if_max"
|
||||
override val description = "добавить элемент, если он больше максимального"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
humanBeing ?: return "[Ошибка] Объект HumanBeing не передан."
|
||||
val max = manager.getMax()
|
||||
return if (max == null || humanBeing > max) {
|
||||
manager.add(humanBeing)
|
||||
"Элемент добавлен (превышает максимум)."
|
||||
} else {
|
||||
"Элемент не добавлен: не превышает текущий максимум (${max.name})."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
class AddIfMinCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "add_if_min"
|
||||
override val description = "добавить элемент, если он меньше минимального"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
humanBeing ?: return "[Ошибка] Объект HumanBeing не передан."
|
||||
val min = manager.getMin()
|
||||
return if (min == null || humanBeing < min) {
|
||||
manager.add(humanBeing)
|
||||
"Элемент добавлен (меньше минимума)."
|
||||
} else {
|
||||
"Элемент не добавлен: не меньше текущего минимума (${min.name})."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
class ClearCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "clear"
|
||||
override val description = "очистить коллекцию"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
manager.clear()
|
||||
return "Коллекция очищена."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package commands
|
||||
|
||||
import models.HumanBeing
|
||||
|
||||
/**
|
||||
* Базовый интерфейс команды.
|
||||
*
|
||||
* Теперь execute() возвращает String — результат для отправки клиенту.
|
||||
* Зависимость от IOManager полностью убрана из команд.
|
||||
*/
|
||||
interface Command {
|
||||
val name: String
|
||||
val description: String
|
||||
|
||||
/**
|
||||
* @param args строковые аргументы (UUID и т.п.)
|
||||
* @param humanBeing объект из запроса — только для add/update/add_if_max/add_if_min
|
||||
* @return строка-результат для клиента
|
||||
*/
|
||||
fun execute(args: List<String>, humanBeing: HumanBeing? = null): String
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package commands
|
||||
|
||||
/**
|
||||
* Завершает программу без сохранения.
|
||||
*/
|
||||
import models.HumanBeing
|
||||
|
||||
class ExitCommand() : Command {
|
||||
override val name = "exit"
|
||||
override val description = "завершить программу"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String = ""
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package commands
|
||||
|
||||
import runner.CommandInvoker
|
||||
import models.HumanBeing
|
||||
|
||||
class HelpCommand(private val invoker: CommandInvoker) : Command {
|
||||
override val name = "help"
|
||||
override val description = "вывести справку по доступным командам"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String =
|
||||
invoker.getCommands().values
|
||||
.sortedBy { it.name }
|
||||
.joinToString("\n") { " ${it.name.padEnd(40)} — ${it.description}" }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package commands
|
||||
|
||||
import runner.CommandInvoker
|
||||
import models.HumanBeing
|
||||
|
||||
class HistoryCommand(private val invoker: CommandInvoker) : Command {
|
||||
override val name = "history"
|
||||
override val description = "вывести последние 12 команд"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
val history = invoker.getHistory()
|
||||
if (history.isEmpty()) return "История пуста."
|
||||
return history.mapIndexed { i, cmd -> " ${i + 1}. $cmd" }.joinToString("\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
class InfoCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "info"
|
||||
override val description = "вывести информацию о коллекции"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String =
|
||||
manager.getInfo()
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
/**
|
||||
* Выводит любой элемент с минимальным значением поля [HumanBeing.name].
|
||||
*/
|
||||
class MinByNameCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "min_by_name"
|
||||
override val description = "вывести элемент с минимальным именем"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String =
|
||||
manager.minByName()?.toString() ?: "Коллекция пуста."
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
/**
|
||||
* Выводит значения поля [models.HumanBeing.minutesOfWaiting] в порядке убывания.
|
||||
*/
|
||||
class PrintDescendingMinutesCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "print_field_descending_minutes_of_waiting"
|
||||
override val description = "вывести minutesOfWaiting в порядке убывания"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
val values = manager.getMinutesOfWaitingDescending()
|
||||
return if (values.isEmpty()) "Коллекция пуста."
|
||||
else values.joinToString("\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import java.util.UUID
|
||||
import models.HumanBeing
|
||||
|
||||
class RemoveByIdCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "remove_by_id"
|
||||
override val description = "удалить элемент по id: remove_by_id <uuid>"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
if (args.isEmpty()) return "[Ошибка] Укажите id. Пример: remove_by_id <uuid>"
|
||||
|
||||
val id = try {
|
||||
UUID.fromString(args[0])
|
||||
} catch (e: IllegalArgumentException) {
|
||||
return "[Ошибка] Некорректный UUID: '${args[0]}'"
|
||||
}
|
||||
|
||||
return if (manager.removeById(id)) "Элемент удалён."
|
||||
else "[Ошибка] Элемент с id '$id' не найден."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import file.FileManager
|
||||
import models.HumanBeing
|
||||
|
||||
class SaveCommand(
|
||||
private val manager: CollectionManager,
|
||||
private val fileManager: FileManager
|
||||
) : Command {
|
||||
override val name = "save"
|
||||
override val description = "[SERVER] сохранить коллекцию в файл"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
return if (fileManager.write(manager.getAll())) "Коллекция сохранена."
|
||||
else "[Ошибка] Не удалось сохранить коллекцию."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
class ShowCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "show"
|
||||
override val description = "вывести все элементы коллекции"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
if (manager.isEmpty()) return "Коллекция пуста."
|
||||
return manager.getAll().joinToString("\n") { it.toString() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
|
||||
/**
|
||||
* Выводит сумму значений поля [models.HumanBeing.minutesOfWaiting].
|
||||
*/
|
||||
class SumOfMinutesCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "sum_of_minutes_of_waiting"
|
||||
override val description = "вывести сумму minutesOfWaiting всех элементов"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String =
|
||||
"Сумма minutesOfWaiting: ${manager.sumOfMinutesOfWaiting()}"
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package commands
|
||||
|
||||
import collection.CollectionManager
|
||||
import models.HumanBeing
|
||||
import java.util.UUID
|
||||
|
||||
class UpdateCommand(private val manager: CollectionManager) : Command {
|
||||
override val name = "update"
|
||||
override val description = "обновить элемент по id: update <uuid>"
|
||||
|
||||
override fun execute(args: List<String>, humanBeing: HumanBeing?): String {
|
||||
if (args.isEmpty()) return "[Ошибка] Укажите id. Пример: update <uuid>"
|
||||
humanBeing ?: return "[Ошибка] Объект HumanBeing не передан."
|
||||
|
||||
val id = try {
|
||||
UUID.fromString(args[0])
|
||||
} catch (e: IllegalArgumentException) {
|
||||
return "[Ошибка] Некорректный UUID: '${args[0]}'"
|
||||
}
|
||||
|
||||
return if (manager.update(id, humanBeing)) "Элемент обновлён."
|
||||
else "[Ошибка] Элемент с id '$id' не найден."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package file
|
||||
|
||||
import models.Car
|
||||
import models.Coordinates
|
||||
import models.HumanBeing
|
||||
import models.WeaponType
|
||||
import java.io.File
|
||||
import java.io.FileNotFoundException
|
||||
import java.io.OutputStreamWriter
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeParseException
|
||||
import java.util.Scanner
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Менеджер файлового хранилища коллекции.
|
||||
*
|
||||
* Читает данные с помощью [Scanner], записывает через [OutputStreamWriter].
|
||||
* Формат хранения — CSV, одна строка = один объект [HumanBeing].
|
||||
*
|
||||
* Порядок полей в CSV:
|
||||
* `id,name,coordX,coordY,creationDate,realHero,hasToothpick,
|
||||
* impactSpeed,soundtrackName,minutesOfWaiting,weaponType,carCool`
|
||||
*
|
||||
* @property filePath путь к CSV-файлу, полученный из аргумента командной строки
|
||||
*/
|
||||
class FileManager(private val filePath: String) {
|
||||
|
||||
companion object {
|
||||
private const val DELIMITER = ","
|
||||
private const val HEADER =
|
||||
"id,name,coordX,coordY,creationDate,realHero," +
|
||||
"hasToothpick,impactSpeed,soundtrackName,minutesOfWaiting,weaponType,carCool"
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает коллекцию из CSV-файла с помощью [Scanner].
|
||||
*
|
||||
* Пропускает заголовок и битые строки (с предупреждением в stderr).
|
||||
* При отсутствии файла или проблемах с доступом возвращает пустой список.
|
||||
*
|
||||
* @return список корректно распарсенных объектов [HumanBeing]
|
||||
*/
|
||||
fun read(): List<HumanBeing> {
|
||||
val file = File(filePath)
|
||||
|
||||
if (!file.exists()) {
|
||||
System.err.println("Файл '$filePath' не найден. Коллекция будет пустой.")
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
if (!file.canRead()) {
|
||||
System.err.println("Нет прав на чтение файла '$filePath'. Коллекция будет пустой.")
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
val result = mutableListOf<HumanBeing>()
|
||||
var lineNumber = 0
|
||||
|
||||
try {
|
||||
Scanner(file, Charsets.UTF_8).use { scanner ->
|
||||
while (scanner.hasNextLine()) {
|
||||
val line = scanner.nextLine().trim()
|
||||
lineNumber++
|
||||
|
||||
// Пропускаем заголовок и пустые строки
|
||||
if (lineNumber == 1 && line.startsWith("id")) continue
|
||||
if (line.isBlank()) continue
|
||||
|
||||
parseLine(line, lineNumber)
|
||||
?.let { result.add(it) }
|
||||
?: System.err.println("Строка $lineNumber пропущена: некорректные данные → '$line'")
|
||||
}
|
||||
}
|
||||
} catch (e: FileNotFoundException) {
|
||||
System.err.println("Файл не найден во время чтения: ${e.message}")
|
||||
}
|
||||
|
||||
println("Загружено элементов: ${result.size} из файла '$filePath'")
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Парсит одну CSV-строку в объект [HumanBeing].
|
||||
*
|
||||
* @param line строка CSV
|
||||
* @param lineNumber номер строки (для сообщений об ошибках)
|
||||
* @return объект [HumanBeing] или null при ошибке парсинга
|
||||
*/
|
||||
private fun parseLine(line: String, lineNumber: Int): HumanBeing? {
|
||||
return try {
|
||||
val parts = line.split(DELIMITER, limit = 12)
|
||||
if (parts.size < 12) {
|
||||
System.err.println("Строка $lineNumber: ожидалось 12 полей, найдено ${parts.size}")
|
||||
return null
|
||||
}
|
||||
|
||||
val id = UUID.fromString(parts[0].trim())
|
||||
val name = parts[1].trim()
|
||||
val coordX = parts[2].trim().toLong()
|
||||
val coordY = parts[3].trim().toInt()
|
||||
val creationDate = LocalDate.parse(parts[4].trim())
|
||||
val realHero = parts[5].trim().toBoolean()
|
||||
val hasToothpick = parts[6].trim().toBoolean()
|
||||
val impactSpeed = parts[7].trim().toDouble()
|
||||
val soundtrackName = parts[8].trim()
|
||||
val minutesOfWaiting = parts[9].trim().toFloat()
|
||||
val weaponType = parts[10].trim().let {
|
||||
if (it.equals("null", ignoreCase = true) || it.isBlank()) null
|
||||
else WeaponType.valueOf(it)
|
||||
}
|
||||
val carCool = parts[11].trim().toBoolean()
|
||||
|
||||
// самая лучшая валидация (100%)
|
||||
require(name.isNotBlank()) { "name не может быть пустым" }
|
||||
|
||||
// от такого может быть диабет
|
||||
HumanBeing(
|
||||
id = id, name = name, coordinates = Coordinates(coordX, coordY),
|
||||
creationDate = creationDate, realHero = realHero, hasToothpick = hasToothpick,
|
||||
impactSpeed = impactSpeed, soundtrackName = soundtrackName,
|
||||
minutesOfWaiting = minutesOfWaiting, weaponType = weaponType, car = Car(carCool)
|
||||
)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
System.err.println("Строка $lineNumber — ошибка данных: ${e.message}")
|
||||
null
|
||||
} catch (e: DateTimeParseException) {
|
||||
System.err.println("Строка $lineNumber — неверный формат даты: ${e.message}")
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
System.err.println("Строка $lineNumber — неожиданная ошибка: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Записывает коллекцию в CSV-файл с помощью [OutputStreamWriter].
|
||||
*
|
||||
* @param items коллекция объектов [HumanBeing] для записи
|
||||
* @return true если запись прошла успешно
|
||||
*/
|
||||
fun write(items: Collection<HumanBeing>): Boolean {
|
||||
val file = File(filePath)
|
||||
|
||||
if (file.exists() && !file.canWrite()) {
|
||||
System.err.println("Нет прав на запись в файл '$filePath'.")
|
||||
return false
|
||||
}
|
||||
|
||||
return try {
|
||||
OutputStreamWriter(file.outputStream(), Charsets.UTF_8).use { writer ->
|
||||
writer.write(HEADER)
|
||||
writer.write("\n")
|
||||
items.forEach { h ->
|
||||
writer.write(toCSVLine(h))
|
||||
writer.write("\n")
|
||||
}
|
||||
}
|
||||
println("Коллекция сохранена в '$filePath' (${items.size} элементов).")
|
||||
true
|
||||
} catch (e: SecurityException) {
|
||||
println("Отказано в доступе к файлу '$filePath': ${e.message}")
|
||||
false
|
||||
} catch (e: Exception) {
|
||||
println("Ошибка записи в файл: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Сериализует объект [HumanBeing] в строку CSV.
|
||||
*
|
||||
* @param h объект для сериализации
|
||||
* @return строка в формате CSV
|
||||
*/
|
||||
private fun toCSVLine(h: HumanBeing): String = listOf(
|
||||
h.id, h.name, h.coordinates.x, h.coordinates.y, h.creationDate,
|
||||
h.realHero, h.hasToothpick, h.impactSpeed, h.soundtrackName,
|
||||
h.minutesOfWaiting, h.weaponType ?: "null", h.car.cool
|
||||
).joinToString(DELIMITER)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package network
|
||||
|
||||
import kotlinx.serialization.SerializationException
|
||||
import lab6.prog.network.AppJson
|
||||
import runner.CommandInvoker
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetAddress
|
||||
|
||||
private const val BUFFER_SIZE = 65507
|
||||
|
||||
/**
|
||||
* UDP-сервер на основе DatagramSocket (датаграммы).
|
||||
*
|
||||
* Однопоточный: receive → deserialize → execute → send.
|
||||
*
|
||||
* @property port порт прослушивания
|
||||
* @property invoker инвокер серверных команд
|
||||
*/
|
||||
class NetworkManager(
|
||||
private val port: Int,
|
||||
private val invoker: CommandInvoker
|
||||
) {
|
||||
private val socket = DatagramSocket(port)
|
||||
|
||||
fun start() {
|
||||
println("[Server] Запущен на порту $port. Ожидание клиентов...")
|
||||
val buf = ByteArray(BUFFER_SIZE)
|
||||
|
||||
while (!socket.isClosed) {
|
||||
try {
|
||||
// 1. Принять датаграмму
|
||||
val packet = DatagramPacket(buf, buf.size)
|
||||
socket.receive(packet)
|
||||
|
||||
val json = String(packet.data, 0, packet.length, Charsets.UTF_8)
|
||||
|
||||
// 2. Десериализовать запрос
|
||||
val request = try {
|
||||
AppJson.decodeFromString<Request>(json)
|
||||
} catch (e: SerializationException) {
|
||||
System.err.println("[Server] Некорректный JSON: ${e.message}")
|
||||
sendResponse(Response(false, "Некорректный формат запроса"), packet.address, packet.port)
|
||||
continue
|
||||
}
|
||||
|
||||
println("[Server] '${request.commandName}' от ${packet.address}:${packet.port}")
|
||||
|
||||
// 3. Выполнить и получить ответ
|
||||
val response = invoker.execute(request)
|
||||
|
||||
// 4. Отправить ответ
|
||||
sendResponse(response, packet.address, packet.port)
|
||||
|
||||
} catch (e: Exception) {
|
||||
if (!socket.isClosed)
|
||||
System.err.println("[Server] Ошибка: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendResponse(response: Response, address: InetAddress, port: Int) {
|
||||
val bytes = AppJson.encodeToString(Response.serializer(), response).toByteArray(Charsets.UTF_8)
|
||||
socket.send(DatagramPacket(bytes, bytes.size, address, port))
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
println("[Server] Остановка...")
|
||||
socket.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package runner
|
||||
|
||||
import commands.Command
|
||||
import network.Request
|
||||
import network.Response
|
||||
|
||||
/**
|
||||
* Серверный инвокер.
|
||||
*
|
||||
* Принимает Request, находит команду, выполняет,
|
||||
* возвращает Response готовый для отправки клиенту.
|
||||
*/
|
||||
class CommandInvoker {
|
||||
|
||||
private val serverOnlyCommands = setOf("save")
|
||||
private val commands = mutableMapOf<String, Command>()
|
||||
private val history = ArrayDeque<String>()
|
||||
|
||||
fun register(command: Command) {
|
||||
commands[command.name] = command
|
||||
}
|
||||
|
||||
fun execute(request: Request): Response {
|
||||
if (request.commandName in serverOnlyCommands) {
|
||||
return Response(false, "Команда '${request.commandName}' недоступна клиенту.")
|
||||
}
|
||||
|
||||
val command = commands[request.commandName]
|
||||
?: return Response(false, "Неизвестная команда: '${request.commandName}'")
|
||||
|
||||
addToHistory(request.commandName)
|
||||
|
||||
return try {
|
||||
val result = command.execute(request.args, request.humanBeing)
|
||||
Response(true, result)
|
||||
} catch (e: Exception) {
|
||||
Response(false, "[Ошибка выполнения] ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
fun getHistory(): List<String> = history.toList()
|
||||
fun getCommands(): Map<String, Command> = commands.toMap()
|
||||
|
||||
private fun addToHistory(name: String) {
|
||||
if (history.size >= 12) history.removeFirst()
|
||||
history.addLast(name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<configuration debug="false" statusListenerClass="ch.qos.logback.core.status.NopStatusListener">
|
||||
|
||||
<appender name="ALL_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>logs/all.log</file>
|
||||
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>logs/archived/all-%d{yyyy-MM-dd_HH-mm}.%i.log</fileNamePattern>
|
||||
|
||||
<maxFileSize>5MB</maxFileSize>
|
||||
|
||||
<maxHistory>30</maxHistory>
|
||||
|
||||
<totalSizeCap>100MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>logs/errors.log</file>
|
||||
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>WARN</level>
|
||||
</filter>
|
||||
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>logs/archived/errors-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
<maxFileSize>2MB</maxFileSize>
|
||||
<maxHistory>10</maxHistory>
|
||||
</rollingPolicy>
|
||||
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="ALL_FILE" />
|
||||
<appender-ref ref="ERROR_FILE" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,7 @@
|
||||
plugins {
|
||||
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0'
|
||||
}
|
||||
rootProject.name = 'Lab6'
|
||||
include 'client'
|
||||
include 'server'
|
||||
include 'common'
|
||||
Reference in New Issue
Block a user