This commit is contained in:
MaxKarme 2022-12-15 13:54:34 +03:00
parent 6663b98a92
commit aad872a57a
7 changed files with 195 additions and 141 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
.idea .idea
out out
logs

View File

@ -3,6 +3,7 @@ import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*; import java.awt.*;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.*;
public class FormMapWithSetAircrafts implements Form { public class FormMapWithSetAircrafts implements Form {
private JPanel MainPane; private JPanel MainPane;
@ -33,9 +34,16 @@ public class FormMapWithSetAircrafts implements Form {
private Canvas canv = new Canvas(this); private Canvas canv = new Canvas(this);
private Queue<IDrawingObject> deletedAircrafts = new ArrayDeque<>(); private Queue<IDrawingObject> deletedAircrafts = new ArrayDeque<>();
JFrame jFrame = getFrame(); JFrame jFrame = getFrame();
Image img; Image img;
private Logger _logger;
public FormMapWithSetAircrafts(Logger logger) {
_logger = logger;
}
private JFrame getFrame() { private JFrame getFrame() {
JFrame frame = new JFrame(); JFrame frame = new JFrame();
frame.setVisible(true); frame.setVisible(true);
@ -90,10 +98,14 @@ public class FormMapWithSetAircrafts implements Form {
String path = chooser.getSelectedFile().getAbsolutePath(); String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.SaveData(path)) { try {
_mapsCollection.SaveData(path);
_logger.info("Данные сохранены в файл " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно"); JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно");
} else JOptionPane.showMessageDialog(jFrame, "Не сохранилось"); } catch (Exception err) {
_logger.error("Ошибка сохранения данных: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Не сохранилось");
}
}); });
loadItem.addActionListener(e -> { loadItem.addActionListener(e -> {
@ -104,10 +116,16 @@ public class FormMapWithSetAircrafts implements Form {
if(chooser.getSelectedFile() == null) return; if(chooser.getSelectedFile() == null) return;
String path = chooser.getSelectedFile().getAbsolutePath(); String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.LoadData(path)) {
try {
_mapsCollection.LoadData(path);
_logger.info("Данные из загружены из файла " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно"); JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно");
ReloadMaps(); ReloadMaps();
} else JOptionPane.showMessageDialog(jFrame, "Не загрузилось"); } catch (Exception err) {
_logger.error("Ошибка загрузки данных " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Не загрузилось");
}
}); });
saveMapItem.addActionListener(e -> { saveMapItem.addActionListener(e -> {
@ -122,10 +140,16 @@ public class FormMapWithSetAircrafts implements Form {
String path = chooser.getSelectedFile().getAbsolutePath(); String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.SaveMap(path, listBoxMaps.getSelectedValue().toString())) { try {
_mapsCollection.SaveMap(path, listBoxMaps.getSelectedValue().toString());
_logger.info("Карта " + listBoxMaps.getSelectedValue().toString() +
" сохранена в файл " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно"); JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно");
} else JOptionPane.showMessageDialog(jFrame, "Не сохранилось"); } catch (Exception err) {
_logger.error("Ошибка сохранения карты " + listBoxMaps.getSelectedValue().toString() +
" в файл " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Не сохранилось");
}
}); });
loadMapItem.addActionListener(e -> { loadMapItem.addActionListener(e -> {
@ -136,10 +160,18 @@ public class FormMapWithSetAircrafts implements Form {
if(chooser.getSelectedFile() == null) return; if(chooser.getSelectedFile() == null) return;
String path = chooser.getSelectedFile().getAbsolutePath(); String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.LoadMap(path)) {
try {
_mapsCollection.LoadMap(path);
_logger.info("Карта " + listBoxMaps.getSelectedValue().toString() +
" загружена из файла " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно"); JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно");
ReloadMaps(); ReloadMaps();
} else JOptionPane.showMessageDialog(jFrame, "Не загрузилось"); } catch (Exception err) {
_logger.error("Ошибка загрузки карты " + listBoxMaps.getSelectedValue().toString() +
" из файла " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Не загрузилось");
}
}); });
_mapsCollection = new MapsCollection(canv.getSize().width, canv.getSize().height); _mapsCollection = new MapsCollection(canv.getSize().width, canv.getSize().height);
@ -154,22 +186,27 @@ public class FormMapWithSetAircrafts implements Form {
listBoxMaps.addListSelectionListener(e -> { listBoxMaps.addListSelectionListener(e -> {
if(listBoxMaps.getSelectedValue() == null) return; if(listBoxMaps.getSelectedValue() == null) return;
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet(); img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet();
_logger.info("Переход на карту " + listBoxMaps.getSelectedValue().toString());
canv.repaint(); canv.repaint();
}); });
buttonAddMap.addActionListener(e -> { buttonAddMap.addActionListener(e -> {
if (comboBoxSelectorMap.getSelectedIndex() == -1 || textBoxNewMapName.getText() == "") if (comboBoxSelectorMap.getSelectedIndex() == -1 || textBoxNewMapName.getText() == "")
{ {
_logger.warn("Не получилось добавить карту: не все данные заполнены");
JOptionPane.showMessageDialog(jFrame, "Не все данные заполнены"); JOptionPane.showMessageDialog(jFrame, "Не все данные заполнены");
return; return;
} }
if (!_mapsDict.containsKey(comboBoxSelectorMap.getSelectedItem().toString())) if (!_mapsDict.containsKey(comboBoxSelectorMap.getSelectedItem().toString()))
{ {
_logger.warn("Не получилось добавить карту: нет такой карты");
JOptionPane.showMessageDialog(jFrame, "Нет такой карты"); JOptionPane.showMessageDialog(jFrame, "Нет такой карты");
return; return;
} }
_mapsCollection.AddMap(textBoxNewMapName.getText(), _mapsCollection.AddMap(textBoxNewMapName.getText(),
_mapsDict.get(comboBoxSelectorMap.getSelectedItem().toString())); _mapsDict.get(comboBoxSelectorMap.getSelectedItem().toString()));
_logger.info("Добавлена карта " + textBoxNewMapName.getText());
ReloadMaps(); ReloadMaps();
}); });
@ -184,6 +221,7 @@ public class FormMapWithSetAircrafts implements Form {
"Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{ {
_mapsCollection.DelMap(mapName); _mapsCollection.DelMap(mapName);
_logger.info("Удалена карта " + mapName);
ReloadMaps(); ReloadMaps();
} }
}); });
@ -200,17 +238,21 @@ public class FormMapWithSetAircrafts implements Form {
formConfig.addListener(drawingAircraft -> { formConfig.addListener(drawingAircraft -> {
if(drawingAircraft == null) return; if(drawingAircraft == null) return;
try {
DrawingObjectAircraft aircraft = new DrawingObjectAircraft(drawingAircraft); DrawingObjectAircraft aircraft = new DrawingObjectAircraft(drawingAircraft);
if (_mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).addAircraft(aircraft) != -1) _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).addAircraft(aircraft);
{
_logger.info("Добавлен новый объект");
JOptionPane.showMessageDialog(jFrame, "Объект добавлен"); JOptionPane.showMessageDialog(jFrame, "Объект добавлен");
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet(); img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet();
canv.repaint(); canv.repaint();
} catch(StorageOverflowException err) {
_logger.warn("Ошибка добавления: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Ошибка переполнения: " + err.getMessage());
} catch(Exception err) {
_logger.fatal("Незивестная ошибка: " + err.getMessage());
} }
else
{
JOptionPane.showMessageDialog(jFrame, "Не удалось добавить объект");
}
}); });
}); });
@ -233,15 +275,20 @@ public class FormMapWithSetAircrafts implements Form {
pos = Integer.parseInt(text); pos = Integer.parseInt(text);
String mapName = listBoxMaps.getSelectedValue().toString(); String mapName = listBoxMaps.getSelectedValue().toString();
IDrawingObject deleted = _mapsCollection.getMap(mapName).removeAircraft(pos);
if(deleted != null) { try {
IDrawingObject deleted = _mapsCollection.getMap(mapName).removeAircraft(pos);
_logger.info("Объект удален");
JOptionPane.showMessageDialog(jFrame, "Объект удален"); JOptionPane.showMessageDialog(jFrame, "Объект удален");
img = _mapsCollection.getMap(mapName).ShowSet(); img = _mapsCollection.getMap(mapName).ShowSet();
deletedAircrafts.add(deleted); deletedAircrafts.add(deleted);
canv.repaint(); canv.repaint();
} else { } catch(AircraftNotFoundException err) {
JOptionPane.showMessageDialog(jFrame, "Не удалось удалить объект"); _logger.warn("Ошибка добавления: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Ошибка удаления: " + err.getMessage());
} catch (Exception err) {
_logger.fatal("Неизвестная ошибка: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Неизвестная ошибка: " + err.getMessage());
} }
}); });
@ -249,6 +296,7 @@ public class FormMapWithSetAircrafts implements Form {
if(listBoxMaps.getSelectedValue() == null) return; if(listBoxMaps.getSelectedValue() == null) return;
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet(); img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet();
_logger.info("Показ хранилища");
canv.repaint(); canv.repaint();
}); });
@ -256,6 +304,7 @@ public class FormMapWithSetAircrafts implements Form {
if(listBoxMaps.getSelectedValue() == null) return; if(listBoxMaps.getSelectedValue() == null) return;
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowOnMap(); img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowOnMap();
_logger.info("Показ карты");
canv.repaint(); canv.repaint();
}); });
@ -267,6 +316,7 @@ public class FormMapWithSetAircrafts implements Form {
if(deletedAircrafts.size() == 0) { if(deletedAircrafts.size() == 0) {
JOptionPane.showMessageDialog(jFrame, "Очередь пуста"); JOptionPane.showMessageDialog(jFrame, "Очередь пуста");
_logger.warn("Очередь удаленных объектов пуста");
return; return;
} }
@ -280,6 +330,8 @@ public class FormMapWithSetAircrafts implements Form {
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true); dialog.setVisible(true);
_logger.info("Показ удаленного объекта");
}); });
leftButton.addActionListener(e -> { leftButton.addActionListener(e -> {

View File

@ -1,5 +1,7 @@
import org.apache.logging.log4j.*;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
new FormMapWithSetAircrafts().run(); new FormMapWithSetAircrafts(LogManager.getLogger(Main.class)).run();
} }
} }

View File

@ -40,19 +40,19 @@ public class MapWithSetAircraftsGeneric<T extends IDrawingObject, U extends Abst
_setAircrafts.Clear(); _setAircrafts.Clear();
} }
public void LoadData(String[] records) { public void LoadData(String[] records) throws StorageOverflowException {
for (String rec : records) for (String rec : records)
{ {
_setAircrafts.Insert((T)DrawingObjectAircraft.Create(rec)); _setAircrafts.Insert((T)DrawingObjectAircraft.Create(rec));
} }
} }
public int addAircraft(T aircraft) public int addAircraft(T aircraft) throws StorageOverflowException
{ {
return _setAircrafts.Insert(aircraft); return _setAircrafts.Insert(aircraft);
} }
public T removeAircraft(int position) public T removeAircraft(int position) throws AircraftNotFoundException
{ {
return _setAircrafts.Remove(position); return _setAircrafts.Remove(position);
} }

View File

@ -1,10 +1,8 @@
import java.io.BufferedReader; import java.io.*;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.zip.DataFormatException;
public class MapsCollection public class MapsCollection
{ {
@ -24,12 +22,11 @@ public class MapsCollection
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
public boolean SaveData(String filename) public void SaveData(String filename) throws IOException
{ {
File file = new File(filename); File file = new File(filename);
if (file.exists()) file.delete(); if (file.exists()) file.delete();
try {
file.createNewFile(); file.createNewFile();
FileWriter writer = new FileWriter(file); FileWriter writer = new FileWriter(file);
@ -42,23 +39,16 @@ public class MapsCollection
writer.flush(); writer.flush();
writer.close(); writer.close();
} catch(Exception err) {
return false;
} }
return true; public void LoadData(String filename) throws IOException, DataFormatException {
}
public boolean LoadData(String filename)
{
File file = new File(filename); File file = new File(filename);
if (!file.exists()) return false; if (!file.exists()) throw new FileNotFoundException("Файл не найден");
try {
BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedReader reader = new BufferedReader(new FileReader(file));
String current = reader.readLine(); String current = reader.readLine();
if (!current.equals("MapsCollection")) return false; if (!current.equals("MapsCollection")) throw new DataFormatException("Неверный формат данных");
_mapStorages.clear(); _mapStorages.clear();
while ((current = reader.readLine()) != null) while ((current = reader.readLine()) != null)
@ -79,22 +69,14 @@ public class MapsCollection
} }
reader.close(); reader.close();
} catch(Exception err) {
return false;
}
return true;
} }
public boolean SaveMap(String filename, String key) { public void SaveMap(String filename, String key) throws IOException {
File file = new File(filename); File file = new File(filename);
if(file.exists()) file.delete(); if(file.exists()) file.delete();
MapWithSetAircraftsGeneric<DrawingObjectAircraft, AbstractMap> item = _mapStorages.getOrDefault(key, null); MapWithSetAircraftsGeneric<DrawingObjectAircraft, AbstractMap> item = _mapStorages.get(key);
if(item == null) return false;
try {
file.createNewFile(); file.createNewFile();
FileWriter writer = new FileWriter(file); FileWriter writer = new FileWriter(file);
@ -102,27 +84,22 @@ public class MapsCollection
writer.append(key + "\n"); writer.append(key + "\n");
writer.append(item.getMap().getClass().getName() + "\n"); writer.append(item.getMap().getClass().getName() + "\n");
ListIterator<DrawingObjectAircraft> iter = item.getAircraftsIter(); ListIterator<DrawingObjectAircraft> iter = item.getAircraftsIter();
while(iter.hasNext()) { while(iter.hasNext()) {
writer.append(AircraftFactory.getDataForSave(iter.next().getAircraft()) + "\n"); writer.append(AircraftFactory.getDataForSave(iter.next().getAircraft()) + "\n");
} }
writer.flush(); writer.flush();
writer.close(); writer.close();
} catch(Exception err) {
return false;
} }
return true; public void LoadMap(String filename) throws IOException, DataFormatException {
}
public boolean LoadMap(String filename) {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) return false; if (!file.exists()) throw new FileNotFoundException("Файл не найден");
try {
BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedReader reader = new BufferedReader(new FileReader(file));
String format = reader.readLine(); String format = reader.readLine();
if (!format.equals("Map")) return false; if (!format.equals("Map")) throw new DataFormatException("Неверный формат данных");
String key = reader.readLine(); String key = reader.readLine();
String mapStr = reader.readLine(); String mapStr = reader.readLine();
@ -148,11 +125,6 @@ public class MapsCollection
_mapStorages.get(key).addAircraft(DrawingObjectAircraft.Create(current)); _mapStorages.get(key).addAircraft(DrawingObjectAircraft.Create(current));
} }
reader.close(); reader.close();
} catch(Exception err) {
return false;
}
return true;
} }
public void AddMap(String name, AbstractMap map) public void AddMap(String name, AbstractMap map)

View File

@ -14,24 +14,26 @@ public class SetAircraftsGeneric<T>
_places = new ArrayList<>(); _places = new ArrayList<>();
_maxCount = count; _maxCount = count;
} }
public int Insert(T aircraft) public int Insert(T aircraft) throws StorageOverflowException
{ {
if (_places.size() == _maxCount) return -1; if (_places.size() == _maxCount) throw new StorageOverflowException(_maxCount);
_places.add(0, aircraft); _places.add(0, aircraft);
return 0; return 0;
} }
public int Insert(T aircraft, int position) public int Insert(T aircraft, int position) throws StorageOverflowException
{ {
if (_places.size() == _maxCount) return -1; if (_places.size() == _maxCount) throw new StorageOverflowException(_maxCount);
_places.add(position, aircraft); _places.add(position, aircraft);
return position; return position;
} }
public T Remove(int position) public T Remove(int position) throws AircraftNotFoundException
{ {
if(position > _maxCount || position < 0) return null; if(position > _places.size() || position < 0) throw new AircraftNotFoundException(position);
T res = _places.get(position); T res = _places.get(position);
_places.remove(res); _places.remove(res);
if(res == null) throw new AircraftNotFoundException(position);
return res; return res;
} }

25
log4j2.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" >
<Appenders>
<File name="error" fileName="logs/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="logs/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>