сделанная работа

This commit is contained in:
pyzhov.egor 2024-05-20 01:33:55 +04:00
parent 09be0cd57d
commit b6884a45fb
12 changed files with 330 additions and 97 deletions

View File

@ -1,6 +1,9 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import Drawnings.DrawningBoat; import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.awt.*; import java.awt.*;
import java.util.Random; import java.util.Random;
@ -21,20 +24,20 @@ public abstract class AbstractCompany {
int maxCount = getMaxCount(); int maxCount = getMaxCount();
_collection.setMaxCount(maxCount); _collection.setMaxCount(maxCount);
} }
public static int add(AbstractCompany company ,DrawningBoat boat) { public static int add(AbstractCompany company ,DrawningBoat boat) throws PositionOutOfCollectionException, CollectionOverflowException {
if (company._collection == null) { if (company._collection == null) {
return -1; return -1;
} }
return company._collection.insert(boat); return company._collection.insert(boat);
} }
public static DrawningBoat remove(AbstractCompany company, int position) { public static DrawningBoat remove(AbstractCompany company, int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (company._collection == null) { if (company._collection == null) {
return null; return null;
} }
return company._collection.remove(position); return company._collection.remove(position);
} }
public DrawningBoat getRandomObject() { public DrawningBoat getRandomObject() throws PositionOutOfCollectionException, ObjectNotFoundException {
if (_collection == null) { if (_collection == null) {
return null; return null;
} }
@ -48,10 +51,16 @@ public abstract class AbstractCompany {
return; return;
} }
for(int i = 0; i < _collection.getCount(); i++) { for(int i = 0; i < _collection.getCount(); i++) {
try {
if(_collection.get(i) != null) { if(_collection.get(i) != null) {
_collection.get(i).drawBoat(g); _collection.get(i).drawBoat(g);
} }
} }
catch (Exception e) {
}
}
} }
protected abstract void drawBackground(Graphics g); protected abstract void drawBackground(Graphics g);
protected abstract void setObjectsPosition(); protected abstract void setObjectsPosition();

View File

@ -48,6 +48,7 @@ public class BoatSharingService extends AbstractCompany {
} }
int row = numRows - 1, col = numCols; int row = numRows - 1, col = numCols;
for (int i=0;i< _collection.getCount(); i++, col--) { for (int i=0;i< _collection.getCount(); i++, col--) {
try {
if (_collection.get(i) != null) { if (_collection.get(i) != null) {
_collection.get(i).setPictureSize(_pictureWidth, _pictureHeight); _collection.get(i).setPictureSize(_pictureWidth, _pictureHeight);
_collection.get(i).setPosition((int)locCoord.get(row*numCols - col).getX() + 5, _collection.get(i).setPosition((int)locCoord.get(row*numCols - col).getX() + 5,
@ -57,7 +58,10 @@ public class BoatSharingService extends AbstractCompany {
row--; row--;
} }
} }
}
catch (Exception e) {
} }
} }
}
} }

View File

@ -1,6 +1,9 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import Drawnings.DrawningBoat; import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
public interface ICollectionGenericObjects<T extends DrawningBoat> { public interface ICollectionGenericObjects<T extends DrawningBoat> {
int getCount(); int getCount();
@ -8,13 +11,13 @@ public interface ICollectionGenericObjects<T extends DrawningBoat> {
void setMaxCount(int count); void setMaxCount(int count);
int getMaxCount(); int getMaxCount();
int insert(T obj); int insert(T obj) throws CollectionOverflowException, PositionOutOfCollectionException;
int insert(T obj, int index); int insert(T obj, int index) throws CollectionOverflowException, PositionOutOfCollectionException;
T remove(int index); T remove(int index) throws PositionOutOfCollectionException, ObjectNotFoundException;
T get(int index); T get(int index) throws PositionOutOfCollectionException, ObjectNotFoundException;
CollectionType GetCollectionType(); CollectionType GetCollectionType();
Iterable<T> GetItems(); Iterable<T> GetItems();

View File

@ -1,6 +1,8 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import Drawnings.DrawningBoat; import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.PositionOutOfCollectionException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
@ -27,14 +29,17 @@ public class ListGenericObjects<T extends DrawningBoat> implements ICollectionGe
return maxCount; return maxCount;
} }
@Override @Override
public int insert(T obj) { public int insert(T obj) throws CollectionOverflowException, PositionOutOfCollectionException {
return insert(obj, count); return insert(obj, count);
} }
@Override @Override
public int insert(T obj, int index) { public int insert(T obj, int index) throws CollectionOverflowException, PositionOutOfCollectionException {
if (index > maxCount || index < 0 || index > count){ if (index > maxCount){
return -1; throw new CollectionOverflowException(maxCount);
}
if (index < 0 || index > count) {
throw new PositionOutOfCollectionException(index);
} }
if(index == count){ if(index == count){
_collection.add(obj); _collection.add(obj);
@ -47,9 +52,9 @@ public class ListGenericObjects<T extends DrawningBoat> implements ICollectionGe
} }
@Override @Override
public T remove(int index) { public T remove(int index) throws PositionOutOfCollectionException {
if (index > maxCount || index < 0 || index >= count){ if (index > maxCount || index < 0 || index >= count){
return null; throw new PositionOutOfCollectionException(index);
} }
count = _collection.size() - 1; count = _collection.size() - 1;
return _collection.remove(index); return _collection.remove(index);
@ -57,9 +62,9 @@ public class ListGenericObjects<T extends DrawningBoat> implements ICollectionGe
} }
@Override @Override
public T get(int index) { public T get(int index) throws PositionOutOfCollectionException {
if (index >= count){ if (index >= count){
return null; throw new PositionOutOfCollectionException(index);
} }
return _collection.get(index); return _collection.get(index);
} }

View File

@ -1,6 +1,10 @@
package CollectionGenericObjects; package CollectionGenericObjects;
import Drawnings.DrawningBoat; import Drawnings.DrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
@ -23,14 +27,14 @@ public class MassiveGenericObjects<T extends DrawningBoat> implements ICollectio
return maxCount; return maxCount;
} }
@Override @Override
public int insert(T obj) { public int insert(T obj) throws PositionOutOfCollectionException, CollectionOverflowException {
return insert(obj, 0); return insert(obj, 0);
} }
@Override @Override
public int insert(T obj, int position) { public int insert(T obj, int position) throws PositionOutOfCollectionException, CollectionOverflowException {
if (position > maxCount|| position < 0) { if (position > maxCount|| position < 0) {
return -1; throw new PositionOutOfCollectionException(position);
} }
for (int i = position; i < maxCount; i++) { for (int i = position; i < maxCount; i++) {
@ -47,13 +51,13 @@ public class MassiveGenericObjects<T extends DrawningBoat> implements ICollectio
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException(maxCount);
} }
@Override @Override
public T remove(int position) { public T remove(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position < 0 || position >= maxCount) { if (position < 0 || position >= maxCount) {
return null; throw new PositionOutOfCollectionException(position);
} }
if (_collection.get(position) != null) { if (_collection.get(position) != null) {
T bf = _collection.get(position); T bf = _collection.get(position);
@ -61,16 +65,19 @@ public class MassiveGenericObjects<T extends DrawningBoat> implements ICollectio
--realSize; --realSize;
return bf; return bf;
} }
return null; throw new ObjectNotFoundException(position);
} }
@Override @Override
public T get(int position) { public T get(int position) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (position >= 0 && position < _collection.size()) { if (position >= 0 && position < _collection.size()) {
if (_collection.get(position) == null) {
throw new ObjectNotFoundException(position);
}
return _collection.get(position); return _collection.get(position);
} }
else { else {
return null; throw new PositionOutOfCollectionException(position);
} }
} }

View File

@ -2,10 +2,14 @@ package CollectionGenericObjects;
import Drawnings.DrawningBoat; import Drawnings.DrawningBoat;
import Drawnings.ExtentionDrawningBoat; import Drawnings.ExtentionDrawningBoat;
import Exceptions.CollectionOverflowException;
import Exceptions.ObjectNotFoundException;
import Exceptions.PositionOutOfCollectionException;
import javax.swing.*; import javax.swing.*;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.InvalidParameterException;
import java.util.*; import java.util.*;
public class StorageCollection<T extends DrawningBoat> { public class StorageCollection<T extends DrawningBoat> {
@ -24,9 +28,9 @@ public class StorageCollection<T extends DrawningBoat> {
keys = new ArrayList<>(); keys = new ArrayList<>();
} }
public boolean SaveData(String filename){ public void SaveData(String filename) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (_storages.isEmpty()) { if (_storages.isEmpty()) {
return false; throw new InvalidParameterException("Коллекций в списке нет");
} }
File file = new File(filename); File file = new File(filename);
if (file.exists()){ if (file.exists()){
@ -36,7 +40,7 @@ public class StorageCollection<T extends DrawningBoat> {
file.createNewFile(); file.createNewFile();
} }
catch (IOException e){ catch (IOException e){
return false; return;
} }
FileWriter fw; FileWriter fw;
try { try {
@ -58,8 +62,11 @@ public class StorageCollection<T extends DrawningBoat> {
sb.append(_separatorForKeyValue); sb.append(_separatorForKeyValue);
for (int j = 0; j < _storages.get(keys.get(i)).getCount(); j++) { for (int j = 0; j < _storages.get(keys.get(i)).getCount(); j++) {
String data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j)); String data;
if (data==null) { try {
data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
continue; continue;
} }
sb.append(data); sb.append(data);
@ -70,14 +77,12 @@ public class StorageCollection<T extends DrawningBoat> {
fw.close(); fw.close();
}catch (IOException e){ }catch (IOException e){
e.getStackTrace(); e.getStackTrace();
return false;
} }
return true;
} }
public boolean SaveOneCollection(String filename, JList<String> stringJList){ public void SaveOneCollection(String filename, JList<String> stringJList) throws PositionOutOfCollectionException, ObjectNotFoundException {
if (_storages.isEmpty() || stringJList.getSelectedIndex() == -1) { if (_storages.isEmpty() || stringJList.getSelectedIndex() == -1) {
return false; throw new InvalidParameterException("Коллекций в списке нет");
} }
FileWriter fw; FileWriter fw;
File file = new File(filename); File file = new File(filename);
@ -88,7 +93,7 @@ public class StorageCollection<T extends DrawningBoat> {
file.createNewFile(); file.createNewFile();
} }
catch (IOException e){ catch (IOException e){
return false; return;
} }
try { try {
@ -101,7 +106,7 @@ public class StorageCollection<T extends DrawningBoat> {
sb.append('\n'); sb.append('\n');
if (_storages.get(keys.get(i)) == null) { if (_storages.get(keys.get(i)) == null) {
fw.close(); fw.close();
return false; throw new InvalidParameterException("Выбранная коллекция отсутствует");
} }
sb.append(keys.get(i)); sb.append(keys.get(i));
sb.append(_separatorForKeyValue); sb.append(_separatorForKeyValue);
@ -110,8 +115,11 @@ public class StorageCollection<T extends DrawningBoat> {
sb.append(_storages.get(keys.get(i)).getMaxCount()); sb.append(_storages.get(keys.get(i)).getMaxCount());
sb.append(_separatorForKeyValue); sb.append(_separatorForKeyValue);
for (int j = 0; j < _storages.get(keys.get(i)).getCount(); j++) { for (int j = 0; j < _storages.get(keys.get(i)).getCount(); j++) {
String data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j)); String data;
if (data==null) { try {
data = ExtentionDrawningBoat.GetDataForSave(this.getObjectFromChooseCollection(keys.get(i), j));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
continue; continue;
} }
sb.append(data); sb.append(data);
@ -121,15 +129,13 @@ public class StorageCollection<T extends DrawningBoat> {
fw.close(); fw.close();
}catch (IOException e){ }catch (IOException e){
e.getStackTrace(); e.getStackTrace();
return false;
} }
return true;
} }
public boolean LoadData(String filename) { public void LoadData(String filename) throws Exception {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) { if (!file.exists()) {
return false; throw new FileNotFoundException("Файл не найден");
} }
FileReader fr; FileReader fr;
try { try {
@ -149,7 +155,7 @@ public class StorageCollection<T extends DrawningBoat> {
ICollectionGenericObjects<DrawningBoat> collection = StorageCollection.CreateCollection(collectionType); ICollectionGenericObjects<DrawningBoat> collection = StorageCollection.CreateCollection(collectionType);
if (collection == null) { if (collection == null) {
bufferedReader.close(); bufferedReader.close();
return false; throw new Exception("Ошибка создания коллекции");
} }
collection.setMaxCount(Integer.parseInt(record[2])); collection.setMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems); String[] set = record[3].split(_separatorItems);
@ -157,10 +163,16 @@ public class StorageCollection<T extends DrawningBoat> {
for (int i = 0; i < set.length; i++) { for (int i = 0; i < set.length; i++) {
DrawningBoat boat; DrawningBoat boat;
if ((boat = ExtentionDrawningBoat.CreateDrawningBoat(set[i])) != null) { if ((boat = ExtentionDrawningBoat.CreateDrawningBoat(set[i])) != null) {
if (collection.insert(boat) == -1) { try {
bufferedReader.close(); collection.insert(boat);
return false;
} }
catch (Exception e) {
bufferedReader.close();
throw e;
}
} }
} }
@ -170,28 +182,26 @@ public class StorageCollection<T extends DrawningBoat> {
} }
} }
else { else {
return false; throw new InvalidParameterException("В файле не корректные данные");
} }
bufferedReader.close(); bufferedReader.close();
}catch (IOException e){ }catch (IOException e){
e.getStackTrace(); e.getStackTrace();
return false;
} }
return true;
} }
public boolean LoadOneCollection(String filename) { public void LoadOneCollection(String filename) throws Exception {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) return false; if (!file.exists()) throw new InvalidParameterException("Файл не найден");
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) { try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine(); String s = fs.readLine();
if (s == null || !s.startsWith(_collectionSingleKey)) if (s == null || !s.startsWith(_collectionSingleKey))
return false; throw new Exception("В файле не корректные данные");
ICollectionGenericObjects<DrawningBoat> collection; ICollectionGenericObjects<DrawningBoat> collection;
s = fs.readLine(); s = fs.readLine();
String[] record = s.split(_separatorForKeyValue); String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) { if (record.length != 4) {
return false; throw new InvalidParameterException("В файле не корректные данные");
} }
if (keys.contains(s)) { if (keys.contains(s)) {
@ -204,17 +214,23 @@ public class StorageCollection<T extends DrawningBoat> {
} }
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Ошибка создания коллекции");
} }
collection.setMaxCount(Integer.parseInt(record[2])); collection.setMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems); String[] set = record[3].split(_separatorItems);
for (String elem : set) { for (String elem : set) {
try {
DrawningBoat boat = ExtentionDrawningBoat.CreateDrawningBoat(elem); DrawningBoat boat = ExtentionDrawningBoat.CreateDrawningBoat(elem);
if (collection.insert((T) boat) == -1) if (collection.insert((T) boat) == -1)
{ {
return false; throw new Exception("Не удалось добавить объект в коллекцию" + record[3]);
} }
} }
catch (CollectionOverflowException exception) {
throw new Exception("Коллекция переполнена", exception);
}
}
if (keys.contains(record[0])) { if (keys.contains(record[0])) {
keys.set(keys.indexOf(record[0]), record[0]); keys.set(keys.indexOf(record[0]), record[0]);
} }
@ -222,7 +238,6 @@ public class StorageCollection<T extends DrawningBoat> {
keys.add(record[0]); keys.add(record[0]);
} }
_storages.put(record[0], (ICollectionGenericObjects<T>) collection); _storages.put(record[0], (ICollectionGenericObjects<T>) collection);
return true;
} }
catch (IOException e) { catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@ -264,7 +279,7 @@ public class StorageCollection<T extends DrawningBoat> {
return _storages.get(name); return _storages.get(name);
} }
public T getObjectFromChooseCollection(String name, int ind){ public T getObjectFromChooseCollection(String name, int ind) throws PositionOutOfCollectionException, ObjectNotFoundException{
return this.getCollection(name).get(ind); return this.getCollection(name).get(ind);
} }

View File

@ -3,6 +3,8 @@ package Drawnings;
import CollectionGenericObjects.*; import CollectionGenericObjects.*;
import CollectionGenericObjects.MassiveGenericObjects; import CollectionGenericObjects.MassiveGenericObjects;
import Exceptions.CollectionOverflowException;
import Exceptions.PositionOutOfCollectionException;
import Forms.FormBoatConfig; import Forms.FormBoatConfig;
import Forms.FormCatamaran; import Forms.FormCatamaran;
import Forms.FormConstructor; import Forms.FormConstructor;
@ -12,11 +14,22 @@ import java.awt.*;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.util.Random; import java.util.Random;
import java.util.Stack; import java.util.Stack;
import java.util.logging.Logger;
import static Drawnings.ExtentionDrawningBoat.GetDataForSave;
import Exceptions.*;
public class DrawningAbstractCompany extends JComponent { public class DrawningAbstractCompany extends JComponent {
private AbstractCompany _company = null; private AbstractCompany _company = null;
DrawningBoat _drawningBoat; DrawningBoat _drawningBoat;
private final StorageCollection<DrawningBoat> storageCollection = new StorageCollection<>(); private final StorageCollection<DrawningBoat> storageCollection = new StorageCollection<>();
private final Logger userLogger;
private final Logger programLogger;
public DrawningAbstractCompany(Logger userLogger, Logger programLogger) {
this.userLogger = userLogger;
this.programLogger = programLogger;
}
public StorageCollection<DrawningBoat> getStorageCollection() { public StorageCollection<DrawningBoat> getStorageCollection() {
return storageCollection; return storageCollection;
} }
@ -30,6 +43,7 @@ public class DrawningAbstractCompany extends JComponent {
return false; return false;
} }
_company = new BoatSharingService(width, height,storageCollection.getCollection(collectionList.getSelectedValue())); _company = new BoatSharingService(width, height,storageCollection.getCollection(collectionList.getSelectedValue()));
userLogger.info("Компания создана на коллекции " + collectionList.getSelectedValue());
return true; return true;
default: default:
return false; return false;
@ -44,15 +58,25 @@ public class DrawningAbstractCompany extends JComponent {
formBoatConfig.getButtonAdd().addActionListener(e -> { formBoatConfig.getButtonAdd().addActionListener(e -> {
if (formBoatConfig.getDrawningConfig().boat != null) { if (formBoatConfig.getDrawningConfig().boat != null) {
_drawningBoat = formBoatConfig.getDrawningConfig().boat; _drawningBoat = formBoatConfig.getDrawningConfig().boat;
if (AbstractCompany.add(_company, _drawningBoat) != -1) { try {
AbstractCompany.add(_company, _drawningBoat);
JOptionPane.showMessageDialog(obj, "Объект добавлен"); JOptionPane.showMessageDialog(obj, "Объект добавлен");
obj.repaint(); obj.repaint();
userLogger.info("Объект добавлен " + GetDataForSave(_drawningBoat));
} }
else { catch (PositionOutOfCollectionException | CollectionOverflowException exception) {
JOptionPane.showMessageDialog(obj, "Не удалось добавить объект"); JOptionPane.showMessageDialog(obj, "Не удалось добавить объект");
programLogger.warning("Объект не добавлен: " + exception.getMessage());
} }
catch (Exception ex) {
JOptionPane.showMessageDialog(obj, "Не удалось добавить объект");
programLogger.warning("Объект не добавлен: " + ex.getMessage());
}
finally {
formBoatConfig.getjFrameBoatConfig().dispatchEvent(new WindowEvent(formBoatConfig.getjFrameBoatConfig(), WindowEvent.WINDOW_CLOSING)); formBoatConfig.getjFrameBoatConfig().dispatchEvent(new WindowEvent(formBoatConfig.getjFrameBoatConfig(), WindowEvent.WINDOW_CLOSING));
} }
}
}); });
} }
@ -67,12 +91,21 @@ public class DrawningAbstractCompany extends JComponent {
"Подтвердение", "Подтвердение",
JOptionPane.YES_NO_OPTION); JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) { if (result == JOptionPane.YES_OPTION) {
DrawningBoat deletableBoat = AbstractCompany.remove(_company, val); DrawningBoat deletableBoat = null;
if (deletableBoat != null) { try {
deletableBoat = AbstractCompany.remove(_company, val);
rubbishBinStack.add(deletableBoat); rubbishBinStack.add(deletableBoat);
JOptionPane.showMessageDialog(obj, "Выполнено"); JOptionPane.showMessageDialog(obj, "Выполнено");
return true; userLogger.info("Объект удален " + GetDataForSave(deletableBoat));
} else {
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
programLogger.warning("Удаление не удалось: " + exception.getMessage());
JOptionPane.showMessageDialog(obj, "Удаление не удалось" + exception.getMessage());
return false;
}
catch (Exception ex) {
programLogger.severe("Удаление не удалось: " + ex.getMessage());
JOptionPane.showMessageDialog(obj, "Удаление не удалось"); JOptionPane.showMessageDialog(obj, "Удаление не удалось");
return false; return false;
} }
@ -86,13 +119,19 @@ public class DrawningAbstractCompany extends JComponent {
DrawningBoat boat = null; DrawningBoat boat = null;
int counter = 100; int counter = 100;
while (boat == null && counter > 0) { while (boat == null && counter > 0) {
try {
boat = _company.getRandomObject(); boat = _company.getRandomObject();
--counter; --counter;
}
if (boat == null) {
return;
}
createFormCatamaran(boat); createFormCatamaran(boat);
userLogger.info("Объект отправлен на проверку" + GetDataForSave(boat));
}
catch (PositionOutOfCollectionException | ObjectNotFoundException exception) {
programLogger.warning("Не удалось отправить объект: " + exception.getMessage());
}
catch (Exception ex) {
programLogger.severe("Не удалось отправить объект: " + ex.getMessage());
}
}
} }
@ -121,14 +160,24 @@ public class DrawningAbstractCompany extends JComponent {
formConstructor.getAddButton().addActionListener(e -> { formConstructor.getAddButton().addActionListener(e -> {
createObject = formConstructor.getConstructor().getObj(); createObject = formConstructor.getConstructor().getObj();
if (AbstractCompany.add(_company, createObject) != -1) { try {
AbstractCompany.add(_company, createObject);
JOptionPane.showMessageDialog(obj, "Выполнено"); JOptionPane.showMessageDialog(obj, "Выполнено");
userLogger.info("Объект из конструктора добавлен " + GetDataForSave(createObject));
} else {
JOptionPane.showMessageDialog(obj, "Добавление не удалось");
} }
catch (PositionOutOfCollectionException | CollectionOverflowException exception) {
JOptionPane.showMessageDialog(obj, "Добавление не удалось");
programLogger.warning("Добавление не удалось: " + exception.getMessage());
}
catch (Exception ex) {
JOptionPane.showMessageDialog(obj, "Добавление не удалось");
programLogger.severe("Добавление не удалось: " + ex.getMessage());
}
finally {
obj.repaint(); obj.repaint();
formConstructor.getjFrameConstructor().dispatchEvent(new WindowEvent(formConstructor.getjFrameConstructor(), WindowEvent.WINDOW_CLOSING)); formConstructor.getjFrameConstructor().dispatchEvent(new WindowEvent(formConstructor.getjFrameConstructor(), WindowEvent.WINDOW_CLOSING));
}
}); });
} }
@ -137,6 +186,7 @@ public class DrawningAbstractCompany extends JComponent {
if (textFieldSetCollectionName.getText().isEmpty() || (!massiveRadioButton.isSelected() && !listRadioButton.isSelected())) { if (textFieldSetCollectionName.getText().isEmpty() || (!massiveRadioButton.isSelected() && !listRadioButton.isSelected())) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не все элементы заполнены", "ERROR", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не все элементы заполнены", "ERROR", JOptionPane.ERROR_MESSAGE);
programLogger.warning("Не все элементы заполнены");
return null; return null;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
@ -145,6 +195,7 @@ public class DrawningAbstractCompany extends JComponent {
else if (listRadioButton.isSelected()) else if (listRadioButton.isSelected())
collectionType = CollectionType.List; collectionType = CollectionType.List;
storageCollection.addCollection(textFieldSetCollectionName.getText(), collectionType); storageCollection.addCollection(textFieldSetCollectionName.getText(), collectionType);
userLogger.info("Коллекция добавлена " + textFieldSetCollectionName.getText());
return storageCollection; return storageCollection;
} }
public StorageCollection<DrawningBoat> deleteCollectionButtonAction(JFrame jFrameCollectionLocomotive, JList<String> keysList) { public StorageCollection<DrawningBoat> deleteCollectionButtonAction(JFrame jFrameCollectionLocomotive, JList<String> keysList) {
@ -152,6 +203,7 @@ public class DrawningAbstractCompany extends JComponent {
int result = JOptionPane.showConfirmDialog( jFrameCollectionLocomotive, "Удалить объект?", int result = JOptionPane.showConfirmDialog( jFrameCollectionLocomotive, "Удалить объект?",
"Подтверждение", JOptionPane.YES_NO_OPTION); "Подтверждение", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) { if (result == JOptionPane.YES_OPTION) {
userLogger.info("Коллекция удалена " + keysList.getSelectedValue());
storageCollection.delCollection(keysList.getSelectedValue()); storageCollection.delCollection(keysList.getSelectedValue());
return storageCollection; return storageCollection;
} }

View File

@ -0,0 +1,20 @@
package Exceptions;
import java.io.Serializable;
public class CollectionOverflowException extends Exception implements Serializable {
public CollectionOverflowException(int count) {
super("В коллекции превышено допустимое количество: " + count);
}
public CollectionOverflowException() {
super();
}
public CollectionOverflowException(String message) {
super(message);
}
public CollectionOverflowException(String message, Exception exception) {
super(message, exception);
}
}

View File

@ -0,0 +1,18 @@
package Exceptions;
import java.io.Serializable;
public class ObjectNotFoundException extends Exception implements Serializable {
public ObjectNotFoundException(int i) {
super("Не найден объект по позиции " + i);
}
public ObjectNotFoundException() {
super();
}
public ObjectNotFoundException(String message) {
super(message);
}
public ObjectNotFoundException(String message, Exception exception) {
super(message, exception);
}
}

View File

@ -0,0 +1,19 @@
package Exceptions;
import java.io.Serializable;
public class PositionOutOfCollectionException extends Exception implements Serializable {
public PositionOutOfCollectionException(int i) {
super("Выход за границы коллекции. Позиция " + i);
}
public PositionOutOfCollectionException() {
super();
}
public PositionOutOfCollectionException(String message) {
super(message);
}
public PositionOutOfCollectionException(String message, Exception exception) {
super(message, exception);
}
}

View File

@ -14,10 +14,13 @@ import java.io.FileFilter;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.logging.Logger;
public class FormBoatCollection extends JFrame { public class FormBoatCollection extends JFrame {
final private Logger userLogger;
final private Logger programLogger;
final private JFrame jFrameCollectionBoats = new JFrame(); final private JFrame jFrameCollectionBoats = new JFrame();
final private DrawningAbstractCompany _company = new DrawningAbstractCompany(); final private DrawningAbstractCompany _company;
final private JButton refreshButton = new JButton("Обновить"); final private JButton refreshButton = new JButton("Обновить");
final private JPanel refreshPanel = new JPanel(); final private JPanel refreshPanel = new JPanel();
final private String[] listOfComboBox = { final private String[] listOfComboBox = {
@ -73,6 +76,12 @@ public class FormBoatCollection extends JFrame {
final private JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию"); final private JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
final private JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию"); final private JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
public FormBoatCollection(Logger userLogger, Logger programLogger) {
this.userLogger = userLogger;
this.programLogger = programLogger;
this._company = new DrawningAbstractCompany(userLogger, programLogger);
}
public void OpenFrame() { public void OpenFrame() {
fileMenu.add(loadItem); fileMenu.add(loadItem);
@ -305,10 +314,15 @@ public class FormBoatCollection extends JFrame {
} }
private void SaveFile() { private void SaveFile() {
String filename = SaveWindow(); String filename = SaveWindow();
if (_company.getStorageCollection().SaveData(filename)) { try {
_company.getStorageCollection().SaveData(filename);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Сохранено"); JOptionPane.showMessageDialog(jFrameCollectionBoats, "Сохранено");
userLogger.info("Сохранение данных в файл " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
programLogger.warning("Сохранение данных не удалось: " + ex.getMessage());
} }
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
} }
private void SaveCollection() { private void SaveCollection() {
String filename = SaveWindow(); String filename = SaveWindow();
@ -319,10 +333,16 @@ public class FormBoatCollection extends JFrame {
if (collectionsList.getSelectedIndex() < 0 || collectionsList.getSelectedValue() == null) { if (collectionsList.getSelectedIndex() < 0 || collectionsList.getSelectedValue() == null) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция не выбрана"); JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция не выбрана");
} }
if (_company.getStorageCollection().SaveOneCollection(filename, collectionsList)) { try {
_company.getStorageCollection().SaveOneCollection(filename, collectionsList);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция сохранена"); JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция сохранена");
userLogger.info("Сохранение коллекции" + collectionsList.getSelectedValue() + "в файл " + filename);
} catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
programLogger.warning("Сохранение коллекции не удалось: " + ex.getMessage());
} }
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Ошибка сохранения");
} }
private String LoadWindow() { private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD); FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
@ -334,20 +354,30 @@ public class FormBoatCollection extends JFrame {
} }
private void LoadFile() { private void LoadFile() {
String filename = LoadWindow(); String filename = LoadWindow();
if (_company.getStorageCollection().LoadData(filename)) { try {
_company.getStorageCollection().LoadData(filename);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Загрузка прошла успешно"); JOptionPane.showMessageDialog(jFrameCollectionBoats, "Загрузка прошла успешно");
updateCollectionsList(_company.getStorageCollection()); updateCollectionsList(_company.getStorageCollection());
userLogger.info("Загрузка данных из файла " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
programLogger.warning("Загрузка данных не удалась: " + ex.getMessage());
} }
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
} }
private void LoadCollection() { private void LoadCollection() {
String filename = LoadWindow(); String filename = LoadWindow();
if (_company.getStorageCollection().LoadOneCollection(filename)) { try {
_company.getStorageCollection().LoadOneCollection(filename);
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция загружена"); JOptionPane.showMessageDialog(jFrameCollectionBoats, "Коллекция загружена");
updateCollectionsList(_company.getStorageCollection()); updateCollectionsList(_company.getStorageCollection());
userLogger.info("Загрузка коллекции " + collectionsList.getSelectedValue() + " из файла " + filename);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
programLogger.warning("Загрузка коллекции не удалась: " + ex.getMessage());
} }
else JOptionPane.showMessageDialog(jFrameCollectionBoats, "Не загрузилось");
} }
private void updateCollectionsList(StorageCollection<DrawningBoat> storageCollection) { private void updateCollectionsList(StorageCollection<DrawningBoat> storageCollection) {

View File

@ -1,9 +1,60 @@
import Forms.FormBoatCollection; import Forms.FormBoatCollection;
import Forms.FormBoatConfig; import Forms.FormBoatConfig;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.logging.*;
public class Main { public class Main {
private static Logger userLogger = Logger.getLogger("userLogger");
private static Logger programLogger = Logger.getLogger("programLogger");
public static void main(String[] args) { public static void main(String[] args) {
FormBoatCollection formBoatCollection = new FormBoatCollection(); try {
FileHandler fileHandlerUser = new FileHandler("userLog.log");
userLogger.setLevel(Level.INFO);
;
fileHandlerUser.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
String formattedDate = dateFormat.format(currentDate);
LocalTime localTime = LocalTime.now();
return formattedDate + " | " + localTime.format(formatter) + " | " + record.getLevel() + " | " + record.getMessage()+ "\n";
}
});
userLogger.addHandler(fileHandlerUser);
}
catch (Exception e) {
userLogger.log(Level.SEVERE, "Ошибка при настройке логгера", e);
}
try {
FileHandler fileHandlerProgram = new FileHandler("programLog.log");
programLogger.setLevel(Level.WARNING);
fileHandlerProgram.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
String formattedDate = dateFormat.format(currentDate);
return record.getLevel() + " | " + record.getMessage() + " | (" + formattedDate + ")" + "\n";
}
});
programLogger.addHandler(fileHandlerProgram);
}
catch (Exception e) {
userLogger.log(Level.SEVERE, "Ошибка при настройке логгера", e);
}
FormBoatCollection formBoatCollection = new FormBoatCollection(userLogger, programLogger);
formBoatCollection.OpenFrame(); formBoatCollection.OpenFrame();
} }