PIbd-23_Nasyrov_A_G_Lab7_hard #7

Closed
gaillard wants to merge 3 commits from lab7_hard into lab6_hard
8 changed files with 156 additions and 62 deletions

View File

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

View File

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

View File

@ -5,7 +5,8 @@ import src.Generics.AirplaneGenericCollection;
import src.MovementStrategy.DrawningObjectAirplane;
import src.Generics.AirplaneGenericStorage;
import src.Generics.AirplaneTrashCollection;
import src.DrawningObjects.ExtentionDrawningAirplane;
import src.Exceptions.AirplaneNotFoundException;
import src.Exceptions.AirplaneStorageOverflowException;
import javax.swing.*;
import java.awt.*;
@ -14,12 +15,11 @@ import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.filechooser.FileFilter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.io.FileNotFoundException;
import org.apache.logging.log4j.*;
class TxtSaveFilter extends FileFilter {
@Override
@ -37,6 +37,7 @@ class TxtSaveFilter extends FileFilter {
}
public class FormAirplaneCollection {
private final Logger _logger;
private final AirplaneGenericStorage _storage;
private JList<String> listBoxStorages;
private DefaultListModel<String> listBoxModel;
@ -64,6 +65,7 @@ public class FormAirplaneCollection {
}
public FormAirplaneCollection() {
_logger = LogManager.getLogger("logger");
JMenuBar menuFile = new JMenuBar();
JMenu file = new JMenu("Файл");
menuFile.add(file);
@ -123,8 +125,10 @@ public class FormAirplaneCollection {
File file = new File(fc.getSelectedFile() + "." + "txt");
try {
_storage.SaveData(file);
} catch (IOException ex) {
throw new RuntimeException(ex);
_logger.info("Сохранено в файл: " + file.getAbsolutePath());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка при сохранении всех объектов " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось сохранить объекты в файл: " + file.getAbsolutePath());
}
}
}
@ -143,8 +147,10 @@ public class FormAirplaneCollection {
}
_storage._airplaneStorages.get(listBoxStorages.getSelectedValue()).SaveData(file, listBoxStorages.getSelectedValue());
ReloadObjects();
} catch (IOException ex) {
throw new RuntimeException(ex);
_logger.info("Сохранена коллекция в файл: " + file.getAbsolutePath());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ошибка при сохранении коллекции " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось сохранить коллекцию в файл: " + file.getAbsolutePath());
}
}
}
@ -159,13 +165,17 @@ public class FormAirplaneCollection {
try {
_storage.LoadData(file);
canv._storage =_storage;
ReloadObjects();
canv.repaint();
} catch (IOException ex) {
throw new RuntimeException(ex);
_logger.info("Загружено из файла: " + file.getAbsolutePath());
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Ошибка при загрузке всех объектов " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось загрузить объекты из файла: " + file.getAbsolutePath());
}
catch (Exception ex){
_logger.fatal("фатальная ошибка");
}
}
ReloadObjects();
canv.repaint();
}
});
loadCollection.addActionListener(new ActionListener() {
@ -179,8 +189,10 @@ public class FormAirplaneCollection {
_storage.LoadCollection(file);
ReloadObjects();
canv.repaint();
_logger.info("Загружен файл с коллекцией: " + file.getAbsolutePath());
} catch (IOException ex) {
throw new RuntimeException(ex);
JOptionPane.showMessageDialog(null, "Ошибка при загрузке коллекции " + ex.getMessage(), "Результат", JOptionPane.ERROR_MESSAGE);
_logger.error("Не удалось загрузить коллекцию из файла: " + file.getAbsolutePath());
}
}
}
@ -189,8 +201,9 @@ public class FormAirplaneCollection {
@Override
public void actionPerformed(ActionEvent e) {
if (storageName.getText() == null)
return;
_logger.error("Не удалось добавить набор: " + storageName);
_storage.AddSet(storageName.getText());
_logger.info("Добавлен набор: " + storageName.getText());
ReloadObjects();
}
});
@ -198,10 +211,11 @@ public class FormAirplaneCollection {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxStorages.getSelectedIndex() == -1) {
return;
_logger.error("Не выбран набор для удаления");
}
_storage.DelSet(listBoxStorages.getSelectedValue(), _trashCollection);
ReloadObjects();
_logger.info("Удален набор: " + listBoxStorages.getSelectedValue());
}
});
callTrashButton.addActionListener(new ActionListener() {
@ -218,24 +232,33 @@ public class FormAirplaneCollection {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxStorages.getSelectedIndex() == -1) {
return;
_logger.warn("Не выбрана коллекция для добавления объекта");
}
AirplaneGenericCollection<DrawningAirplane, DrawningObjectAirplane> _airplanes = _storage.Get(listBoxStorages.getSelectedValue());
FormAirplaneConfig form = new FormAirplaneConfig();
form.addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_airplanes.Insert(form._airplane)) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
form._airplane._pictureWidth = pictureBoxWidth;
form._airplane._pictureHeight = pictureBoxHeight;
try {
if (_airplanes.Insert(form._airplane)) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
form._airplane._pictureWidth = pictureBoxWidth;
form._airplane._pictureHeight = pictureBoxHeight;
Draw();
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
_logger.warn("Не удалось добавить объект " );
}
form.frameConfig.dispose();
Draw();
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
_logger.info("Добавлен объект");
} catch (AirplaneStorageOverflowException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
_logger.warn("Не удалось добавить объект " + ex.getMessage());
}
catch (Exception ex){
_logger.fatal("фатальная ошибка");
}
form.frameConfig.dispose();
Draw();
}
});
form.cancelButton.addActionListener(new ActionListener() {
@ -251,26 +274,34 @@ public class FormAirplaneCollection {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxStorages.getSelectedIndex() == -1) {
return;
_logger.warn("Не выбрана коллекция для удаления объекта");
}
AirplaneGenericCollection<DrawningAirplane, DrawningObjectAirplane> _airplanes = _storage.Get(listBoxStorages.getSelectedValue());
if (_airplanes == null) {
return;
_logger.warn("Набор равен null");
}
String tmp = airplaneNumb.getText();
int numb;
int numb=Integer.parseInt(tmp);
try {
numb = Integer.parseInt(tmp);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Введите число", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
if (_airplanes.Get(numb)!=null){
DrawningAirplane curAirplane = _airplanes.Get(numb);
_trashCollection.Push(curAirplane);
_airplanes.Remove(numb);
_airplanes.ShowAirplanes();
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
_logger.info("Удален объект по позиции " + numb);
} else{
throw new AirplaneNotFoundException(numb);
}
} catch (AirplaneNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
_logger.warn("Не удалось удалить объект" + ex.getMessage());
}
catch (Exception ex){
_logger.fatal("фатальная ошибка");
}
DrawningAirplane curAirplane = _airplanes.Get(numb);
_trashCollection.Push(curAirplane);
_airplanes.Remove(numb);
_airplanes.ShowAirplanes();
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
}
});

View File

@ -2,8 +2,9 @@ package src.Generics;
import src.DrawningObjects.DrawningAirplane;
import src.MovementStrategy.IMoveableObject;
import src.DrawningObjects.ExtentionDrawningAirplane;
import src.MovementStrategy.DrawningObjectAirplane;
import com.sun.nio.sctp.InvalidStreamException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
@ -38,7 +39,7 @@ public class AirplaneGenericCollection<T extends DrawningAirplane, U extends IMo
}
data.append(records);
if(data.length() == 0)
return false;
throw new InvalidStreamException("Нет данных для сохранения");
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();

View File

@ -1,9 +1,11 @@
package src.Generics;
import com.sun.nio.sctp.InvalidStreamException;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import src.MovementStrategy.DrawningObjectAirplane;
import src.DrawningObjects.DrawningAirplane;
@ -30,7 +32,7 @@ public class AirplaneGenericStorage {
data.append(String.format("%s%c%s\n", record.getKey(), _separatorForKeyValue, records.toString()));
}
if(data.length() == 0)
return false;
throw new InvalidStreamException("Нет данных для сохранения");
FileWriter writer = new FileWriter(f);
writer.write(data.toString());
writer.flush();
@ -39,7 +41,7 @@ public class AirplaneGenericStorage {
}
public boolean LoadData(File f) throws FileNotFoundException {
if(!f.exists())
return false;
throw new FileNotFoundException("Файл не найден");
StringBuilder bufferTextFromFile =new StringBuilder();
Scanner s = new Scanner(f);
while(s.hasNext())
@ -47,9 +49,9 @@ public class AirplaneGenericStorage {
s.close();
var strs = bufferTextFromFile.toString().split("\n");
if(strs == null || strs.length == 0)
return false;
throw new NullPointerException("Нет данных для загрузки");
if (!strs[0].startsWith("AirplaneStorage"))
return false;
throw new IllegalArgumentException("Неверный формат данных");
_airplaneStorages.clear();
for(String data : strs){
String st = new String("\\" + Character.toString( _separatorForKeyValue));
@ -78,7 +80,7 @@ public class AirplaneGenericStorage {
public boolean LoadCollection(File f) throws FileNotFoundException {
if(!f.exists())
return false;
throw new FileNotFoundException("Файл не найден");
StringBuilder bufferTextFromFile =new StringBuilder();
Scanner s = new Scanner(f);
while(s.hasNext())
@ -86,9 +88,9 @@ public class AirplaneGenericStorage {
s.close();
var strs = bufferTextFromFile.toString().split("\n");
if(strs == null || strs.length == 0)
return false;
throw new NullPointerException("Нет данных для загрузки");
if (!strs[0].startsWith("AirplaneCollection"))
return false;
throw new IllegalArgumentException("Неверный формат данных");
String collectionName = strs[1];
AirplaneGenericCollection<DrawningAirplane, DrawningObjectAirplane> collection = GetCollection(collectionName);
if(collection == null)

View File

@ -1,4 +1,7 @@
package src.Generics;
import src.Exceptions.AirplaneNotFoundException;
import src.Exceptions.AirplaneStorageOverflowException;
import java.util.ArrayList;
import java.util.List;
@ -18,6 +21,8 @@ public class SetGeneric <T extends Object>{
}
public boolean Insert(T airplane, int position){
if(_places.size() == _maxCount)
throw new AirplaneStorageOverflowException(_maxCount);
if (!(position >= 0 && position <= _places.size() && _places.size() < _maxCount))
return false;
_places.add(position, airplane);
@ -27,7 +32,7 @@ public class SetGeneric <T extends Object>{
public boolean Remove(int position){
if(!(position >= 0 && position < _places.size()))
return false;
throw new AirplaneNotFoundException(position);
_places.remove(position);
return true;
}

View File

@ -1,19 +1,9 @@
package src;
import src.DrawningObjects.DrawningAirplaneWithRadar;
import src.DrawningObjects.DrawningAirplane;
import src.MovementStrategy.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Main {
public static void main(String[] args) throws IOException {
System.setProperty("log4j.configurationFile", "C:\\Users\\1\\Desktop\\улгту\\2 курс\\РПП\\PIbd-23_Nasyrov_A_G_AirplaneWithRadar_hard\\src\\loggerFile.xml");
FormAirplaneCollection form = new FormAirplaneCollection();
}
}

32
src/loggerFile.xml Normal file
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>