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();
}
@FXML
private void ButtonSelectBus_Click(ActionEvent event) throws IOException {
private void ButtonSelectBus_Click(ActionEvent event) throws IOException, StorageOverflowException {
SelectedBus = _bus;
if (SelectedBus == null) {

View File

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

View File

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

View File

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

View File

@ -60,7 +60,7 @@ public class MapsCollection {
return null;
}
public IDrawingObject get(String name, int id) {
public IDrawingObject get(String name, int id) throws BusNotFoundException {
if (_mapStorages.containsKey(name))
{
return _mapStorages.get(name).getBus(id);
@ -132,21 +132,7 @@ public class MapsCollection {
{
return false;
}
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 {
if (str.contains("MapsCollectionStorage")) {
String[] data = reader.readLine().split(":");
AbstractMap map = switch (data[1]) {
@ -165,9 +151,26 @@ public class MapsCollection {
_mapStorages.get(data[0]).LoadData(k);
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;
}

View File

@ -17,13 +17,16 @@ class SetBusesGeneric<T> {
_places = new ArrayList<>();
}
public int Insert(T bus)
{
public int Insert(T bus) throws StorageOverflowException {
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;
BusyPlaces++;
@ -31,17 +34,20 @@ class SetBusesGeneric<T> {
return position;
}
public T Remove(int position)
{
if (position < 0 || position >= _maxCount) return null;
public T Remove(int position) throws BusNotFoundException {
if (position < 0 || position >= _maxCount)
throw new BusNotFoundException();
T savedBus = _places.get(position - 1);
if (savedBus == null) {
throw new BusNotFoundException();
}
_places.set(position - 1, null);
return savedBus;
}
public T Get(int position)
{
if (position < 0 || position >= _maxCount) return null;
public T Get(int position) throws BusNotFoundException {
if (position < 0 || position >= _maxCount)
throw new BusNotFoundException();
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.kordamp.bootstrapfx.core;
requires javafx.graphics;
requires org.apache.logging.log4j;
requires org.apache.log4j;
opens com.example.doubledeckerbus to javafx.fxml;
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>