8 Commits

10 changed files with 187 additions and 94 deletions

View File

@@ -7,5 +7,14 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/apache-log4j-1.2.17/log4j-1.2.17.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

0
loginfo.log Normal file
View File

0
logwarn.log Normal file
View File

View File

@@ -6,8 +6,13 @@ import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import org.apache.log4j.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class FormMapWithSetShipsGeneric extends JFrame{
@@ -26,7 +31,6 @@ public class FormMapWithSetShipsGeneric extends JFrame{
private JTextField maskedTextBoxPosition;
private JTextField textBoxNewMapName;
private final int picWidth=600;
private final int picHeight=400;
private JButton ButtonAddMap;
private JList ListBoxMaps;
@@ -46,6 +50,7 @@ public class FormMapWithSetShipsGeneric extends JFrame{
put("Карта море",new SeaMap());
}};
private final MapsCollection _mapsCollection;
private static Logger _logger = Logger.getLogger("FormMapWithSetShipsGeneric");
public void UpdateWindow(BufferedImage bmp)
{
pictureBoxShip.removeAll();
@@ -98,19 +103,30 @@ public class FormMapWithSetShipsGeneric extends JFrame{
public void actionPerformed(ActionEvent e) {
FormShipConfig formShipConfig = new FormShipConfig();
formShipConfig.AddEvent(newShip -> {
if (ListBoxMaps.getSelectedIndex() == -1) {
return;
}
if (newShip != null) {
DrawingObjectShip ship = new DrawingObjectShip(newShip);
if (_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Add(ship) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен");
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект");
try
{
if (ListBoxMaps.getSelectedIndex() == -1) {
return;
}
if (newShip != null) {
DrawingObjectShip ship = new DrawingObjectShip(newShip);
if (_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Add(ship) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен");
_logger.log(Level.INFO,"Добавлен объект: "+ship);
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.INFO,"Не удалось добавить объект:"+ship);
}
}
}catch (StorageOverflowException ex)
{
_logger.log(Level.WARN,"Ошибка переполнения хранилища: "+ex.getMessage());
JOptionPane.showMessageDialog(null, "Ошибка переполнения хранилища: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Неизвестная ошибка: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.FATAL,"Неизвестная ошибка: "+ex.getMessage());
}
});
formShipConfig.setSize(850, 300);
formShipConfig.setVisible(true);
@@ -122,6 +138,7 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if (ListBoxMaps.getSelectedIndex() == -1)
return;
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
_logger.log(Level.INFO, "Переход на карту: "+ListBoxMaps.getSelectedValue().toString());
}
});
ButtonDeleteShip.addActionListener(new ActionListener() {
@@ -137,14 +154,26 @@ public class FormMapWithSetShipsGeneric extends JFrame{
return;
}
int pos=Integer.parseInt(maskedTextBoxPosition.getText());
if(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Delete(pos)!=null)
try
{
JOptionPane.showMessageDialog(null, "Объект удален");
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект");
var delShip = _mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).Delete(pos);
if(delShip!=null)
{
JOptionPane.showMessageDialog(null, "Объект удален");
_logger.log(Level.INFO,"Объект удален"+delShip);
UpdateWindow(_mapsCollection.Get(ListBoxMaps.getSelectedValue().toString()).ShowSet());
}
else
{
JOptionPane.showMessageDialog(null, "Не удалось удалить объект","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.INFO,"Не удалось удалить объект"+delShip);
}
} catch (ShipNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Ошибка удаления: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.WARN,"Ошибка удаления: "+ex.getMessage());
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Неизвестная ошибка: "+ex.getMessage(),"Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.FATAL,"Неизвестная ошибка: "+ex.getMessage());
}
}
});
@@ -252,13 +281,16 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if (ComboBoxSelectorMap.getSelectedIndex() == -1 || textBoxNewMapName.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"Не все данные заполнены","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не все данные заполнены");
return;
}
if(!_mapsDict.containsKey(ComboBoxSelectorMap.getSelectedItem()))
{
JOptionPane.showMessageDialog(null,"Нет такой карты","Ошибка",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Нет такой карты");
}
_mapsCollection.AddMap(textBoxNewMapName.getText(),_mapsDict.get(ComboBoxSelectorMap.getSelectedItem().toString()));
_logger.log(Level.INFO,"Добавлена карта: "+textBoxNewMapName.getText());
ReloadMaps();
}
});
@@ -272,6 +304,7 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if(JOptionPane.showConfirmDialog(null,"Удалить карту"+ListBoxMaps.getSelectedValue().toString()+"?","Удаление",JOptionPane.YES_NO_OPTION)==0)
{
_mapsCollection.DelMap(ListBoxMaps.getSelectedValue().toString());
_logger.log(Level.INFO, "Удалена карта: "+ListBoxMaps.getSelectedValue().toString());
ReloadMaps();
}
}
@@ -302,15 +335,13 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
if (_mapsCollection.SaveData(fc.getSelectedFile().getPath())) {
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
File selectedFile=fc.getSelectedFile();
_mapsCollection.SaveData(selectedFile.getPath());
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Сохранение прошло успешно");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не сохранилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не сохранилось: "+ex.getMessage());
}
}
}
@@ -323,17 +354,14 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
if(_mapsCollection.LoadData(fc.getSelectedFile().getPath()))
{
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
File selectedFile=fc.getSelectedFile();
_mapsCollection.LoadData(selectedFile.getPath());
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Загрузка прошло успешно");
} catch (FileNotFoundException | IllegalArgumentException ex ) {
JOptionPane.showMessageDialog(null, "Не загрузилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не загрузилось: "+ex.getMessage());
}
}
}
@@ -351,15 +379,13 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
if (_mapsCollection.SaveMapData(fc.getSelectedFile().getPath(),ListBoxMaps.getSelectedValue().toString())){
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
File selectedFile=fc.getSelectedFile();
_mapsCollection.SaveMapData(selectedFile.getPath(),ListBoxMaps.getSelectedValue().toString());
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Сохранение прошло успешно");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Не сохранилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не сохранилось: "+ex.getMessage());
}
}
}
@@ -372,17 +398,14 @@ public class FormMapWithSetShipsGeneric extends JFrame{
if(returnVal==JFileChooser.APPROVE_OPTION)
{
try {
if(_mapsCollection.LoadMapData(fc.getSelectedFile().getPath()))
{
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
File selectedFile=fc.getSelectedFile();
_mapsCollection.LoadMapData(selectedFile.getPath());
ReloadMaps();
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат",JOptionPane.INFORMATION_MESSAGE);
_logger.log(Level.INFO,"Загрузка прошло успешно");
} catch (FileNotFoundException | IllegalArgumentException ex ) {
JOptionPane.showMessageDialog(null, "Не загрузилось: "+ex.getMessage(), "Результат",JOptionPane.ERROR_MESSAGE);
_logger.log(Level.ERROR,"Не загрузилось: "+ex.getMessage());
}
}
}

View File

@@ -20,12 +20,10 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
_pictureHeight = picHeight;
_map = map;
}
public int Add(T ship)
{
public int Add(T ship) throws StorageOverflowException {
return _setShips.Insert(ship);
}
public T Delete(int position)
{
public T Delete(int position) throws ShipNotFoundException {
T ship=_setShips.Remove(position);
_deletedShips.add(ship);
return ship;
@@ -42,8 +40,7 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
DrawShips(gr);
return bmp;
}
public BufferedImage ShowOnMap()
{
public BufferedImage ShowOnMap(){
Shaking();
for(var ship : _setShips)
{
@@ -59,8 +56,7 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
}
private void Shaking()
{
private void Shaking(){
int j = _setShips.Count() - 1;
for (int i = 0; i < _setShips.Count(); i++)
{
@@ -71,8 +67,16 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
var ship = _setShips.Get(j);
if (ship != null)
{
_setShips.Insert(ship, i);
_setShips.Remove(j);
try {
_setShips.Insert(ship, i);
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
try {
_setShips.Remove(j);
} catch (ShipNotFoundException e) {
throw new RuntimeException(e);
}
break;
}
}
@@ -154,8 +158,7 @@ public class MapWithSetShipsGeneric<T extends IDrawingObject, U extends Abstrac
}
return data.toString();
}
public void LoadData(String[] records)
{
public void LoadData(String[] records) throws StorageOverflowException {
for(var rec:records)
{
_setShips.Insert((T) DrawingObjectShip.Create(rec));

View File

@@ -46,7 +46,7 @@ public class MapsCollection {
}
return null;
}
public boolean SaveData(String filename) throws IOException {
public void SaveData(String filename) throws IOException {
File file = new File(filename);
if(file.exists())
{
@@ -60,20 +60,19 @@ public class MapsCollection {
fw.write(String.format("%s%c%s%s",storage,separatorDict,_mapStorages.get(storage).GetData(separatorDict,separatorData),System.lineSeparator()));
}
}
return true;
}
public boolean LoadData(String filename) throws IOException {
public void LoadData(String filename) throws FileNotFoundException {
File file=new File(filename);
if(!file.exists())
{
return false;
throw new FileNotFoundException("Файл не найден");
}
try(BufferedReader fr = new BufferedReader(new FileReader(file)))
{
String str="";
if((str=fr.readLine())==null || !str.contains("MapsCollection"))
{
return false;
throw new IllegalArgumentException("Формат данных в файле неправильный");
}
_mapStorages.clear();
while((str=fr.readLine())!=null)
@@ -95,10 +94,13 @@ public class MapsCollection {
_mapStorages.get(tempElem[0]).LoadData(tempElem[2].split(String.valueOf(separatorData)));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean SaveMapData(String filename,String Key)throws IOException
public void SaveMapData(String filename,String Key)throws IOException
{
File file = new File(filename);
if(file.exists())
@@ -113,20 +115,19 @@ public class MapsCollection {
fw.write(String.format("Objects_In_Map_Info:%s",System.lineSeparator()));
fw.write(String.format("%s%s",Map.GetDataForMap(separatorDict,separatorData,false),System.lineSeparator()));
}
return true;
}
public boolean LoadMapData(String filename) throws IOException {
public void LoadMapData(String filename) throws FileNotFoundException {
File file=new File(filename);
if(!file.exists())
{
return false;
throw new FileNotFoundException("Файл не найден");
}
try(BufferedReader fr = new BufferedReader(new FileReader(file)))
{
String str="";
if((str=fr.readLine())==null || !str.contains("Map_Info:"))
{
return false;
throw new IllegalArgumentException("Формат данных в файле неправильный");
}
str=fr.readLine();
var tempElem = str.split(String.format("\\%c",separatorDict));
@@ -150,16 +151,18 @@ public class MapsCollection {
String str_second=fr.readLine();
if(!str_second.contains("Objects_In_Map_Info:"))
{
return false;
throw new IllegalArgumentException("Формат данных в файле неправильный");
}
str_second= fr.readLine();
str=str+str_second;
System.out.println(str);
tempElem = str.split(String.format("\\%c",separatorDict));
if(tempElem.length==3) {
_mapStorages.get(tempElem[0]).LoadData(tempElem[2].split(String.valueOf(separatorData)));
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (StorageOverflowException e) {
throw new RuntimeException(e);
}
return true;
}
}

View File

@@ -12,21 +12,22 @@ public class SetShipsGeneric<T extends Object> implements Iterable<T>{
_maxCount=count;
_places = new ArrayList<>();
}
public int Insert(T ship)
{
public int Insert(T ship) throws StorageOverflowException {
return Insert(ship, 0);
}
public int Insert(T ship, int position)
{
public int Insert(T ship, int position) throws StorageOverflowException {
if(_maxCount == Count())
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > Count() || _maxCount == Count()) return -1;
_places.add(position,ship);
return position;
}
public T Remove(int position)
{
public T Remove(int position) throws ShipNotFoundException {
if (position >= Count() || position < 0)
{
return null;
throw new ShipNotFoundException(position);
}
T ship = (T) _places.get(position);
_places.remove(ship);
@@ -44,8 +45,7 @@ public class SetShipsGeneric<T extends Object> implements Iterable<T>{
}
return _places.get(position);
}
public void Set(int position,T value)
{
public void Set(int position,T value) throws StorageOverflowException {
if (position < _maxCount || position >= 0)
{
Insert(value,position);

View File

@@ -0,0 +1,14 @@
public class ShipNotFoundException extends Exception{
public ShipNotFoundException(int i){
super(String.format("%s%d","Не найден объект по позиции",i));
}
public ShipNotFoundException(){
super();
}
public ShipNotFoundException(String message){
super(message);
}
public ShipNotFoundException(String message,Exception ex){
super(message,ex);
}
}

View File

@@ -0,0 +1,14 @@
public class StorageOverflowException extends Exception {
public StorageOverflowException(int count){
super("В наборе превышено допустимое количество: "+count);
}
public StorageOverflowException(){
super();
}
public StorageOverflowException(String message){
super(message);
}
public StorageOverflowException(String message,Exception ex){
super(message,ex);
}
}

27
src/log4j.properties Normal file
View File

@@ -0,0 +1,27 @@
log4j.logger.FormMapWithSetShipsGeneric=INFO, fileAppender,adminAppender
log4j.additivity.file=false
log4j.additivity.admin=false
log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.File=loginfo.log
log4j.appender.fileAppender.MaxFileSize=1MB
log4j.appender.fileAppender.MaxBackupIndex=1
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.fileAppender.filter.F1.LevelMin=INFO
log4j.appender.fileAppender.filter.F1.LevelMax=INFO
log4j.appender.fileAppender.filter.F1.AcceptOnMatch=true
log4j.appender.fileAppender.layout.ConversionPattern=%-5p %c{1}:%L - %m %d{dd-MM-yyyy}%n
log4j.appender.adminAppender=org.apache.log4j.RollingFileAppender
log4j.appender.adminAppender.File=logwarn.log
log4j.appender.adminAppender.MaxFileSize=1MB
log4j.appender.adminAppender.MaxBackupIndex=1
log4j.appender.adminAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.adminAppender.filter.F1=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.adminAppender.filter.F1.LevelMin=WARN
log4j.appender.adminAppender.filter.F1.LevelMax=ERROR
log4j.appender.adminAppender.filter.F1.AcceptOnMatch=true
log4j.appender.adminAppender.layout.ConversionPattern=%-5p %c{1}:%L - %m %d{dd-MM-yyyy}%n