Polevoy S.V Lab_work7 #8
21
ArtilleryNotFoundException.java
Normal file
21
ArtilleryNotFoundException.java
Normal file
@ -0,0 +1,21 @@
|
||||
public class ArtilleryNotFoundException extends RuntimeException {
|
||||
public ArtilleryNotFoundException() {
|
||||
|
||||
}
|
||||
|
||||
public ArtilleryNotFoundException(int i) {
|
||||
super("Не найден объект по позиции " + i);
|
||||
}
|
||||
|
||||
public ArtilleryNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ArtilleryNotFoundException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ArtilleryNotFoundException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
19
FileFormatException.java
Normal file
19
FileFormatException.java
Normal file
@ -0,0 +1,19 @@
|
||||
import java.io.IOException;
|
||||
|
||||
public class FileFormatException extends IOException {
|
||||
public FileFormatException() {
|
||||
|
||||
}
|
||||
|
||||
public FileFormatException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public FileFormatException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public FileFormatException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
@ -1,3 +1,5 @@
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.filechooser.FileNameExtensionFilter;
|
||||
import javax.swing.text.DefaultFormatterFactory;
|
||||
@ -41,6 +43,13 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
private final MapsCollection _mapsCollection;
|
||||
private final Stack<IDrawingObject> deletedObjects = new Stack<>();
|
||||
|
||||
private Logger logger;
|
||||
|
||||
public FormMapWithSetArtilleries(Logger logger) {
|
||||
this();
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public FormMapWithSetArtilleries() {
|
||||
this.setTitle("Artillery");
|
||||
this.setContentPane(paneArtilleries);
|
||||
@ -67,13 +76,13 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
dialog.showSaveDialog(this);
|
||||
|
||||
try {
|
||||
if (_mapsCollection.saveData(dialog.getSelectedFile().getAbsolutePath())) {
|
||||
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} else {
|
||||
JOptionPane.showMessageDialog(this, "Не сохранилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
_mapsCollection.saveData(dialog.getSelectedFile().getAbsolutePath());
|
||||
logger.info("Сохранение в файл \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
|
||||
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("Ошибка сохранения в файл: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Не сохранилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
});
|
||||
fileMenu.add(saveMenuItem);
|
||||
@ -85,14 +94,13 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
dialog.showOpenDialog(this);
|
||||
|
||||
try {
|
||||
if (_mapsCollection.loadData(dialog.getSelectedFile().getAbsolutePath())) {
|
||||
reloadMaps();
|
||||
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} else {
|
||||
JOptionPane.showMessageDialog(this, "Не загрузилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
_mapsCollection.loadData(dialog.getSelectedFile().getAbsolutePath());
|
||||
reloadMaps();
|
||||
logger.info("Загрузка из файла \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
|
||||
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} catch (Exception ex) {
|
||||
logger.error("Ошибка загрузки из файла: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Не загрузилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
});
|
||||
fileMenu.add(loadMenuItem);
|
||||
@ -104,13 +112,12 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
dialog.showSaveDialog(this);
|
||||
|
||||
try {
|
||||
if (_mapsCollection.saveMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""), dialog.getSelectedFile().getAbsolutePath())) {
|
||||
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} else {
|
||||
JOptionPane.showMessageDialog(this, "Не сохранилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
_mapsCollection.saveMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""), dialog.getSelectedFile().getAbsolutePath());
|
||||
logger.info("Сохранение карты в файл \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
|
||||
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} catch (Exception ex) {
|
||||
logger.error("Ошибка сохранения карты в файл: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Не сохранилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
});
|
||||
fileMenu.add(saveMapMenuItem);
|
||||
@ -122,14 +129,13 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
dialog.showOpenDialog(this);
|
||||
|
||||
try {
|
||||
if (_mapsCollection.loadMap(dialog.getSelectedFile().getAbsolutePath())) {
|
||||
reloadMaps();
|
||||
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} else {
|
||||
JOptionPane.showMessageDialog(this, "Не загрузилось", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
_mapsCollection.loadMap(dialog.getSelectedFile().getAbsolutePath());
|
||||
reloadMaps();
|
||||
logger.info("Загрузка карты из файла \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
|
||||
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
} catch (Exception ex) {
|
||||
logger.error("Ошибка загрузки карты из файла: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Не загрузилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
});
|
||||
fileMenu.add(loadMapMenuItem);
|
||||
@ -143,15 +149,18 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
|
||||
buttonAddMap.addActionListener(e -> {
|
||||
if (comboBoxMapSelector.getSelectedIndex() == -1 || textFieldMapName.getText() == null || textFieldMapName.getText().isEmpty()) {
|
||||
logger.warn("Не удалось добавить карту: Не все данные заполнены");
|
||||
JOptionPane.showMessageDialog(this, "Не все данные заполнены", "Ошибка", JOptionPane.ERROR_MESSAGE);
|
||||
return;
|
||||
}
|
||||
if (!_mapsDict.containsKey((String)comboBoxMapSelector.getSelectedItem())) {
|
||||
logger.warn("Не удалось добавить карту: Нет такой карты");
|
||||
JOptionPane.showMessageDialog(this, "Нет такой карты", "Ошибка", JOptionPane.ERROR_MESSAGE);
|
||||
return;
|
||||
}
|
||||
_mapsCollection.addMap(textFieldMapName.getText(), _mapsDict.get((String)comboBoxMapSelector.getSelectedItem()));
|
||||
reloadMaps();
|
||||
logger.info("Добавлена карта \"" + textFieldMapName.getText() + "\" типа " + comboBoxMapSelector.getSelectedItem());
|
||||
});
|
||||
|
||||
buttonDeleteMap.addActionListener(e -> {
|
||||
@ -161,6 +170,7 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
|
||||
if (JOptionPane.showConfirmDialog(this, "Удалить карту " + listBoxMaps.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
|
||||
_mapsCollection.deleteMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""));
|
||||
logger.info("Удалена карта \"" + listBoxMaps.getSelectedValue() + "\"");
|
||||
reloadMaps();
|
||||
}
|
||||
});
|
||||
@ -169,6 +179,7 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
if (listBoxMaps.getSelectedValue() != null) {
|
||||
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
|
||||
repaint();
|
||||
logger.info("Переход на карту \"" + listBoxMaps.getSelectedValue() + "\"");
|
||||
}
|
||||
});
|
||||
|
||||
@ -180,16 +191,23 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
}
|
||||
|
||||
if (artillery != null) {
|
||||
DrawingObjectArtillery objectArtillery = new DrawingObjectArtillery(artillery);
|
||||
if (_mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).addArtillery(objectArtillery) != -1)
|
||||
{
|
||||
JOptionPane.showMessageDialog(this, "Объект добавлен", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
|
||||
repaint();
|
||||
}
|
||||
else
|
||||
{
|
||||
JOptionPane.showMessageDialog(this, "Не удалось добавить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
try {
|
||||
DrawingObjectArtillery objectArtillery = new DrawingObjectArtillery(artillery);
|
||||
if (_mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).addArtillery(objectArtillery) != -1) {
|
||||
JOptionPane.showMessageDialog(this, "Объект добавлен", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
|
||||
repaint();
|
||||
logger.info("Добавлен новый объект");
|
||||
} else {
|
||||
logger.warn("Не удалось добавить объект");
|
||||
JOptionPane.showMessageDialog(this, "Не удалось добавить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
} catch (StorageOverflowException ex) {
|
||||
logger.warn("Ошибка переполнения хранилища: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Ошибка переполнения хранилища: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Неизвестная ошибка: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Неизвестная ошибка: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -208,14 +226,24 @@ public class FormMapWithSetArtilleries extends JFrame {
|
||||
|
||||
int position = Integer.parseInt(text);
|
||||
|
||||
IDrawingObject deleted = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).removeArtilleryAt(position);
|
||||
if (deleted != null) {
|
||||
deletedObjects.push(deleted);
|
||||
JOptionPane.showMessageDialog(this, "Объект удалён", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
|
||||
repaint();
|
||||
} else {
|
||||
JOptionPane.showMessageDialog(this, "Не удалось удалить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
try {
|
||||
IDrawingObject deleted = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).removeArtilleryAt(position);
|
||||
if (deleted != null) {
|
||||
deletedObjects.push(deleted);
|
||||
JOptionPane.showMessageDialog(this, "Объект удалён", "Успех", JOptionPane.INFORMATION_MESSAGE);
|
||||
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
|
||||
repaint();
|
||||
logger.info("Удалён объект");
|
||||
} else {
|
||||
logger.warn("Не удалось удалить объект по позиции " + position + ". Объект равен null");
|
||||
JOptionPane.showMessageDialog(this, "Не удалось удалить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
} catch (ArtilleryNotFoundException ex) {
|
||||
logger.warn("Ошибка удаления: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Не удалось найти артиллерию по позиции: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
} catch (Exception ex) {
|
||||
logger.error("Неизвестная ошибка: " + ex.getMessage());
|
||||
JOptionPane.showMessageDialog(this, "Неизвестная ошибка: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
import java.io.*;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
|
||||
@ -44,7 +45,7 @@ public class MapsCollection {
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public boolean saveData(String filename) throws IOException {
|
||||
public void saveData(String filename) throws IOException {
|
||||
File file = new File(filename);
|
||||
|
||||
if (file.exists()) {
|
||||
@ -60,22 +61,20 @@ public class MapsCollection {
|
||||
writer.println(String.format("%s%c%s", storage.getKey(), separatorDict, storage.getValue().getData(separatorDict, separatorData)));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean loadData(String filename) throws IOException {
|
||||
public void loadData(String filename) throws IOException {
|
||||
File file = new File(filename);
|
||||
|
||||
if (!file.exists()) {
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
String currentLine = reader.readLine();
|
||||
|
||||
if (currentLine == null || !currentLine.contains("MapsCollection")) {
|
||||
return false;
|
||||
throw new FileFormatException("Неверный формат файла");
|
||||
}
|
||||
|
||||
_mapsStorage.clear();
|
||||
@ -92,12 +91,10 @@ public class MapsCollection {
|
||||
_mapsStorage.get(elements[0]).loadData(elements[2].split(separatorData + "\n?"));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public boolean saveMap(String mapName, String filename) throws IOException {
|
||||
public void saveMap(String mapName, String filename) throws Exception {
|
||||
File file = new File(filename);
|
||||
|
||||
if (file.exists()) {
|
||||
@ -109,7 +106,7 @@ public class MapsCollection {
|
||||
MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap> map = _mapsStorage.getOrDefault(mapName, null);
|
||||
|
||||
if (map == null) {
|
||||
return false;
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
|
||||
try (PrintWriter writer = new PrintWriter(file)) {
|
||||
@ -121,22 +118,20 @@ public class MapsCollection {
|
||||
writer.println(artillery.getInfo());
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean loadMap(String filename) throws IOException {
|
||||
public void loadMap(String filename) throws IOException {
|
||||
File file = new File(filename);
|
||||
|
||||
if (!file.exists()) {
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
String currentLine = reader.readLine();
|
||||
|
||||
if (currentLine == null || !currentLine.contains("Map")) {
|
||||
return false;
|
||||
throw new FileFormatException("Неверный формат файла");
|
||||
}
|
||||
|
||||
String mapName = reader.readLine();
|
||||
@ -145,7 +140,7 @@ public class MapsCollection {
|
||||
if (_mapsStorage.containsKey(mapName)) {
|
||||
map = _mapsStorage.get(mapName);
|
||||
if (!map.getMap().getClass().getSimpleName().equals(reader.readLine())) {
|
||||
return false;
|
||||
throw new FileFormatException("Неверный формат файла");
|
||||
}
|
||||
map._setArtilleries.clear();
|
||||
} else {
|
||||
@ -162,7 +157,5 @@ public class MapsCollection {
|
||||
|
||||
_mapsStorage.put(mapName, map);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
import javax.swing.*;
|
||||
import org.apache.logging.log4j.*;
|
||||
|
||||
public class Program {
|
||||
public static void main(String[] args) {
|
||||
FormMapWithSetArtilleries form = new FormMapWithSetArtilleries();
|
||||
FormMapWithSetArtilleries form = new FormMapWithSetArtilleries(LogManager.getLogger(Program.class));
|
||||
form.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
|
||||
}
|
||||
}
|
||||
|
@ -20,7 +20,11 @@ public class SetArtilleriesGeneric<T> {
|
||||
}
|
||||
|
||||
public int insert(T artillery, int position) {
|
||||
if (position < 0 || position > getCount() || getCount() == _maxCount) {
|
||||
if (getCount() == _maxCount) {
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
|
||||
if (position < 0 || position > getCount()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
@ -37,6 +41,10 @@ public class SetArtilleriesGeneric<T> {
|
||||
|
||||
T result = _places.get(position);
|
||||
|
||||
if (result == null) {
|
||||
throw new ArtilleryNotFoundException(position);
|
||||
}
|
||||
|
||||
_places.remove(position);
|
||||
|
||||
return result;
|
||||
|
19
StorageOverflowException.java
Normal file
19
StorageOverflowException.java
Normal file
@ -0,0 +1,19 @@
|
||||
public class StorageOverflowException extends RuntimeException{
|
||||
public StorageOverflowException() {
|
||||
}
|
||||
|
||||
public StorageOverflowException(String message) {
|
||||
super(message);
|
||||
}
|
||||
public StorageOverflowException(int count) {
|
||||
super("В наборе превышено допустимое количество: " + count);
|
||||
}
|
||||
|
||||
public StorageOverflowException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public StorageOverflowException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
25
log4j2.xml
Normal file
25
log4j2.xml
Normal file
@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="info" >
|
||||
<Appenders>
|
||||
<File name="error" fileName="error.log" append="true">
|
||||
<PatternLayout>
|
||||
<Pattern>%-5level %msg (%d{dd.MM.yyyy})%n</Pattern>
|
||||
</PatternLayout>
|
||||
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
|
||||
</File>
|
||||
<File name="info" fileName="info.log" append="true">
|
||||
<PatternLayout>
|
||||
<Pattern>%-5level %msg (%d{dd.MM.yyyy})%n</Pattern>
|
||||
</PatternLayout>
|
||||
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="ACCEPT"/>
|
||||
</File>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="INFO">
|
||||
<AppenderRef ref="info" />
|
||||
<AppenderRef ref="error" />
|
||||
</Root>
|
||||
</Loggers>
|
||||
|
||||
</Configuration>
|
Loading…
x
Reference in New Issue
Block a user