PIbd - 21 Bakalskaya E.D. LabWork7 Hard #10

Closed
ekallin wants to merge 12 commits from LabWork7 into LabWork6
9 changed files with 215 additions and 87 deletions

18
.idea/java.iml generated
View File

@ -7,5 +7,23 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/apache-log4j-2.22.0-bin/log4j-core-2.22.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/apache-log4j-2.22.0-bin/log4j-api-2.22.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

View File

@ -5,11 +5,13 @@ import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Stack;
//готовая лаба 3
import org.apache.logging.log4j.*;
public class FormLocomotiveCollections {
private final Logger _logger;
FormElectricLocomotive formElectricLocomotive;
FormLocomotiveConfig formLocomotiveConfig;
private JPanel MainPanel;
@ -30,14 +32,18 @@ public class FormLocomotiveCollections {
FrameElectricLocomotive _frameRemovedLocomotives;
private Stack<DrawingLocomotive> _stackRemoveObjects;
FrameDopClassParameters frameDopClassParameters;
public JPanel getPictureBoxCollections() {
return MainPanel;
}
public FormLocomotiveCollections() {
_logger = LogManager.getLogger("logger");
formElectricLocomotive = new FormElectricLocomotive();
formLocomotiveConfig = new FormLocomotiveConfig();
_storage = new LocomotivesGenericStorage(400,300);
_storage = new LocomotivesGenericStorage(400, 300);
_stackRemoveObjects = new Stack<>();
listBoxStorage.addListSelectionListener(this::listBoxObjectsSelectedIndexChanged);
@ -49,48 +55,60 @@ public class FormLocomotiveCollections {
"Где данные? Напиши хоть что-нибудь",
"Ошибка",
JOptionPane.INFORMATION_MESSAGE);
return;
_logger.error("Не удалось добавить набор: " + NameStorage);
}
_storage.AddSet(NameStorage);
ReloadObjects();
Refresh();
_logger.info("Добавлен набор: " + NameStorage);
});
ButtonRemoveObject.addActionListener(e ->
{
if (listBoxStorage.getSelectedIndex() == -1) {
return;
_logger.error("Не выбран набор для удаления");
}
JOptionPane.showMessageDialog(this.getPictureBoxCollections(), "Коллекция удалена", "Удаление", JOptionPane.INFORMATION_MESSAGE);
_storage.DelSet((String) listBoxStorage.getSelectedValue()); //ТУТ СТРИНГ ОБРАТИ ВНИМАНИЕ КАК-НИБУДЬ
ReloadObjects();
_logger.info("Удален набор: " + listBoxStorage.getSelectedValue());
});
ButtonAddLocomotive.addActionListener(e -> {
if (listBoxStorage.getSelectedIndex() == -1)
return;
_logger.warn("Не выбрана коллекция для добавления объекта");
var obj = _storage.get(listBoxStorage.getSelectedValue().toString()); // ТУТ ЕЩЕ РАЗ - ОБРАТИ ВНИМАНИЕ НА СТРИНГ
if (obj == null) {
return;
_logger.warn("Набор равен null");
}
FrameLocomotiveConfig frameLocomotiveConfig = new FrameLocomotiveConfig();
frameLocomotiveConfig.setVisible(true);
frameLocomotiveConfig._formLocomotiveConfig.buttonOk.addActionListener(e2 ->{
frameLocomotiveConfig._formLocomotiveConfig.buttonOk.addActionListener(e2 -> {
frameLocomotiveConfig.dispose();
loco = frameLocomotiveConfig._formLocomotiveConfig._loco;
if(loco != null){
if (obj.AddOverload(loco)!= -1) {
JOptionPane.showMessageDialog(getPictureBoxCollections(), "Объект добавлен");
Refresh();
} else {
JOptionPane.showMessageDialog(getPictureBoxCollections(), "Не удалось добавить объект");
try {
if (loco != null) {
if (obj.AddOverload(loco) != -1) {
JOptionPane.showMessageDialog(getPictureBoxCollections(), "Объект добавлен");
Refresh();
} else {
JOptionPane.showMessageDialog(getPictureBoxCollections(), "Не удалось добавить объект");
}
}
frameLocomotiveConfig._formLocomotiveConfig.buttonClose.addActionListener(e3 -> {
frameLocomotiveConfig.dispose();
});
_logger.info("Добавлен локомотив");
} catch (LocoStorageOverflowException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
_logger.warn("Не удалось добавить объект " + ex.getMessage());
}
catch (Exception ex){
_logger.fatal("фатальная ошибка");
}
});
frameLocomotiveConfig._formLocomotiveConfig.buttonClose.addActionListener(e3 -> {
frameLocomotiveConfig.dispose();
});
});
ButtonCreateRandomLoco.addActionListener(e -> {
@ -101,49 +119,30 @@ public class FormLocomotiveCollections {
ButtonRemoveLocomotive.addActionListener(e -> {
if (listBoxStorage.getSelectedIndex() == -1) {
return;
_logger.warn("Не выбрана коллекция для удаления объекта");
}
var obj = _storage.get(listBoxStorage.getSelectedValue().toString());
if (obj == null) {
return;
_logger.warn("Набор равен null");
}
int pos;
try {
pos = Integer.parseInt(textFieldNumber.getText());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this.getPictureBoxCollections(),
"Неверное значение",
"Ошибка",
JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = {"Да", "Нет"};
int n = JOptionPane.showOptionDialog(this.getPictureBoxCollections(),
"Удалить объект?",
"Все серьезно",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);
if (n == 1) {
return;
}
DrawingLocomotive removedPlane = obj.SubOverload(pos);
if (removedPlane != null) {
_stackRemoveObjects.push(removedPlane);
Refresh();
int pos = Integer.parseInt(textFieldNumber.getText());
JOptionPane.showMessageDialog(this.getPictureBoxCollections(),
"Объект удален",
"Успех",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this.getPictureBoxCollections(),
"Не удалось удалить объект",
"Ошибка",
JOptionPane.ERROR_MESSAGE);
try {
DrawingLocomotive removedPlane = obj.SubOverload(pos);
_stackRemoveObjects.push(removedPlane);
Refresh();
JOptionPane.showMessageDialog(this.getPictureBoxCollections(),
"Объект удален",
"Успех",
JOptionPane.INFORMATION_MESSAGE);
_logger.info("Удален объект " + removedPlane);
} catch (LocoNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
_logger.warn("Не удалось удалить объект" + ex.getMessage());
}
catch (Exception ex){
_logger.fatal("фатальная ошибка");
}
});
@ -152,7 +151,7 @@ public class FormLocomotiveCollections {
});
Button_OpenFormRemovedLocomotives.addActionListener(e -> {
if(_stackRemoveObjects.empty()) {
if (_stackRemoveObjects.empty()) {
JOptionPane.showMessageDialog(this.getPictureBoxCollections(),
"Вы ничего не удалили, кажется...",
"ой",
@ -178,10 +177,19 @@ public class FormLocomotiveCollections {
fileChooser.setDialogTitle("Выберите файл для загрузки данных");
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.LoadData(selectedFile.getAbsolutePath())) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
try {
if (_storage.LoadData(selectedFile.getAbsolutePath())) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
_logger.info("Загружено из файла: " + selectedFile.getAbsolutePath());
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Ошибка при загрузке всех объектов " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось загрузить объекты из файла: " + selectedFile.getAbsolutePath());
}
catch (Exception ex){
_logger.fatal("фатальная ошибка");
}
}
ReloadObjects();
@ -195,10 +203,15 @@ public class FormLocomotiveCollections {
fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt"));
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.SaveData(selectedFile.getAbsolutePath()))
try {
_storage.SaveData(selectedFile.getAbsolutePath());
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE);
_logger.info("Сохранено в файл: " + selectedFile.getAbsolutePath());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка при сохранении всех объектов " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось сохранить объекты в файл: " + selectedFile.getAbsolutePath());
}
}
}
);
@ -210,10 +223,16 @@ public class FormLocomotiveCollections {
fileChooser.setDialogTitle("Выберите файл для загрузки данных");
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.LoadDataSingle(selectedFile.getAbsolutePath())) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
try {
if (_storage.LoadDataSingle(selectedFile.getAbsolutePath())) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
_logger.info("Загружен файл с коллекцией: " + selectedFile.getAbsolutePath());
} else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Ошибка при загрузке коллекции " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось загрузить коллекцию из файла: " + selectedFile.getAbsolutePath());
}
}
ReloadObjects();
@ -231,10 +250,15 @@ public class FormLocomotiveCollections {
fileChooser.setDialogTitle("Выберите файл для сохранения данных");
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.SaveDataSingle(selectedFile.getAbsolutePath(), (String) listBoxStorage.getSelectedValue()))
try {
_storage.SaveDataSingle(selectedFile.getAbsolutePath(), (String) listBoxStorage.getSelectedValue());
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE);
_logger.info("Сохранена коллекция в файл: " + selectedFile.getAbsolutePath());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка при сохранении коллекции " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось сохранить коллекцию в файл: " + selectedFile.getAbsolutePath());
}
}
}
);

View File

@ -0,0 +1,22 @@
package ProjectElectricLocomotive;
import java.io.Serializable;
//create lab 7
public class LocoNotFoundException extends RuntimeException implements Serializable {
public LocoNotFoundException(int i) {
super("Не найден объект по позиции " + i);
}
public LocoNotFoundException(Throwable ex) {
super(ex);
}
public LocoNotFoundException(String message) {
super(message);
}
public LocoNotFoundException(String message, Throwable ex) { //Throwable люди пишут, посмотри внимательно
super(message, ex);
}
}

View File

@ -0,0 +1,19 @@
package ProjectElectricLocomotive;
import java.io.Serializable;
public class LocoStorageOverflowException extends RuntimeException implements Serializable {
public LocoStorageOverflowException(Throwable ex){
super(ex);
}
public LocoStorageOverflowException(int count){
super("В наборе превышено допустимое количество локомотивов: " + count);
}
public LocoStorageOverflowException(String message){
super(message);
}
public LocoStorageOverflowException(String message, Throwable ex){
super(message, ex);
}
}

View File

@ -44,6 +44,9 @@ public class LocomotiveGenericCollection<T extends DrawingLocomotive,U extends I
{
_collection.Remove(pos);
}
else{
throw new LocoNotFoundException(pos);
}
return loco;
}

View File

@ -1,5 +1,7 @@
package ProjectElectricLocomotive;
import com.sun.nio.sctp.InvalidStreamException;
import java.io.*;
import java.util.*;
@ -10,6 +12,9 @@ import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*import org.slf4j.Logger;
import org.slf4j.LoggerFactory;*/
public class LocomotivesGenericStorage {
private static final String _separatorForKeyValue = "@";
@ -60,7 +65,7 @@ public class LocomotivesGenericStorage {
return null;
}
public boolean SaveDataSingle(String filename, String key) {
public boolean SaveDataSingle(String filename, String key){
var file = new File(filename);
if (file.exists()) {
file.delete();
@ -70,29 +75,29 @@ public class LocomotivesGenericStorage {
for (DrawingLocomotive elem : _locomotiveStorage.get(key).GetLocomotives())
data.append(elem != null ? ExtentionDrawingLoco.GetDataForSave(elem, _separatorForObjectSingle) + "\n" : "");
if (data.isEmpty()) {
return false;
throw new InvalidStreamException("Нет данных для сохранения");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(_keywordSingle + System.lineSeparator() + data);
} catch (IOException e) {
} catch (Exception ex) {
return false;
}
return true;
}
public boolean LoadDataSingle(String filename){
public boolean LoadDataSingle(String filename) throws IOException {
if (!new File(filename).exists()) {
return false;
throw new FileNotFoundException("Файл не найден");
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String s = reader.readLine();
if (s == null || s.isEmpty())
return false;
throw new NullPointerException("Нет данных для загрузки");
if (!s.startsWith(_keywordSingle))
return false;
throw new IllegalArgumentException("Неверный формат данных");
String key = reader.readLine();
if (key == null || key.isEmpty())
return false;
throw new NullPointerException("Нет данных для загрузки");
LocomotiveGenericCollection<DrawingLocomotive, DrawingObjectLocomotive> collection;
if (_locomotiveStorage.containsKey(key)){
collection = _locomotiveStorage.get(key);
@ -115,7 +120,7 @@ public class LocomotivesGenericStorage {
_pictureHeight
);
if (plane == null || collection.AddOverload(plane) == -1)
return false;
throw new NoSuchElementException("Не найден объект");
}
_locomotiveStorage.put(key, collection);
} catch (IOException e) {
@ -138,7 +143,7 @@ public class LocomotivesGenericStorage {
data.append(record.getKey()).append(_separatorForKeyValue).append(records).append("\n");
}
if (data.isEmpty()) {
return false;
throw new InvalidStreamException("Нет данных для сохранения");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(_keyword + System.lineSeparator() + data);
@ -148,18 +153,18 @@ public class LocomotivesGenericStorage {
return true;
}
public boolean LoadData(String filename) {
public boolean LoadData(String filename) throws FileNotFoundException {
var file = new File(filename);
if (!file.exists()) {
return false;
throw new FileNotFoundException("Файл не найден");
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String s = reader.readLine();
if (s == null || s.isEmpty())
return false;
throw new NullPointerException("Нет данных для загрузки");
if (!s.startsWith(_keyword)) {
return false;
throw new IllegalArgumentException("Неверный формат данных");
}
_locomotiveStorage.clear();
s = reader.readLine();
@ -180,7 +185,7 @@ public class LocomotivesGenericStorage {
_pictureWidth, _pictureHeight
);
if (plane == null || collection.AddOverload(plane) == -1)
return false;
throw new NoSuchElementException("Не найден объект");
}
_locomotiveStorage.put(record[0], collection);
}

View File

@ -3,6 +3,7 @@ package ProjectElectricLocomotive;
public class Main {
public static void main(String[] args)
{
FrameLocomotiveCollection mainFrame = new FrameLocomotiveCollection();
System.setProperty("log4j.configurationFile", "C:\\code\\java\\ProjectElectricLocomotive\\loggerFile.xml");
new FrameLocomotiveCollection();
}
}

View File

@ -25,8 +25,10 @@ public class SetGeneric<T extends DrawingLocomotive>{
public int Insert(T loco, int position)
{
if(position < 0 || position > maxCount)
if(position < 0)
return -1;
if(_places.size() >= maxCount)
throw new LocoStorageOverflowException(maxCount);
else
{
_places.add(position, loco);
@ -41,6 +43,8 @@ public class SetGeneric<T extends DrawingLocomotive>{
else
{
T plane = _places.get(position);
if(plane == null)
throw new LocoNotFoundException(position);
_places.set(position, null);
return plane;
}

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<!-- Секция аппендеров -->
<Appenders>
<!-- Файловый аппендер -->
<File name="fileWarnings" fileName="logWarnings.log">
<PatternLayout>
<Pattern> %m (дата-%d{d.M.y}) %ex%n</Pattern>
</PatternLayout>
</File>
<File name="fileInfo" fileName="logInfo.log">
<PatternLayout>
<Pattern> %m (дата-%d{d.M.y}) %ex%n</Pattern>
</PatternLayout>
<Filters>
<!-- Now deny warn, error and fatal messages -->
<ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
<!-- This filter accepts info, warn, error, fatal and denies debug/trace -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
</File>
</Appenders>
<!-- Секция логгеров -->
<Loggers>
<Logger name="logger" level="info" additivity="false">
<AppenderRef ref="fileInfo" level="INFO"/>
<AppenderRef ref="fileWarnings" level="WARN"/>
</Logger>
</Loggers>
</Configuration>