From dcf18b6524c5ba9030ec553c4dee3085b533f625 Mon Sep 17 00:00:00 2001 From: ZakenChannel Date: Wed, 15 May 2024 02:02:49 +0400 Subject: [PATCH] lab 7 done --- ProjectAirFighter/pom.xml | 24 ++++ .../projectairfighter/FormConstructor.java | 4 +- .../projectairfighter/FormPlaneConfig.java | 4 +- .../FormWarPlaneCollection.java | 131 ++++++++++-------- .../AbstractCompany.java | 28 ++-- .../collectiongenericobjects/Hangar.java | 11 +- .../ICollectionGenericObjects.java | 12 +- .../ListGenericObjects.java | 24 ++-- .../MassiveGenericObjects.java | 106 ++++++++------ .../StorageCollection.java | 46 +++--- .../CollectionOverflowException.java | 21 +++ .../exceptions/ObjectNotFoundException.java | 22 +++ .../PositionOutOfCollectionException.java | 23 +++ .../src/main/java/module-info.java | 4 + .../src/main/resources/log4j2.xml | 35 +++++ .../src/main/resources/logback.xml | 40 ++++++ 16 files changed, 385 insertions(+), 150 deletions(-) create mode 100644 ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/CollectionOverflowException.java create mode 100644 ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/ObjectNotFoundException.java create mode 100644 ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/PositionOutOfCollectionException.java create mode 100644 ProjectAirFighter/src/main/resources/log4j2.xml create mode 100644 ProjectAirFighter/src/main/resources/logback.xml diff --git a/ProjectAirFighter/pom.xml b/ProjectAirFighter/pom.xml index 6083573..5a192ce 100644 --- a/ProjectAirFighter/pom.xml +++ b/ProjectAirFighter/pom.xml @@ -42,6 +42,30 @@ ${junit.version} test + + + ch.qos.logback + logback-classic + 1.4.12 + + + + org.slf4j + slf4j-api + 2.0.11 + + + + org.apache.logging.log4j + log4j-core + 2.23.1 + + + org.apache.logging.log4j + log4j-api + 2.23.1 + + diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/FormConstructor.java b/ProjectAirFighter/src/main/java/com/projectairfighter/FormConstructor.java index 6e5ba31..14e6d91 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/FormConstructor.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/FormConstructor.java @@ -4,6 +4,8 @@ import com.projectairfighter.collectiongenericobjects.Constructor; import com.projectairfighter.drawnings.*; import com.projectairfighter.entities.EntityAirFighter; import com.projectairfighter.entities.EntityWarPlane; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; import javafx.application.Application; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; @@ -54,7 +56,7 @@ public class FormConstructor extends Application { } @FXML - public void buttonGoToForm() { + public void buttonGoToForm() throws PositionOutOfCollectionException, ObjectNotFoundException { FormWarPlaneCollection formWarPlaneCollection = FormWarPlaneCollection.getFormWarPlaneCollection(); if (drawningWarPlane != null && formWarPlaneCollection != null) { formWarPlaneCollection.createObject(drawningWarPlane); diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/FormPlaneConfig.java b/ProjectAirFighter/src/main/java/com/projectairfighter/FormPlaneConfig.java index 567fe6a..bf1d8ea 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/FormPlaneConfig.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/FormPlaneConfig.java @@ -2,6 +2,8 @@ package com.projectairfighter; import com.projectairfighter.drawnings.*; import com.projectairfighter.entities.EntityAirFighter; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.fxml.FXML; @@ -246,7 +248,7 @@ public class FormPlaneConfig extends Application implements Initializable { } @FXML - public void buttonAdd(ActionEvent event) { + public void buttonAdd(ActionEvent event) throws PositionOutOfCollectionException, ObjectNotFoundException { FormWarPlaneCollection formWarPlaneCollection = FormWarPlaneCollection.getFormWarPlaneCollection(); if (plane != null && formWarPlaneCollection != null) { formWarPlaneCollection.createObject(plane); diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/FormWarPlaneCollection.java b/ProjectAirFighter/src/main/java/com/projectairfighter/FormWarPlaneCollection.java index 8f03986..e4003ce 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/FormWarPlaneCollection.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/FormWarPlaneCollection.java @@ -2,6 +2,9 @@ package com.projectairfighter; import com.projectairfighter.collectiongenericobjects.*; import com.projectairfighter.drawnings.DrawningWarPlane; +import com.projectairfighter.exceptions.CollectionOverflowException; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; import javafx.application.Application; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; @@ -12,6 +15,8 @@ import javafx.scene.canvas.Canvas; import javafx.scene.control.*; import javafx.stage.FileChooser; import javafx.stage.Stage; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; @@ -21,37 +26,20 @@ import java.util.Stack; public class FormWarPlaneCollection extends Application implements Initializable { private StorageCollection storageCollection; - private Stack removedPlanesStack; - private AbstractCompany company; - - // Окно отрисовки - @FXML - private Canvas canvasWarPlane; - - @FXML - private ComboBox comboBox; - - @FXML - private TextField textBox; - - @FXML - private SplitPane splitPane; - - @FXML - private TextField textFieldCollectionName; - - @FXML - private RadioButton radioButtonMassive; - - @FXML - private RadioButton radioButtonList; - - @FXML - private ListView listViewCollection; + @FXML private Canvas canvasWarPlane; + @FXML private ComboBox comboBox; + @FXML private TextField textBox; + @FXML private SplitPane splitPane; + @FXML private TextField textFieldCollectionName; + @FXML private RadioButton radioButtonMassive; + @FXML private RadioButton radioButtonList; + @FXML private ListView listViewCollection; private static FormWarPlaneCollection formWarPlaneCollection; + private static final Logger userLogger = LogManager.getLogger("useractions"); + private static final Logger errorsLogger = LogManager.getLogger("errors"); public static void setFormWarPlaneCollection(FormWarPlaneCollection controller) { formWarPlaneCollection = controller; @@ -72,15 +60,20 @@ public class FormWarPlaneCollection extends Application implements Initializable splitPane.getItems().get(1).setDisable(true); } - public void createObject(DrawningWarPlane drawningAirFighter) { + public void createObject(DrawningWarPlane drawningAirFighter) throws PositionOutOfCollectionException, ObjectNotFoundException { if (company == null) return; - int result = company.addPlane(drawningAirFighter); - if (result != -1) { - showAlert("Объект добавлен"); - company.show(canvasWarPlane); - } else { - showAlert("Не удалось создать"); + try { + int result = company.addPlane(drawningAirFighter); + if (result != -1) { + showAlert("Объект добавлен"); + company.show(canvasWarPlane); + } else { + showAlert("Не удалось создать"); + } + } catch (CollectionOverflowException e) { + showError("Ошибка переполнения коллекции"); + errorsLogger.warn("Ошибка: {}", e.getMessage()); } } @@ -97,27 +90,37 @@ public class FormWarPlaneCollection extends Application implements Initializable confirmationDialog.showAndWait().ifPresent(response -> { if (response == ButtonType.OK) { int pos = Integer.parseInt(text); - DrawningWarPlane removedPlane = company.removePlane(pos); - if (removedPlane != null) { - removedPlanesStack.push(removedPlane); - showAlert("Объект удален"); - company.show(canvasWarPlane); - } else { - showAlert("Не удалось удалить объект"); + try { + DrawningWarPlane removedPlane = company.removePlane(pos); + if (removedPlane != null) { + removedPlanesStack.push(removedPlane); + showAlert("Объект удален"); + company.show(canvasWarPlane); + userLogger.info("Удаление объекта по индексу {}", pos); + } else { + showAlert("Не удалось удалить объект"); + userLogger.info("Не удалось удалить объект из коллекции по индексу {}", pos); + } + } catch (ObjectNotFoundException e) { + showError("Ошибка: отсутствует объект"); + errorsLogger.warn("Ошибка: {}", e.getMessage()); + } catch (PositionOutOfCollectionException e) { + showError("Ошибка: неправильная позиция"); + errorsLogger.warn("Ошибка: {}", e.getMessage()); } } }); } @FXML - private void buttonRefresh() { + private void buttonRefresh() throws PositionOutOfCollectionException, ObjectNotFoundException { if (company == null) return; company.show(canvasWarPlane); } @FXML - private void buttonGoToCheck() { + private void buttonGoToCheck() throws PositionOutOfCollectionException, ObjectNotFoundException { if (company == null) return; DrawningWarPlane warPlane = null; @@ -140,7 +143,7 @@ public class FormWarPlaneCollection extends Application implements Initializable if (company == null) return; try { - FXMLLoader loader = new FXMLLoader(getClass().getResource("FormConstructor.fxml")); + FXMLLoader loader = new FXMLLoader(getClass().getResource("FormConstructr.fxml")); Parent root = loader.load(); FormConstructor controller = loader.getController(); Stage stage = new Stage(); @@ -149,7 +152,7 @@ public class FormWarPlaneCollection extends Application implements Initializable FormWarPlaneCollection.setFormWarPlaneCollection(this); stage.show(); } catch (IOException e) { - e.printStackTrace(); + errorsLogger.fatal("Ошибка: {}", e.getMessage()); } } @@ -172,7 +175,7 @@ public class FormWarPlaneCollection extends Application implements Initializable FormWarPlaneCollection.setFormWarPlaneCollection(this); stage.showAndWait(); } catch (IOException e) { - e.printStackTrace(); + errorsLogger.fatal("Ошибка: {}", e.getMessage()); } } @@ -186,7 +189,7 @@ public class FormWarPlaneCollection extends Application implements Initializable stage.setScene(new Scene(root)); stage.showAndWait(); } catch (IOException e) { - e.printStackTrace(); + errorsLogger.fatal("Ошибка: {}", e.getMessage()); } } @@ -194,6 +197,7 @@ public class FormWarPlaneCollection extends Application implements Initializable void buttonCollectionAdd() { if (textFieldCollectionName.getText().isEmpty() || (!radioButtonList.isSelected() && !radioButtonMassive.isSelected())) { showError("Не все данные заполнены"); + userLogger.info("Не удалось добавить коллекцию: не все данные заполнены"); return; } @@ -205,6 +209,7 @@ public class FormWarPlaneCollection extends Application implements Initializable } storageCollection.addCollection(textFieldCollectionName.getText(), collectionType); + userLogger.info("Добавлена коллекция типа {} с названием {}", collectionType, textFieldCollectionName.getText()); refreshListBoxItems(); } @@ -224,6 +229,7 @@ public class FormWarPlaneCollection extends Application implements Initializable } storageCollection.delCollection(listViewCollection.getSelectionModel().getSelectedItem()); + userLogger.info("Удаление коллекции с названием {}", listViewCollection.getSelectionModel().getSelectedItem()); refreshListBoxItems(); } @@ -240,11 +246,15 @@ public class FormWarPlaneCollection extends Application implements Initializable File selectedFile = fileChooser.showSaveDialog(null); if (selectedFile != null) { - boolean success = storageCollection.saveData(selectedFile.getAbsolutePath()); - if (success) { - showAlert("Сохранение прошло успешно", "Результат", Alert.AlertType.INFORMATION); - } else { + try { + boolean success = storageCollection.saveData(selectedFile.getAbsolutePath()); + if (success) { + showAlert("Сохранение прошло успешно", "Результат", Alert.AlertType.INFORMATION); + userLogger.info("Сохранение в файл: {}", selectedFile.getName()); + } + } catch (Exception ex) { showAlert("Не сохранилось", "Результат", Alert.AlertType.ERROR); + errorsLogger.error("Ошибка: {}", ex.getMessage()); } } } @@ -267,11 +277,13 @@ public class FormWarPlaneCollection extends Application implements Initializable File selectedFile = fileChooser.showSaveDialog(null); if (selectedFile != null) { - boolean success = storageCollection.saveData(selectedFile.getAbsolutePath(), listViewCollection.getSelectionModel().getSelectedItem()); - if (success) { + try { + storageCollection.saveData(selectedFile.getAbsolutePath(), listViewCollection.getSelectionModel().getSelectedItem()); showAlert("Сохранение прошло успешно", "Результат", Alert.AlertType.INFORMATION); - } else { + userLogger.info("Сохранение в файл: {}", selectedFile.getName()); + } catch (Exception ex) { showAlert("Не сохранилось", "Результат", Alert.AlertType.ERROR); + errorsLogger.error("Ошибка: {}", ex.getMessage()); } } } @@ -289,13 +301,14 @@ public class FormWarPlaneCollection extends Application implements Initializable File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { - boolean success = storageCollection.loadData(selectedFile.getAbsolutePath()); - - if (success) { + try { + storageCollection.loadData(selectedFile.getAbsolutePath()); refreshListBoxItems(); showAlert("Загрузка прошла успешно", "Результат", Alert.AlertType.INFORMATION); - } else { + userLogger.info("Загрузка из файла: {}", selectedFile.getName()); + } catch (Exception e) { showAlert("Загрузка не выполнена", "Результат", Alert.AlertType.ERROR); + errorsLogger.error("Ошибка: {}", e.getMessage()); } } } @@ -356,7 +369,7 @@ public class FormWarPlaneCollection extends Application implements Initializable } private void showError(String message) { - Alert alert = new Alert(Alert.AlertType.INFORMATION); + Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Ошибка"); alert.setHeaderText(null); alert.setContentText(message); diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/AbstractCompany.java b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/AbstractCompany.java index 032d85e..917f807 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/AbstractCompany.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/AbstractCompany.java @@ -1,6 +1,9 @@ package com.projectairfighter.collectiongenericobjects; import com.projectairfighter.drawnings.DrawningWarPlane; +import com.projectairfighter.exceptions.CollectionOverflowException; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; @@ -13,10 +16,10 @@ public abstract class AbstractCompany { protected final int pictureWidth; protected final int pictureHeight; - protected ICollectionGenericObjects collection = null; + protected ICollectionGenericObjects collection; private int getMaxCount() { - return pictureWidth * pictureHeight / (placeSizeWidth * placeSizeHeight); + return (pictureWidth / placeSizeWidth) * (pictureHeight / placeSizeHeight); } public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) { @@ -26,35 +29,38 @@ public abstract class AbstractCompany { this.collection.setMaxCount(getMaxCount()); } - public int addPlane(DrawningWarPlane plane) { + public int addPlane(DrawningWarPlane plane) throws PositionOutOfCollectionException, CollectionOverflowException { if (collection == null) { return -1; } return collection.insert(plane); } - public DrawningWarPlane removePlane(int position) { + public DrawningWarPlane removePlane(int position) throws PositionOutOfCollectionException, ObjectNotFoundException { return collection != null ? collection.remove(position) : null; } - public DrawningWarPlane getRandomPlane() { - Random rnd = new Random(); - return collection != null ? collection.get(rnd.nextInt(getMaxCount())) : null; + public DrawningWarPlane getRandomPlane() throws PositionOutOfCollectionException, ObjectNotFoundException { + return collection != null ? collection.get(new Random().nextInt(getMaxCount())) : null; } - public void show(Canvas canvas) { + public void show(Canvas canvas) throws PositionOutOfCollectionException, ObjectNotFoundException { GraphicsContext graphicsContext = canvas.getGraphicsContext2D(); graphicsContext.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); drawBackground(graphicsContext); setObjectsPosition(); for (int i = 0; i < (collection != null ? collection.getCount() : 0); i++) { - DrawningWarPlane obj = collection.get(i); - if (obj != null) obj.drawTransport(graphicsContext); + try + { + DrawningWarPlane obj = collection.get(i); + if (obj != null) obj.drawTransport(graphicsContext); + } + catch (ObjectNotFoundException ignored) {} } } protected abstract void drawBackground(GraphicsContext gc); - protected abstract void setObjectsPosition(); + protected abstract void setObjectsPosition() throws PositionOutOfCollectionException, ObjectNotFoundException; } diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/Hangar.java b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/Hangar.java index 40520f2..ccde651 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/Hangar.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/Hangar.java @@ -1,6 +1,8 @@ package com.projectairfighter.collectiongenericobjects; import com.projectairfighter.drawnings.DrawningWarPlane; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; @@ -17,7 +19,7 @@ public class Hangar extends AbstractCompany { int posX = 0; for (int i = 0; i < pictureWidth / placeSizeWidth; i++) { int posY = 0; - gc.strokeLine(posX, posY, posX, posY + placeSizeHeight * (pictureHeight / placeSizeHeight)); + gc.strokeLine(posX, posY, posX, posY + placeSizeHeight * ((double) pictureHeight / placeSizeHeight)); for (int j = 0; j <= pictureHeight / placeSizeHeight; j++) { gc.strokeLine(posX, posY, posX + placeSizeWidth - 30, posY); posY += placeSizeHeight; @@ -27,13 +29,16 @@ public class Hangar extends AbstractCompany { } @Override - protected void setObjectsPosition() { + protected void setObjectsPosition() throws PositionOutOfCollectionException { int counter = 0; int valPlaceY = pictureHeight / placeSizeHeight; int valPlaceX = pictureWidth / placeSizeWidth; for (int y = ((valPlaceY - 1) * placeSizeHeight) + 8; y >= 0; y -= placeSizeHeight) { for (int x = ((valPlaceX - 1) * placeSizeWidth) + 10; x >= 0; x -= placeSizeWidth) { - DrawningWarPlane plane = collection != null ? collection.get(counter) : null; + DrawningWarPlane plane = null; + try { + plane = collection != null ? collection.get(counter) : null; + } catch (ObjectNotFoundException ignore) { } if (plane != null) { plane.setPictureSize(pictureWidth, pictureHeight); plane.setPosition(x, y); diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ICollectionGenericObjects.java b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ICollectionGenericObjects.java index 6958689..2811c32 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ICollectionGenericObjects.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ICollectionGenericObjects.java @@ -1,5 +1,9 @@ package com.projectairfighter.collectiongenericobjects; +import com.projectairfighter.exceptions.CollectionOverflowException; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; + public interface ICollectionGenericObjects { /** * Количество объектов в коллекции @@ -18,7 +22,7 @@ public interface ICollectionGenericObjects { * @param obj Добавляемый объект * @return 1 - вставка прошла удачно, 0 - вставка не удалась */ - int insert(T obj); + int insert(T obj) throws CollectionOverflowException, PositionOutOfCollectionException; /** * Добавление объекта в коллекцию на конкретную позицию @@ -27,7 +31,7 @@ public interface ICollectionGenericObjects { * @param position Позиция * @return 1 - вставка прошла удачно, 0 - вставка не удалась */ - int insert(T obj, int position); + int insert(T obj, int position) throws PositionOutOfCollectionException, CollectionOverflowException; /** * Удаление объекта из коллекции с конкретной позиции @@ -35,7 +39,7 @@ public interface ICollectionGenericObjects { * @param position Позиция * @return Удаленный объект или null, если удаление не удалось */ - T remove(int position); + T remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException; /** * Получение объекта по позиции @@ -43,7 +47,7 @@ public interface ICollectionGenericObjects { * @param position Позиция * @return Объект или null, если объекта с такой позицией нет */ - T get(int position); + T get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException; void clear(); diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ListGenericObjects.java b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ListGenericObjects.java index 06f40f7..632984f 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ListGenericObjects.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/ListGenericObjects.java @@ -1,5 +1,8 @@ package com.projectairfighter.collectiongenericobjects; +import com.projectairfighter.exceptions.CollectionOverflowException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -56,7 +59,7 @@ public class ListGenericObjects implements ICollectionGenericObjects { */ @Override public Iterable getItems() { - return () -> new Iterator() { + return () -> new Iterator<>() { private int currentIndex = 0; @Override @@ -80,27 +83,32 @@ public class ListGenericObjects implements ICollectionGenericObjects { } @Override - public int insert(T obj) { + public int insert(T obj) throws CollectionOverflowException { if (getCount() == maxCount) { - return -1; + throw new CollectionOverflowException(collection.size()); } collection.add(obj); return getCount(); } @Override - public int insert(T obj, int position) { - if (position < 0 || position >= getCount() || getCount() == maxCount) { - return -1; + public int insert(T obj, int position) throws PositionOutOfCollectionException, CollectionOverflowException { + if (position < 0 || position >= getCount()) { + throw new PositionOutOfCollectionException(); } + + if (getCount() == maxCount){ + throw new CollectionOverflowException(); + } + collection.add(position, obj); return position; } @Override - public T remove(int position) { + public T remove(int position) throws PositionOutOfCollectionException { if (position >= getCount() || position < 0) { - return null; + throw new PositionOutOfCollectionException(); } T obj = collection.get(position); collection.remove(position); diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/MassiveGenericObjects.java b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/MassiveGenericObjects.java index 523f3b6..0f28141 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/MassiveGenericObjects.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/MassiveGenericObjects.java @@ -1,5 +1,9 @@ package com.projectairfighter.collectiongenericobjects; +import com.projectairfighter.exceptions.CollectionOverflowException; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; + import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; @@ -34,11 +38,17 @@ public class MassiveGenericObjects implements ICollectionGenericObjects { } @Override - public T get(int position) { - if (position >= 0 && position < getCount()) { - return collection[position]; + public T get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException { + if (position < 0 && position >= getCount()) { + throw new PositionOutOfCollectionException(); } - return null; + + if (collection[position] == null) + { + throw new ObjectNotFoundException(position); + } + + return collection[position]; } @Override @@ -53,6 +63,53 @@ public class MassiveGenericObjects implements ICollectionGenericObjects { return CollectionType.Massive; } + @Override + public int insert(T obj) throws PositionOutOfCollectionException, CollectionOverflowException { + return insert(obj, 0); + } + + @Override + public int insert(T obj, int position) throws PositionOutOfCollectionException, CollectionOverflowException { + if (position < 0 || position >= getCount()) { + throw new PositionOutOfCollectionException(position); + } + if (collection[position] == null) { + collection[position] = obj; + return position; + } + + for (int i = position + 1; i < getCount(); i++) { + if (collection[i] == null) { + collection[i] = obj; + return i; + } + } + for (int i = position - 1; i >= 0; i--) { + if (collection[i] == null) { + collection[i] = obj; + return i; + } + } + + throw new CollectionOverflowException(collection.length); + } + + @Override + public T remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException { + if (position < 0 || position >= getCount()) { + throw new PositionOutOfCollectionException(position); + } + + if (collection[position] == null) + { + throw new ObjectNotFoundException(position); + } + + T obj = collection[position]; + collection[position] = null; + return obj; + } + @Override public Iterable getItems() { return () -> new Iterator<>() { @@ -77,46 +134,5 @@ public class MassiveGenericObjects implements ICollectionGenericObjects { } }; } - - @Override - public int insert(T obj) { - return insert(obj, 0); - } - - @Override - public int insert(T obj, int position) { - if (position < 0 || position >= getCount()) { - return -1; - } - if (collection[position] == null) { - collection[position] = obj; - return position; - } - - for (int i = position + 1; i < getCount(); i++) { - if (collection[i] == null) { - collection[i] = obj; - return i; - } - } - for (int i = position - 1; i >= 0; i--) { - if (collection[i] == null) { - collection[i] = obj; - return i; - } - } - - return -1; - } - - @Override - public T remove(int position) { - if (position < 0 || position >= getCount()) { - return null; - } - T obj = collection[position]; - collection[position] = null; - return obj; - } } diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/StorageCollection.java b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/StorageCollection.java index 716febd..7291eca 100644 --- a/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/StorageCollection.java +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/collectiongenericobjects/StorageCollection.java @@ -1,6 +1,9 @@ package com.projectairfighter.collectiongenericobjects; import com.projectairfighter.drawnings.DrawningWarPlane; +import com.projectairfighter.exceptions.CollectionOverflowException; +import com.projectairfighter.exceptions.ObjectNotFoundException; +import com.projectairfighter.exceptions.PositionOutOfCollectionException; import java.io.*; import java.util.*; @@ -119,7 +122,7 @@ public class StorageCollection { * @param index Индекс элемента в коллекции. * @return Элемент коллекции или null, если коллекция с данным названием отсутствует или индекс некорректен. */ - public T getElement(String name, int index) { + public T getElement(String name, int index) throws PositionOutOfCollectionException, ObjectNotFoundException { return storages.get(name).get(index); } @@ -131,7 +134,7 @@ public class StorageCollection { */ public boolean saveData(String path) { if (storages.isEmpty()) { - return false; + throw new IllegalArgumentException("В хранилище отсутствуют коллекции для сохранения"); } File file = new File(path); @@ -179,11 +182,10 @@ public class StorageCollection { * * @param path путь к файлу * @param collection название коллекции для сохранения - * @return результат сохранения */ - public boolean saveData(String path, String collection) { + public void saveData(String path, String collection) throws IOException { if (storages.isEmpty()) { - return false; + throw new IllegalArgumentException("В хранилище отсутствуют коллекции для сохранения"); } File file = new File(path); @@ -221,9 +223,8 @@ public class StorageCollection { writer.newLine(); } } catch (IOException e) { - return false; + throw new IOException("Ошибка чтения файла"); } - return true; } /** @@ -235,7 +236,7 @@ public class StorageCollection { * @return результат обработки */ @SuppressWarnings("unchecked") - private boolean processRecord(String recordLine, String keyValueSeparator, String itemSeparator) { + private boolean processRecord(String recordLine, String keyValueSeparator, String itemSeparator) throws CollectionOverflowException { String[] record = recordLine.split(keyValueSeparator); if (record.length != 4) { return false; @@ -252,7 +253,7 @@ public class StorageCollection { } if (collection == null) { - return false; + throw new IllegalStateException("Не удалось определить тип коллекции:" + record[1]); } collection.setMaxCount(Integer.parseInt(record[2])); @@ -260,8 +261,16 @@ public class StorageCollection { String[] items = record[3].split(itemSeparator, -1); for (String elem : items) { T ship = (T) createDrawingPlane(elem); - if (ship != null && collection.insert(ship) == -1) { - return false; + + try + { + if (ship != null && collection.insert(ship) == -1) + throw new IllegalStateException("Объект не удалось добавить в коллекцию: " + record[3]); + } + catch (CollectionOverflowException ex){ + throw new CollectionOverflowException("Коллекция переполнена", ex); + } catch (PositionOutOfCollectionException ex) { + throw new CollectionOverflowException("Выход за пределы коллекции", ex); } } storages.put(record[0], collection); @@ -272,35 +281,36 @@ public class StorageCollection { /** * Загрузка информации из файла */ - public boolean loadData(String filename) { + public void loadData(String filename) throws IOException, CollectionOverflowException { File file = new File(filename); if (!file.exists()) { - return false; + throw new FileNotFoundException("Файл не существует"); } try (BufferedReader br = new BufferedReader(new FileReader(file))) { String str = br.readLine(); if (str == null) { - return false; + throw new IllegalArgumentException("Файл пуст"); } if (str.equals(COLLECTION_KEY)) { while ((str = br.readLine()) != null) { if (!processRecord(str, SEPARATOR_FOR_KEY_VALUE_ALL_COL, SEPARATOR_ITEMS_ALL_COL)) { - return false; + return; } } } else if (str.equals(COLLECTION_KEY_ONE_COL)) { while ((str = br.readLine()) != null) { if (!processRecord(str, SEPARATOR_FOR_KEY_VALUE_ONE_TYPE_COL, SEPARATOR_ITEMS_ONE_TYPE_COL)) { - return false; + return; } } + } else { + throw new IllegalArgumentException("В файле неверные данные"); } } catch (IOException e) { - return false; + throw new IOException("Ошибка чтения файла"); } - return true; } /** diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/CollectionOverflowException.java b/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/CollectionOverflowException.java new file mode 100644 index 0000000..ab98f11 --- /dev/null +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/CollectionOverflowException.java @@ -0,0 +1,21 @@ +package com.projectairfighter.exceptions; + +import java.io.Serializable; + +public class CollectionOverflowException extends Exception implements Serializable { + public CollectionOverflowException(int count) { + super("В коллекции превышено допустимое количество: " + count); + } + + public CollectionOverflowException() { + super(); + } + + public CollectionOverflowException(String message) { + super(message); + } + + public CollectionOverflowException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/ObjectNotFoundException.java b/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/ObjectNotFoundException.java new file mode 100644 index 0000000..02ab432 --- /dev/null +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/ObjectNotFoundException.java @@ -0,0 +1,22 @@ +package com.projectairfighter.exceptions; + +import java.io.Serializable; + +public class ObjectNotFoundException extends Exception implements Serializable { + public ObjectNotFoundException(int i) { + super("Не найден объект по позиции " + i); + } + + public ObjectNotFoundException() { + super(); + } + + public ObjectNotFoundException(String message) { + super(message); + } + + public ObjectNotFoundException(String message, Throwable cause) { + super(message, cause); + } +} + diff --git a/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/PositionOutOfCollectionException.java b/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/PositionOutOfCollectionException.java new file mode 100644 index 0000000..3e6fc10 --- /dev/null +++ b/ProjectAirFighter/src/main/java/com/projectairfighter/exceptions/PositionOutOfCollectionException.java @@ -0,0 +1,23 @@ +package com.projectairfighter.exceptions; + +import java.io.Serializable; + +public class PositionOutOfCollectionException extends Exception implements Serializable { + + public PositionOutOfCollectionException(int i) { + super("Выход за границы коллекции. Позиция " + i); + } + + public PositionOutOfCollectionException() { + super(); + } + + public PositionOutOfCollectionException(String message) { + super(message); + } + + public PositionOutOfCollectionException(String message, Throwable cause) { + super(message, cause); + } +} + diff --git a/ProjectAirFighter/src/main/java/module-info.java b/ProjectAirFighter/src/main/java/module-info.java index 5eb9f2c..af450fd 100644 --- a/ProjectAirFighter/src/main/java/module-info.java +++ b/ProjectAirFighter/src/main/java/module-info.java @@ -3,6 +3,9 @@ module com.projectairfighter { requires javafx.fxml; requires org.controlsfx.controls; + requires org.slf4j; + requires org.apache.logging.log4j.core; + requires org.apache.logging.log4j; opens com.projectairfighter to javafx.fxml; exports com.projectairfighter; @@ -14,4 +17,5 @@ module com.projectairfighter { opens com.projectairfighter.movementstrategy to javafx.fxml; exports com.projectairfighter.collectiongenericobjects; opens com.projectairfighter.collectiongenericobjects to javafx.fxml; + exports com.projectairfighter.exceptions; } \ No newline at end of file diff --git a/ProjectAirFighter/src/main/resources/log4j2.xml b/ProjectAirFighter/src/main/resources/log4j2.xml new file mode 100644 index 0000000..5d1564a --- /dev/null +++ b/ProjectAirFighter/src/main/resources/log4j2.xml @@ -0,0 +1,35 @@ + + + + + + + %d{dd.MM.yyyy} - %msg%n + + + + + + + %d{dd.MM.yyyy} [%level] - %msg%n + + + + + + + + + + + + + + + + + + + + + diff --git a/ProjectAirFighter/src/main/resources/logback.xml b/ProjectAirFighter/src/main/resources/logback.xml new file mode 100644 index 0000000..9ab376a --- /dev/null +++ b/ProjectAirFighter/src/main/resources/logback.xml @@ -0,0 +1,40 @@ + + + + logs/actions.log + + logs/actions_%d{yyyy-MM-dd}.log + 30 + + + %date{dd.MM.yyyy HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n + + + + + logs/errors.log + + logs/errors_%d{yyyy-MM-dd}.log + 30 + + + %date{dd.MM.yyyy HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n + + + + + + + + + + + + + + + + + + + -- 2.25.1