Lab work 07

This commit is contained in:
Кашин Максим 2022-12-13 21:50:42 +04:00
parent b126dd0068
commit 090b6447fc
9 changed files with 184 additions and 70 deletions

View File

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

View File

@ -0,0 +1,15 @@
import java.io.IOException;
public class FileDataFormatException extends IOException {
public FileDataFormatException(){
}
public FileDataFormatException(String message){
super(message);
}
public FileDataFormatException(String message,Throwable exception){
super(message,exception);
}
protected FileDataFormatException(Throwable exception){
super(exception);
}
}

View File

@ -3,6 +3,7 @@ import java.awt.*;
import java.util.HashMap; import java.util.HashMap;
import java.io.IOException; import java.io.IOException;
import java.util.Optional; import java.util.Optional;
import org.apache.logging.log4j.Logger;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileNameExtensionFilter;
public class FormMapWithSetGasolineTanker extends JFrame{ public class FormMapWithSetGasolineTanker extends JFrame{
@ -46,6 +47,13 @@ public class FormMapWithSetGasolineTanker extends JFrame{
getImage().getScaledInstance(10,10,Image.SCALE_SMOOTH)); getImage().getScaledInstance(10,10,Image.SCALE_SMOOTH));
ImageIcon spriteRight =new ImageIcon((new ImageIcon("Material\\KeyRight.png")). ImageIcon spriteRight =new ImageIcon((new ImageIcon("Material\\KeyRight.png")).
getImage().getScaledInstance(10,10,Image.SCALE_SMOOTH)); getImage().getScaledInstance(10,10,Image.SCALE_SMOOTH));
private Logger logger;
public FormMapWithSetGasolineTanker(Logger logger){
this();
this.logger=logger;
}
public FormMapWithSetGasolineTanker(){ public FormMapWithSetGasolineTanker(){
setTitle("Gasoline tanker"); setTitle("Gasoline tanker");
setContentPane(MainPanel); setContentPane(MainPanel);
@ -101,13 +109,12 @@ public class FormMapWithSetGasolineTanker extends JFrame{
dialog.showSaveDialog(this); dialog.showSaveDialog(this);
try { try {
if (_mapsCollection.SaveData(dialog.getSelectedFile().getAbsolutePath())) { _mapsCollection.SaveData(dialog.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(this, "Save was successful", "Outcome", JOptionPane.INFORMATION_MESSAGE); logger.info("Saving all maps to a file: "+dialog.getSelectedFile().getAbsolutePath());
} else { JOptionPane.showMessageDialog(this, "\n" + "Save all maps successfully", "Outcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "\n" + "Not preserved", "Outcome", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) {
} logger.error("Error saving all maps to file: "+ex.getMessage());
} catch (IOException ex) { JOptionPane.showMessageDialog(this, "Error saving all maps: "+ex.getMessage(), "Outcome", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} }
}); });
fileMenu.add(SaveMenuItem); fileMenu.add(SaveMenuItem);
@ -119,14 +126,13 @@ public class FormMapWithSetGasolineTanker extends JFrame{
dialog.showOpenDialog(this); dialog.showOpenDialog(this);
try { try {
if (_mapsCollection.LoadData(dialog.getSelectedFile().getAbsolutePath())) { _mapsCollection.LoadData(dialog.getSelectedFile().getAbsolutePath());
ReloadMaps(); ReloadMaps();
JOptionPane.showMessageDialog(this, "Download successful", "Outcome", JOptionPane.INFORMATION_MESSAGE); logger.info("Loading all maps from a file: "+dialog.getSelectedFile().getAbsolutePath());
} else { JOptionPane.showMessageDialog(this, "Download of all maps was successful", "Outcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "\n" + "Didn't load", "Outcome", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) {
} logger.error("\n" + "Error loading all maps from file: "+ex.getMessage());
} catch (IOException ex) { JOptionPane.showMessageDialog(this, "\n" + "Error loading all maps"+ex.getMessage(), "Outcome", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} }
}); });
fileMenu.add(LoadMenuItem); fileMenu.add(LoadMenuItem);
@ -138,13 +144,12 @@ public class FormMapWithSetGasolineTanker extends JFrame{
dialog.showSaveDialog(this); dialog.showSaveDialog(this);
try { try {
if (_mapsCollection.SaveMap((String) Optional.ofNullable(ListBoxMaps.getSelectedValue()).orElse(""), dialog.getSelectedFile().getAbsolutePath())) { _mapsCollection.SaveMap((String) Optional.ofNullable(ListBoxMaps.getSelectedValue()).orElse(""), dialog.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(this, "\n" + "Save was successful", "Outcome", JOptionPane.INFORMATION_MESSAGE); logger.info("Saving a map to a file: "+dialog.getSelectedFile().getAbsolutePath());
} else { JOptionPane.showMessageDialog(this, "\n" + "The map was saved successfully", "Outcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "Not preserved", "Outcome", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) {
} logger.error("\n" + "Error saving map to file: "+ex.getMessage());
} catch (IOException ex) { JOptionPane.showMessageDialog(this, "\n" + "Map saving error: "+ex.getMessage(), "Outcome", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} }
}); });
fileMenu.add(SaveMapMenuItem); fileMenu.add(SaveMapMenuItem);
@ -156,14 +161,13 @@ public class FormMapWithSetGasolineTanker extends JFrame{
dialog.showOpenDialog(this); dialog.showOpenDialog(this);
try { try {
if (_mapsCollection.LoadMap(dialog.getSelectedFile().getAbsolutePath())) { _mapsCollection.LoadMap(dialog.getSelectedFile().getAbsolutePath());
ReloadMaps(); ReloadMaps();
JOptionPane.showMessageDialog(this, "Download successful", "Outcome", JOptionPane.INFORMATION_MESSAGE); logger.info("Loading a map from a file: "+dialog.getSelectedFile().getAbsolutePath());
} else { JOptionPane.showMessageDialog(this, "\n" + "Map loading successful", "Outcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "\n" + "Didn't load", "Outcome", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) {
} logger.error("\n" + "Error loading map from file: "+ex.getMessage());
} catch (IOException ex) { JOptionPane.showMessageDialog(this, "Map loading error"+ex.getMessage(), "Outcome", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} }
}); });
fileMenu.add(LoadMapMenuItem); fileMenu.add(LoadMapMenuItem);
@ -175,6 +179,7 @@ public class FormMapWithSetGasolineTanker extends JFrame{
return; return;
bufferedImage = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).ShowSet(); bufferedImage = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).ShowSet();
repaint(); repaint();
logger.info("Переход на карту "+ListBoxMaps.getSelectedValue());
}); });
DeleteMapButton.addActionListener(e -> { DeleteMapButton.addActionListener(e -> {
@ -186,6 +191,7 @@ public class FormMapWithSetGasolineTanker extends JFrame{
"Removal",JOptionPane.YES_NO_OPTION)==0) "Removal",JOptionPane.YES_NO_OPTION)==0)
{ {
_mapsCollection.DelMap(ListBoxMaps.getSelectedValue().toString()); _mapsCollection.DelMap(ListBoxMaps.getSelectedValue().toString());
logger.info("Карта "+ListBoxMaps.getSelectedValue()+" deleted");
ReloadMaps(); ReloadMaps();
} }
}); });
@ -193,16 +199,19 @@ public class FormMapWithSetGasolineTanker extends JFrame{
CreateMapButton.addActionListener(e -> { CreateMapButton.addActionListener(e -> {
if (СomboBoxSelectorMap.getSelectedIndex() == -1 || TextFieldMap.getText()==null || TextFieldMap.getText().equals("")) if (СomboBoxSelectorMap.getSelectedIndex() == -1 || TextFieldMap.getText()==null || TextFieldMap.getText().equals(""))
{ {
logger.warn("When adding a card, not all data was filled in");
JOptionPane.showMessageDialog(this,"\n" + "Not all data is complete","Error",JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(this,"\n" + "Not all data is complete","Error",JOptionPane.ERROR_MESSAGE);
return; return;
} }
if (!_mapsDict.containsKey(СomboBoxSelectorMap.getSelectedItem())) if (!_mapsDict.containsKey(СomboBoxSelectorMap.getSelectedItem()))
{ {
logger.warn("Card does not exist");
JOptionPane.showMessageDialog(this,"No such card","Error",JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(this,"No such card","Error",JOptionPane.ERROR_MESSAGE);
return; return;
} }
_mapsCollection.AddMap(TextFieldMap.getText(), _mapsDict.get(СomboBoxSelectorMap.getSelectedItem().toString())); _mapsCollection.AddMap(TextFieldMap.getText(), _mapsDict.get(СomboBoxSelectorMap.getSelectedItem().toString()));
ReloadMaps(); ReloadMaps();
logger.info("Map added: "+TextFieldMap.getText());
}); });
ButtonShowOnMap.addActionListener(e -> { ButtonShowOnMap.addActionListener(e -> {
@ -231,14 +240,24 @@ public class FormMapWithSetGasolineTanker extends JFrame{
FormGasolineTankerConfig dialog=new FormGasolineTankerConfig(); FormGasolineTankerConfig dialog=new FormGasolineTankerConfig();
dialog.addListener(obj -> { dialog.addListener(obj -> {
if (obj!=null) { if (obj!=null) {
DrawingObjectGasolineTanker gasolineTanker = new DrawingObjectGasolineTanker(obj); try {
DrawingObjectGasolineTanker gasolineTanker = new DrawingObjectGasolineTanker(obj);
if (_mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).plus(gasolineTanker) >= 0) { if (_mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).plus(gasolineTanker) >= 0) {
JOptionPane.showMessageDialog(this, "Object added", "Success", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(this, "Object added", "Success", JOptionPane.INFORMATION_MESSAGE);
bufferedImage = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).ShowSet(); bufferedImage = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).ShowSet();
repaint(); repaint();
} else { logger.info("New object added");
JOptionPane.showMessageDialog(this, "\n" + "Failed to add object", "Error", JOptionPane.INFORMATION_MESSAGE); } else {
logger.warn("Failed to add object");
JOptionPane.showMessageDialog(this, "Не удалось добавить объект", "Error", JOptionPane.ERROR_MESSAGE);
}
}catch (StorageOverflowException ex){
logger.warn("Storage is full: "+ex.getMessage());
JOptionPane.showMessageDialog(this, "Error. Storage is full: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}catch (Exception ex){
logger.fatal("Unknown error: "+ex.getMessage());
JOptionPane.showMessageDialog(this, "Error. Unknown error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} }
} }
}); });
@ -246,9 +265,8 @@ public class FormMapWithSetGasolineTanker extends JFrame{
}); });
ButtonRemoveGasolineTanker.addActionListener(e -> { ButtonRemoveGasolineTanker.addActionListener(e -> {
String txt=TextBoxPosition.getText(); String txt = TextBoxPosition.getText();
if (txt==null||ListBoxMaps.getSelectedIndex() ==-1) if (txt == null || ListBoxMaps.getSelectedIndex() == -1) {
{
return; return;
} }
int result = JOptionPane.showConfirmDialog( int result = JOptionPane.showConfirmDialog(
@ -256,19 +274,26 @@ public class FormMapWithSetGasolineTanker extends JFrame{
"Delete object?", "Delete object?",
"Removal", "Removal",
JOptionPane.YES_NO_CANCEL_OPTION); JOptionPane.YES_NO_CANCEL_OPTION);
if (result!=0) if (result != 0) {
{
return; return;
} }
int pos = Integer.parseInt(txt); int pos = Integer.parseInt(txt);
if(_mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).minus(pos)!=null){ try {
JOptionPane.showMessageDialog(this, "Object removed", "Success", JOptionPane.INFORMATION_MESSAGE); if (_mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).minus(pos) != null) {
bufferedImage = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).ShowSet(); JOptionPane.showMessageDialog(this, "Object removed", "Success", JOptionPane.INFORMATION_MESSAGE);
repaint(); bufferedImage = _mapsCollection.get(ListBoxMaps.getSelectedValue().toString()).ShowSet();
} repaint();
else logger.info("Object in position"+pos+"deleted");
{ } else {
JOptionPane.showMessageDialog(this,"Failed to delete object","\n" + "Error",JOptionPane.INFORMATION_MESSAGE); logger.warn("Failed to delete object at position"+pos);
JOptionPane.showMessageDialog(this, "Failed to delete object", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch(GasolineTankerNotFoundException ex){
logger.warn("Deletion error: "+ex.getMessage());
JOptionPane.showMessageDialog(this, "Deletion error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}catch (Exception ex){
logger.fatal("Unknown error: "+ex.getMessage());
JOptionPane.showMessageDialog(this, "Unknown error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} }
}); });

View File

@ -0,0 +1,16 @@
public class GasolineTankerNotFoundException extends RuntimeException{
public GasolineTankerNotFoundException(){
}
public GasolineTankerNotFoundException(String message){
super(message);
}
public GasolineTankerNotFoundException(String message,Throwable exception){
super(message,exception);
}
public GasolineTankerNotFoundException(Throwable exception){
super(exception);
}
protected GasolineTankerNotFoundException(int pos){
super("Gasoline tanker by position "+pos+" not found");
}
}

View File

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

View File

@ -39,7 +39,7 @@ public class MapsCollection {
return null; return null;
} }
@SuppressWarnings("ResultOfMethodCallIgnored") @SuppressWarnings("ResultOfMethodCallIgnored")
public boolean SaveData(String filename) throws IOException { public void SaveData(String filename) throws IOException {
File file = new File(filename); File file = new File(filename);
@ -55,21 +55,20 @@ public class MapsCollection {
writer.println(String.format("%s%c%s", storage.getKey(), separatorDict, storage.getValue().GetData(separatorDict, separatorData))); writer.println(String.format("%s%c%s", storage.getKey(), separatorDict, storage.getValue().GetData(separatorDict, separatorData)));
} }
} }
return true;
} }
public boolean LoadData(String filename) throws IOException { public void LoadData(String filename) throws IOException {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) if (!file.exists())
return false; throw new FileNotFoundException("File not found");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine(); String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("MapsCollection")) if (currentLine == null || !currentLine.contains("MapsCollection"))
return false; throw new FileDataFormatException("Data format is not correct");
_mapStorages.clear(); _mapStorages.clear();
@ -84,11 +83,10 @@ public class MapsCollection {
_mapStorages.get(elements[0]).LoadData(elements[2].split(separatorData + "\n?")); _mapStorages.get(elements[0]).LoadData(elements[2].split(separatorData + "\n?"));
} }
} }
return true;
} }
@SuppressWarnings("ResultOfMethodCallIgnored") @SuppressWarnings("ResultOfMethodCallIgnored")
public boolean SaveMap(String mapName, String filename) throws IOException { public void SaveMap(String mapName, String filename) throws IOException {
File file = new File(filename); File file = new File(filename);
if (file.exists()) if (file.exists())
@ -99,7 +97,7 @@ public class MapsCollection {
MapWithSetGasolineTankerGeneric<DrawingObjectGasolineTanker, AbstractMap> map = _mapStorages.getOrDefault(mapName, null); MapWithSetGasolineTankerGeneric<DrawingObjectGasolineTanker, AbstractMap> map = _mapStorages.getOrDefault(mapName, null);
if (map == null) if (map == null)
return false; throw new IndexOutOfBoundsException();
try (PrintWriter writer = new PrintWriter(file)) { try (PrintWriter writer = new PrintWriter(file)) {
writer.println("Map"); writer.println("Map");
@ -109,20 +107,19 @@ public class MapsCollection {
writer.println(gasolineTanker.GetInfo()); writer.println(gasolineTanker.GetInfo());
} }
} }
return true;
} }
public boolean LoadMap(String filename) throws IOException { public void LoadMap(String filename) throws IOException {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) if (!file.exists())
return false; throw new FileNotFoundException("File not found");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine(); String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("Map")) if (currentLine == null || !currentLine.contains("Map"))
return false; throw new FileDataFormatException("Data format is not correct");
String mapName = reader.readLine(); String mapName = reader.readLine();
@ -130,7 +127,7 @@ public class MapsCollection {
if (_mapStorages.containsKey(mapName)) { if (_mapStorages.containsKey(mapName)) {
map = _mapStorages.get(mapName); map = _mapStorages.get(mapName);
if (!map.GetMap().getClass().getSimpleName().equals(reader.readLine())) { if (!map.GetMap().getClass().getSimpleName().equals(reader.readLine())) {
return false; throw new FileDataFormatException("Data format is not correct");
} }
map._setGasolineTanker.Clear(); map._setGasolineTanker.Clear();
} else { } else {
@ -145,6 +142,5 @@ public class MapsCollection {
} }
_mapStorages.put(mapName, map); _mapStorages.put(mapName, map);
} }
return true;
} }
} }

View File

@ -15,8 +15,8 @@ public class SetGasolineTankerGeneric <T extends Object> implements Iterable<T>{
public int Insert(T gasolineTanker) public int Insert(T gasolineTanker)
{ {
if (_places.size()+1>=_maxCount) if (Count()>=_maxCount)
return -1; throw new StorageOverflowException(_maxCount);
_places.add(0,gasolineTanker); _places.add(0,gasolineTanker);
return 0; return 0;
} }
@ -24,9 +24,7 @@ public class SetGasolineTankerGeneric <T extends Object> implements Iterable<T>{
public int Insert(T gasolineTanker, int position) public int Insert(T gasolineTanker, int position)
{ {
if (position>=_maxCount||position<0) if (position>=_maxCount||position<0)
return -1; throw new StorageOverflowException(_maxCount);
if (_places.size()+1>=_maxCount)
return -1;
_places.add(position,gasolineTanker); _places.add(position,gasolineTanker);
return position; return position;
} }
@ -36,6 +34,8 @@ public class SetGasolineTankerGeneric <T extends Object> implements Iterable<T>{
if (position>=_maxCount||position<0) if (position>=_maxCount||position<0)
return null; return null;
T deleted=_places.get(position); T deleted=_places.get(position);
if (deleted==null)
throw new GasolineTankerNotFoundException(position);
_places.remove(position); _places.remove(position);
return deleted; return deleted;
} }

View File

@ -0,0 +1,16 @@
public class StorageOverflowException extends RuntimeException{
public StorageOverflowException(){
}
public StorageOverflowException(String message){
super(message);
}
public StorageOverflowException(String message,Throwable exception){
super(message,exception);
}
protected StorageOverflowException(Throwable exception){
super(exception);
}
public StorageOverflowException(int count){
super("Storage limit exceeded: "+count);
}
}

27
src/log4j2.xml Normal file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<Configuration status="info">
<Appenders>
<File name="error" fileName="Errors.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="Infos.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>