From aad872a57ac82673e5cb1903fc3a4ce06d6e4e49 Mon Sep 17 00:00:00 2001 From: MaxKarme <91691525+MaxKarme@users.noreply.github.com> Date: Thu, 15 Dec 2022 13:54:34 +0300 Subject: [PATCH] part 1 --- .gitignore | 3 +- FormMapWithSetAircrafts.java | 94 ++++++++++++---- Main.java | 6 +- MapWithSetAircraftsGeneric.java | 6 +- MapsCollection.java | 188 ++++++++++++++------------------ SetAircraftsGeneric.java | 14 ++- log4j2.xml | 25 +++++ 7 files changed, 195 insertions(+), 141 deletions(-) create mode 100644 log4j2.xml diff --git a/.gitignore b/.gitignore index fca352e..7d1cff2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea -out \ No newline at end of file +out +logs \ No newline at end of file diff --git a/FormMapWithSetAircrafts.java b/FormMapWithSetAircrafts.java index 30c2f1f..76cbb75 100644 --- a/FormMapWithSetAircrafts.java +++ b/FormMapWithSetAircrafts.java @@ -3,6 +3,7 @@ import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.util.*; import java.util.List; +import org.apache.logging.log4j.*; public class FormMapWithSetAircrafts implements Form { private JPanel MainPane; @@ -33,9 +34,16 @@ public class FormMapWithSetAircrafts implements Form { private Canvas canv = new Canvas(this); private Queue deletedAircrafts = new ArrayDeque<>(); + JFrame jFrame = getFrame(); Image img; + private Logger _logger; + + public FormMapWithSetAircrafts(Logger logger) { + _logger = logger; + } + private JFrame getFrame() { JFrame frame = new JFrame(); frame.setVisible(true); @@ -90,10 +98,14 @@ public class FormMapWithSetAircrafts implements Form { String path = chooser.getSelectedFile().getAbsolutePath(); - if(_mapsCollection.SaveData(path)) { + try { + _mapsCollection.SaveData(path); + _logger.info("Данные сохранены в файл " + chooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно"); - } else JOptionPane.showMessageDialog(jFrame, "Не сохранилось"); - + } catch (Exception err) { + _logger.error("Ошибка сохранения данных: " + err.getMessage()); + JOptionPane.showMessageDialog(jFrame, "Не сохранилось"); + } }); loadItem.addActionListener(e -> { @@ -104,10 +116,16 @@ public class FormMapWithSetAircrafts implements Form { if(chooser.getSelectedFile() == null) return; String path = chooser.getSelectedFile().getAbsolutePath(); - if(_mapsCollection.LoadData(path)) { + + try { + _mapsCollection.LoadData(path); + _logger.info("Данные из загружены из файла " + chooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно"); ReloadMaps(); - } else JOptionPane.showMessageDialog(jFrame, "Не загрузилось"); + } catch (Exception err) { + _logger.error("Ошибка загрузки данных " + chooser.getSelectedFile().getAbsolutePath()); + JOptionPane.showMessageDialog(jFrame, "Не загрузилось"); + } }); saveMapItem.addActionListener(e -> { @@ -122,10 +140,16 @@ public class FormMapWithSetAircrafts implements Form { 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, "Сохранение прошло успешно"); - } else JOptionPane.showMessageDialog(jFrame, "Не сохранилось"); - + } catch (Exception err) { + _logger.error("Ошибка сохранения карты " + listBoxMaps.getSelectedValue().toString() + + " в файл " + chooser.getSelectedFile().getAbsolutePath()); + JOptionPane.showMessageDialog(jFrame, "Не сохранилось"); + } }); loadMapItem.addActionListener(e -> { @@ -136,10 +160,18 @@ public class FormMapWithSetAircrafts implements Form { if(chooser.getSelectedFile() == null) return; String path = chooser.getSelectedFile().getAbsolutePath(); - if(_mapsCollection.LoadMap(path)) { + + try { + _mapsCollection.LoadMap(path); + _logger.info("Карта " + listBoxMaps.getSelectedValue().toString() + + " загружена из файла " + chooser.getSelectedFile().getAbsolutePath()); JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно"); 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); @@ -154,22 +186,27 @@ public class FormMapWithSetAircrafts implements Form { listBoxMaps.addListSelectionListener(e -> { if(listBoxMaps.getSelectedValue() == null) return; img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet(); + _logger.info("Переход на карту " + listBoxMaps.getSelectedValue().toString()); canv.repaint(); }); buttonAddMap.addActionListener(e -> { if (comboBoxSelectorMap.getSelectedIndex() == -1 || textBoxNewMapName.getText() == "") { + _logger.warn("Не получилось добавить карту: не все данные заполнены"); JOptionPane.showMessageDialog(jFrame, "Не все данные заполнены"); return; } if (!_mapsDict.containsKey(comboBoxSelectorMap.getSelectedItem().toString())) { + _logger.warn("Не получилось добавить карту: нет такой карты"); JOptionPane.showMessageDialog(jFrame, "Нет такой карты"); return; } _mapsCollection.AddMap(textBoxNewMapName.getText(), _mapsDict.get(comboBoxSelectorMap.getSelectedItem().toString())); + + _logger.info("Добавлена карта " + textBoxNewMapName.getText()); ReloadMaps(); }); @@ -184,6 +221,7 @@ public class FormMapWithSetAircrafts implements Form { "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { _mapsCollection.DelMap(mapName); + _logger.info("Удалена карта " + mapName); ReloadMaps(); } }); @@ -200,17 +238,21 @@ public class FormMapWithSetAircrafts implements Form { formConfig.addListener(drawingAircraft -> { if(drawingAircraft == null) return; - DrawingObjectAircraft aircraft = new DrawingObjectAircraft(drawingAircraft); - if (_mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).addAircraft(aircraft) != -1) - { + try { + DrawingObjectAircraft aircraft = new DrawingObjectAircraft(drawingAircraft); + _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).addAircraft(aircraft); + + _logger.info("Добавлен новый объект"); JOptionPane.showMessageDialog(jFrame, "Объект добавлен"); img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet(); 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); 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, "Объект удален"); img = _mapsCollection.getMap(mapName).ShowSet(); deletedAircrafts.add(deleted); canv.repaint(); - } else { - JOptionPane.showMessageDialog(jFrame, "Не удалось удалить объект"); + } catch(AircraftNotFoundException err) { + _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; img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet(); + _logger.info("Показ хранилища"); canv.repaint(); }); @@ -256,6 +304,7 @@ public class FormMapWithSetAircrafts implements Form { if(listBoxMaps.getSelectedValue() == null) return; img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowOnMap(); + _logger.info("Показ карты"); canv.repaint(); }); @@ -267,6 +316,7 @@ public class FormMapWithSetAircrafts implements Form { if(deletedAircrafts.size() == 0) { JOptionPane.showMessageDialog(jFrame, "Очередь пуста"); + _logger.warn("Очередь удаленных объектов пуста"); return; } @@ -280,6 +330,8 @@ public class FormMapWithSetAircrafts implements Form { dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); + + _logger.info("Показ удаленного объекта"); }); leftButton.addActionListener(e -> { diff --git a/Main.java b/Main.java index 36c5cc4..8b23885 100644 --- a/Main.java +++ b/Main.java @@ -1,5 +1,7 @@ +import org.apache.logging.log4j.*; + public class Main { public static void main(String[] args) { - new FormMapWithSetAircrafts().run(); + new FormMapWithSetAircrafts(LogManager.getLogger(Main.class)).run(); } -} +} \ No newline at end of file diff --git a/MapWithSetAircraftsGeneric.java b/MapWithSetAircraftsGeneric.java index 6a437cf..0b401f0 100644 --- a/MapWithSetAircraftsGeneric.java +++ b/MapWithSetAircraftsGeneric.java @@ -40,19 +40,19 @@ public class MapWithSetAircraftsGeneric(_pictureWidth, _pictureHeight, map)); - _mapStorages.get(elem[0]).LoadData(elem[2].split(separatorData + "")); - } - - reader.close(); - } catch(Exception err) { - return false; - } - - return true; - } - - - public boolean SaveMap(String filename, String key) { - File file = new File(filename); - if(file.exists()) file.delete(); - - MapWithSetAircraftsGeneric item = _mapStorages.getOrDefault(key, null); - if(item == null) return false; - - try { - file.createNewFile(); - FileWriter writer = new FileWriter(file); - - writer.append("Map\n"); - writer.append(key + "\n"); - writer.append(item.getMap().getClass().getName() + "\n"); - ListIterator iter = item.getAircraftsIter(); - while(iter.hasNext()) { - writer.append(AircraftFactory.getDataForSave(iter.next().getAircraft()) + "\n"); - } - - writer.flush(); - writer.close(); - } catch(Exception err) { - return false; - } - - return true; - } - - public boolean LoadMap(String filename) { - File file = new File(filename); - if (!file.exists()) return false; - - try { - BufferedReader reader = new BufferedReader(new FileReader(file)); - String format = reader.readLine(); - if (!format.equals("Map")) return false; - - String key = reader.readLine(); - String mapStr = reader.readLine(); + if (!current.equals("MapsCollection")) throw new DataFormatException("Неверный формат данных"); + _mapStorages.clear(); + while ((current = reader.readLine()) != null) + { + String elem[] = current.split("\\" + separatorDict); AbstractMap map = null; - - switch (mapStr) + switch (elem[1]) { case "SimpleMap": map = new SimpleMap(); @@ -138,21 +64,67 @@ public class MapsCollection map = new MyMap(); break; } - - if(_mapStorages.containsKey(key)) _mapStorages.get(key).ClearMap(); - else _mapStorages.put(key, new MapWithSetAircraftsGeneric<>(_pictureWidth, _pictureHeight, map)); - - String current = null; - while ((current = reader.readLine()) != null) - { - _mapStorages.get(key).addAircraft(DrawingObjectAircraft.Create(current)); - } - reader.close(); - } catch(Exception err) { - return false; + _mapStorages.put(elem[0], new MapWithSetAircraftsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages.get(elem[0]).LoadData(elem[2].split(separatorData + "")); } - return true; + reader.close(); + } + + + public void SaveMap(String filename, String key) throws IOException { + File file = new File(filename); + if(file.exists()) file.delete(); + + MapWithSetAircraftsGeneric item = _mapStorages.get(key); + file.createNewFile(); + FileWriter writer = new FileWriter(file); + + writer.append("Map\n"); + writer.append(key + "\n"); + writer.append(item.getMap().getClass().getName() + "\n"); + ListIterator iter = item.getAircraftsIter(); + + while(iter.hasNext()) { + writer.append(AircraftFactory.getDataForSave(iter.next().getAircraft()) + "\n"); + } + + writer.flush(); + writer.close(); + } + + public void LoadMap(String filename) throws IOException, DataFormatException { + File file = new File(filename); + if (!file.exists()) throw new FileNotFoundException("Файл не найден"); + + BufferedReader reader = new BufferedReader(new FileReader(file)); + String format = reader.readLine(); + if (!format.equals("Map")) throw new DataFormatException("Неверный формат данных"); + + String key = reader.readLine(); + String mapStr = reader.readLine(); + + AbstractMap map = null; + + switch (mapStr) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "MyMap": + map = new MyMap(); + break; + } + + if(_mapStorages.containsKey(key)) _mapStorages.get(key).ClearMap(); + else _mapStorages.put(key, new MapWithSetAircraftsGeneric<>(_pictureWidth, _pictureHeight, map)); + + String current = null; + while ((current = reader.readLine()) != null) + { + _mapStorages.get(key).addAircraft(DrawingObjectAircraft.Create(current)); + } + reader.close(); } public void AddMap(String name, AbstractMap map) diff --git a/SetAircraftsGeneric.java b/SetAircraftsGeneric.java index 86d854f..0f6a5ca 100644 --- a/SetAircraftsGeneric.java +++ b/SetAircraftsGeneric.java @@ -14,24 +14,26 @@ public class SetAircraftsGeneric _places = new ArrayList<>(); _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); 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); 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); _places.remove(res); + + if(res == null) throw new AircraftNotFoundException(position); return res; } diff --git a/log4j2.xml b/log4j2.xml new file mode 100644 index 0000000..8dc02cd --- /dev/null +++ b/log4j2.xml @@ -0,0 +1,25 @@ + + + + + + %-5level %msg (%d{dd.MM.yyyy})%n + + + + + + %-5level %msg (%d{dd.MM.yyyy})%n + + + + + + + + + + + + + \ No newline at end of file