From f1ef3bf68b605eadc8180905a495d2df76111809 Mon Sep 17 00:00:00 2001 From: vraskulin Date: Wed, 15 Feb 2017 16:05:18 +0300 Subject: [PATCH] Narrowed variables scope. --- .../plugins/card/images/DownloadPictures.java | 26 +++++++++---------- .../mage/plugins/card/images/ImageCache.java | 19 ++++++-------- .../main/java/mage/server/ChatManager.java | 3 +-- .../main/java/mage/server/ChatSession.java | 2 -- .../main/java/mage/server/MageServerImpl.java | 2 +- .../src/main/java/mage/server/MailClient.java | 3 +-- .../src/main/java/mage/server/Main.java | 2 +- .../src/main/java/mage/server/Session.java | 2 +- .../main/java/mage/server/SessionManager.java | 3 ++- .../java/mage/server/TableController.java | 6 ++--- .../java/mage/server/draft/CubeFactory.java | 6 ++--- .../server/game/DeckValidatorFactory.java | 3 +-- .../java/mage/server/game/GameController.java | 3 +-- .../java/mage/server/game/GameFactory.java | 3 +-- .../java/mage/server/game/GamesRoomImpl.java | 5 ++-- .../java/mage/server/game/PlayerFactory.java | 6 ++--- .../java/mage/server/game/ReplaySession.java | 1 - .../tournament/TournamentController.java | 2 +- .../server/tournament/TournamentFactory.java | 3 +-- .../java/mage/server/util/SystemUtil.java | 2 +- 20 files changed, 42 insertions(+), 60 deletions(-) diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java b/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java index 4510e7df0e..953f606511 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/images/DownloadPictures.java @@ -240,12 +240,9 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab private static List getNeededCards(List allCards) { - List cardsToDownload = Collections.synchronizedList(new ArrayList<>()); - /** * read all card names and urls */ - List allCardsUrls = Collections.synchronizedList(new ArrayList<>()); HashSet ignoreUrls = SettingsManager.getIntance().getIgnoreUrls(); /** @@ -261,6 +258,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab int numberCardImages = allCards.size(); int numberWithoutTokens = 0; + List allCardsUrls = Collections.synchronizedList(new ArrayList<>()); try { offlineMode = true; allCards.parallelStream().forEach(card -> { @@ -290,11 +288,11 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab if (card.getFlipCardName() == null || card.getFlipCardName().trim().isEmpty()) { throw new IllegalStateException("Flipped card can't have empty name."); } - url = new CardDownloadData(card.getFlipCardName(), card.getSetCode(), card.getCardNumber(), card.usesVariousArt(), 0, "", "", false, card.isDoubleFaced(), card.isNightCard()); - url.setFlipCard(true); - url.setFlippedSide(true); - url.setType2(isType2); - allCardsUrls.add(url); + CardDownloadData cardDownloadData = new CardDownloadData(card.getFlipCardName(), card.getSetCode(), card.getCardNumber(), card.usesVariousArt(), 0, "", "", false, card.isDoubleFaced(), card.isNightCard()); + cardDownloadData.setFlipCard(true); + cardDownloadData.setFlippedSide(true); + cardDownloadData.setType2(isType2); + allCardsUrls.add(cardDownloadData); } } else if (card.getCardNumber().isEmpty() || "0".equals(card.getCardNumber())) { System.err.println("There was a critical error!"); @@ -315,6 +313,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab /** * check to see which cards we already have */ + List cardsToDownload = Collections.synchronizedList(new ArrayList<>()); allCardsUrls.parallelStream().forEach(card -> { TFile file = new TFile(CardImageUtils.generateImagePath(card)); if (!file.exists()) { @@ -348,19 +347,18 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab try(InputStreamReader input = new InputStreamReader(in); BufferedReader reader = new BufferedReader(input)) { - String line; - line = reader.readLine(); + String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.startsWith("|")) { // new format String[] params = line.split("\\|", -1); if (params.length >= 5) { int type = 0; - String fileName = ""; if (params[4] != null && !params[4].isEmpty()) { type = Integer.parseInt(params[4].trim()); } + String fileName = ""; if (params.length > 5 && params[5] != null && !params[5].isEmpty()) { fileName = params[5].trim(); } @@ -516,7 +514,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab private final String actualFilename; private final boolean useSpecifiedPaths; - public DownloadTask(CardDownloadData card, URL url, int count) { + DownloadTask(CardDownloadData card, URL url, int count) { this.card = card; this.url = url; this.count = count; @@ -524,7 +522,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab useSpecifiedPaths = false; } - public DownloadTask(CardDownloadData card, URL url, String actualFilename, int count) { + DownloadTask(CardDownloadData card, URL url, String actualFilename, int count) { this.card = card; this.url = url; this.count = count; @@ -583,7 +581,6 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab } return; } - BufferedOutputStream out; // Logger.getLogger(this.getClass()).info(url.toString()); boolean useTempFile = false; @@ -602,6 +599,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab if (responseCode == 200 || useTempFile) { if (!useTempFile) { + BufferedOutputStream out; try (BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream())) { //try (BufferedInputStream in = new BufferedInputStream(url.openConnection(p).getInputStream())) { out = new BufferedOutputStream(new TFileOutputStream(temporaryFile)); diff --git a/Mage.Client/src/main/java/org/mage/plugins/card/images/ImageCache.java b/Mage.Client/src/main/java/org/mage/plugins/card/images/ImageCache.java index 5595794bd7..05ad7b0747 100644 --- a/Mage.Client/src/main/java/org/mage/plugins/card/images/ImageCache.java +++ b/Mage.Client/src/main/java/org/mage/plugins/card/images/ImageCache.java @@ -39,7 +39,7 @@ import org.mage.plugins.card.utils.CardImageUtils; * look * */ -public class ImageCache { +public final class ImageCache { private static final Logger LOGGER = Logger.getLogger(ImageCache.class); @@ -157,6 +157,9 @@ public class ImageCache { }); } + private ImageCache() { + } + public static BufferedImage getMorphImage() { CardDownloadData info = new CardDownloadData("Morph", "KTK", "0", false, 0, "KTK", ""); info.setToken(true); @@ -222,8 +225,7 @@ public class ImageCache { */ private static BufferedImage getImage(String key) { try { - BufferedImage image = IMAGE_CACHE.get(key); - return image; + return IMAGE_CACHE.get(key); } catch (NullPointerException ex) { // unfortunately NullOutputException, thrown when apply() returns // null, is not public @@ -244,11 +246,7 @@ public class ImageCache { * the cache. */ private static BufferedImage tryGetImage(String key) { - if (IMAGE_CACHE.containsKey(key)) { - return IMAGE_CACHE.get(key); - } else { - return null; - } + return IMAGE_CACHE.containsKey(key) ? IMAGE_CACHE.get(key) : null; } /** @@ -279,11 +277,11 @@ public class ImageCache { if (file == null) { return null; } - BufferedImage image = null; if (!file.exists()) { LOGGER.debug("File does not exist: " + file.toString()); return null; } + BufferedImage image = null; try { try (TFileInputStream inputStream = new TFileInputStream(file)) { image = ImageIO.read(inputStream); @@ -395,8 +393,7 @@ public class ImageCache { public static TFile getTFile(String path) { try { - TFile file = new TFile(path); - return file; + return new TFile(path); } catch (NullPointerException ex) { LOGGER.warn("Imagefile does not exist: " + path); } diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index ec7fe0dcfd..521fd616b0 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -271,8 +271,7 @@ public class ChatManager { } public ArrayList getChatSessions() { - ArrayList chatSessionList = new ArrayList<>(chatSessions.values()); - return chatSessionList; + return new ArrayList<>(chatSessions.values()); } diff --git a/Mage.Server/src/main/java/mage/server/ChatSession.java b/Mage.Server/src/main/java/mage/server/ChatSession.java index 5f84426857..34119c0852 100644 --- a/Mage.Server/src/main/java/mage/server/ChatSession.java +++ b/Mage.Server/src/main/java/mage/server/ChatSession.java @@ -28,7 +28,6 @@ package mage.server; import mage.interfaces.callback.ClientCallback; -import mage.server.exceptions.UserNotFoundException; import mage.view.ChatMessage; import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageType; @@ -36,7 +35,6 @@ import mage.view.ChatMessage.SoundToPlay; import org.apache.log4j.Logger; import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Optional; diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 842e85376b..0a9e40aecc 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -227,13 +227,13 @@ public class MageServerImpl implements MageServer { // check AI players max String maxAiOpponents = ConfigSettings.getInstance().getMaxAiOpponents(); if (maxAiOpponents != null) { - int max = Integer.parseInt(maxAiOpponents); int aiPlayers = 0; for (String playerType : options.getPlayerTypes()) { if (!playerType.equals("Human")) { aiPlayers++; } } + int max = Integer.parseInt(maxAiOpponents); if (aiPlayers > max) { user.showUserMessage("Create tournament", "It's only allowed to use a maximum of " + max + " AI players."); throw new MageException("No message"); diff --git a/Mage.Server/src/main/java/mage/server/MailClient.java b/Mage.Server/src/main/java/mage/server/MailClient.java index 16c8f3ae59..29ffdcc76a 100644 --- a/Mage.Server/src/main/java/mage/server/MailClient.java +++ b/Mage.Server/src/main/java/mage/server/MailClient.java @@ -37,8 +37,7 @@ public class MailClient { message.setSubject(subject); message.setText(text); - Transport trnsport; - trnsport = session.getTransport("smtps"); + Transport trnsport = session.getTransport("smtps"); trnsport.connect(null, properties.getProperty("mail.password")); message.saveChanges(); trnsport.sendMessage(message, message.getAllRecipients()); diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 1839fa3e44..18e2650663 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -116,13 +116,13 @@ public class Main { } logger.info("Loading extension packages..."); - List extensions = new ArrayList<>(); if (!extensionFolder.exists()) { if (!extensionFolder.mkdirs()) { logger.error("Could not create extensions directory."); } } File[] extensionDirectories = extensionFolder.listFiles(); + List extensions = new ArrayList<>(); if (extensionDirectories != null) { for (File f : extensionDirectories) { if (f.isDirectory()) { diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index eee18acbb6..f87eeeae6e 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -101,11 +101,11 @@ public class Session { return returnMessage; } AuthorizedUserRepository.instance.add(userName, password, email); - String subject = "XMage Registration Completed"; String text = "You are successfully registered as " + userName + '.'; text += " Your initial, generated password is: " + password; boolean success; + String subject = "XMage Registration Completed"; if (!ConfigSettings.getInstance().getMailUser().isEmpty()) { success = MailClient.sendMessage(email, subject, text); } else { diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 0083d0fcc9..5692f0e0f3 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -173,8 +173,9 @@ public class SessionManager { */ public void disconnectUser(String sessionId, String userSessionId) { if (isAdmin(sessionId)) { - User userAdmin, user; + User userAdmin; if ((userAdmin = getUserFromSession(sessionId)) != null) { + User user; if ((user = getUserFromSession(userSessionId)) != null) { user.showUserMessage("Admin operation", "Your session was disconnected by Admin."); userAdmin.showUserMessage("Admin action", "User" + user.getName() + " was disconnected."); diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 254caa0b4e..f4490101b7 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -911,9 +911,6 @@ public class TableController { public boolean isMatchTableStillValid() { // check only normal match table with state != Finished if (!table.isTournament()) { - int humanPlayers = 0; - int aiPlayers = 0; - int validHumanPlayers = 0; if (!(table.getState() == TableState.WAITING || table.getState() == TableState.STARTING || table.getState() == TableState.READY_TO_START)) { if (match == null) { logger.debug("- Match table with no match:"); @@ -927,6 +924,9 @@ public class TableController { } } // check for active players + int validHumanPlayers = 0; + int aiPlayers = 0; + int humanPlayers = 0; for (Map.Entry userPlayerEntry : userPlayerMap.entrySet()) { MatchPlayer matchPlayer = match.getPlayer(userPlayerEntry.getValue()); if (matchPlayer == null) { diff --git a/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java b/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java index ad59a9b0ae..939b36598e 100644 --- a/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java +++ b/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java @@ -55,9 +55,8 @@ public class CubeFactory { public DraftCube createDraftCube(String draftCubeName) { DraftCube draftCube; - Constructor con; try { - con = draftCubes.get(draftCubeName).getConstructor(); + Constructor con = draftCubes.get(draftCubeName).getConstructor(); draftCube = (DraftCube)con.newInstance(); } catch (Exception ex) { logger.fatal("CubeFactory error", ex); @@ -71,9 +70,8 @@ public class CubeFactory { public DraftCube createDeckDraftCube(String draftCubeName, Deck cubeFromDeck) { DraftCube draftCube; - Constructor con; try { - con = draftCubes.get(draftCubeName).getConstructor(Deck.class); + Constructor con = draftCubes.get(draftCubeName).getConstructor(Deck.class); draftCube = (DraftCube)con.newInstance(cubeFromDeck); } catch (Exception ex) { logger.fatal("CubeFactory error", ex); diff --git a/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java b/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java index ceff42329a..168c025fb9 100644 --- a/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java @@ -55,9 +55,8 @@ public class DeckValidatorFactory { public DeckValidator createDeckValidator(String deckType) { DeckValidator validator; - Constructor con; try { - con = deckTypes.get(deckType).getConstructor(); + Constructor con = deckTypes.get(deckType).getConstructor(); validator = (DeckValidator)con.newInstance(); } catch (Exception ex) { logger.fatal("DeckValidatorFactory error", ex); diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index e514e233bd..97a7fb25d6 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -621,9 +621,8 @@ public class GameController implements GameCallback { } public void cheat(UUID userId, UUID playerId, DeckCardLists deckList) { - Deck deck; try { - deck = Deck.load(deckList, false, false); + Deck deck = Deck.load(deckList, false, false); game.loadCards(deck.getCards(), playerId); for (Card card : deck.getCards()) { card.putOntoBattlefield(game, Zone.OUTSIDE, null, playerId); diff --git a/Mage.Server/src/main/java/mage/server/game/GameFactory.java b/Mage.Server/src/main/java/mage/server/game/GameFactory.java index c3a22eb59b..f31f3ee7cd 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/GameFactory.java @@ -62,9 +62,8 @@ public class GameFactory { public Match createMatch(String gameType, MatchOptions options) { Match match; - Constructor con; try { - con = games.get(gameType).getConstructor(MatchOptions.class); + Constructor con = games.get(gameType).getConstructor(MatchOptions.class); match = con.newInstance(options); } catch (Exception ex) { logger.fatal("Error creating match - " + gameType, ex); diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java index a1c280cedf..adc697bdb8 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java @@ -29,7 +29,6 @@ package mage.server.game; import java.io.Serializable; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.UUID; @@ -89,10 +88,10 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } private void update() { - ArrayList tableList = new ArrayList<>(); - ArrayList matchList = new ArrayList<>(); List allTables = new ArrayList<>(tables.values()); allTables.sort(new TableListSorter()); + ArrayList matchList = new ArrayList<>(); + ArrayList tableList = new ArrayList<>(); for (Table table : allTables) { if (table.getState() != TableState.FINISHED) { tableList.add(new TableView(table)); diff --git a/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java b/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java index 9d9581aa83..f7e430e808 100644 --- a/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java @@ -54,13 +54,11 @@ public class PlayerFactory { private PlayerFactory() {} public Player createPlayer(String playerType, String name, RangeOfInfluence range, int skill) { - Player player; - Constructor con; try { Class playerTypeClass = playerTypes.get(playerType); if (playerTypeClass != null) { - con = playerTypeClass.getConstructor(String.class, RangeOfInfluence.class, int.class); - player = (Player)con.newInstance(name, range, skill); + Constructor con = playerTypeClass.getConstructor(String.class, RangeOfInfluence.class, int.class); + Player player = (Player) con.newInstance(name, range, skill); logger.trace("Player created: " + name + " - " + player.getId()); return player; } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java index 71c1787d78..b1c68f0665 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java @@ -33,7 +33,6 @@ import java.util.UUID; import mage.game.Game; import mage.game.GameState; import mage.interfaces.callback.ClientCallback; -import mage.server.User; import mage.server.UserManager; import mage.view.GameView; diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index c99e136e32..03e980e319 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -418,10 +418,10 @@ public class TournamentController { } // replace player that quits with draft bot if (humans > 1) { - String replacePlayerName = "Draftbot"; Optional user = UserManager.getInstance().getUser(userId); TableController tableController = TableManager.getInstance().getController(tableId); if (tableController != null) { + String replacePlayerName = "Draftbot"; if (user.isPresent()) { replacePlayerName = "Draftbot (" + user.get().getName() + ')'; } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java index dad91bc46b..d6c0d1b554 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java @@ -64,9 +64,8 @@ public class TournamentFactory { public Tournament createTournament(String tournamentType, TournamentOptions options) { Tournament tournament; - Constructor con; try { - con = tournaments.get(tournamentType).getConstructor(TournamentOptions.class); + Constructor con = tournaments.get(tournamentType).getConstructor(TournamentOptions.class); tournament = con.newInstance(options); // transfer set information, create short info string for included sets tournament.setTournamentType(tournamentTypes.get(tournamentType)); diff --git a/Mage.Server/src/main/java/mage/server/util/SystemUtil.java b/Mage.Server/src/main/java/mage/server/util/SystemUtil.java index 15d276dfd4..64fa68e0aa 100644 --- a/Mage.Server/src/main/java/mage/server/util/SystemUtil.java +++ b/Mage.Server/src/main/java/mage/server/util/SystemUtil.java @@ -45,7 +45,6 @@ public class SystemUtil { public static void addCardsForTesting(Game game) { try { File f = new File(INIT_FILE_PATH); - Pattern pattern = Pattern.compile("([a-zA-Z]+):([\\w]+):([a-zA-Z ,\\/\\-.!'\\d:]+?):(\\d+)"); if (!f.exists()) { logger.warn("Couldn't find init file: " + INIT_FILE_PATH); return; @@ -54,6 +53,7 @@ public class SystemUtil { logger.info("Parsing init.txt... "); try (Scanner scanner = new Scanner(f)) { + Pattern pattern = Pattern.compile("([a-zA-Z]+):([\\w]+):([a-zA-Z ,\\/\\-.!'\\d:]+?):(\\d+)"); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (line.isEmpty() || line.startsWith("#")) {