Try/finally refactored to try with resources

This commit is contained in:
vraskulin 2017-01-26 20:58:40 +03:00
parent d8c4e60138
commit 31589778ca
7 changed files with 61 additions and 186 deletions

View file

@ -27,6 +27,9 @@
*/ */
package org.mage.plugins.card.dl.sources; package org.mage.plugins.card.dl.sources;
import org.apache.log4j.Logger;
import org.mage.plugins.card.images.CardDownloadData;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -36,8 +39,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger;
import org.mage.plugins.card.images.CardDownloadData;
/** /**
* *
@ -184,30 +185,18 @@ public class TokensMtgImageSource implements CardImageSource {
tokensData = new ArrayList<>(); tokensData = new ArrayList<>();
// get tokens data from resource file // get tokens data from resource file
InputStream inputStream = null; try(InputStream inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv")) {
try {
inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv");
List<TokenData> fileTokensData = parseTokensData(inputStream); List<TokenData> fileTokensData = parseTokensData(inputStream);
tokensData.addAll(fileTokensData); tokensData.addAll(fileTokensData);
} catch (Exception exception) { } catch (Exception exception) {
logger.warn("Failed to get tokens description from resource file tokens-mtg-onl-list.csv", exception); logger.warn("Failed to get tokens description from resource file tokens-mtg-onl-list.csv", exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
logger.error("Input stream close failed:", e);
}
}
} }
// description on site may contain new information // description on site may contain new information
// try to add it // try to add it
try { URL url = new URL("http://tokens.mtg.onl/data/SetsWithTokens.csv");
URL url = new URL("http://tokens.mtg.onl/data/SetsWithTokens.csv"); try(InputStream inputStream = url.openStream()) {
inputStream = url.openStream();
List<TokenData> siteTokensData = parseTokensData(inputStream); List<TokenData> siteTokensData = parseTokensData(inputStream);
List<TokenData> newTokensData = new ArrayList<>(); List<TokenData> newTokensData = new ArrayList<>();
for (TokenData siteData : siteTokensData) { for (TokenData siteData : siteTokensData) {
boolean isNew = true; boolean isNew = true;
@ -227,14 +216,6 @@ public class TokensMtgImageSource implements CardImageSource {
tokensData.addAll(newTokensData); tokensData.addAll(newTokensData);
} catch (Exception exception) { } catch (Exception exception) {
logger.warn("Failed to get tokens description from tokens.mtg.onl", exception); logger.warn("Failed to get tokens description from tokens.mtg.onl", exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
logger.error("Input stream close failed:", e);
}
}
} }
} }
} }
@ -245,12 +226,9 @@ public class TokensMtgImageSource implements CardImageSource {
private List<TokenData> parseTokensData(InputStream inputStream) throws IOException { private List<TokenData> parseTokensData(InputStream inputStream) throws IOException {
List<TokenData> newTokensData = new ArrayList<>(); List<TokenData> newTokensData = new ArrayList<>();
InputStreamReader inputReader = null; try(InputStreamReader inputReader = new InputStreamReader(inputStream, "Cp1252");
BufferedReader reader = null; BufferedReader reader = new BufferedReader(inputReader)) {
try {
// we have to specify encoding to read special comma // we have to specify encoding to read special comma
inputReader = new InputStreamReader(inputStream, "Cp1252");
reader = new BufferedReader(inputReader);
reader.readLine(); // skip header reader.readLine(); // skip header
String line = reader.readLine(); String line = reader.readLine();
@ -282,21 +260,6 @@ public class TokensMtgImageSource implements CardImageSource {
line = reader.readLine(); line = reader.readLine();
} }
} finally {
if (inputReader != null) {
try {
inputReader.close();
} catch (Exception e) {
logger.error("Input reader close failed:", e);
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
logger.error("Buffered reader close failed:", e);
}
}
} }
return newTokensData; return newTokensData;

View file

@ -1,45 +1,5 @@
package org.mage.plugins.card.images; package org.mage.plugins.card.images;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.AccessDeniedException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
import mage.client.constants.Constants; import mage.client.constants.Constants;
import mage.client.dialog.PreferencesDialog; import mage.client.dialog.PreferencesDialog;
@ -51,18 +11,27 @@ import net.java.truevfs.access.TFileOutputStream;
import net.java.truevfs.access.TVFS; import net.java.truevfs.access.TVFS;
import net.java.truevfs.kernel.spec.FsSyncException; import net.java.truevfs.kernel.spec.FsSyncException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.mage.plugins.card.dl.sources.AltMtgOnlTokensImageSource; import org.mage.plugins.card.dl.sources.*;
import org.mage.plugins.card.dl.sources.CardImageSource;
import org.mage.plugins.card.dl.sources.GrabbagImageSource;
import org.mage.plugins.card.dl.sources.MagicCardsImageSource;
import org.mage.plugins.card.dl.sources.MagidexImageSource;
import org.mage.plugins.card.dl.sources.MtgOnlTokensImageSource;
import org.mage.plugins.card.dl.sources.MythicspoilerComSource;
import org.mage.plugins.card.dl.sources.TokensMtgImageSource;
import org.mage.plugins.card.dl.sources.WizardCardsImageSource;
import org.mage.plugins.card.properties.SettingsManager; import org.mage.plugins.card.properties.SettingsManager;
import org.mage.plugins.card.utils.CardImageUtils; import org.mage.plugins.card.utils.CardImageUtils;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.AccessDeniedException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class DownloadPictures extends DefaultBoundedRangeModel implements Runnable { public class DownloadPictures extends DefaultBoundedRangeModel implements Runnable {
private static final Logger logger = Logger.getLogger(DownloadPictures.class); private static final Logger logger = Logger.getLogger(DownloadPictures.class);
@ -376,11 +345,9 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
return list; return list;
} }
BufferedReader reader = null;
InputStreamReader input = null; try(InputStreamReader input = new InputStreamReader(in);
try { BufferedReader reader = new BufferedReader(input)) {
input = new InputStreamReader(in);
reader = new BufferedReader(input);
String line; String line;
line = reader.readLine(); line = reader.readLine();
@ -425,22 +392,6 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
} catch (Exception ex) { } catch (Exception ex) {
logger.error(ex); logger.error(ex);
throw new RuntimeException("DownloadPictures : readFile() error"); throw new RuntimeException("DownloadPictures : readFile() error");
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
logger.error("Input close failed:", e);
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
logger.error("Reader close failed:", e);
}
}
} }
return list; return list;
} }

View file

@ -1,22 +1,15 @@
package org.mage.plugins.counter; package org.mage.plugins.counter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import mage.interfaces.PluginException; import mage.interfaces.PluginException;
import mage.interfaces.plugin.CounterPlugin; import mage.interfaces.plugin.CounterPlugin;
import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Init;
import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.annotations.events.PluginLoaded;
import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.base.annotations.meta.Author;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.*;
/** /**
* Implementation of {@link CounterPlugin}.<br/> * Implementation of {@link CounterPlugin}.<br/>
* Stores data in data folder. * Stores data in data folder.
@ -72,12 +65,10 @@ public class CounterPluginImpl implements CounterPlugin {
public void addGamePlayed() throws PluginException { public void addGamePlayed() throws PluginException {
if (!isLoaded) return; if (!isLoaded) return;
File data = new File(PLUGIN_DATA_FOLDER_PATH + File.separator + DATA_STORAGE_FILE); File data = new File(PLUGIN_DATA_FOLDER_PATH + File.separator + DATA_STORAGE_FILE);
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
if (data.exists()) { if (data.exists()) {
int prev = 0; int prev = 0;
try {
ois = new ObjectInputStream(new FileInputStream(data)); try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(data))) {
Object o = ois.readObject(); Object o = ois.readObject();
CounterBean c; CounterBean c;
if (o instanceof CounterBean) { if (o instanceof CounterBean) {
@ -90,13 +81,10 @@ public class CounterPluginImpl implements CounterPlugin {
throw new PluginException(e); throw new PluginException(e);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new PluginException(e); throw new PluginException(e);
} finally {
if (ois != null) try { ois.close(); } catch (Exception e) {}
} }
try { try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(data))) {
synchronized (this) { synchronized (this) {
oos = new ObjectOutputStream(new FileOutputStream(data));
CounterBean c = new CounterBean(); CounterBean c = new CounterBean();
c.setGamesPlayed(prev+1); c.setGamesPlayed(prev+1);
oos.writeObject(c); oos.writeObject(c);
@ -104,8 +92,6 @@ public class CounterPluginImpl implements CounterPlugin {
} }
} catch (IOException e) { } catch (IOException e) {
throw new PluginException(e); throw new PluginException(e);
} finally {
if (oos != null) try { oos.close(); } catch (Exception e) {}
} }
} else { } else {
log.error("Counter plugin: data file doesn't exist, please restart plugin."); log.error("Counter plugin: data file doesn't exist, please restart plugin.");
@ -120,10 +106,8 @@ public class CounterPluginImpl implements CounterPlugin {
return 0; return 0;
} }
if (data.exists()) { if (data.exists()) {
ObjectInputStream ois = null; try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(data))) {
try {
synchronized (this) { synchronized (this) {
ois = new ObjectInputStream(new FileInputStream(data));
Object o = ois.readObject(); Object o = ois.readObject();
CounterBean c = null; CounterBean c = null;
if (o instanceof CounterBean) { if (o instanceof CounterBean) {
@ -138,8 +122,6 @@ public class CounterPluginImpl implements CounterPlugin {
throw new PluginException(e); throw new PluginException(e);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new PluginException(e); throw new PluginException(e);
} finally {
if (ois != null) try { ois.close(); } catch (Exception e) {}
} }
} else { } else {
log.error("Counter plugin: data file doesn't exist, please restart plugin."); log.error("Counter plugin: data file doesn't exist, please restart plugin.");

View file

@ -56,7 +56,7 @@ public class SystemUtil {
try (Scanner scanner = new Scanner(f)) { try (Scanner scanner = new Scanner(f)) {
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim(); String line = scanner.nextLine().trim();
if (line.trim().isEmpty() || line.startsWith("#")) { if (line.isEmpty() || line.startsWith("#")) {
continue; continue;
} }
@ -69,11 +69,12 @@ public class SystemUtil {
String zone = m.group(1); String zone = m.group(1);
String nickname = m.group(2); String nickname = m.group(2);
Player player = findPlayer(game, nickname); Optional<Player> playerOptional = findPlayer(game, nickname);
if (player == null) { if (!playerOptional.isPresent()) {
logger.warn("Was skipped: " + line); logger.warn("Was skipped: " + line);
continue; continue;
} }
Player player = playerOptional.get();
Zone gameZone; Zone gameZone;
if ("hand".equalsIgnoreCase(zone)) { if ("hand".equalsIgnoreCase(zone)) {
@ -148,13 +149,13 @@ public class SystemUtil {
* @param name * @param name
* @return * @return
*/ */
private static Player findPlayer(Game game, String name) { private static Optional<Player> findPlayer(Game game, String name) {
for (Player player : game.getPlayers().values()) { for (Player player : game.getPlayers().values()) {
if (player.getName().equals(name)) { if (player.getName().equals(name)) {
return player; return Optional.of(player);
} }
} }
return null; return Optional.empty();
} }
public static String sanitize(String input) { public static String sanitize(String input) {

View file

@ -1,15 +1,5 @@
package org.mage.test.serverside.base; package org.mage.test.serverside.base;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mage.cards.Card; import mage.cards.Card;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository; import mage.cards.repository.CardRepository;
@ -35,6 +25,13 @@ import org.junit.BeforeClass;
import org.mage.test.player.RandomPlayer; import org.mage.test.player.RandomPlayer;
import org.mage.test.player.TestPlayer; import org.mage.test.player.TestPlayer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* Base class for all tests. * Base class for all tests.
* *
@ -181,8 +178,7 @@ public abstract class MageTestBase {
protected void parseScenario(String filename) throws FileNotFoundException { protected void parseScenario(String filename) throws FileNotFoundException {
parserState = ParserState.INIT; parserState = ParserState.INIT;
File f = new File(filename); File f = new File(filename);
Scanner scanner = new Scanner(f); try(Scanner scanner = new Scanner(f)) {
try {
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim(); String line = scanner.nextLine().trim();
if (line == null || line.isEmpty() || line.startsWith("#")) { if (line == null || line.isEmpty() || line.startsWith("#")) {
@ -198,8 +194,6 @@ public abstract class MageTestBase {
} }
parseLine(line); parseLine(line);
} }
} finally {
scanner.close();
} }
} }

View file

@ -1,15 +1,5 @@
package org.mage.test.serverside.base; package org.mage.test.serverside.base;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mage.cards.Card; import mage.cards.Card;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository; import mage.cards.repository.CardRepository;
@ -33,6 +23,13 @@ import org.apache.log4j.Logger;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.mage.test.player.TestPlayer; import org.mage.test.player.TestPlayer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* Base class for all tests. * Base class for all tests.
* *
@ -167,8 +164,7 @@ public abstract class MageTestPlayerBase {
protected void parseScenario(String filename) throws FileNotFoundException { protected void parseScenario(String filename) throws FileNotFoundException {
parserState = ParserState.INIT; parserState = ParserState.INIT;
File f = new File(filename); File f = new File(filename);
Scanner scanner = new Scanner(f); try(Scanner scanner = new Scanner(f)) {
try {
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim(); String line = scanner.nextLine().trim();
if (line == null || line.isEmpty() || line.startsWith("#")) { if (line == null || line.isEmpty() || line.startsWith("#")) {
@ -184,8 +180,6 @@ public abstract class MageTestPlayerBase {
} }
parseLine(line); parseLine(line);
} }
} finally {
scanner.close();
} }
} }

View file

@ -32,11 +32,7 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.ArrayList; import java.util.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarInputStream; import java.util.jar.JarInputStream;
@ -111,9 +107,8 @@ public class ClassScanner {
List<Class> cards = new ArrayList<>(); List<Class> cards = new ArrayList<>();
if (!file.exists()) return cards; if (!file.exists()) return cards;
JarInputStream jarFile = null;
try { try(JarInputStream jarFile = new JarInputStream(new FileInputStream(file))) {
jarFile = new JarInputStream(new FileInputStream(file));
while (true) { while (true) {
JarEntry jarEntry = jarFile.getNextJarEntry(); JarEntry jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) { if (jarEntry == null) {
@ -127,11 +122,6 @@ public class ClassScanner {
} }
} }
} catch (IOException ex) { } catch (IOException ex) {
} finally {
try {
if(jarFile != null) jarFile.close();
} catch (IOException ex) {
}
} }
return cards; return cards;
} }