This commit is contained in:
MaxKarme 2022-12-15 13:54:34 +03:00
parent 6663b98a92
commit aad872a57a
7 changed files with 195 additions and 141 deletions

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
.idea
out
out
logs

View File

@ -3,6 +3,7 @@ import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.util.*;
import java.util.List;
import org.apache.logging.log4j.*;
public class FormMapWithSetAircrafts implements Form {
private JPanel MainPane;
@ -33,9 +34,16 @@ public class FormMapWithSetAircrafts implements Form {
private Canvas canv = new Canvas(this);
private Queue<IDrawingObject> deletedAircrafts = new ArrayDeque<>();
JFrame jFrame = getFrame();
Image img;
private Logger _logger;
public FormMapWithSetAircrafts(Logger logger) {
_logger = logger;
}
private JFrame getFrame() {
JFrame frame = new JFrame();
frame.setVisible(true);
@ -90,10 +98,14 @@ public class FormMapWithSetAircrafts implements Form {
String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.SaveData(path)) {
try {
_mapsCollection.SaveData(path);
_logger.info("Данные сохранены в файл " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно");
} else JOptionPane.showMessageDialog(jFrame, "Не сохранилось");
} catch (Exception err) {
_logger.error("Ошибка сохранения данных: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Не сохранилось");
}
});
loadItem.addActionListener(e -> {
@ -104,10 +116,16 @@ public class FormMapWithSetAircrafts implements Form {
if(chooser.getSelectedFile() == null) return;
String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.LoadData(path)) {
try {
_mapsCollection.LoadData(path);
_logger.info("Данные из загружены из файла " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно");
ReloadMaps();
} else JOptionPane.showMessageDialog(jFrame, "Не загрузилось");
} catch (Exception err) {
_logger.error("Ошибка загрузки данных " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Не загрузилось");
}
});
saveMapItem.addActionListener(e -> {
@ -122,10 +140,16 @@ public class FormMapWithSetAircrafts implements Form {
String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.SaveMap(path, listBoxMaps.getSelectedValue().toString())) {
try {
_mapsCollection.SaveMap(path, listBoxMaps.getSelectedValue().toString());
_logger.info("Карта " + listBoxMaps.getSelectedValue().toString() +
" сохранена в файл " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Сохранение прошло успешно");
} else JOptionPane.showMessageDialog(jFrame, "Не сохранилось");
} catch (Exception err) {
_logger.error("Ошибка сохранения карты " + listBoxMaps.getSelectedValue().toString() +
" в файл " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Не сохранилось");
}
});
loadMapItem.addActionListener(e -> {
@ -136,10 +160,18 @@ public class FormMapWithSetAircrafts implements Form {
if(chooser.getSelectedFile() == null) return;
String path = chooser.getSelectedFile().getAbsolutePath();
if(_mapsCollection.LoadMap(path)) {
try {
_mapsCollection.LoadMap(path);
_logger.info("Карта " + listBoxMaps.getSelectedValue().toString() +
" загружена из файла " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Загрузка прошла успешно");
ReloadMaps();
} else JOptionPane.showMessageDialog(jFrame, "Не загрузилось");
} catch (Exception err) {
_logger.error("Ошибка загрузки карты " + listBoxMaps.getSelectedValue().toString() +
" из файла " + chooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(jFrame, "Не загрузилось");
}
});
_mapsCollection = new MapsCollection(canv.getSize().width, canv.getSize().height);
@ -154,22 +186,27 @@ public class FormMapWithSetAircrafts implements Form {
listBoxMaps.addListSelectionListener(e -> {
if(listBoxMaps.getSelectedValue() == null) return;
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet();
_logger.info("Переход на карту " + listBoxMaps.getSelectedValue().toString());
canv.repaint();
});
buttonAddMap.addActionListener(e -> {
if (comboBoxSelectorMap.getSelectedIndex() == -1 || textBoxNewMapName.getText() == "")
{
_logger.warn("Не получилось добавить карту: не все данные заполнены");
JOptionPane.showMessageDialog(jFrame, "Не все данные заполнены");
return;
}
if (!_mapsDict.containsKey(comboBoxSelectorMap.getSelectedItem().toString()))
{
_logger.warn("Не получилось добавить карту: нет такой карты");
JOptionPane.showMessageDialog(jFrame, "Нет такой карты");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.getText(),
_mapsDict.get(comboBoxSelectorMap.getSelectedItem().toString()));
_logger.info("Добавлена карта " + textBoxNewMapName.getText());
ReloadMaps();
});
@ -184,6 +221,7 @@ public class FormMapWithSetAircrafts implements Form {
"Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
_mapsCollection.DelMap(mapName);
_logger.info("Удалена карта " + mapName);
ReloadMaps();
}
});
@ -200,17 +238,21 @@ public class FormMapWithSetAircrafts implements Form {
formConfig.addListener(drawingAircraft -> {
if(drawingAircraft == null) return;
DrawingObjectAircraft aircraft = new DrawingObjectAircraft(drawingAircraft);
if (_mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).addAircraft(aircraft) != -1)
{
try {
DrawingObjectAircraft aircraft = new DrawingObjectAircraft(drawingAircraft);
_mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).addAircraft(aircraft);
_logger.info("Добавлен новый объект");
JOptionPane.showMessageDialog(jFrame, "Объект добавлен");
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet();
canv.repaint();
} catch(StorageOverflowException err) {
_logger.warn("Ошибка добавления: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Ошибка переполнения: " + err.getMessage());
} catch(Exception err) {
_logger.fatal("Незивестная ошибка: " + err.getMessage());
}
else
{
JOptionPane.showMessageDialog(jFrame, "Не удалось добавить объект");
}
});
});
@ -233,15 +275,20 @@ public class FormMapWithSetAircrafts implements Form {
pos = Integer.parseInt(text);
String mapName = listBoxMaps.getSelectedValue().toString();
IDrawingObject deleted = _mapsCollection.getMap(mapName).removeAircraft(pos);
if(deleted != null) {
try {
IDrawingObject deleted = _mapsCollection.getMap(mapName).removeAircraft(pos);
_logger.info("Объект удален");
JOptionPane.showMessageDialog(jFrame, "Объект удален");
img = _mapsCollection.getMap(mapName).ShowSet();
deletedAircrafts.add(deleted);
canv.repaint();
} else {
JOptionPane.showMessageDialog(jFrame, "Не удалось удалить объект");
} catch(AircraftNotFoundException err) {
_logger.warn("Ошибка добавления: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Ошибка удаления: " + err.getMessage());
} catch (Exception err) {
_logger.fatal("Неизвестная ошибка: " + err.getMessage());
JOptionPane.showMessageDialog(jFrame, "Неизвестная ошибка: " + err.getMessage());
}
});
@ -249,6 +296,7 @@ public class FormMapWithSetAircrafts implements Form {
if(listBoxMaps.getSelectedValue() == null) return;
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowSet();
_logger.info("Показ хранилища");
canv.repaint();
});
@ -256,6 +304,7 @@ public class FormMapWithSetAircrafts implements Form {
if(listBoxMaps.getSelectedValue() == null) return;
img = _mapsCollection.getMap(listBoxMaps.getSelectedValue().toString()).ShowOnMap();
_logger.info("Показ карты");
canv.repaint();
});
@ -267,6 +316,7 @@ public class FormMapWithSetAircrafts implements Form {
if(deletedAircrafts.size() == 0) {
JOptionPane.showMessageDialog(jFrame, "Очередь пуста");
_logger.warn("Очередь удаленных объектов пуста");
return;
}
@ -280,6 +330,8 @@ public class FormMapWithSetAircrafts implements Form {
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
_logger.info("Показ удаленного объекта");
});
leftButton.addActionListener(e -> {

View File

@ -1,5 +1,7 @@
import org.apache.logging.log4j.*;
public class Main {
public static void main(String[] args) {
new FormMapWithSetAircrafts().run();
new FormMapWithSetAircrafts(LogManager.getLogger(Main.class)).run();
}
}
}

View File

@ -40,19 +40,19 @@ public class MapWithSetAircraftsGeneric<T extends IDrawingObject, U extends Abst
_setAircrafts.Clear();
}
public void LoadData(String[] records) {
public void LoadData(String[] records) throws StorageOverflowException {
for (String rec : records)
{
_setAircrafts.Insert((T)DrawingObjectAircraft.Create(rec));
}
}
public int addAircraft(T aircraft)
public int addAircraft(T aircraft) throws StorageOverflowException
{
return _setAircrafts.Insert(aircraft);
}
public T removeAircraft(int position)
public T removeAircraft(int position) throws AircraftNotFoundException
{
return _setAircrafts.Remove(position);
}

View File

@ -1,10 +1,8 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.zip.DataFormatException;
public class MapsCollection
{
@ -24,112 +22,40 @@ public class MapsCollection
_pictureHeight = pictureHeight;
}
public boolean SaveData(String filename)
public void SaveData(String filename) throws IOException
{
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.append("MapsCollection\n");
FileWriter writer = new FileWriter(file);
writer.append("MapsCollection\n");
for(String key : _mapStorages.keySet()) {
String record = key + separatorDict + _mapStorages.get(key).GetData(separatorDict, separatorData) + "\n";
writer.append(record);
}
writer.flush();
writer.close();
} catch(Exception err) {
return false;
for(String key : _mapStorages.keySet()) {
String record = key + separatorDict + _mapStorages.get(key).GetData(separatorDict, separatorData) + "\n";
writer.append(record);
}
return true;
writer.flush();
writer.close();
}
public boolean LoadData(String filename)
{
public void LoadData(String filename) throws IOException, DataFormatException {
File file = new File(filename);
if (!file.exists()) return false;
if (!file.exists()) throw new FileNotFoundException("Файл не найден");
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String current = reader.readLine();
BufferedReader reader = new BufferedReader(new FileReader(file));
String current = reader.readLine();
if (!current.equals("MapsCollection")) return false;
_mapStorages.clear();
while ((current = reader.readLine()) != null)
{
String elem[] = current.split("\\" + separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MyMap":
map = new MyMap();
break;
}
_mapStorages.put(elem[0], new MapWithSetAircraftsGeneric<DrawingObjectAircraft, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.get(elem[0]).LoadData(elem[2].split(separatorData + ""));
}
reader.close();
} catch(Exception err) {
return false;
}
return true;
}
public boolean SaveMap(String filename, String key) {
File file = new File(filename);
if(file.exists()) file.delete();
MapWithSetAircraftsGeneric<DrawingObjectAircraft, AbstractMap> item = _mapStorages.getOrDefault(key, null);
if(item == null) return false;
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.append("Map\n");
writer.append(key + "\n");
writer.append(item.getMap().getClass().getName() + "\n");
ListIterator<DrawingObjectAircraft> iter = item.getAircraftsIter();
while(iter.hasNext()) {
writer.append(AircraftFactory.getDataForSave(iter.next().getAircraft()) + "\n");
}
writer.flush();
writer.close();
} catch(Exception err) {
return false;
}
return true;
}
public boolean LoadMap(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String format = reader.readLine();
if (!format.equals("Map")) return false;
String key = reader.readLine();
String mapStr = reader.readLine();
if (!current.equals("MapsCollection")) throw new DataFormatException("Неверный формат данных");
_mapStorages.clear();
while ((current = reader.readLine()) != null)
{
String elem[] = current.split("\\" + separatorDict);
AbstractMap map = null;
switch (mapStr)
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
@ -138,21 +64,67 @@ public class MapsCollection
map = new MyMap();
break;
}
if(_mapStorages.containsKey(key)) _mapStorages.get(key).ClearMap();
else _mapStorages.put(key, new MapWithSetAircraftsGeneric<>(_pictureWidth, _pictureHeight, map));
String current = null;
while ((current = reader.readLine()) != null)
{
_mapStorages.get(key).addAircraft(DrawingObjectAircraft.Create(current));
}
reader.close();
} catch(Exception err) {
return false;
_mapStorages.put(elem[0], new MapWithSetAircraftsGeneric<DrawingObjectAircraft, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.get(elem[0]).LoadData(elem[2].split(separatorData + ""));
}
return true;
reader.close();
}
public void SaveMap(String filename, String key) throws IOException {
File file = new File(filename);
if(file.exists()) file.delete();
MapWithSetAircraftsGeneric<DrawingObjectAircraft, AbstractMap> item = _mapStorages.get(key);
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.append("Map\n");
writer.append(key + "\n");
writer.append(item.getMap().getClass().getName() + "\n");
ListIterator<DrawingObjectAircraft> iter = item.getAircraftsIter();
while(iter.hasNext()) {
writer.append(AircraftFactory.getDataForSave(iter.next().getAircraft()) + "\n");
}
writer.flush();
writer.close();
}
public void LoadMap(String filename) throws IOException, DataFormatException {
File file = new File(filename);
if (!file.exists()) throw new FileNotFoundException("Файл не найден");
BufferedReader reader = new BufferedReader(new FileReader(file));
String format = reader.readLine();
if (!format.equals("Map")) throw new DataFormatException("Неверный формат данных");
String key = reader.readLine();
String mapStr = reader.readLine();
AbstractMap map = null;
switch (mapStr)
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MyMap":
map = new MyMap();
break;
}
if(_mapStorages.containsKey(key)) _mapStorages.get(key).ClearMap();
else _mapStorages.put(key, new MapWithSetAircraftsGeneric<>(_pictureWidth, _pictureHeight, map));
String current = null;
while ((current = reader.readLine()) != null)
{
_mapStorages.get(key).addAircraft(DrawingObjectAircraft.Create(current));
}
reader.close();
}
public void AddMap(String name, AbstractMap map)

View File

@ -14,24 +14,26 @@ public class SetAircraftsGeneric<T>
_places = new ArrayList<>();
_maxCount = count;
}
public int Insert(T aircraft)
public int Insert(T aircraft) throws StorageOverflowException
{
if (_places.size() == _maxCount) return -1;
if (_places.size() == _maxCount) throw new StorageOverflowException(_maxCount);
_places.add(0, aircraft);
return 0;
}
public int Insert(T aircraft, int position)
public int Insert(T aircraft, int position) throws StorageOverflowException
{
if (_places.size() == _maxCount) return -1;
if (_places.size() == _maxCount) throw new StorageOverflowException(_maxCount);
_places.add(position, aircraft);
return position;
}
public T Remove(int position)
public T Remove(int position) throws AircraftNotFoundException
{
if(position > _maxCount || position < 0) return null;
if(position > _places.size() || position < 0) throw new AircraftNotFoundException(position);
T res = _places.get(position);
_places.remove(res);
if(res == null) throw new AircraftNotFoundException(position);
return res;
}

25
log4j2.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" >
<Appenders>
<File name="error" fileName="logs/error.log" append="true">
<PatternLayout>
<Pattern>%-5level %msg (%d{dd.MM.yyyy})%n</Pattern>
</PatternLayout>
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="info" fileName="logs/info.log" append="true">
<PatternLayout>
<Pattern>%-5level %msg (%d{dd.MM.yyyy})%n</Pattern>
</PatternLayout>
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="ACCEPT"/>
</File>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="info" />
<AppenderRef ref="error" />
</Root>
</Loggers>
</Configuration>