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

View File

@ -39,7 +39,7 @@ public class MapsCollection {
return null;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public boolean SaveData(String filename) throws IOException {
public void SaveData(String filename) throws IOException {
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)));
}
}
return true;
}
public boolean LoadData(String filename) throws IOException {
public void LoadData(String filename) throws IOException {
File file = new File(filename);
if (!file.exists())
return false;
throw new FileNotFoundException("File not found");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("MapsCollection"))
return false;
throw new FileDataFormatException("Data format is not correct");
_mapStorages.clear();
@ -84,11 +83,10 @@ public class MapsCollection {
_mapStorages.get(elements[0]).LoadData(elements[2].split(separatorData + "\n?"));
}
}
return true;
}
@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);
if (file.exists())
@ -99,7 +97,7 @@ public class MapsCollection {
MapWithSetGasolineTankerGeneric<DrawingObjectGasolineTanker, AbstractMap> map = _mapStorages.getOrDefault(mapName, null);
if (map == null)
return false;
throw new IndexOutOfBoundsException();
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("Map");
@ -109,20 +107,19 @@ public class MapsCollection {
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);
if (!file.exists())
return false;
throw new FileNotFoundException("File not found");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("Map"))
return false;
throw new FileDataFormatException("Data format is not correct");
String mapName = reader.readLine();
@ -130,7 +127,7 @@ public class MapsCollection {
if (_mapStorages.containsKey(mapName)) {
map = _mapStorages.get(mapName);
if (!map.GetMap().getClass().getSimpleName().equals(reader.readLine())) {
return false;
throw new FileDataFormatException("Data format is not correct");
}
map._setGasolineTanker.Clear();
} else {
@ -145,6 +142,5 @@ public class MapsCollection {
}
_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)
{
if (_places.size()+1>=_maxCount)
return -1;
if (Count()>=_maxCount)
throw new StorageOverflowException(_maxCount);
_places.add(0,gasolineTanker);
return 0;
}
@ -24,9 +24,7 @@ public class SetGasolineTankerGeneric <T extends Object> implements Iterable<T>{
public int Insert(T gasolineTanker, int position)
{
if (position>=_maxCount||position<0)
return -1;
if (_places.size()+1>=_maxCount)
return -1;
throw new StorageOverflowException(_maxCount);
_places.add(position,gasolineTanker);
return position;
}
@ -36,6 +34,8 @@ public class SetGasolineTankerGeneric <T extends Object> implements Iterable<T>{
if (position>=_maxCount||position<0)
return null;
T deleted=_places.get(position);
if (deleted==null)
throw new GasolineTankerNotFoundException(position);
_places.remove(position);
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>