From bc5cce4b554779d29cfad9bcbc8e4dd98b38c7e6 Mon Sep 17 00:00:00 2001 From: IlyasValiulov <148232695+IlyasValiulov@users.noreply.github.com> Date: Fri, 10 May 2024 12:11:23 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=967=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WarmlyShip/WarmlyShip.iml | 18 +++ .../AbstractCompany.java | 5 +- .../ICollectionGenericObjects.java | 10 +- .../ListGenericObjects.java | 18 +-- .../MassiveGenericObjects.java | 17 +- .../ShipPortService.java | 9 +- .../StorageCollection.java | 61 +++++--- .../DrawingShip/CanvasFormShipCollection.java | 12 +- .../CollectionOverflowException.java | 8 + .../Exceptions/ObjectNotFoundException.java | 8 + .../PositionOutOfCollectionException.java | 8 + WarmlyShip/src/FormAdditionalCollection.java | 64 +++++--- WarmlyShip/src/FormShipCollection.java | 148 ++++++++++++------ WarmlyShip/src/FormShipConfig.java | 24 ++- WarmlyShip/src/Main.java | 7 +- WarmlyShip/src/log4j2.xml | 26 +++ 16 files changed, 314 insertions(+), 129 deletions(-) create mode 100644 WarmlyShip/src/Exceptions/CollectionOverflowException.java create mode 100644 WarmlyShip/src/Exceptions/ObjectNotFoundException.java create mode 100644 WarmlyShip/src/Exceptions/PositionOutOfCollectionException.java create mode 100644 WarmlyShip/src/log4j2.xml diff --git a/WarmlyShip/WarmlyShip.iml b/WarmlyShip/WarmlyShip.iml index c90834f..b341a83 100644 --- a/WarmlyShip/WarmlyShip.iml +++ b/WarmlyShip/WarmlyShip.iml @@ -7,5 +7,23 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WarmlyShip/src/CollectionGenericObjects/AbstractCompany.java b/WarmlyShip/src/CollectionGenericObjects/AbstractCompany.java index d87c264..2e3b29f 100644 --- a/WarmlyShip/src/CollectionGenericObjects/AbstractCompany.java +++ b/WarmlyShip/src/CollectionGenericObjects/AbstractCompany.java @@ -1,6 +1,8 @@ package CollectionGenericObjects; import DrawingShip.DrawingShip; +import Exceptions.ObjectNotFoundException; +import Exceptions.PositionOutOfCollectionException; import java.awt.*; @@ -21,8 +23,7 @@ public abstract class AbstractCompany { _collection.SetMaxCount(GetMaxCount()); } //перегрузка операторов в джаве не возможна - public DrawingShip GetRandomObject() - { + public DrawingShip GetRandomObject() throws PositionOutOfCollectionException, ObjectNotFoundException { return _collection.Get((int)(Math.random()*GetMaxCount() + 0)); } public void SetPosition() diff --git a/WarmlyShip/src/CollectionGenericObjects/ICollectionGenericObjects.java b/WarmlyShip/src/CollectionGenericObjects/ICollectionGenericObjects.java index a6fb6c2..304c333 100644 --- a/WarmlyShip/src/CollectionGenericObjects/ICollectionGenericObjects.java +++ b/WarmlyShip/src/CollectionGenericObjects/ICollectionGenericObjects.java @@ -1,12 +1,16 @@ package CollectionGenericObjects; +import Exceptions.CollectionOverflowException; +import Exceptions.ObjectNotFoundException; +import Exceptions.PositionOutOfCollectionException; + public interface ICollectionGenericObjects { int getCount(); void SetMaxCount(int count); - int Insert(T obj); - T Remove(int position); - T Get(int position); + int Insert(T obj) throws CollectionOverflowException; + T Remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException; + T Get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException; CollectionType GetCollectionType(); Iterable GetItems(); void ClearCollection(); diff --git a/WarmlyShip/src/CollectionGenericObjects/ListGenericObjects.java b/WarmlyShip/src/CollectionGenericObjects/ListGenericObjects.java index 7f16b2d..38a2fce 100644 --- a/WarmlyShip/src/CollectionGenericObjects/ListGenericObjects.java +++ b/WarmlyShip/src/CollectionGenericObjects/ListGenericObjects.java @@ -1,5 +1,8 @@ package CollectionGenericObjects; +import Exceptions.CollectionOverflowException; +import Exceptions.PositionOutOfCollectionException; + import java.util.*; public class ListGenericObjects implements ICollectionGenericObjects { @@ -23,22 +26,19 @@ public class ListGenericObjects implements ICollectionGenericObjects { return collectionType; } @Override - public T Get(int position) - { - if (position >= getCount() || position < 0) return null; + public T Get(int position) throws PositionOutOfCollectionException { + if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position); return _collection.get(position); } @Override - public int Insert(T obj) - { - if (getCount() == _maxCount) return -1; + public int Insert(T obj) throws CollectionOverflowException { + if (getCount() == _maxCount) throw new CollectionOverflowException(getCount()); _collection.add(obj); return getCount(); } @Override - public T Remove(int position) - { - if (position >= getCount() || position < 0) return null; + public T Remove(int position) throws PositionOutOfCollectionException { + if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection.get(position); _collection.remove(position); return obj; diff --git a/WarmlyShip/src/CollectionGenericObjects/MassiveGenericObjects.java b/WarmlyShip/src/CollectionGenericObjects/MassiveGenericObjects.java index 6d47e72..dbc04f0 100644 --- a/WarmlyShip/src/CollectionGenericObjects/MassiveGenericObjects.java +++ b/WarmlyShip/src/CollectionGenericObjects/MassiveGenericObjects.java @@ -1,6 +1,9 @@ package CollectionGenericObjects; import DrawingShip.DrawingShip; +import Exceptions.CollectionOverflowException; +import Exceptions.ObjectNotFoundException; +import Exceptions.PositionOutOfCollectionException; import java.lang.reflect.Array; import java.util.*; @@ -27,7 +30,7 @@ public class MassiveGenericObjects implements ICollectionGenericObjects{ return collectionType; } @Override - public int Insert(T obj) { + public int Insert(T obj) throws CollectionOverflowException { int index = 0; while (index < getCount()) { @@ -38,19 +41,21 @@ public class MassiveGenericObjects implements ICollectionGenericObjects{ } ++index; } - return -1; + throw new CollectionOverflowException(Count); } @Override - public T Remove(int position) { + public T Remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException { if (position >= getCount() || position < 0) - return null; + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = (T) _collection[position]; _collection[position] = null; return obj; } @Override - public T Get(int position) { - if (position >= getCount() || position < 0) return null; + public T Get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException { + if (position >= getCount() || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return (T) _collection[position]; } @Override diff --git a/WarmlyShip/src/CollectionGenericObjects/ShipPortService.java b/WarmlyShip/src/CollectionGenericObjects/ShipPortService.java index 693c0df..5b8679d 100644 --- a/WarmlyShip/src/CollectionGenericObjects/ShipPortService.java +++ b/WarmlyShip/src/CollectionGenericObjects/ShipPortService.java @@ -31,10 +31,13 @@ public class ShipPortService extends AbstractCompany{ int curWidth = width - 1; int curHeight = 0; for (int i = 0; i < (_collection.getCount()); i++) { - if (_collection.Get(i) != null) { - _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4); + try { + if (_collection.Get(i) != null) { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 4); + } } + catch (Exception ex) {} if (curWidth > 0) curWidth--; else { diff --git a/WarmlyShip/src/CollectionGenericObjects/StorageCollection.java b/WarmlyShip/src/CollectionGenericObjects/StorageCollection.java index 3486e82..e47ba59 100644 --- a/WarmlyShip/src/CollectionGenericObjects/StorageCollection.java +++ b/WarmlyShip/src/CollectionGenericObjects/StorageCollection.java @@ -2,6 +2,9 @@ package CollectionGenericObjects; import DrawingShip.DrawingShip; import DrawingShip.ExtentionDrawningShip; +import Exceptions.CollectionOverflowException; +import Exceptions.ObjectNotFoundException; +import Exceptions.PositionOutOfCollectionException; import java.io.*; import java.util.*; @@ -37,7 +40,7 @@ public class StorageCollection { return null; } //дополнительное задание номер 1 - public T Get(String name, int position){ + public T Get(String name, int position) throws ObjectNotFoundException, PositionOutOfCollectionException { if(_storages.containsKey(name)) return _storages.get(name).Remove(position); return null; @@ -48,8 +51,8 @@ public class StorageCollection { private String _separatorForKeyValue = "\\|"; private String _separatorItemsS = ";"; private String _separatorItems = "\\;"; - public boolean SaveData(String filename) { - if (_storages.isEmpty()) return false; + public void SaveData(String filename) throws Exception { + if (_storages.isEmpty()) throw new Exception("В хранилище отсутствуют коллекции для сохранения"); File file = new File(filename); if (file.exists()) file.delete(); try { @@ -78,10 +81,9 @@ public class StorageCollection { } catch (IOException e) { throw new RuntimeException(e); } - return true; } - public boolean SaveOneCollection(String filename, String name) { - if (_storages.isEmpty()) return false; + public void SaveOneCollection(String filename, String name) throws Exception { + if (_storages.isEmpty()) throw new Exception("В хранилище отсутствуют коллекции для сохранения"); File file = new File(filename); if (file.exists()) file.delete(); try { @@ -108,15 +110,14 @@ public class StorageCollection { } catch (IOException e) { throw new RuntimeException(e); } - return true; } - public boolean LoadData(String filename) { + public void LoadData(String filename) throws Exception { File file = new File(filename); - if (!file.exists()) return false; + if (!file.exists()) throw new Exception("Файл не существует"); try (BufferedReader fs = new BufferedReader(new FileReader(filename))) { String s = fs.readLine(); if (s == null || s.isEmpty() || !s.startsWith(_collectionKey)) - return false; + throw new Exception("В файле нет данных или данные неверные"); _storages.clear(); s = ""; while ((s = fs.readLine()) != null) { @@ -127,56 +128,68 @@ public class StorageCollection { ICollectionGenericObjects collection = CreateCollection(record[1]); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.SetMaxCount(Integer.parseInt(record[2])); String[] set = record[3].split(_separatorItems); for (String elem : set) { - DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem); - if (collection.Insert((T) ship) == -1) + try { - return false; + DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem); + if (collection.Insert((T) ship) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } _storages.put(record[0], collection); } - return true; } catch (IOException e) { throw new RuntimeException(e); } } - public boolean LoadOneCollection(String filename) { + public void LoadOneCollection(String filename) throws Exception { File file = new File(filename); - if (!file.exists()) return false; + if (!file.exists()) throw new Exception("Файл не существует"); try (BufferedReader fs = new BufferedReader(new FileReader(filename))) { String s = fs.readLine(); if (s == null || s.isEmpty() || !s.startsWith(_collectionName)) - return false; + throw new Exception("В файле нет данных или данные неверные"); if (_storages.containsKey(s)) { _storages.get(s).ClearCollection(); } s = fs.readLine(); String[] record = s.split(_separatorForKeyValue); if (record.length != 4) { - return false; + throw new Exception("Неверные данные"); } ICollectionGenericObjects collection = CreateCollection(record[1]); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.SetMaxCount(Integer.parseInt(record[2])); String[] set = record[3].split(_separatorItems); for (String elem : set) { - DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem); - if (collection.Insert((T) ship) == -1) + try { - return false; + DrawingShip ship = ExtentionDrawningShip.CreateDrawingShip(elem); + if (collection.Insert((T) ship) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } _storages.put(record[0], collection); - return true; } catch (IOException e) { throw new RuntimeException(e); diff --git a/WarmlyShip/src/DrawingShip/CanvasFormShipCollection.java b/WarmlyShip/src/DrawingShip/CanvasFormShipCollection.java index 01f9908..51305a3 100644 --- a/WarmlyShip/src/DrawingShip/CanvasFormShipCollection.java +++ b/WarmlyShip/src/DrawingShip/CanvasFormShipCollection.java @@ -19,12 +19,14 @@ public class CanvasFormShipCollection extends JComponent } company.DrawBackgound(g); for (int i = 0; i < company._collection.getCount(); i++) { - - Graphics2D g2d = (Graphics2D) g; - T obj = (T)company._collection.Get(i); - if (obj instanceof DrawingShip) { - ((DrawingShip) obj).DrawTransport(g2d); + try { + Graphics2D g2d = (Graphics2D) g; + T obj = (T) company._collection.Get(i); + if (obj instanceof DrawingShip) { + ((DrawingShip) obj).DrawTransport(g2d); + } } + catch (Exception ex) {} } super.repaint(); } diff --git a/WarmlyShip/src/Exceptions/CollectionOverflowException.java b/WarmlyShip/src/Exceptions/CollectionOverflowException.java new file mode 100644 index 0000000..1940df8 --- /dev/null +++ b/WarmlyShip/src/Exceptions/CollectionOverflowException.java @@ -0,0 +1,8 @@ +package Exceptions; +//неиспользованные методы +public class CollectionOverflowException extends Exception { + public CollectionOverflowException(int count) {super("В коллекции превышено допустимое количество: " + count); } + public CollectionOverflowException() { super(); } + public CollectionOverflowException(String message) { super(message); } + public CollectionOverflowException(String message, Exception exception) { super(message, exception); } +} diff --git a/WarmlyShip/src/Exceptions/ObjectNotFoundException.java b/WarmlyShip/src/Exceptions/ObjectNotFoundException.java new file mode 100644 index 0000000..ff5da41 --- /dev/null +++ b/WarmlyShip/src/Exceptions/ObjectNotFoundException.java @@ -0,0 +1,8 @@ +package Exceptions; +//неиспользованные методы +public class ObjectNotFoundException extends Exception{ + public ObjectNotFoundException(int i) { super("Не найден объект по позиции " + i); } + public ObjectNotFoundException() { super(); } + public ObjectNotFoundException(String message) { super(message); } + public ObjectNotFoundException(String message, Throwable cause) {super(message, cause); } +} diff --git a/WarmlyShip/src/Exceptions/PositionOutOfCollectionException.java b/WarmlyShip/src/Exceptions/PositionOutOfCollectionException.java new file mode 100644 index 0000000..c817b33 --- /dev/null +++ b/WarmlyShip/src/Exceptions/PositionOutOfCollectionException.java @@ -0,0 +1,8 @@ +package Exceptions; +//неиспользуемые методы +public class PositionOutOfCollectionException extends Exception{ + public PositionOutOfCollectionException(int i) { super("Выход за границы коллекции. Позиция " + i); } + public PositionOutOfCollectionException() { super(); } + public PositionOutOfCollectionException(String message) { super(message); } + public PositionOutOfCollectionException(String message, Throwable cause) { super(message, cause); } +} diff --git a/WarmlyShip/src/FormAdditionalCollection.java b/WarmlyShip/src/FormAdditionalCollection.java index 849c2dc..7fda9f6 100644 --- a/WarmlyShip/src/FormAdditionalCollection.java +++ b/WarmlyShip/src/FormAdditionalCollection.java @@ -9,6 +9,7 @@ import DrawingShip.DrawingWarmlyShip; import DrawingShip.CanvasWarmlyShip; import Entities.EntityShip; import Entities.EntityWarmlyShip; +import Exceptions.CollectionOverflowException; import javax.swing.*; import java.awt.*; @@ -16,6 +17,8 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; +import static DrawingShip.ExtentionDrawningShip.GetDataForSave; + public class FormAdditionalCollection extends JFrame { public DrawingShip drawingShip = null; private AbstractCompany company = null; @@ -25,9 +28,14 @@ public class FormAdditionalCollection extends JFrame { private JButton buttonGenerate = new JButton("Создать"); private JList listEntity = new JList(); private JList listDecks = new JList(); - public FormAdditionalCollection() { + private org.apache.logging.log4j.Logger logger; + private org.apache.logging.log4j.Logger loggerErrow; + public FormAdditionalCollection(org.apache.logging.log4j.Logger logger, + org.apache.logging.log4j.Logger logger2) { setTitle("Random ship"); setMinimumSize(new Dimension(650,310)); + this.logger = logger; + this.loggerErrow = logger2; additionalCollection = new AdditionalCollections(3, (Class) EntityShip.class, (Class) IDifferentDecks.class); AddEntities(); @@ -35,31 +43,39 @@ public class FormAdditionalCollection extends JFrame { buttonGenerate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - drawingShip = additionalCollection.CreateAdditionalCollectionShip(); - drawingShip.SetPictureSize(getWidth(), getHeight()); - drawingShip.SetPosition(50,50); - canvasship._drawingShip = drawingShip; - canvasship.repaint(); - DrawingShip copyShip; - if (drawingShip instanceof DrawingWarmlyShip) - copyShip = new DrawingWarmlyShip((EntityWarmlyShip) drawingShip.EntityShip, drawingShip.drawingDecks); - else - copyShip = new DrawingShip(drawingShip.EntityShip, drawingShip.drawingDecks); - company._collection.Insert(copyShip); - FormShipCollection.canvasShow(); - - String[] data1 = new String[additionalCollection.CountEntities]; - for (int i = 0; i < additionalCollection.CountEntities; i++) { - EntityShip entity = additionalCollection._collectionEntity[i]; - data1[i] = ToString(entity); + try { + drawingShip = additionalCollection.CreateAdditionalCollectionShip(); + drawingShip.SetPictureSize(getWidth(), getHeight()); + drawingShip.SetPosition(50, 50); + canvasship._drawingShip = drawingShip; + canvasship.repaint(); + DrawingShip copyShip; + if (drawingShip instanceof DrawingWarmlyShip) + copyShip = new DrawingWarmlyShip((EntityWarmlyShip) drawingShip.EntityShip, drawingShip.drawingDecks); + else + copyShip = new DrawingShip(drawingShip.EntityShip, drawingShip.drawingDecks); + company._collection.Insert(copyShip); + FormShipCollection.canvasShow(); + logger.info("Добавлен объект: " + GetDataForSave(copyShip)); + String[] data1 = new String[additionalCollection.CountEntities]; + for (int i = 0; i < additionalCollection.CountEntities; i++) { + EntityShip entity = additionalCollection._collectionEntity[i]; + data1[i] = ToString(entity); + } + String[] data2 = new String[additionalCollection.CountDecks]; + for (int i = 0; i < additionalCollection.CountDecks; i++) { + IDifferentDecks decks = additionalCollection._collectionDecks[i]; + data2[i] = ToString(decks); + } + listEntity.setListData(data1); + listDecks.setListData(data2); } - String[] data2 = new String[additionalCollection.CountDecks]; - for (int i = 0; i < additionalCollection.CountDecks; i++) { - IDifferentDecks decks = additionalCollection._collectionDecks[i]; - data2[i] = ToString(decks); + catch (CollectionOverflowException ex) { + loggerErrow.warn(ex.toString()); + } + catch (Exception ex) { + loggerErrow.fatal("Ошибка в выводу форме FormAdditionalCollection"); } - listEntity.setListData(data1); - listDecks.setListData(data2); } }); buttonGenerate.setBounds(450, 10, 100, 50); diff --git a/WarmlyShip/src/FormShipCollection.java b/WarmlyShip/src/FormShipCollection.java index 1dfd2fd..f49b61d 100644 --- a/WarmlyShip/src/FormShipCollection.java +++ b/WarmlyShip/src/FormShipCollection.java @@ -1,7 +1,8 @@ import CollectionGenericObjects.*; import DrawingShip.CanvasFormShipCollection; import DrawingShip.DrawingShip; -import DrawingShip.DrawingWarmlyShip; +import Exceptions.ObjectNotFoundException; +import Exceptions.PositionOutOfCollectionException; import javax.swing.*; import javax.swing.text.MaskFormatter; @@ -9,9 +10,10 @@ import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; -import java.util.Random; import java.util.Stack; +import java.util.logging.Logger; +import static DrawingShip.ExtentionDrawningShip.GetDataForSave; import static java.lang.Integer.parseInt; public class FormShipCollection extends JFrame{ @@ -42,10 +44,17 @@ public class FormShipCollection extends JFrame{ private JMenuItem saveItem = new JMenuItem("Save"); private JMenuItem loadCollection = new JMenuItem("Load coll"); private JMenuItem saveCollection = new JMenuItem("Save coll"); - public FormShipCollection(String title, Dimension dimension) { + private org.apache.logging.log4j.Logger logger; + private org.apache.logging.log4j.Logger loggerErrow; + public FormShipCollection(String title, Dimension dimension, + org.apache.logging.log4j.Logger logger1, org.apache.logging.log4j.Logger logger2) { this.title = title; this.dimension = dimension; + this.logger = logger1; + logger.info("Форма загрузилась"); + this.loggerErrow = logger2; } + public static void canvasShow() { _company.SetPosition(); _canvasWarmlyShip.SetCollectionToCanvas(_company); @@ -70,7 +79,8 @@ public class FormShipCollection extends JFrame{ @Override public void actionPerformed(ActionEvent e) { if (_company == null) return; - FormShipConfig form = new FormShipConfig("", new Dimension(700, 300)); + FormShipConfig form = new FormShipConfig("", new Dimension(700, 300), + logger, loggerErrow); form.setCompany(_company); form.Init(); } @@ -88,14 +98,21 @@ public class FormShipCollection extends JFrame{ "Удалить", "Удаление", JOptionPane.YES_NO_OPTION); if (resultConfirmDialog == JOptionPane.NO_OPTION) return; - DrawingShip obj = _storageCollection.Get( - listBoxCollection.getSelectedValue().toString(), pos); - if (obj != null) { - JOptionPane.showMessageDialog(null, "Объект удален"); - _collectionRemoveObjects.push(obj); - canvasShow(); + try { + DrawingShip obj = _storageCollection.Get( + listBoxCollection.getSelectedValue().toString(), pos); + if (obj != null) { + JOptionPane.showMessageDialog(null, "Объект удален"); + _collectionRemoveObjects.push(obj); + canvasShow(); + logger.info("Объект удален по позиции " + pos); + } } - else { + catch (PositionOutOfCollectionException | ObjectNotFoundException ex) { + loggerErrow.warn(ex.toString()); + } + catch (Exception ex) { + loggerErrow.fatal(ex.toString()); JOptionPane.showMessageDialog(null, "Объект не удалось удалить"); } } @@ -108,23 +125,24 @@ public class FormShipCollection extends JFrame{ { return; } - DrawingShip ship = null; - int counter = 100; - while (ship == null) - { - ship = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; + try { + + DrawingShip ship = null; + int counter = 100; + while (ship == null) { + ship = _company.GetRandomObject(); + counter--; + if (counter <= 0) { + break; + } } + if (ship == null) { + return; + } + FormWarmlyShip form = new FormWarmlyShip("Теплоход", new Dimension(900, 565)); + form.Init(ship); } - if (ship == null) - { - return; - } - FormWarmlyShip form = new FormWarmlyShip("Теплоход", new Dimension(900,565)); - form.Init(ship); + catch (Exception ex) {} } }); @@ -135,8 +153,13 @@ public class FormShipCollection extends JFrame{ { return; } - FormAdditionalCollection form = new FormAdditionalCollection(); - form.setCompany(_company); + try { + FormAdditionalCollection form = new FormAdditionalCollection(logger, loggerErrow); + form.setCompany(_company); + } + catch (Exception ex) { + loggerErrow.warn(ex.toString()); + } } }); @@ -159,17 +182,20 @@ public class FormShipCollection extends JFrame{ JOptionPane.showMessageDialog(null, "Не все данные заполнены"); return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.isSelected()) - { - collectionType = CollectionType.Massive; + try { + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.isSelected()) { + collectionType = CollectionType.Massive; + } else if (radioButtonList.isSelected()) { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollection.getText(), collectionType); + RerfreshListBoxItems(); + logger.info("Добавлена коллекция: " + textBoxCollection.getText()); } - else if (radioButtonList.isSelected()) - { - collectionType = CollectionType.List; + catch (Exception ex) { + loggerErrow.error(ex.toString()); } - _storageCollection.AddCollection(textBoxCollection.getText(), collectionType); - RerfreshListBoxItems(); } }); @@ -184,8 +210,14 @@ public class FormShipCollection extends JFrame{ "Удалить", "Удаление", JOptionPane.YES_NO_OPTION); if (resultConfirmDialog == JOptionPane.NO_OPTION) return; - _storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString()); - RerfreshListBoxItems(); + try { + _storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString()); + RerfreshListBoxItems(); + logger.info("Удалена коллекция: " + textBoxCollection.getText()); + } + catch (Exception ex) { + loggerErrow.error(ex.toString()); + } } }); @@ -323,10 +355,15 @@ public class FormShipCollection extends JFrame{ } private void SaveFile() { String filename = SaveWindow(); - if (_storageCollection.SaveData(filename)) { + try { + _storageCollection.SaveData(filename); JOptionPane.showMessageDialog(null, "Сохранено"); + logger.info("Сохранение в файл: " + filename); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Ошибка сохранения"); + loggerErrow.error(ex.toString()); } - else JOptionPane.showMessageDialog(null, "Ошибка сохранения"); } private void SaveCollection() { String filename = SaveWindow(); @@ -337,10 +374,16 @@ public class FormShipCollection extends JFrame{ if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) { JOptionPane.showMessageDialog(null, "Коллекция не выбрана"); } - if (_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString())) { + try { + _storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString()); JOptionPane.showMessageDialog(null, "Коллекция сохранена"); + logger.info("Сохранение коллекции:" + + listBoxCollection.getSelectedValue().toString() + " в файл: " + filename); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Ошибка сохранения"); + loggerErrow.error(ex.toString()); } - else JOptionPane.showMessageDialog(null, "Ошибка сохранения"); } private String LoadWindow() { FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD); @@ -352,20 +395,29 @@ public class FormShipCollection extends JFrame{ } private void LoadFile() { String filename = LoadWindow(); - if (_storageCollection.LoadData(filename)) { + try { + _storageCollection.LoadData(filename); JOptionPane.showMessageDialog(null, "Загрузка прошла успешно"); RerfreshListBoxItems(); + logger.info("Загрузка файла: " + filename); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Не загрузилось"); + loggerErrow.error(ex.toString()); } - else JOptionPane.showMessageDialog(null, "Не загрузилось"); - } private void LoadCollection() { String filename = LoadWindow(); - if (_storageCollection.LoadOneCollection(filename)) { + try { + _storageCollection.LoadOneCollection(filename); JOptionPane.showMessageDialog(null, "Коллекция загружена"); RerfreshListBoxItems(); + logger.info("Загрузка коллекции: "); + } + catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Не загрузилось"); + loggerErrow.error(ex.toString()); } - else JOptionPane.showMessageDialog(null, "Не загрузилось"); } private void RerfreshListBoxItems() { diff --git a/WarmlyShip/src/FormShipConfig.java b/WarmlyShip/src/FormShipConfig.java index dd53c60..77fcc7b 100644 --- a/WarmlyShip/src/FormShipConfig.java +++ b/WarmlyShip/src/FormShipConfig.java @@ -6,6 +6,8 @@ import DiffetentsDrawingDecks.IDifferentDecks; import DrawingShip.DrawingShip; import DrawingShip.DrawingWarmlyShip; import Entities.EntityWarmlyShip; +import Exceptions.CollectionOverflowException; +import org.apache.logging.log4j.Logger; import javax.swing.*; import javax.swing.event.ChangeEvent; @@ -21,6 +23,8 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; +import static DrawingShip.ExtentionDrawningShip.GetDataForSave; + public class FormShipConfig extends JFrame { private String title; private Dimension dimension; @@ -53,10 +57,14 @@ public class FormShipConfig extends JFrame { private JPanel panelColorCyan = new JPanel(); private JButton buttonAdd = new JButton("Add"); private JButton buttonCansel = new JButton("Cancel"); - - public FormShipConfig(String title, Dimension dimension) { + private org.apache.logging.log4j.Logger logger; + private org.apache.logging.log4j.Logger loggerErrow; + public FormShipConfig(String title, Dimension dimension, org.apache.logging.log4j.Logger logger, + org.apache.logging.log4j.Logger logger2) { this.title = title; this.dimension = dimension; + this.logger = logger; + this.loggerErrow = logger2; } public void Init() { SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1); @@ -301,8 +309,16 @@ public class FormShipConfig extends JFrame { copyShip = new DrawingWarmlyShip((EntityWarmlyShip) _ship.EntityShip, _ship.drawingDecks); else copyShip = new DrawingShip(_ship.EntityShip, _ship.drawingDecks); - company._collection.Insert(copyShip); - FormShipCollection.canvasShow(); + try { + company._collection.Insert(copyShip); + FormShipCollection.canvasShow(); + logger.info("Добавлен объект: " + GetDataForSave(copyShip)); + } catch (CollectionOverflowException ex) { + loggerErrow.warn(ex.toString()); + JOptionPane.showMessageDialog(null, "Коллекция переполнена"); + } catch (Exception ex) { + loggerErrow.fatal("Ошибка при добавлении объекта с формы config"); + } dispose(); } }); diff --git a/WarmlyShip/src/Main.java b/WarmlyShip/src/Main.java index e50a0ea..65f2bb5 100644 --- a/WarmlyShip/src/Main.java +++ b/WarmlyShip/src/Main.java @@ -1,8 +1,13 @@ +import org.apache.logging.log4j.LogManager; + import java.awt.*; public class Main { public static void main(String[] args) { - FormShipCollection form = new FormShipCollection("Коллекция судов", new Dimension(1100, 648)); + org.apache.logging.log4j.Logger logger1 = LogManager.getLogger("logging.file1"); + org.apache.logging.log4j.Logger logger2 = LogManager.getLogger("logging.file2"); + FormShipCollection form = new FormShipCollection("Коллекция судов", + new Dimension(1100, 648), logger1, logger2); form.Init(); } } \ No newline at end of file diff --git a/WarmlyShip/src/log4j2.xml b/WarmlyShip/src/log4j2.xml new file mode 100644 index 0000000..bfdb06a --- /dev/null +++ b/WarmlyShip/src/log4j2.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- 2.25.1