Доделан логгер, лаб7 хард готова

This commit is contained in:
Данила Мочалов 2022-12-04 17:50:10 +04:00
parent 8dd844aa14
commit c3fc932a2a
6 changed files with 112 additions and 68 deletions

View File

@ -6,7 +6,8 @@ import java.awt.event.ActionListener;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.text.ParseException; import java.text.ParseException;
import java.util.HashMap; import java.util.HashMap;
import java.util.logging.Logger; import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
public class FormMapWithSetLocomotives extends JComponent { public class FormMapWithSetLocomotives extends JComponent {
private BufferedImage bufferImg = null; private BufferedImage bufferImg = null;
@ -30,7 +31,12 @@ public class FormMapWithSetLocomotives extends JComponent {
JScrollPane listScroller = new JScrollPane(); JScrollPane listScroller = new JScrollPane();
JList listBoxMaps; JList listBoxMaps;
public FormMapWithSetLocomotives() { private final Logger logger;
public FormMapWithSetLocomotives(Logger logger) {
this.logger = logger;
formFrame = new JFrame("Form Map With SetLocomotives"); formFrame = new JFrame("Form Map With SetLocomotives");
formFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); formFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
formFrame.setSize(750, 500); formFrame.setSize(750, 500);
@ -79,7 +85,7 @@ public class FormMapWithSetLocomotives extends JComponent {
return; return;
} }
_mapsCollection.AddMap(textFieldNewMapName.getText(), _mapsDict.get(mapSelectComboBox.getSelectedItem().toString())); _mapsCollection.AddMap(textFieldNewMapName.getText(), _mapsDict.get(mapSelectComboBox.getSelectedItem().toString()));
Logger.getGlobal().info("Map " + textFieldNewMapName.getText() + " added"); logger.log(Level.INFO, "Map " + textFieldNewMapName.getText() + " added");
ReloadMaps(); ReloadMaps();
}); });
statusPanel.add(addMapButton); statusPanel.add(addMapButton);
@ -89,7 +95,7 @@ public class FormMapWithSetLocomotives extends JComponent {
listBoxMaps.addListSelectionListener(e -> { listBoxMaps.addListSelectionListener(e -> {
if(listBoxMaps.getSelectedValue() == null) return; if(listBoxMaps.getSelectedValue() == null) return;
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet();
Logger.getGlobal().info("Map switched to " + listBoxMaps.getSelectedValue().toString()); logger.log(Level.INFO,"Map switched to " + listBoxMaps.getSelectedValue().toString());
repaint(); repaint();
}); });
statusPanel.add(listBoxMaps); statusPanel.add(listBoxMaps);
@ -108,7 +114,7 @@ public class FormMapWithSetLocomotives extends JComponent {
} }
if(listBoxMaps.getSelectedValue().toString() == null) return; if(listBoxMaps.getSelectedValue().toString() == null) return;
_mapsCollection.DelMap(listBoxMaps.getSelectedValue().toString()); _mapsCollection.DelMap(listBoxMaps.getSelectedValue().toString());
Logger.getGlobal().info("Map " +listBoxMaps.getSelectedValue().toString() +" deleted"); logger.log(Level.INFO,"Map " +listBoxMaps.getSelectedValue().toString() +" deleted");
ReloadMaps(); ReloadMaps();
repaint(); repaint();
}); });
@ -129,7 +135,7 @@ public class FormMapWithSetLocomotives extends JComponent {
if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Plus(objectLocomotive)!= -1){ if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Plus(objectLocomotive)!= -1){
JOptionPane.showMessageDialog(formFrame, "Object added", "Success", JOptionPane.OK_CANCEL_OPTION); JOptionPane.showMessageDialog(formFrame, "Object added", "Success", JOptionPane.OK_CANCEL_OPTION);
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet();
Logger.getGlobal().info("Object " + locomotive + " added"); logger.log(Level.INFO,"Object " + locomotive + " added");
repaint(); repaint();
} }
else { else {
@ -138,11 +144,11 @@ public class FormMapWithSetLocomotives extends JComponent {
} }
catch (StorageOverflowException ex) { catch (StorageOverflowException ex) {
JOptionPane.showMessageDialog(formFrame, "Storage overflow error: "+ ex.getMessage()); JOptionPane.showMessageDialog(formFrame, "Storage overflow error: "+ ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.WARN,"Error " + ex.getMessage());
} }
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage()); JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.FATAL,"Error " + ex.getMessage());
} }
} }
}); });
@ -175,7 +181,7 @@ public class FormMapWithSetLocomotives extends JComponent {
if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Minus(position) != null) { if (_mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).Minus(position) != null) {
JOptionPane.showMessageDialog(formFrame, "Object removed", "Success", JOptionPane.OK_CANCEL_OPTION); JOptionPane.showMessageDialog(formFrame, "Object removed", "Success", JOptionPane.OK_CANCEL_OPTION);
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet(); bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowSet();
Logger.getGlobal().info("Locomotive deleted at position " + position); logger.log(Level.INFO,"Locomotive deleted at position " + position);
repaint(); repaint();
} }
else{ else{
@ -183,11 +189,11 @@ public class FormMapWithSetLocomotives extends JComponent {
}} }}
catch (LocomotiveNotFoundException ex) { catch (LocomotiveNotFoundException ex) {
JOptionPane.showMessageDialog(formFrame, "Locomotive not found error: " + ex.getMessage()); JOptionPane.showMessageDialog(formFrame, "Locomotive not found error: " + ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.WARN,"Error " + ex.getMessage());
} }
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage()); JOptionPane.showMessageDialog(formFrame, "Unknown error: "+ ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.FATAL,"Error " + ex.getMessage());
} }
}); });
statusPanel.add(deleteLocomotiveButton); statusPanel.add(deleteLocomotiveButton);
@ -215,9 +221,13 @@ public class FormMapWithSetLocomotives extends JComponent {
bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowOnMap(); bufferImg = _mapsCollection.Get(listBoxMaps.getSelectedValue().toString()).ShowOnMap();
repaint(); repaint();
} }
catch (StorageOverflowException ex) {
JOptionPane.showMessageDialog(formFrame, "Storage overflow error: "+ ex.getMessage());
logger.log(Level.WARN,"Error " + ex.getMessage());
}
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Unknown error: "+ ex.getMessage()); JOptionPane.showMessageDialog(null, "Unknown error: "+ ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.FATAL,"Error " + ex.getMessage());
} }
}); });
statusPanel.add(showOnMapButton); statusPanel.add(showOnMapButton);
@ -305,11 +315,11 @@ public class FormMapWithSetLocomotives extends JComponent {
try { try {
_mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath()); _mapsCollection.SaveData(fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Save success"); JOptionPane.showMessageDialog(null, "Save success");
Logger.getGlobal().info("Saved all to " + fileChooser.getSelectedFile().getAbsolutePath()); logger.log(Level.INFO,"Saved all to " + fileChooser.getSelectedFile().getAbsolutePath());
} }
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Save error: " + ex.getMessage()); JOptionPane.showMessageDialog(null, "Save error: " + ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.ERROR,"Error " + ex.getMessage());
} }
} }
@ -324,13 +334,13 @@ public class FormMapWithSetLocomotives extends JComponent {
try { try {
_mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath()); _mapsCollection.LoadData(fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Load success"); JOptionPane.showMessageDialog(null, "Load success");
Logger.getGlobal().info("Loaded all from " + fileChooser.getSelectedFile().getAbsolutePath()); logger.log(Level.INFO,"Loaded all from " + fileChooser.getSelectedFile().getAbsolutePath());
ReloadMaps(); ReloadMaps();
repaint(); repaint();
} }
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Load error: " + ex.getMessage()); JOptionPane.showMessageDialog(null, "Load error: " + ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.ERROR,"Error " + ex.getMessage());
} }
} }
}); });
@ -350,12 +360,12 @@ public class FormMapWithSetLocomotives extends JComponent {
try { try {
_mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath()); _mapsCollection.SaveMap(listBoxMaps.getSelectedValue().toString(), fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Map saving success"); JOptionPane.showMessageDialog(null, "Map saving success");
Logger.getGlobal().info("Saved map to " + fileChooser.getSelectedFile().getAbsolutePath()); logger.log(Level.INFO,"Saved map to " + fileChooser.getSelectedFile().getAbsolutePath());
repaint(); repaint();
} }
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Map saving error: " + ex.getMessage()); JOptionPane.showMessageDialog(null, "Map saving error: " + ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.ERROR,"Error " + ex.getMessage());
} }
} }
}); });
@ -370,13 +380,13 @@ public class FormMapWithSetLocomotives extends JComponent {
try { try {
_mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath()); _mapsCollection.LoadMap(fileChooser.getSelectedFile().getAbsolutePath());
JOptionPane.showMessageDialog(null, "Load Map success"); JOptionPane.showMessageDialog(null, "Load Map success");
Logger.getGlobal().info("Loaded map from " + fileChooser.getSelectedFile().getAbsolutePath()); logger.log(Level.INFO,"Loaded map from " + fileChooser.getSelectedFile().getAbsolutePath());
ReloadMaps(); ReloadMaps();
repaint(); repaint();
} }
catch (Exception ex) { catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Load Map error: " + ex.getMessage()); JOptionPane.showMessageDialog(null, "Load Map error: " + ex.getMessage());
Logger.getGlobal().severe("Error " + ex.getMessage()); logger.log(Level.ERROR,"Error " + ex.getMessage());
} }
} }
}); });

View File

@ -1,24 +1,11 @@
import javax.swing.*; import org.apache.logging.log4j.LogManager;
import java.awt.*; import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class Main { public class Main {
private static Logger logger = null; private static Logger logger = null;
public static void main(String[] args) { public static void main(String[] args) {
try { logger = LogManager.getLogger(Main.class);
FileInputStream stream = new FileInputStream(new File("C:/secondCourse/OOP/PIbd-23_Mochalov_D.V._Locomotive_Hard/log.config")); new FormMapWithSetLocomotives(logger);
LogManager.getLogManager().readConfiguration(stream);
logger = Logger.getGlobal();
stream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
new FormMapWithSetLocomotives();
} }
} }

View File

@ -2,7 +2,6 @@ import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.logging.Logger;
import java.util.zip.DataFormatException; import java.util.zip.DataFormatException;
public class MapsCollection { public class MapsCollection {
@ -92,13 +91,11 @@ public class MapsCollection {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) if (!file.exists())
{ {
Logger.getGlobal().severe("FileNotFoundException " + filename);
throw new FileNotFoundException("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedReader br = new BufferedReader(new FileReader(filename));
String curLine = br.readLine(); String curLine = br.readLine();
if (!curLine.contains("SingleMap")) { if (!curLine.contains("SingleMap")) {
Logger.getGlobal().severe("FileFormatException " + filename);
throw new DataFormatException("Неверный формат данных"); throw new DataFormatException("Неверный формат данных");
} }
String mapName = br.readLine(); String mapName = br.readLine();
@ -136,14 +133,12 @@ public class MapsCollection {
File file = new File(filename); File file = new File(filename);
if (!file.exists()) if (!file.exists())
{ {
Logger.getGlobal().severe("FileNotFoundException " + filename);
throw new FileNotFoundException("Файл не найден"); throw new FileNotFoundException("Файл не найден");
} }
BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedReader br = new BufferedReader(new FileReader(filename));
String curLine = br.readLine(); String curLine = br.readLine();
if (!curLine.contains("MapsCollection")) { if (!curLine.contains("MapsCollection")) {
Logger.getGlobal().severe("FileFormatException " + filename);
throw new DataFormatException("Неверный формат данных"); throw new DataFormatException("Неверный формат данных");
} }

View File

@ -1,6 +1,5 @@
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.logging.Logger;
public class SetLocomotivesGeneric <T> public class SetLocomotivesGeneric <T>
{ {
@ -26,7 +25,6 @@ public class SetLocomotivesGeneric <T>
public int Insert (T locomotive, int position) throws StorageOverflowException{ public int Insert (T locomotive, int position) throws StorageOverflowException{
if (position < 0) return -1; if (position < 0) return -1;
if (Count() >= _maxCount) { if (Count() >= _maxCount) {
Logger.getGlobal().warning("StorageOverflowException");
throw new StorageOverflowException(_maxCount); throw new StorageOverflowException(_maxCount);
} }
_places.add(position, locomotive); _places.add(position, locomotive);
@ -36,7 +34,6 @@ public class SetLocomotivesGeneric <T>
public T Remove (int position) throws LocomotiveNotFoundException { public T Remove (int position) throws LocomotiveNotFoundException {
if (position >= _maxCount || position < 0) return null; if (position >= _maxCount || position < 0) return null;
if (_places.get(position) == null) { if (_places.get(position) == null) {
Logger.getGlobal().warning("LocomotiveNotFoundException at " + position);
throw new LocomotiveNotFoundException(position); throw new LocomotiveNotFoundException(position);
} }
T result = _places.get(position); T result = _places.get(position);

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="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="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>

30
pom.xml Normal file
View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>PIbd-23_Mochalov_D.V._Locomotive_Hard</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.19.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.19.0</version>
</dependency>
</dependencies>
</project>