This commit is contained in:
shadowik 2022-12-26 04:32:24 +04:00
parent b29d0761a5
commit 6df97d8386
10 changed files with 205 additions and 91 deletions

View File

@ -0,0 +1,24 @@
package com.example.doubledeckerbus;
public class BusNotFoundException extends Exception {
public BusNotFoundException(int num)
{
super("Object not found by position " + num);
}
public BusNotFoundException()
{
super();
}
public BusNotFoundException(String message)
{
super(message);
}
public BusNotFoundException(String message, Throwable cause)
{
super(message, cause);
}
public BusNotFoundException(Throwable cause)
{
super(cause);
}
}

View File

@ -146,7 +146,7 @@ public class ControllerBus {
BorderChanged(); BorderChanged();
} }
@FXML @FXML
private void ButtonSelectBus_Click(ActionEvent event) throws IOException { private void ButtonSelectBus_Click(ActionEvent event) throws IOException, StorageOverflowException {
SelectedBus = _bus; SelectedBus = _bus;
if (SelectedBus == null) { if (SelectedBus == null) {

View File

@ -1,4 +1,5 @@
package com.example.doubledeckerbus; package com.example.doubledeckerbus;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
@ -13,11 +14,12 @@ import javafx.scene.paint.Color;
import javafx.stage.FileChooser; import javafx.stage.FileChooser;
import javafx.stage.Stage; import javafx.stage.Stage;
import java.io.File; import java.io.*;
import java.io.IOException; import java.util.*;
import java.util.HashMap;
import java.util.Objects; import org.apache.logging.log4j.Level;
import java.util.Optional; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ControllerMapWithSetBus { public class ControllerMapWithSetBus {
@ -28,8 +30,9 @@ public class ControllerMapWithSetBus {
_mapsDict.put("Водная карта", new WaterMap()); _mapsDict.put("Водная карта", new WaterMap());
} }
AbstractMap map = new SimpleMap(); AbstractMap map = new SimpleMap();
private final Logger _logger = LogManager.getLogger(ControllerMapWithSetBus.class);
public static int AddNewBus (DrawingObjectBus bus) { public static int AddNewBus (DrawingObjectBus bus) throws StorageOverflowException {
return _mapsCollection.GetId(selected).add(bus); return _mapsCollection.GetId(selected).add(bus);
} }
static public MapsCollection _mapsCollection; static public MapsCollection _mapsCollection;
@ -61,11 +64,15 @@ public class ControllerMapWithSetBus {
private TextField TextFieldMap; private TextField TextFieldMap;
@FXML @FXML
private void initialize(){ private void initialize() throws FileNotFoundException {
gc = canvasBus.getGraphicsContext2D(); gc = canvasBus.getGraphicsContext2D();
if (selected != null) { if (selected != null) {
showStorage(); showStorage();
} }
Properties prop = new Properties();
// InputStream = new FileInputStream("/home/user/IdeaProjects/PIbd-21_Zaharchenko_M.I._DoubleDeckerBus._Hard/DoubleDeckerBus/src/main/resources/com/example/doubledeckerbus/log4j2.xml");
Logger log = LogManager.getLogger(ControllerMapWithSetBus.class);
if (_mapsCollection == null) if (_mapsCollection == null)
_mapsCollection = new MapsCollection((int) canvasBus.getWidth(), (int) canvasBus.getHeight()); _mapsCollection = new MapsCollection((int) canvasBus.getWidth(), (int) canvasBus.getHeight());
comboBoxSelectorMap.setItems(countOfMap); comboBoxSelectorMap.setItems(countOfMap);
@ -73,6 +80,7 @@ public class ControllerMapWithSetBus {
listViewMaps.getSelectionModel().selectedItemProperty() listViewMaps.getSelectionModel().selectedItemProperty()
.addListener((observableValue, s, t1) -> { .addListener((observableValue, s, t1) -> {
selected = t1; selected = t1;
_logger.info("Another Map has been chosen");
showStorage(); showStorage();
}); });
listViewMaps.setItems(_mapsCollection.toObserveList()); listViewMaps.setItems(_mapsCollection.toObserveList());
@ -137,14 +145,21 @@ public class ControllerMapWithSetBus {
String selectedMapName = listViewMaps.getSelectionModel().getSelectedItem(); String selectedMapName = listViewMaps.getSelectionModel().getSelectedItem();
Alert alert; Alert alert;
if (selectedMapName != null && selectedMapName.length() != 0 && _mapsCollection.get(selectedMapName).add(objectBus) != -1) try {
{ if (selectedMapName != null && selectedMapName.length() != 0 && _mapsCollection.get(selectedMapName).add(objectBus) != -1)
alert = new Alert(Alert.AlertType.INFORMATION, "Объект добавлен", ButtonType.OK); {
_mapsCollection.get(selectedMapName).ShowSet(gc); alert = new Alert(Alert.AlertType.INFORMATION, "Объект добавлен", ButtonType.OK);
} _mapsCollection.get(selectedMapName).ShowSet(gc);
else _logger.info("Bus added");
{ }
alert = new Alert(Alert.AlertType.ERROR, "Не удалось добавить объект", ButtonType.OK); else
{
alert = new Alert(Alert.AlertType.ERROR, "Не удалось добавить объект", ButtonType.OK);
_logger.warn("Bus not added");
}
} catch (StorageOverflowException e) {
_logger.warn("StorageOverFlow");
alert = new Alert(Alert.AlertType.ERROR, "Хранилище переполнено");
} }
showStorage(); showStorage();
alert.showAndWait(); alert.showAndWait();
@ -181,6 +196,7 @@ public class ControllerMapWithSetBus {
return; return;
} }
_mapsCollection.DelMap(listViewMaps.getSelectionModel().getSelectedItem()); _mapsCollection.DelMap(listViewMaps.getSelectionModel().getSelectedItem());
_logger.info("Map was deleted");
ReloadMaps(); ReloadMaps();
showStorage(); showStorage();
} }
@ -200,6 +216,7 @@ public class ControllerMapWithSetBus {
Form.myStage.setScene(scene); Form.myStage.setScene(scene);
Form.myStage.show(); Form.myStage.show();
} }
_logger.info("Bus Edited");
} }
@FXML @FXML
@ -222,27 +239,42 @@ public class ControllerMapWithSetBus {
int pos; int pos;
try { try {
pos = Integer.parseInt(textBoxPosition.getText()); pos = Integer.parseInt(textBoxPosition.getText());
if (pos < 1 || pos > _mapsCollection.GetId(selected).getCount()) return;
}
catch (Exception e) {
return;
}
if (_mapsCollection.GetId(selected).remove(pos) != null) if (pos < 1 || pos > _mapsCollection.GetId(selected).getCount()) return;
{
alert = new Alert(Alert.AlertType.WARNING); if (_mapsCollection.GetId(selected).remove(pos) != null)
alert.setTitle("RemoveBus"); {
alert.setContentText("Вы удалили объект"); alert = new Alert(Alert.AlertType.WARNING);
option = alert.showAndWait(); alert.setTitle("RemoveBus");
alert.setContentText("Вы удалили объект");
option = alert.showAndWait();
_logger.info("Bus removed");
}
else
{
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait();
}
showStorage();
} }
else catch (BusNotFoundException e) {
{
alert = new Alert(Alert.AlertType.WARNING); alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus"); alert.setTitle("RemoveBus");
alert.setContentText("Не удалось удалить объект"); alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait(); option = alert.showAndWait();
_logger.warn("bus not found");
} }
showStorage(); catch (Exception e) {
alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("RemoveBus");
alert.setContentText("Не удалось удалить объект");
option = alert.showAndWait();
_logger.warn("strange error");
}
} }
@FXML @FXML
@ -250,10 +282,11 @@ public class ControllerMapWithSetBus {
{ {
FirstIncome(); FirstIncome();
showStorage(); showStorage();
_logger.info("show storage");
} }
@FXML @FXML
private void ButtonShowOnMap_Click(ActionEvent event) { private void ButtonShowOnMap_Click(ActionEvent event) throws StorageOverflowException, BusNotFoundException {
FirstIncome(); FirstIncome();
if (selected == null) { if (selected == null) {
return; return;
@ -261,6 +294,7 @@ public class ControllerMapWithSetBus {
gc.setFill(Color.WHITE); gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvasBus.getWidth(), canvasBus.getHeight()); gc.fillRect(0, 0, canvasBus.getWidth(), canvasBus.getHeight());
_mapsCollection.GetId(selected).ShowOnMap(gc); _mapsCollection.GetId(selected).ShowOnMap(gc);
_logger.info("show on map");
} }
@FXML @FXML
@ -280,6 +314,7 @@ public class ControllerMapWithSetBus {
case "buttonRight" -> dir = Direction.Right; case "buttonRight" -> dir = Direction.Right;
} }
_mapsCollection.GetId(selected).MoveObject(dir); _mapsCollection.GetId(selected).MoveObject(dir);
_logger.info("Button move click");
} }
@FXML @FXML
@ -296,25 +331,27 @@ public class ControllerMapWithSetBus {
File selectedDirectory = fileChooser.showSaveDialog(stage); File selectedDirectory = fileChooser.showSaveDialog(stage);
if (selectedDirectory != null) if (selectedDirectory != null)
{ {
String filepath = selectedDirectory.getPath(); try {
if (_mapsCollection.SaveData(filepath)) String filepath = selectedDirectory.getPath();
{ _mapsCollection.SaveData(filepath);
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK); infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK);
_logger.info("Save was successful");
} }
else catch (Exception e) {
{ infoAlert = new Alert(Alert.AlertType.INFORMATION, "Exception " + e.getMessage(), ButtonType.OK);
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK); _logger.warn("Save wasnt successful");
} }
} }
else else
{ {
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK); infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
_logger.info("Not saved");
} }
infoAlert.showAndWait(); infoAlert.showAndWait();
} }
@FXML @FXML
private void ButtonLoad_Click(ActionEvent event) throws IOException { private void ButtonLoad_Click(ActionEvent event) throws IOException, StorageOverflowException {
Alert infoAlert; Alert infoAlert;
Stage stage = (Stage)(buttonLeft.getScene().getWindow()); Stage stage = (Stage)(buttonLeft.getScene().getWindow());
FileChooser fileChooser = new FileChooser(); FileChooser fileChooser = new FileChooser();
@ -326,20 +363,21 @@ public class ControllerMapWithSetBus {
File selectedDirectory = fileChooser.showOpenDialog(stage); File selectedDirectory = fileChooser.showOpenDialog(stage);
if (selectedDirectory != null) if (selectedDirectory != null)
{ {
String filepath = selectedDirectory.getPath(); try {
if (_mapsCollection.LoadData(filepath)) String filepath = selectedDirectory.getPath();
{ _mapsCollection.LoadData(filepath);
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Load was successful", ButtonType.OK); infoAlert = new Alert(Alert.AlertType.INFORMATION, "Load was successful", ButtonType.OK);
_logger.info("Load was successful");
ReloadMaps(); ReloadMaps();
} } catch (Exception e) {
else infoAlert = new Alert(Alert.AlertType.ERROR, "StrangeException: " + e.getMessage(), ButtonType.OK);
{ _logger.warn("StrangeException");
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not loaded", ButtonType.OK);
} }
} }
else else
{ {
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not loaded", ButtonType.OK); infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not loaded", ButtonType.OK);
_logger.info("The file was not loaded");
} }
infoAlert.showAndWait(); infoAlert.showAndWait();
} }
@ -358,19 +396,21 @@ public class ControllerMapWithSetBus {
File selectedDirectory = fileChooser.showSaveDialog(stage); File selectedDirectory = fileChooser.showSaveDialog(stage);
if (selectedDirectory != null) if (selectedDirectory != null)
{ {
String filepath = selectedDirectory.getPath(); try {
if (_mapsCollection.SaveStorage(filepath, listViewMaps.getSelectionModel().getSelectedItem())) String filepath = selectedDirectory.getPath();
{ _mapsCollection.SaveStorage(filepath, listViewMaps.getSelectionModel().getSelectedItem());
infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK); infoAlert = new Alert(Alert.AlertType.INFORMATION, "Save was successful", ButtonType.OK);
_logger.info("Save storage was successful");
} }
else catch (Exception e) {
{ infoAlert = new Alert(Alert.AlertType.INFORMATION, "Exseption " + e.getMessage() , ButtonType.OK);
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK); _logger.warn("Save storage wasnt successful");
} }
} }
else else
{ {
infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK); infoAlert = new Alert(Alert.AlertType.INFORMATION, "The file was not saved", ButtonType.OK);
_logger.info("Save storage wasnt successful");
} }
infoAlert.showAndWait(); infoAlert.showAndWait();
} }
@ -383,6 +423,7 @@ public class ControllerMapWithSetBus {
gc.setFill(Color.WHITE); gc.setFill(Color.WHITE);
gc.fillRect(0, 0, pictureBoxBus.getWidth(), pictureBoxBus.getHeight()); gc.fillRect(0, 0, pictureBoxBus.getWidth(), pictureBoxBus.getHeight());
_mapsCollection.GetId(selected).ShowSet(gc); _mapsCollection.GetId(selected).ShowSet(gc);
_logger.info("showStorage");
} }

View File

@ -129,7 +129,7 @@ public class ControllerPolymorph {
BorderChanged(); BorderChanged();
} }
@FXML @FXML
private void ButtonSelectBus_Click(ActionEvent event) throws IOException { private void ButtonSelectBus_Click(ActionEvent event) throws IOException, StorageOverflowException {
SelectedBus = _bus; SelectedBus = _bus;
if (SelectedBus == null) { if (SelectedBus == null) {

View File

@ -29,13 +29,11 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
_map = map; _map = map;
} }
public int add(T bus) public int add(T bus) throws StorageOverflowException {
{
return _setBuses.Insert(bus); return _setBuses.Insert(bus);
} }
public T remove(int position) public T remove(int position) throws BusNotFoundException {
{
T deletedBus = _setBuses.Remove(position); T deletedBus = _setBuses.Remove(position);
_deletedBuses.push(deletedBus); _deletedBuses.push(deletedBus);
return deletedBus; return deletedBus;
@ -53,8 +51,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
DrawBuses(gc); DrawBuses(gc);
} }
public void ShowOnMap(GraphicsContext gc) public void ShowOnMap(GraphicsContext gc) throws StorageOverflowException, BusNotFoundException {
{
Shaking(); Shaking();
for (var bus: _setBuses.GetBuses()) for (var bus: _setBuses.GetBuses())
{ {
@ -74,8 +71,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
} }
} }
private void Shaking() private void Shaking() throws StorageOverflowException, BusNotFoundException {
{
int j = _setBuses.Count() - 1; int j = _setBuses.Count() - 1;
for (int i = 0; i < _setBuses.Count(); i++) for (int i = 0; i < _setBuses.Count(); i++)
{ {
@ -144,7 +140,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
return _setBuses.Count(); return _setBuses.Count();
} }
public T getBus(int ind){ public T getBus(int ind) throws BusNotFoundException {
return _setBuses.Get(ind); return _setBuses.Get(ind);
} }
@ -159,8 +155,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void LoadData(String[] data) public void LoadData(String[] data) throws StorageOverflowException {
{
for (String items : data) for (String items : data)
{ {
_setBuses.Insert((T)(DrawingObjectBus.Create(items))); _setBuses.Insert((T)(DrawingObjectBus.Create(items)));
@ -168,8 +163,7 @@ public class MapWithSetBusesGeneric<T extends IDrawingObject, U extends Abstract
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void LoadData(String data) public void LoadData(String data) throws StorageOverflowException {
{
_setBuses.Insert((T)(DrawingObjectBus.Create(data))); _setBuses.Insert((T)(DrawingObjectBus.Create(data)));
} }

View File

@ -60,7 +60,7 @@ public class MapsCollection {
return null; return null;
} }
public IDrawingObject get(String name, int id) { public IDrawingObject get(String name, int id) throws BusNotFoundException {
if (_mapStorages.containsKey(name)) if (_mapStorages.containsKey(name))
{ {
return _mapStorages.get(name).getBus(id); return _mapStorages.get(name).getBus(id);
@ -132,21 +132,7 @@ public class MapsCollection {
{ {
return false; return false;
} }
if (!str.contains("MapsCollectionStorage")) { if (str.contains("MapsCollectionStorage")) {
while ((str = reader.readLine()) != null) {
String[] elem = str.split(String.format("\\%c", separatorDict));
AbstractMap map = switch (elem[1]) {
case "SimpleMap" -> new SimpleMap();
case "WaterMap" -> new WaterMap();
default -> null;
};
if (elem.length == 3) {
_mapStorages.get(elem[0]).LoadData(elem[2].split(String.format("%c", separatorData)));
}
}
}
else {
String[] data = reader.readLine().split(":"); String[] data = reader.readLine().split(":");
AbstractMap map = switch (data[1]) { AbstractMap map = switch (data[1]) {
@ -165,9 +151,26 @@ public class MapsCollection {
_mapStorages.get(data[0]).LoadData(k); _mapStorages.get(data[0]).LoadData(k);
k = reader.readLine(); k = reader.readLine();
} }
}
else {
while ((str = reader.readLine()) != null) {
String[] elem = str.split(String.format("\\%c", separatorDict));
AbstractMap map = switch (elem[1]) {
case "SimpleMap" -> new SimpleMap();
case "WaterMap" -> new WaterMap();
default -> null;
};
_mapStorages.put(elem[0], new MapWithSetBusesGeneric<>(_pictureWidth, _pictureHeight, map));
if (elem.length == 3) {
_mapStorages.get(elem[0]).LoadData(elem[2].split(String.format("%c", separatorData)));
}
}
} }
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
} }
return true; return true;
} }

View File

@ -17,13 +17,16 @@ class SetBusesGeneric<T> {
_places = new ArrayList<>(); _places = new ArrayList<>();
} }
public int Insert(T bus) public int Insert(T bus) throws StorageOverflowException {
{
return Insert(bus, 0); return Insert(bus, 0);
} }
public int Insert(T bus, int position) public int Insert(T bus, int position) throws StorageOverflowException {
{ if (_places.size() == _maxCount)
{
throw new StorageOverflowException(_places.size());
}
if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) return -1; if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) return -1;
BusyPlaces++; BusyPlaces++;
@ -31,17 +34,20 @@ class SetBusesGeneric<T> {
return position; return position;
} }
public T Remove(int position) public T Remove(int position) throws BusNotFoundException {
{ if (position < 0 || position >= _maxCount)
if (position < 0 || position >= _maxCount) return null; throw new BusNotFoundException();
T savedBus = _places.get(position - 1); T savedBus = _places.get(position - 1);
if (savedBus == null) {
throw new BusNotFoundException();
}
_places.set(position - 1, null); _places.set(position - 1, null);
return savedBus; return savedBus;
} }
public T Get(int position) public T Get(int position) throws BusNotFoundException {
{ if (position < 0 || position >= _maxCount)
if (position < 0 || position >= _maxCount) return null; throw new BusNotFoundException();
return _places.get(position); return _places.get(position);
} }

View File

@ -0,0 +1,25 @@
package com.example.doubledeckerbus;
public class StorageOverflowException extends Exception
{
public StorageOverflowException(int count)
{
super("The set exceeded the allowed number of elements: " + count);
}
public StorageOverflowException()
{
super();
}
public StorageOverflowException(String message)
{
super(message);
}
public StorageOverflowException(String message, Throwable cause)
{
super(message, cause);
}
public StorageOverflowException(Throwable cause)
{
super(cause);
}
}

View File

@ -5,6 +5,8 @@ module com.example.doubledeckerbus {
requires org.controlsfx.controls; requires org.controlsfx.controls;
requires org.kordamp.bootstrapfx.core; requires org.kordamp.bootstrapfx.core;
requires javafx.graphics; requires javafx.graphics;
requires org.apache.logging.log4j;
requires org.apache.log4j;
opens com.example.doubledeckerbus to javafx.fxml; opens com.example.doubledeckerbus to javafx.fxml;
exports com.example.doubledeckerbus; exports com.example.doubledeckerbus;

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<File name="InfoFile" fileName="info.log" immediateFlush="false" append="true">
<PatternLayout pattern="[%-4level]: %msg (date-%d{yyy.MM.dd})%n"/>
<LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="WarnErrorFatalFile" fileName="warn.log" immediateFlush="false" append="true">
<PatternLayout pattern="[%.5level]: %msg (date-%d{yyy.MM.dd})%n"/>
<LevelRangeFilter minLevel="FATAL" maxLevel="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="InfoFile" level="info"/>
<AppenderRef ref="WarnErrorFatalFile" level="warn"/>
</Root>
</Loggers>
</Configuration>