PIbd-12_Kuznetsov_D.V. LabWork07 Hard #9

Closed
ZakenChannel wants to merge 1 commits from Lab_7 into Lab_6
16 changed files with 385 additions and 150 deletions

View File

@ -42,6 +42,30 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.11</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.23.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.23.1</version>
</dependency>
</dependencies>
<build>

View File

@ -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);

View File

@ -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);

View File

@ -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<DrawningWarPlane> storageCollection;
private Stack<DrawningWarPlane> removedPlanesStack;
private AbstractCompany company;
// Окно отрисовки
@FXML
private Canvas canvasWarPlane;
@FXML
private ComboBox<String> comboBox;
@FXML
private TextField textBox;
@FXML
private SplitPane splitPane;
@FXML
private TextField textFieldCollectionName;
@FXML
private RadioButton radioButtonMassive;
@FXML
private RadioButton radioButtonList;
@FXML
private ListView<String> listViewCollection;
@FXML private Canvas canvasWarPlane;
@FXML private ComboBox<String> comboBox;
@FXML private TextField textBox;
@FXML private SplitPane splitPane;
@FXML private TextField textFieldCollectionName;
@FXML private RadioButton radioButtonMassive;
@FXML private RadioButton radioButtonList;
@FXML private ListView<String> 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);

View File

@ -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<DrawningWarPlane> collection = null;
protected ICollectionGenericObjects<DrawningWarPlane> collection;
private int getMaxCount() {
return pictureWidth * pictureHeight / (placeSizeWidth * placeSizeHeight);
return (pictureWidth / placeSizeWidth) * (pictureHeight / placeSizeHeight);
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningWarPlane> 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;
}

View File

@ -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);

View File

@ -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<T> {
/**
* Количество объектов в коллекции
@ -18,7 +22,7 @@ public interface ICollectionGenericObjects<T> {
* @param obj Добавляемый объект
* @return 1 - вставка прошла удачно, 0 - вставка не удалась
*/
int insert(T obj);
int insert(T obj) throws CollectionOverflowException, PositionOutOfCollectionException;
/**
* Добавление объекта в коллекцию на конкретную позицию
@ -27,7 +31,7 @@ public interface ICollectionGenericObjects<T> {
* @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<T> {
* @param position Позиция
* @return Удаленный объект или null, если удаление не удалось
*/
T remove(int position);
T remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException;
/**
* Получение объекта по позиции
@ -43,7 +47,7 @@ public interface ICollectionGenericObjects<T> {
* @param position Позиция
* @return Объект или null, если объекта с такой позицией нет
*/
T get(int position);
T get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException;
void clear();

View File

@ -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<T> implements ICollectionGenericObjects<T> {
*/
@Override
public Iterable<T> getItems() {
return () -> new Iterator<T>() {
return () -> new Iterator<>() {
private int currentIndex = 0;
@Override
@ -80,27 +83,32 @@ public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
}
@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);

View File

@ -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<T> implements ICollectionGenericObjects<T> {
}
@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<T> implements ICollectionGenericObjects<T> {
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<T> getItems() {
return () -> new Iterator<>() {
@ -77,46 +134,5 @@ public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T> {
}
};
}
@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;
}
}

View File

@ -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<T extends DrawningWarPlane> {
* @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<T extends DrawningWarPlane> {
*/
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<T extends DrawningWarPlane> {
*
* @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<T extends DrawningWarPlane> {
writer.newLine();
}
} catch (IOException e) {
return false;
throw new IOException("Ошибка чтения файла");
}
return true;
}
/**
@ -235,7 +236,7 @@ public class StorageCollection<T extends DrawningWarPlane> {
* @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<T extends DrawningWarPlane> {
}
if (collection == null) {
return false;
throw new IllegalStateException("Не удалось определить тип коллекции:" + record[1]);
}
collection.setMaxCount(Integer.parseInt(record[2]));
@ -260,8 +261,16 @@ public class StorageCollection<T extends DrawningWarPlane> {
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<T extends DrawningWarPlane> {
/**
* Загрузка информации из файла
*/
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;
}
/**

View File

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

View File

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

View File

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

View File

@ -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;
}

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<!-- Appender for user actions (INFO level) -->
<File name="UserActionsFile" fileName="logs/user_actions.log">
<PatternLayout>
<pattern>%d{dd.MM.yyyy} - %msg%n</pattern>
</PatternLayout>
</File>
<!-- Appender for all errors (WARN, ERROR, FATAL) -->
<File name="ErrorFile" fileName="logs/errors.log">
<PatternLayout>
<pattern>%d{dd.MM.yyyy} [%level] - %msg%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<!-- Logger for user actions (INFO level) -->
<Logger name="useractions" level="info" additivity="false">
<AppenderRef ref="UserActionsFile"/>
</Logger>
<!-- Logger for errors -->
<Logger name="errors" level="warn" additivity="false">
<AppenderRef ref="ErrorFile"/>
</Logger>
<!-- Root logger for all errors (WARN, ERROR, FATAL) -->
<Root level="warn">
<AppenderRef ref="ErrorFile"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,40 @@
<configuration>
<appender name="ACTIONS" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/actions.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/actions_%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date{dd.MM.yyyy HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<appender name="ERRORS" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/errors.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/errors_%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date{dd.MM.yyyy HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<!-- Logger для действий пользователя -->
<logger level="INFO" additivity="false">
<appender-ref ref="ACTIONS" />
</logger>
<!-- Logger для ошибок -->
<logger level="WARN" additivity="false">
<appender-ref ref="ERRORS" />
</logger>
<!-- Root logger для остальных сообщений -->
<root level="ERROR">
<appender-ref ref="ERRORS" />
</root>
</configuration>