diff --git a/Mage.Client/src/main/java/mage/client/SessionHandler.java b/Mage.Client/src/main/java/mage/client/SessionHandler.java index f82c485e88..a690513ec5 100644 --- a/Mage.Client/src/main/java/mage/client/SessionHandler.java +++ b/Mage.Client/src/main/java/mage/client/SessionHandler.java @@ -1,9 +1,7 @@ package mage.client; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.UUID; +import java.util.*; + import mage.cards.decks.DeckCardLists; import mage.client.chat.LocalCommands; import mage.constants.ManaType; @@ -129,7 +127,7 @@ public final class SessionHandler { return session.isTableOwner(roomId, tableId); } - public static UUID getTableChatId(UUID tableId) { + public static Optional getTableChatId(UUID tableId) { return session.getTableChatId(tableId); } @@ -141,7 +139,7 @@ public final class SessionHandler { return session.startMatch(roomId, tableId); } - public static UUID getGameChatId(UUID gameId) { + public static Optional getGameChatId(UUID gameId) { return session.getGameChatId(gameId); } @@ -161,7 +159,7 @@ public final class SessionHandler { return session.joinTournament(tournamentId); } - public static UUID getTournamentChatId(UUID tournamentId) { + public static Optional getTournamentChatId(UUID tournamentId) { return session.getTournamentChatId(tournamentId); } @@ -255,7 +253,7 @@ public final class SessionHandler { session.sendCardMark(draftId, id); } - public static UUID getRoomChatId(UUID roomId) { + public static Optional getRoomChatId(UUID roomId) { return session.getRoomChatId(roomId); } @@ -264,7 +262,7 @@ public final class SessionHandler { return session.getRoomUsers(roomId); } catch (MageRemoteException e) { e.printStackTrace(); - return null; + return Collections.emptyList(); } } @@ -273,7 +271,7 @@ public final class SessionHandler { return session.getFinishedMatches(roomId); } catch (MageRemoteException e) { e.printStackTrace(); - return null; + return new ArrayList<>(); } } @@ -290,7 +288,7 @@ public final class SessionHandler { return session.getTables(roomId); } catch (MageRemoteException e) { e.printStackTrace(); - return null; + return new ArrayList<>(); } } @@ -318,7 +316,7 @@ public final class SessionHandler { return session.sendPlayerManaType(gameId, playerId, data); } - public static TableView getTable(UUID roomId, UUID tableId) { + public static Optional getTable(UUID roomId, UUID tableId) { return session.getTable(roomId, tableId); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java b/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java index 3f1292c447..9a690da6c3 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java @@ -35,19 +35,23 @@ package mage.client.dialog; import java.awt.Dimension; import java.util.List; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import javax.swing.Icon; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; + import mage.client.MageFrame; import mage.client.SessionHandler; import mage.client.chat.ChatPanelBasic; import mage.client.components.MageComponents; import mage.client.components.tray.MageTray; + import static mage.client.dialog.PreferencesDialog.KEY_TABLE_WAITING_COLUMNS_ORDER; import static mage.client.dialog.PreferencesDialog.KEY_TABLE_WAITING_COLUMNS_WIDTH; + import mage.client.util.GUISizeHelper; import mage.client.util.audio.AudioManager; import mage.client.util.gui.TableUtil; @@ -58,7 +62,6 @@ import mage.view.TableView; import org.apache.log4j.Logger; /** - * * @author BetaSteward_at_googlemail.com */ public class TableWaitingDialog extends MageDialog { @@ -159,9 +162,9 @@ public class TableWaitingDialog extends MageDialog { this.btnMoveDown.setVisible(false); this.btnMoveUp.setVisible(false); } - UUID chatId = SessionHandler.getTableChatId(tableId); - if (chatId != null) { - this.chatPanel.connect(chatId); + Optional chatId = SessionHandler.getTableChatId(tableId); + if (chatId.isPresent()) { + this.chatPanel.connect(chatId.get()); updateTask.execute(); this.setModal(false); this.setLocation(100, 100); @@ -234,30 +237,30 @@ public class TableWaitingDialog extends MageDialog { javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addContainerGap() - .addComponent(btnMoveDown) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnMoveUp) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(btnStart) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnCancel) - .addContainerGap()) - .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE) + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(btnMoveDown) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnMoveUp) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btnStart) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnCancel) + .addContainerGap()) + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE) ); layout.setVerticalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(btnMoveDown) - .addComponent(btnMoveUp) - .addComponent(btnCancel) - .addComponent(btnStart)) - .addContainerGap()) + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(btnMoveDown) + .addComponent(btnMoveUp) + .addComponent(btnCancel) + .addComponent(btnStart)) + .addContainerGap()) ); pack(); @@ -416,8 +419,15 @@ class UpdateSeatsTask extends SwingWorker { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - this.publish(SessionHandler.getTable(roomId, tableId)); - Thread.sleep(1000); + SessionHandler.getTable(roomId, tableId).ifPresent(tableView -> { + + this.publish(tableView); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); } return null; } diff --git a/Mage.Client/src/main/java/mage/client/game/GamePanel.java b/Mage.Client/src/main/java/mage/client/game/GamePanel.java index 700a750685..bba5988920 100644 --- a/Mage.Client/src/main/java/mage/client/game/GamePanel.java +++ b/Mage.Client/src/main/java/mage/client/game/GamePanel.java @@ -80,6 +80,7 @@ import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.plaf.basic.BasicSplitPaneUI; + import mage.cards.Card; import mage.cards.action.ActionCallback; import mage.choices.Choice; @@ -99,7 +100,9 @@ import mage.client.dialog.PickChoiceDialog; import mage.client.dialog.PickNumberDialog; import mage.client.dialog.PickPileDialog; import mage.client.dialog.PreferencesDialog; + import static mage.client.dialog.PreferencesDialog.*; + import mage.client.dialog.ShowCardsDialog; import mage.client.game.FeedbackPanel.FeedbackMode; import mage.client.plugins.adapters.MageActionCallback; @@ -116,11 +119,13 @@ import mage.constants.Constants; import mage.constants.EnlargeMode; import mage.constants.PhaseStep; import mage.constants.PlayerAction; + import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_ABILITY_FIRST; import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_ABILITY_LAST; import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_NAME_FIRST; import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_NAME_LAST; import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_RESET_ALL; + import mage.constants.Zone; import mage.game.events.PlayerQueryEvent; import mage.view.AbilityPickerView; @@ -139,7 +144,6 @@ import org.mage.card.arcane.CardPanel; import org.mage.plugins.card.utils.impl.ImageManagerImpl; /** - * * @author BetaSteward_at_googlemail.com, nantuko8 */ public final class GamePanel extends javax.swing.JPanel { @@ -194,6 +198,7 @@ public final class GamePanel extends javax.swing.JPanel { TRIGGER_ORDER } + // CardView popupMenu was invoked last private CardView cardViewPopupMenu; @@ -497,7 +502,7 @@ public final class GamePanel extends javax.swing.JPanel { this.pnlReplay.setVisible(false); this.gameChatPanel.clear(); - this.gameChatPanel.connect(SessionHandler.getGameChatId(gameId)); + SessionHandler.getGameChatId(gameId).ifPresent(uuid -> this.gameChatPanel.connect(uuid)); if (!SessionHandler.joinGame(gameId)) { removeGame(); } else { @@ -529,7 +534,8 @@ public final class GamePanel extends javax.swing.JPanel { this.pnlReplay.setVisible(false); this.gameChatPanel.clear(); - this.gameChatPanel.connect(SessionHandler.getGameChatId(gameId)); + SessionHandler.getGameChatId(gameId).ifPresent(uuid -> + this.gameChatPanel.connect(uuid)); if (!SessionHandler.watchGame(gameId)) { removeGame(); } @@ -1770,24 +1776,24 @@ public final class GamePanel extends javax.swing.JPanel { pnlReplay.setLayout(gl_pnlReplay); gl_pnlReplay.setHorizontalGroup( gl_pnlReplay.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(gl_pnlReplay.createSequentialGroup() - .addComponent(btnPreviousPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(btnStopReplay, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnNextPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnSkipForward, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(gl_pnlReplay.createSequentialGroup() + .addComponent(btnPreviousPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btnStopReplay, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnNextPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnSkipForward, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) ); gl_pnlReplay.setVerticalGroup( gl_pnlReplay.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(btnSkipForward, 0, 0, Short.MAX_VALUE) - .addComponent(btnNextPlay, 0, 0, Short.MAX_VALUE) - .addComponent(btnStopReplay, 0, 0, Short.MAX_VALUE) - .addComponent(btnPlay, 0, 0, Short.MAX_VALUE) - .addComponent(btnPreviousPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 31, Short.MAX_VALUE) + .addComponent(btnSkipForward, 0, 0, Short.MAX_VALUE) + .addComponent(btnNextPlay, 0, 0, Short.MAX_VALUE) + .addComponent(btnStopReplay, 0, 0, Short.MAX_VALUE) + .addComponent(btnPlay, 0, 0, Short.MAX_VALUE) + .addComponent(btnPreviousPlay, javax.swing.GroupLayout.PREFERRED_SIZE, 31, Short.MAX_VALUE) ); // Game info panel (buttons on the right panel) @@ -1861,8 +1867,8 @@ public final class GamePanel extends javax.swing.JPanel { } }; String[] phases = {"Untap", "Upkeep", "Draw", "Main1", - "Combat_Start", "Combat_Attack", "Combat_Block", "Combat_Damage", "Combat_End", - "Main2", "Cleanup", "Next_Turn"}; + "Combat_Start", "Combat_Attack", "Combat_Block", "Combat_Damage", "Combat_End", + "Main2", "Cleanup", "Next_Turn"}; for (String name : phases) { createPhaseButton(name, phasesMouseAdapter); } @@ -1899,46 +1905,46 @@ public final class GamePanel extends javax.swing.JPanel { javax.swing.GroupLayout gl_helperHandButtonsStackArea = new javax.swing.GroupLayout(pnlHelperHandButtonsStackArea); gl_helperHandButtonsStackArea.setHorizontalGroup( gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) - .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() - // .addGap(0) - .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) - .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() - .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) - .addComponent(helper, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(handContainer, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() + // .addGap(0) + .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) + .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() + .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) + .addComponent(helper, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(handContainer, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ) + .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) + .addComponent(pnlShortCuts, 410, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) + .addComponent(stackObjects, 410, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) + ) ) - .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) - .addComponent(pnlShortCuts, 410, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) - .addComponent(stackObjects, 410, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) - ) - ) - .addGap(0) - //.addComponent(jPhases, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() - .addComponent(pnlBattlefield, GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) - .addComponent(phasesContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) - ))) + .addGap(0) + //.addComponent(jPhases, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() + .addComponent(pnlBattlefield, GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) + .addComponent(phasesContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + ))) ); gl_helperHandButtonsStackArea.setVerticalGroup( gl_helperHandButtonsStackArea.createParallelGroup(Alignment.TRAILING) - .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() - .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) - .addComponent(pnlBattlefield, GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) - .addComponent(phasesContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) - ) - //.addPreferredGap(ComponentPlacement.RELATED) - .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) - .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() - .addGap(2) - .addComponent(pnlShortCuts, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) - .addComponent(stackObjects, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() + .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) + .addComponent(pnlBattlefield, GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) + .addComponent(phasesContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) - .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() - .addComponent(helper, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) - .addComponent(handContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + //.addPreferredGap(ComponentPlacement.RELATED) + .addGroup(gl_helperHandButtonsStackArea.createParallelGroup(Alignment.LEADING) + .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() + .addGap(2) + .addComponent(pnlShortCuts, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(stackObjects, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + ) + .addGroup(gl_helperHandButtonsStackArea.createSequentialGroup() + .addComponent(helper, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(handContainer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + ) ) ) - ) ); pnlHelperHandButtonsStackArea.setLayout(gl_helperHandButtonsStackArea); @@ -1971,11 +1977,11 @@ public final class GamePanel extends javax.swing.JPanel { this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jSplitPane0, javax.swing.GroupLayout.DEFAULT_SIZE, 1078, Short.MAX_VALUE) + .addComponent(jSplitPane0, javax.swing.GroupLayout.DEFAULT_SIZE, 1078, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jSplitPane0, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE) + .addComponent(jSplitPane0, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE) ); } @@ -2353,7 +2359,7 @@ public final class GamePanel extends javax.swing.JPanel { private mage.client.components.ability.AbilityPicker abilityPicker; private mage.client.cards.BigCard bigCard; -// private JPanel cancelSkipPanel; + // private JPanel cancelSkipPanel; private KeyboundButton btnCancelSkip; private KeyboundButton btnSkipToNextTurn; // F4 private KeyboundButton btnSkipToEndTurn; // F5 diff --git a/Mage.Client/src/main/java/mage/client/table/TablesPanel.java b/Mage.Client/src/main/java/mage/client/table/TablesPanel.java index 59cdb09259..5a6be71f1a 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablesPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TablesPanel.java @@ -480,7 +480,7 @@ public class TablesPanel extends javax.swing.JPanel { if (SessionHandler.getSession() != null) { btnQuickStart.setVisible(SessionHandler.isTestMode()); gameChooser.init(); - chatRoomId = SessionHandler.getRoomChatId(roomId); + chatRoomId = SessionHandler.getRoomChatId(roomId).orElse(null); } if (newTableDialog == null) { newTableDialog = new NewTableDialog(); @@ -520,7 +520,7 @@ public class TablesPanel extends javax.swing.JPanel { this.messages = serverMessages; this.currentMessage = 0; } - if (serverMessages == null || serverMessages.isEmpty()) { + if (serverMessages.isEmpty()) { this.jPanelBottom.setVisible(false); } else { this.jPanelBottom.setVisible(true); @@ -1447,7 +1447,7 @@ class UpdateTablesTask extends SwingWorker> { protected Void doInBackground() throws Exception { while (!isCancelled()) { Collection tables = SessionHandler.getTables(roomId); - if (tables != null) { + if (!tables.isEmpty()) { this.publish(tables); } Thread.sleep(3000); @@ -1633,7 +1633,7 @@ class UpdateMatchesTask extends SwingWorker> { protected Void doInBackground() throws Exception { while (!isCancelled()) { Collection matches = SessionHandler.getFinishedMatches(roomId); - if (matches != null) { + if (!matches.isEmpty()) { this.publish(matches); } Thread.sleep(10000); diff --git a/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java b/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java index 884cb53ef4..27a93236c3 100644 --- a/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java +++ b/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java @@ -40,6 +40,7 @@ import java.awt.event.ActionEvent; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; @@ -48,6 +49,8 @@ import javax.swing.Action; import javax.swing.Icon; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; + +import mage.cards.o.Opt; import mage.client.MageFrame; import mage.client.SessionHandler; import mage.client.chat.ChatPanelBasic; @@ -202,9 +205,9 @@ public class TournamentPanel extends javax.swing.JPanel { public synchronized void showTournament(UUID tournamentId) { this.tournamentId = tournamentId; // MageFrame.addTournament(tournamentId, this); - UUID chatRoomId = SessionHandler.getTournamentChatId(tournamentId); - if (SessionHandler.joinTournament(tournamentId) && chatRoomId != null) { - this.chatPanel1.connect(chatRoomId); + Optional chatRoomId = SessionHandler.getTournamentChatId(tournamentId); + if (SessionHandler.joinTournament(tournamentId) && chatRoomId.isPresent()) { + this.chatPanel1.connect(chatRoomId.get()); startTasks(); this.setVisible(true); this.repaint(); diff --git a/Mage.Common/src/mage/interfaces/MageServer.java b/Mage.Common/src/mage/interfaces/MageServer.java index d7da351f8b..bf144fa715 100644 --- a/Mage.Common/src/mage/interfaces/MageServer.java +++ b/Mage.Common/src/mage/interfaces/MageServer.java @@ -28,6 +28,7 @@ package mage.interfaces; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.UUID; import mage.MageException; @@ -113,7 +114,7 @@ public interface MageServer { boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException; - TableView getTable(UUID roomId, UUID tableId) throws MageException; + Optional getTable(UUID roomId, UUID tableId) throws MageException; List getTables(UUID roomId) throws MageException; @@ -124,13 +125,13 @@ public interface MageServer { void leaveChat(UUID chatId, String sessionId) throws MageException; - UUID getTableChatId(UUID tableId) throws MageException; + Optional getTableChatId(UUID tableId) throws MageException; - UUID getGameChatId(UUID gameId) throws MageException; + Optional getGameChatId(UUID gameId) throws MageException; - UUID getRoomChatId(UUID roomId) throws MageException; + Optional getRoomChatId(UUID roomId) throws MageException; - UUID getTournamentChatId(UUID tournamentId) throws MageException; + Optional getTournamentChatId(UUID tournamentId) throws MageException; //room methods UUID getMainRoomId() throws MageException; diff --git a/Mage.Common/src/mage/remote/SessionImpl.java b/Mage.Common/src/mage/remote/SessionImpl.java index 1fb7a8dfe2..46d6cc8aa4 100644 --- a/Mage.Common/src/mage/remote/SessionImpl.java +++ b/Mage.Common/src/mage/remote/SessionImpl.java @@ -600,7 +600,7 @@ public class SessionImpl implements Session { } @Override - public UUID getRoomChatId(UUID roomId) { + public Optional getRoomChatId(UUID roomId) { try { if (isConnected()) { return server.getRoomChatId(roomId); @@ -608,11 +608,11 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } - return null; + return Optional.empty(); } @Override - public UUID getTableChatId(UUID tableId) { + public Optional getTableChatId(UUID tableId) { try { if (isConnected()) { return server.getTableChatId(tableId); @@ -620,11 +620,11 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } - return null; + return Optional.empty(); } @Override - public UUID getGameChatId(UUID gameId) { + public Optional getGameChatId(UUID gameId) { try { if (isConnected()) { return server.getGameChatId(gameId); @@ -634,11 +634,11 @@ public class SessionImpl implements Session { } catch (Throwable t) { handleThrowable(t); } - return null; + return Optional.empty(); } @Override - public TableView getTable(UUID roomId, UUID tableId) { + public Optional getTable(UUID roomId, UUID tableId) { try { if (isConnected()) { return server.getTable(roomId, tableId); @@ -646,7 +646,7 @@ public class SessionImpl implements Session { } catch (MageException ex) { handleMageException(ex); } - return null; + return Optional.empty(); } @Override @@ -735,7 +735,7 @@ public class SessionImpl implements Session { } catch (Throwable t) { handleThrowable(t); } - return null; + return new ArrayList<>(); } @Override @@ -750,7 +750,7 @@ public class SessionImpl implements Session { } catch (Throwable t) { handleThrowable(t); } - return null; + return new ArrayList<>(); } @Override @@ -765,7 +765,7 @@ public class SessionImpl implements Session { } catch (Throwable t) { handleThrowable(t); } - return null; + return new ArrayList<>(); } @Override @@ -784,7 +784,7 @@ public class SessionImpl implements Session { } @Override - public UUID getTournamentChatId(UUID tournamentId) { + public Optional getTournamentChatId(UUID tournamentId) { try { if (isConnected()) { return server.getTournamentChatId(tournamentId); @@ -794,7 +794,7 @@ public class SessionImpl implements Session { } catch (Throwable t) { handleThrowable(t); } - return null; + return Optional.empty(); } @Override @@ -1420,7 +1420,7 @@ public class SessionImpl implements Session { } catch (Throwable t) { handleThrowable(t); } - return null; + return new ArrayList<>(); } @Override diff --git a/Mage.Common/src/mage/remote/interfaces/ChatSession.java b/Mage.Common/src/mage/remote/interfaces/ChatSession.java index 41b4062a33..f3bb97580c 100644 --- a/Mage.Common/src/mage/remote/interfaces/ChatSession.java +++ b/Mage.Common/src/mage/remote/interfaces/ChatSession.java @@ -27,6 +27,7 @@ */ package mage.remote.interfaces; +import java.util.Optional; import java.util.UUID; /** @@ -34,13 +35,13 @@ import java.util.UUID; */ public interface ChatSession { - UUID getRoomChatId(UUID roomId); + Optional getRoomChatId(UUID roomId); - UUID getTableChatId(UUID tableId); + Optional getTableChatId(UUID tableId); - UUID getGameChatId(UUID gameId); + Optional getGameChatId(UUID gameId); - UUID getTournamentChatId(UUID tournamentId); + Optional getTournamentChatId(UUID tournamentId); boolean joinChat(UUID chatId); diff --git a/Mage.Common/src/mage/remote/interfaces/PlayerActions.java b/Mage.Common/src/mage/remote/interfaces/PlayerActions.java index 1fcde3cdbc..dd80ae37b6 100644 --- a/Mage.Common/src/mage/remote/interfaces/PlayerActions.java +++ b/Mage.Common/src/mage/remote/interfaces/PlayerActions.java @@ -34,6 +34,7 @@ import mage.remote.MageRemoteException; import mage.view.TableView; import mage.view.TournamentView; +import java.util.Optional; import java.util.UUID; /** @@ -71,7 +72,7 @@ public interface PlayerActions { boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password); - TableView getTable(UUID roomId, UUID tableId); + Optional getTable(UUID roomId, UUID tableId); TournamentView getTournament(UUID tournamentId) throws MageRemoteException; diff --git a/Mage.Common/src/mage/remote/interfaces/ServerState.java b/Mage.Common/src/mage/remote/interfaces/ServerState.java index 8e8ea6398b..e0ad641237 100644 --- a/Mage.Common/src/mage/remote/interfaces/ServerState.java +++ b/Mage.Common/src/mage/remote/interfaces/ServerState.java @@ -29,6 +29,7 @@ package mage.remote.interfaces; import java.util.Collection; import java.util.List; +import java.util.Optional; import java.util.UUID; import mage.remote.MageRemoteException; import mage.view.MatchView; diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java index 0d820cc517..072e5673e9 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java @@ -51,7 +51,6 @@ import static javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN; import static javax.swing.JTable.AUTO_RESIZE_OFF; /** - * * @author BetaSteward_at_googlemail.com */ public class ConsolePanel extends javax.swing.JPanel { @@ -148,12 +147,12 @@ public class ConsolePanel extends javax.swing.JPanel { javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( - jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( - jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE) + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE) ); jPanel4.setVerifyInputWhenFocusTarget(false); @@ -181,61 +180,61 @@ public class ConsolePanel extends javax.swing.JPanel { javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( - jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel4Layout.createSequentialGroup() - .addContainerGap() - .addComponent(btnDisconnect) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) - .addGroup(jPanel4Layout.createSequentialGroup() - .addComponent(btnEndSession) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnMuteUser)) - .addGroup(jPanel4Layout.createSequentialGroup() - .addComponent(btnDeActivate) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnLockUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(lblMinutes) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) - .addComponent(spinnerMuteDurationMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) - .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel4Layout.createSequentialGroup() + .addContainerGap() + .addComponent(btnDisconnect) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addGroup(jPanel4Layout.createSequentialGroup() + .addComponent(btnEndSession) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnMuteUser)) + .addGroup(jPanel4Layout.createSequentialGroup() + .addComponent(btnDeActivate) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btnLockUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(lblMinutes) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(spinnerMuteDurationMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( - jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel4Layout.createSequentialGroup() - .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel4Layout.createSequentialGroup() - .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(btnDisconnect) - .addComponent(btnEndSession) - .addComponent(btnMuteUser)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(btnDeActivate) - .addComponent(btnLockUser))) - .addGroup(jPanel4Layout.createSequentialGroup() - .addGap(16, 16, 16) - .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(lblMinutes) - .addComponent(spinnerMuteDurationMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) - .addContainerGap()) + jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel4Layout.createSequentialGroup() + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel4Layout.createSequentialGroup() + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(btnDisconnect) + .addComponent(btnEndSession) + .addComponent(btnMuteUser)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(btnDeActivate) + .addComponent(btnLockUser))) + .addGroup(jPanel4Layout.createSequentialGroup() + .addGap(16, 16, 16) + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(lblMinutes) + .addComponent(spinnerMuteDurationMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( - jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( - jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() - .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addGap(0, 0, 0) - .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) - .addGap(0, 0, 0)) + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(0, 0, 0) + .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0)) ); jSplitPane1.setLeftComponent(jPanel1); @@ -246,12 +245,12 @@ public class ConsolePanel extends javax.swing.JPanel { javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( - jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE) + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( - jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE) + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE) ); btnRemoveTable.setText("Remove Table"); @@ -260,32 +259,32 @@ public class ConsolePanel extends javax.swing.JPanel { javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( - jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel6Layout.createSequentialGroup() - .addContainerGap() - .addComponent(btnRemoveTable) - .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel6Layout.createSequentialGroup() + .addContainerGap() + .addComponent(btnRemoveTable) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( - jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(jPanel6Layout.createSequentialGroup() - .addComponent(btnRemoveTable) - .addContainerGap(31, Short.MAX_VALUE)) + jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel6Layout.createSequentialGroup() + .addComponent(btnRemoveTable) + .addContainerGap(31, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( - jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( - jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() - .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addGap(0, 0, 0) - .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(0, 0, 0) + .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jSplitPane1.setRightComponent(jPanel2); @@ -293,12 +292,12 @@ public class ConsolePanel extends javax.swing.JPanel { javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING) + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING) ); layout.setVerticalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING) + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING) ); }// //GEN-END:initComponents @@ -558,7 +557,7 @@ class UpdateUsersTask extends SwingWorker> { if (peopleIps.get(s) == null) { logger.warn("Found new user: " + u1.getUserName() + ',' + u1.getHost()); peopleIps.put(s, "1"); - } + } break; } } diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index e6ad4bf1d3..996a568c0d 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -211,7 +211,12 @@ public class MageServerImpl implements MageServer { @Override public TableView execute() throws MageException { try { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session to found : " + sessionId); + return null; + } + UUID userId = session.get().getUserId(); Optional _user = UserManager.instance.getUser(userId); if (!_user.isPresent()) { logger.error("User for session not found. session = " + sessionId); @@ -247,9 +252,14 @@ public class MageServerImpl implements MageServer { user.showUserMessage("Create tournament", message); throw new MageException("No message"); } - TableView table = GamesRoomManager.instance.getRoom(roomId).createTournamentTable(userId, options); - logger.debug("Tournament table " + table.getTableId() + " created"); - return table; + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (!room.isPresent()) { + + } else { + TableView table = room.get().createTournamentTable(userId, options); + logger.debug("Tournament table " + table.getTableId() + " created"); + return table; + } } catch (Exception ex) { handleException(ex); } @@ -261,8 +271,13 @@ public class MageServerImpl implements MageServer { @Override public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { execute("removeTable", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TableManager.instance.removeTable(userId, tableId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + TableManager.instance.removeTable(userId, tableId); + } }); } @@ -271,13 +286,23 @@ public class MageServerImpl implements MageServer { return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() { @Override public Boolean execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return false; + } + UUID userId = session.get().getUserId(); logger.debug(name + " joins tableId: " + tableId); if (userId == null) { logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); return false; } - return GamesRoomManager.instance.getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (!room.isPresent()) { + logger.error("room not found : " + roomId); + return false; + } + return room.get().joinTable(userId, tableId, name, playerType, skill, deckList, password); } }); @@ -288,7 +313,12 @@ public class MageServerImpl implements MageServer { return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() { @Override public Boolean execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return false; + } + UUID userId = session.get().getUserId(); if (logger.isTraceEnabled()) { Optional user = UserManager.instance.getUser(userId); user.ifPresent(user1 -> logger.trace("join tourn. tableId: " + tableId + ' ' + name)); @@ -297,7 +327,11 @@ public class MageServerImpl implements MageServer { logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); return false; } - return GamesRoomManager.instance.getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (room.isPresent()) { + return room.get().joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); + } + return null; } }); @@ -308,10 +342,16 @@ public class MageServerImpl implements MageServer { return executeWithResult("submitDeck", sessionId, new ActionWithBooleanResult() { @Override public Boolean execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - boolean ret = TableManager.instance.submitDeck(userId, tableId, deckList); - logger.debug("Session " + sessionId + " submitted deck"); - return ret; + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return false; + } else { + UUID userId = session.get().getUserId(); + boolean ret = TableManager.instance.submitDeck(userId, tableId, deckList); + logger.debug("Session " + sessionId + " submitted deck"); + return ret; + } } }); } @@ -319,9 +359,15 @@ public class MageServerImpl implements MageServer { @Override public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { execute("updateDeck", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TableManager.instance.updateDeck(userId, tableId, deckList); - logger.trace("Session " + sessionId + " updated deck"); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + + } else { + UUID userId = session.get().getUserId(); + TableManager.instance.updateDeck(userId, tableId, deckList); + logger.trace("Session " + sessionId + " updated deck"); + } }); } @@ -329,11 +375,11 @@ public class MageServerImpl implements MageServer { //FIXME: why no sessionId here??? public List getTables(UUID roomId) throws MageException { try { - GamesRoom room = GamesRoomManager.instance.getRoom(roomId); - if (room != null) { - return room.getTables(); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (room.isPresent()) { + return room.get().getTables(); } else { - return null; + return new ArrayList<>(); } } catch (Exception ex) { handleException(ex); @@ -345,47 +391,44 @@ public class MageServerImpl implements MageServer { //FIXME: why no sessionId here??? public List getFinishedMatches(UUID roomId) throws MageException { try { - GamesRoom room = GamesRoomManager.instance.getRoom(roomId); - if (room != null) { - return room.getFinished(); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (room.isPresent()) { + return room.get().getFinished(); } else { - return null; + return new ArrayList<>(); } } catch (Exception ex) { handleException(ex); } - return null; + return new ArrayList<>(); } @Override public List getRoomUsers(UUID roomId) throws MageException { try { - GamesRoom room = GamesRoomManager.instance.getRoom(roomId); - if (room != null) { - return room.getRoomUsersInfo(); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (room.isPresent()) { + return room.get().getRoomUsersInfo(); } else { - return null; + return new ArrayList<>(); } } catch (Exception ex) { handleException(ex); } - return null; + return new ArrayList<>(); } @Override //FIXME: why no sessionId here??? - public TableView getTable(UUID roomId, UUID tableId) throws MageException { + public Optional getTable(UUID roomId, UUID tableId) throws MageException { try { - GamesRoom room = GamesRoomManager.instance.getRoom(roomId); - if (room != null) { - return room.getTable(tableId); - } else { - return null; - } + Optional room = GamesRoomManager.instance.getRoom(roomId); + return room.flatMap(r -> r.getTable(tableId)); + } catch (Exception ex) { handleException(ex); } - return null; + return Optional.empty(); } @Override @@ -405,12 +448,22 @@ public class MageServerImpl implements MageServer { // } @Override public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - if (!TableManager.instance.getController(tableId).changeTableStateToStarting()) { + Optional controller = TableManager.instance.getController(tableId); + if (!controller.isPresent()) { + logger.error("table not found : " + tableId); + return false; + } + if (!controller.get().changeTableStateToStarting()) { return false; } execute("startMatch", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TableManager.instance.startMatch(userId, roomId, tableId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + TableManager.instance.startMatch(userId, roomId, tableId); + } }); return true; } @@ -427,12 +480,22 @@ public class MageServerImpl implements MageServer { // } @Override public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - if (!TableManager.instance.getController(tableId).changeTableStateToStarting()) { + Optional controller = TableManager.instance.getController(tableId); + if (!controller.isPresent()) { + logger.error("table not found : " + tableId); + return false; + } + if (!controller.get().changeTableStateToStarting()) { return false; } execute("startTournament", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TableManager.instance.startTournament(userId, roomId, tableId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + TableManager.instance.startTournament(userId, roomId, tableId); + } }); return true; } @@ -463,8 +526,13 @@ public class MageServerImpl implements MageServer { @Override public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException { execute("joinChat", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ChatManager.instance.joinChat(chatId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ChatManager.instance.joinChat(chatId, userId); + } }); } @@ -472,8 +540,13 @@ public class MageServerImpl implements MageServer { public void leaveChat(final UUID chatId, final String sessionId) throws MageException { execute("leaveChat", sessionId, () -> { if (chatId != null) { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ChatManager.instance.leaveChat(chatId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ChatManager.instance.leaveChat(chatId, userId); + } } else { logger.warn("The chatId is null. sessionId = " + sessionId); } @@ -493,13 +566,18 @@ public class MageServerImpl implements MageServer { @Override //FIXME: why no sessionId here??? - public UUID getRoomChatId(UUID roomId) throws MageException { + public Optional getRoomChatId(UUID roomId) throws MageException { try { - return GamesRoomManager.instance.getRoom(roomId).getChatId(); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (!room.isPresent()) { + logger.error("roomId not found : " + roomId); + return Optional.empty(); + } + return Optional.of(room.get().getChatId()); } catch (Exception ex) { handleException(ex); } - return null; + return Optional.empty(); } @Override @@ -507,8 +585,14 @@ public class MageServerImpl implements MageServer { return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() { @Override public Boolean execute() { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - return TableManager.instance.isTableOwner(tableId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return false; + } else { + UUID userId = session.get().getUserId(); + return TableManager.instance.isTableOwner(tableId, userId); + } } }); } @@ -516,63 +600,99 @@ public class MageServerImpl implements MageServer { @Override public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException { execute("swapSeats", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TableManager.instance.swapSeats(tableId, userId, seatNum1, seatNum2); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + TableManager.instance.swapSeats(tableId, userId, seatNum1, seatNum2); + } }); } @Override public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - TableState tableState = TableManager.instance.getController(tableId).getTableState(); - if (tableState != TableState.WAITING && tableState != TableState.READY_TO_START) { - // table was already started, so player can't leave anymore now - return false; + Optional tableController = TableManager.instance.getController(tableId); + if (tableController.isPresent()) { + TableState tableState = tableController.get().getTableState(); + if (tableState != TableState.WAITING && tableState != TableState.READY_TO_START) { + // table was already started, so player can't leave anymore now + return false; + } + execute("leaveTable", sessionId, () -> { + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (!room.isPresent()) { + logger.error("room not found : " + roomId); + } else { + + room.get().leaveTable(userId, tableId); + } + } + }); + } else { + logger.error("table not found : " + tableId); } - execute("leaveTable", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - GamesRoomManager.instance.getRoom(roomId).leaveTable(userId, tableId); - }); return true; } @Override //FIXME: why no sessionId here??? - public UUID getTableChatId(UUID tableId) throws MageException { + public Optional getTableChatId(UUID tableId) throws MageException { try { return TableManager.instance.getChatId(tableId); } catch (Exception ex) { handleException(ex); } - return null; + return Optional.empty(); } @Override public void joinGame(final UUID gameId, final String sessionId) throws MageException { execute("joinGame", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - GameManager.instance.joinGame(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + GameManager.instance.joinGame(gameId, userId); + } }); } @Override public void joinDraft(final UUID draftId, final String sessionId) throws MageException { execute("joinDraft", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - DraftManager.instance.joinDraft(draftId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + DraftManager.instance.joinDraft(draftId, userId); + } }); } @Override public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { execute("joinTournament", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TournamentManager.instance.joinTournament(tournamentId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + TournamentManager.instance.joinTournament(tournamentId, userId); + } }); } @Override //FIXME: why no sessionId here??? - public UUID getGameChatId(UUID gameId) throws MageException { + public Optional getGameChatId(UUID gameId) throws MageException { try { return GameManager.instance.getChatId(gameId); } catch (Exception ex) { @@ -583,13 +703,13 @@ public class MageServerImpl implements MageServer { @Override //FIXME: why no sessionId here??? - public UUID getTournamentChatId(UUID tournamentId) throws MageException { + public Optional getTournamentChatId(UUID tournamentId) throws MageException { try { return TournamentManager.instance.getChatId(tournamentId); } catch (Exception ex) { handleException(ex); } - return null; + return Optional.empty(); } @Override @@ -661,11 +781,12 @@ public class MageServerImpl implements MageServer { @Override public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { execute("sendCardMark", sessionId, () -> { - Session session = SessionManager.instance.getSession(sessionId); - if (session != null) { - DraftManager.instance.sendCardMark(draftId, session.getUserId(), cardPick); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); } else { - logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); + UUID userId = session.get().getUserId(); + DraftManager.instance.sendCardMark(draftId, userId, cardPick); } }); } @@ -673,11 +794,13 @@ public class MageServerImpl implements MageServer { @Override public void quitMatch(final UUID gameId, final String sessionId) throws MageException { execute("quitMatch", sessionId, () -> { - Session session = SessionManager.instance.getSession(sessionId); - if (session != null) { - GameManager.instance.quitMatch(gameId, session.getUserId()); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); } else { - logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); + UUID userId = session.get().getUserId(); + + GameManager.instance.quitMatch(gameId, userId); } }); } @@ -685,11 +808,13 @@ public class MageServerImpl implements MageServer { @Override public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { execute("quitTournament", sessionId, () -> { - Session session = SessionManager.instance.getSession(sessionId); - if (session != null) { - TournamentManager.instance.quit(tournamentId, session.getUserId()); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); } else { - logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); + UUID userId = session.get().getUserId(); + + TournamentManager.instance.quit(tournamentId, userId); } }); } @@ -697,16 +822,17 @@ public class MageServerImpl implements MageServer { @Override public void quitDraft(final UUID draftId, final String sessionId) throws MageException { execute("quitDraft", sessionId, () -> { - Session session = SessionManager.instance.getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); - return; - } - UUID tableId = DraftManager.instance.getControllerByDraftId(draftId).getTableId(); - Table table = TableManager.instance.getTable(tableId); - if (table.isTournament()) { - UUID tournamentId = table.getTournament().getId(); - TournamentManager.instance.quit(tournamentId, session.getUserId()); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + UUID tableId = DraftManager.instance.getControllerByDraftId(draftId).getTableId(); + Table table = TableManager.instance.getTable(tableId); + if (table.isTournament()) { + UUID tournamentId = table.getTournament().getId(); + TournamentManager.instance.quit(tournamentId, userId); + } } }); } @@ -714,12 +840,13 @@ public class MageServerImpl implements MageServer { @Override public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException { execute("sendPlayerAction", sessionId, () -> { - Session session = SessionManager.instance.getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); - return; + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + GameManager.instance.sendPlayerAction(playerAction, gameId, userId, data); } - GameManager.instance.sendPlayerAction(playerAction, gameId, session.getUserId(), data); }); } @@ -728,8 +855,18 @@ public class MageServerImpl implements MageServer { return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { @Override public Boolean execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - return GamesRoomManager.instance.getRoom(roomId).watchTable(userId, tableId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return false; + } else { + UUID userId = session.get().getUserId(); + if (GamesRoomManager.instance.getRoom(roomId).isPresent()) { + return GamesRoomManager.instance.getRoom(roomId).get().watchTable(userId, tableId); + } else { + return false; + } + } } }); } @@ -742,19 +879,29 @@ public class MageServerImpl implements MageServer { @Override public void watchGame(final UUID gameId, final String sessionId) throws MageException { execute("watchGame", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - GameManager.instance.watchGame(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + GameManager.instance.watchGame(gameId, userId); + } }); } @Override public void stopWatching(final UUID gameId, final String sessionId) throws MageException { execute("stopWatching", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - UserManager.instance.getUser(userId).ifPresent(user -> { - GameManager.instance.stopWatching(gameId, userId); - user.removeGameWatchInfo(gameId); - }); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + UserManager.instance.getUser(userId).ifPresent(user -> { + GameManager.instance.stopWatching(gameId, userId); + user.removeGameWatchInfo(gameId); + }); + } }); } @@ -762,48 +909,78 @@ public class MageServerImpl implements MageServer { @Override public void replayGame(final UUID gameId, final String sessionId) throws MageException { execute("replayGame", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ReplayManager.instance.replayGame(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ReplayManager.instance.replayGame(gameId, userId); + } }); } @Override public void startReplay(final UUID gameId, final String sessionId) throws MageException { execute("startReplay", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ReplayManager.instance.startReplay(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ReplayManager.instance.startReplay(gameId, userId); + } }); } @Override public void stopReplay(final UUID gameId, final String sessionId) throws MageException { execute("stopReplay", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ReplayManager.instance.stopReplay(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ReplayManager.instance.stopReplay(gameId, userId); + } }); } @Override public void nextPlay(final UUID gameId, final String sessionId) throws MageException { execute("nextPlay", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ReplayManager.instance.nextPlay(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ReplayManager.instance.nextPlay(gameId, userId); + } }); } @Override public void previousPlay(final UUID gameId, final String sessionId) throws MageException { execute("previousPlay", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ReplayManager.instance.previousPlay(gameId, userId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ReplayManager.instance.previousPlay(gameId, userId); + } }); } @Override public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { execute("skipForward", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - ReplayManager.instance.skipForward(gameId, userId, moves); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + ReplayManager.instance.skipForward(gameId, userId, moves); + } }); } @@ -832,8 +1009,13 @@ public class MageServerImpl implements MageServer { public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { execute("cheat", sessionId, () -> { if (testMode) { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - GameManager.instance.cheat(gameId, userId, playerId, deckList); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + GameManager.instance.cheat(gameId, userId, playerId, deckList); + } } }); } @@ -844,8 +1026,13 @@ public class MageServerImpl implements MageServer { @Override public Boolean execute() { if (testMode) { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - return GameManager.instance.cheat(gameId, userId, playerId, cardName); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + return GameManager.instance.cheat(gameId, userId, playerId, cardName); + } } return false; } @@ -957,8 +1144,13 @@ public class MageServerImpl implements MageServer { @Override public void removeTable(final String sessionId, final UUID tableId) throws MageException { execute("removeTable", sessionId, () -> { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - TableManager.instance.removeTable(userId, tableId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); + TableManager.instance.removeTable(userId, tableId); + } }); } @@ -971,8 +1163,13 @@ public class MageServerImpl implements MageServer { public void sendFeedbackMessage(final String sessionId, final String username, final String title, final String type, final String message, final String email) throws MageException { if (title != null && message != null) { execute("sendFeedbackMessage", sessionId, () -> { - String host = SessionManager.instance.getSession(sessionId).getHost(); - FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error(String.format("Session not found: %s", sessionId)); + } else { + FeedbackServiceImpl.instance.feedback(username, title, type, message, email, session.get().getHost()); + + } }); } } @@ -1104,8 +1301,14 @@ public class MageServerImpl implements MageServer { @Override public GameView execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - return GameManager.instance.getGameView(gameId, userId, playerId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return null; + } else { + UUID userId = session.get().getUserId(); + return GameManager.instance.getGameView(gameId, userId, playerId); + } } } @@ -1120,8 +1323,14 @@ public class MageServerImpl implements MageServer { @Override public Boolean execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); - return TableManager.instance.watchTable(userId, tableId); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return false; + } else { + UUID userId = session.get().getUserId(); + return TableManager.instance.watchTable(userId, tableId); + } } } @@ -1140,9 +1349,9 @@ public class MageServerImpl implements MageServer { @Override public DraftPickView execute() { - Session session = SessionManager.instance.getSession(sessionId); - if (session != null) { - return DraftManager.instance.sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); + Optional session = SessionManager.instance.getSession(sessionId); + if (session.isPresent()) { + return DraftManager.instance.sendCardPick(draftId, session.get().getUserId(), cardPick, hiddenCards); } else { logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); } @@ -1163,7 +1372,12 @@ public class MageServerImpl implements MageServer { @Override public TableView execute() throws MageException { - UUID userId = SessionManager.instance.getSession(sessionId).getUserId(); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + return null; + } + UUID userId = session.get().getUserId(); Optional _user = UserManager.instance.getUser(userId); if (!_user.isPresent()) { logger.error("User for session not found. session = " + sessionId); @@ -1183,13 +1397,19 @@ public class MageServerImpl implements MageServer { throw new MageException("No message"); } - TableView table = GamesRoomManager.instance.getRoom(roomId).createTable(userId, options); - if (logger.isDebugEnabled()) { - logger.debug("TABLE created - tableId: " + table.getTableId() + ' ' + table.getTableName()); - logger.debug("- " + user.getName() + " userId: " + user.getId()); - logger.debug("- chatId: " + TableManager.instance.getChatId(table.getTableId())); + Optional room = GamesRoomManager.instance.getRoom(roomId); + if (room.isPresent()) { + TableView table = room.get().createTable(userId, options); + if (logger.isDebugEnabled()) { + logger.debug("TABLE created - tableId: " + table.getTableId() + ' ' + table.getTableName()); + logger.debug("- " + user.getName() + " userId: " + user.getId()); + logger.debug("- chatId: " + TableManager.instance.getChatId(table.getTableId())); + } + return table; + } else { + return null; } - return table; } } + } diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 1e7bd375c6..233649b2f3 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -263,17 +263,20 @@ public final class Main { @Override public void handleConnectionException(Throwable throwable, Client client) { - Session session = SessionManager.instance.getSession(client.getSessionId()); - if (session != null) { - + String sessionId = client.getSessionId(); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + UUID userId = session.get().getUserId(); StringBuilder sessionInfo = new StringBuilder(); - Optional user = UserManager.instance.getUser(session.getUserId()); + Optional user = UserManager.instance.getUser(userId); if (user.isPresent()) { sessionInfo.append(user.get().getName()).append(" [").append(user.get().getGameInfo()).append(']'); } else { sessionInfo.append("[user missing] "); } - sessionInfo.append(" at ").append(session.getHost()).append(" sessionId: ").append(session.getId()); + sessionInfo.append(" at ").append(session.get().getHost()).append(" sessionId: ").append(session.get().getId()); if (throwable instanceof ClientDisconnectedException) { // Seems like the random diconnects from public server land here and should not be handled as explicit disconnects // So it should be possible to reconnect to server and continue games if DisconnectReason is set to LostConnection @@ -372,7 +375,12 @@ public final class Main { } else { host = "localhost"; } - SessionManager.instance.getSession(sessionId).setHost(host); + Optional session = SessionManager.instance.getSession(sessionId); + if (!session.isPresent()) { + logger.error("Session not found : " + sessionId); + } else { + session.get().setHost(host); + } return null; } diff --git a/Mage.Server/src/main/java/mage/server/Room.java b/Mage.Server/src/main/java/mage/server/Room.java index 32d6e9a512..fc983b42bb 100644 --- a/Mage.Server/src/main/java/mage/server/Room.java +++ b/Mage.Server/src/main/java/mage/server/Room.java @@ -29,6 +29,7 @@ package mage.server; import java.rmi.Remote; +import java.util.Optional; import java.util.UUID; /** diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 61d60ccafe..e18a28630f 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -27,16 +27,12 @@ */ package mage.server; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import mage.MageException; import mage.constants.Constants; import mage.interfaces.callback.ClientCallback; import mage.players.net.UserData; import mage.players.net.UserGroup; +import mage.server.game.GamesRoom; import mage.server.game.GamesRoomManager; import mage.server.util.ConfigSettings; import mage.server.util.SystemUtil; @@ -47,8 +43,13 @@ import org.jboss.remoting.callback.Callback; import org.jboss.remoting.callback.HandleCallbackException; import org.jboss.remoting.callback.InvokerCallbackHandler; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** - * * @author BetaSteward_at_googlemail.com */ public class Session { @@ -129,7 +130,7 @@ public class Session { } } - static private String validateUserName(String userName) { + private static String validateUserName(String userName) { if (userName.equals("Admin")) { return "User name Admin already in use"; } @@ -152,7 +153,7 @@ public class Session { return null; } - static private String validatePassword(String password, String userName) { + private static String validatePassword(String password, String userName) { ConfigSettings config = ConfigSettings.instance; if (password.length() < config.getMinPasswordLength()) { return "Password may not be shorter than " + config.getMinPasswordLength() + " characters"; @@ -171,7 +172,7 @@ public class Session { return null; } - static private String validateEmail(String email) { + private static String validateEmail(String email) { if (email == null || email.isEmpty()) { return "Email address cannot be blank"; @@ -248,10 +249,12 @@ public class Session { } this.userId = user.getId(); if (reconnect) { // must be connected to receive the message - UUID chatId = GamesRoomManager.instance.getRoom(GamesRoomManager.instance.getMainRoomId()).getChatId(); - if (chatId != null) { - ChatManager.instance.joinChat(chatId, userId); + Optional room = GamesRoomManager.instance.getRoom(GamesRoomManager.instance.getMainRoomId()); + if (!room.isPresent()) { + logger.error("main room not found"); + return null; } + ChatManager.instance.joinChat(room.get().getChatId(), userId); ChatManager.instance.sendReconnectMessage(userId); } return null; @@ -331,7 +334,7 @@ public class Session { return; //user was already disconnected by other thread } User user = _user.get(); - if(!user.isConnected()){ + if (!user.isConnected()) { return; } if (!user.getSessionId().equals(sessionId)) { @@ -381,7 +384,7 @@ public class Session { callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { ex.printStackTrace(); - UserManager.instance.getUser(userId).ifPresent(user-> { + UserManager.instance.getUser(userId).ifPresent(user -> { logger.warn("SESSION CALLBACK EXCEPTION - " + user.getName() + " userId " + userId); logger.warn(" - method: " + call.getMethod()); logger.warn(" - cause: " + getBasicCause(ex).toString()); diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index fb4032904f..1a8abc9f9d 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -49,15 +49,15 @@ public enum SessionManager { private final ConcurrentHashMap sessions = new ConcurrentHashMap<>(); - public Session getSession(@Nonnull String sessionId) { + public Optional getSession(@Nonnull String sessionId) { Session session = sessions.get(sessionId); if (session != null && session.getUserId() != null && UserManager.instance.getUser(session.getUserId()) == null) { logger.error("User for session " + sessionId + " with userId " + session.getUserId() + " is missing. Session removed."); // can happen if user from same host signs in multiple time with multiple clients, after he disconnects with one client disconnect(sessionId, DisconnectReason.ConnectingOtherInstance); - return null; + return Optional.empty(); } - return session; + return Optional.of(session); } public void createSession(String sessionId, InvokerCallbackHandler callbackHandler) { @@ -168,26 +168,26 @@ public enum SessionManager { */ public void disconnectUser(String sessionId, String userSessionId) { if (isAdmin(sessionId)) { - User userAdmin; - if ((userAdmin = getUserFromSession(sessionId)) != null) { - User user; - if ((user = getUserFromSession(userSessionId)) != null) { + getUserFromSession(sessionId).ifPresent(admin -> { + Optional u = getUserFromSession(userSessionId); + if (u.isPresent()) { + User user = u.get(); user.showUserMessage("Admin operation", "Your session was disconnected by Admin."); - userAdmin.showUserMessage("Admin action", "User" + user.getName() + " was disconnected."); + admin.showUserMessage("Admin action", "User" + user.getName() + " was disconnected."); disconnect(userSessionId, DisconnectReason.AdminDisconnect); } else { - userAdmin.showUserMessage("Admin operation", "User with sessionId " + userSessionId + " could not be found!"); + admin.showUserMessage("Admin operation", "User with sessionId " + userSessionId + " could not be found!"); } - } + }); } } - private User getUserFromSession(String sessionId) { - Session session = getSession(sessionId); - if (session == null) { - return null; + private Optional getUserFromSession(String sessionId) { + Optional session = getSession(sessionId); + if (!session.isPresent()) { + return Optional.empty(); } - return UserManager.instance.getUser(session.getUserId()).get(); + return UserManager.instance.getUser(session.get().getUserId()); } public void endUserSession(String sessionId, String userSessionId) { diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 40af1f89c8..e45b0ed816 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -242,7 +242,7 @@ public class TableController { newTournamentPlayer.setState(oldTournamentPlayer.getState()); newTournamentPlayer.setReplacedTournamentPlayer(oldTournamentPlayer); - DraftManager.instance.getController(table.getId()).replacePlayer(oldPlayer, newPlayer); + DraftManager.instance.getController(table.getId()).ifPresent(controller -> controller.replacePlayer(oldPlayer, newPlayer)); return true; } @@ -307,29 +307,29 @@ public class TableController { user.showUserMessage("Join Table", message); return false; } - + boolean restrictedColor = false; String badColor = ""; int colorVal = edhPowerLevel % 10; if (colorVal == 6 && deckEdhPowerLevel >= 10000000) { restrictedColor = true; - badColor = "white"; + badColor = "white"; } if (colorVal == 4 && deckEdhPowerLevel % 10000000 >= 1000000) { restrictedColor = true; - badColor = "blue"; + badColor = "blue"; } if (colorVal == 3 && deckEdhPowerLevel % 1000000 >= 100000) { restrictedColor = true; - badColor = "black"; + badColor = "black"; } if (colorVal == 2 && deckEdhPowerLevel % 100000 >= 10000) { restrictedColor = true; - badColor = "red"; + badColor = "red"; } if (colorVal == 1 && deckEdhPowerLevel % 10000 >= 1000) { restrictedColor = true; - badColor = "green"; + badColor = "green"; } if (restrictedColor) { String message = new StringBuilder("Your deck contains ") diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index 135c630c3d..a8f0bd5f37 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -49,6 +49,7 @@ import mage.game.match.Match; import mage.game.match.MatchOptions; import mage.game.tournament.Tournament; import mage.game.tournament.TournamentOptions; +import mage.game.tournament.TournamentPlayer; import mage.players.Player; import mage.server.game.GameController; import mage.server.game.GameManager; @@ -114,19 +115,22 @@ public enum TableManager { return tables.get(tableId); } - public Match getMatch(UUID tableId) { + public Optional getMatch(UUID tableId) { if (controllers.containsKey(tableId)) { - return controllers.get(tableId).getMatch(); + return Optional.of(controllers.get(tableId).getMatch()); } - return null; + return Optional.empty(); } public Collection getTables() { return tables.values(); } - public TableController getController(UUID tableId) { - return controllers.get(tableId); + public Optional getController(UUID tableId) { + if (controllers.containsKey(tableId)) { + return Optional.of(controllers.get(tableId)); + } + return Optional.empty(); } public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException { @@ -214,11 +218,11 @@ public enum TableManager { } } - public UUID getChatId(UUID tableId) { + public Optional getChatId(UUID tableId) { if (controllers.containsKey(tableId)) { - return controllers.get(tableId).getChatId(); + return Optional.of(controllers.get(tableId).getChatId()); } - return null; + return Optional.empty(); } /** @@ -313,9 +317,9 @@ public enum TableManager { } } - public void addPlayer(UUID userId, UUID tableId, Player player, String playerType, Deck deck) throws GameException { + public void addPlayer(UUID userId, UUID tableId, TournamentPlayer player) throws GameException { if (controllers.containsKey(tableId)) { - controllers.get(tableId).addPlayer(userId, player, playerType, deck); + controllers.get(tableId).addPlayer(userId, player.getPlayer(), player.getPlayerType(), player.getDeck()); } } @@ -352,10 +356,10 @@ public enum TableManager { Collection users = UserManager.instance.getUsers(); logger.debug("--------User: " + users.size() + " [userId | since | lock | name -----------------------"); for (User user : users) { - Session session = SessionManager.instance.getSession(user.getSessionId()); + Optional session = SessionManager.instance.getSession(user.getSessionId()); String sessionState = "N"; - if (session != null) { - if (session.isLocked()) { + if (session.isPresent()) { + if (session.get().isLocked()) { sessionState = "L"; } else { sessionState = "+"; @@ -390,8 +394,7 @@ public enum TableManager { if (table.getState() != TableState.FINISHED) { // remove tables and games not valid anymore logger.debug(table.getId() + " [" + table.getName() + "] " + formatter.format(table.getStartTime() == null ? table.getCreateTime() : table.getCreateTime()) + " (" + table.getState().toString() + ") " + (table.isTournament() ? "- Tournament" : "")); - TableController tableController = getController(table.getId()); - if (tableController != null) { + getController(table.getId()).ifPresent(tableController -> { if ((table.isTournament() && !tableController.isTournamentStillValid()) || (!table.isTournament() && !tableController.isMatchTableStillValid())) { try { @@ -401,7 +404,7 @@ public enum TableManager { logger.error(e); } } - } + }); } } catch (Exception ex) { logger.debug("Table Health check error tableId: " + table.getId()); diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index f6d6b06375..78fe830993 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -27,14 +27,8 @@ */ package mage.server; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import mage.cards.decks.Deck; @@ -246,10 +240,9 @@ public class User { public void fireCallback(final ClientCallback call) { if (isConnected()) { - Session session = SessionManager.instance.getSession(sessionId); - if (session != null) { - session.fireCallback(call); - } + SessionManager.instance.getSession(sessionId).ifPresent(session -> + session.fireCallback(call) + ); } } @@ -378,8 +371,13 @@ public class User { entry.getValue().construct(0); // TODO: Check if this is correct } for (Entry entry : sideboarding.entrySet()) { - TableController controller = TableManager.instance.getController(entry.getKey()); - ccSideboard(entry.getValue(), entry.getKey(), controller.getRemainingTime(), controller.getOptions().isLimited()); + Optional controller = TableManager.instance.getController(entry.getKey()); + if(controller.isPresent()) { + ccSideboard(entry.getValue(), entry.getKey(), controller.get().getRemainingTime(), controller.get().getOptions().isLimited()); + } + else{ + logger.error("sideboarding id not found : "+entry.getKey()); + } } ServerMessagesUtil.instance.incReconnects(); logger.trace(userName + " ended reconnect"); @@ -784,8 +782,11 @@ public class User { if (table.getState() == TableState.FINISHED) { number++; } else { - TableController tableController = TableManager.instance.getController(table.getId()); - if (tableController != null && tableController.isUserStillActive(userId)) { + Optional tableController = TableManager.instance.getController(table.getId()); + if(!tableController.isPresent()){ + logger.error("table not found : "+table.getId()); + } + else if (tableController.get().isUserStillActive(userId)) { number++; } } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index 24aa15760d..b89624fc81 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -30,6 +30,7 @@ package mage.server.draft; import java.io.File; import java.util.Map.Entry; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -129,11 +130,11 @@ public class DraftController { checkStart(); } - public DraftSession getDraftSession(UUID playerId) { + public Optional getDraftSession(UUID playerId) { if (draftSessions.containsKey(playerId)) { - return draftSessions.get(playerId); + return Optional.of(draftSessions.get(playerId)); } - return null; + return Optional.empty(); } public boolean replacePlayer(Player oldPlayer, Player newPlayer) { diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftManager.java b/Mage.Server/src/main/java/mage/server/draft/DraftManager.java index b566475855..3a123ab9e4 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftManager.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftManager.java @@ -28,6 +28,7 @@ package mage.server.draft; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -87,12 +88,7 @@ public enum DraftManager { return draftControllers.get(draftId); } - public DraftController getController(UUID tableId) { - for (DraftController controller: draftControllers.values()) { - if (controller.getTableId().equals(tableId)) { - return controller; - } - } - return null; + public Optional getController(UUID tableId) { + return draftControllers.values().stream().filter(controller -> controller.getTableId().equals(tableId)).findFirst(); } } diff --git a/Mage.Server/src/main/java/mage/server/game/GameManager.java b/Mage.Server/src/main/java/mage/server/game/GameManager.java index 59fe34a923..ba72920585 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameManager.java +++ b/Mage.Server/src/main/java/mage/server/game/GameManager.java @@ -28,6 +28,7 @@ package mage.server.game; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mage.cards.decks.DeckCardLists; @@ -59,12 +60,12 @@ public enum GameManager { } } - public UUID getChatId(UUID gameId) { + public Optional getChatId(UUID gameId) { GameController gameController = gameControllers.get(gameId); if (gameController != null) { - return gameController.getChatId(); + return Optional.of(gameController.getChatId()); } - return null; + return Optional.empty(); } public void sendPlayerUUID(UUID gameId, UUID userId, UUID data) { diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoom.java b/Mage.Server/src/main/java/mage/server/game/GamesRoom.java index 1466c542f8..8e62b5dcc9 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoom.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoom.java @@ -29,6 +29,7 @@ package mage.server.game; import java.util.List; +import java.util.Optional; import java.util.UUID; import mage.MageException; import mage.cards.decks.DeckCardLists; @@ -55,7 +56,7 @@ public interface GamesRoom extends Room { TableView createTournamentTable(UUID userId, TournamentOptions options); void removeTable(UUID userId, UUID tableId); void removeTable(UUID tableId); - TableView getTable(UUID tableId); + Optional getTable(UUID tableId); void leaveTable(UUID userId, UUID tableId); boolean watchTable(UUID userId, UUID tableId) throws MageException; 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 6d70bf273c..e9b6bc74d2 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java @@ -28,10 +28,7 @@ package mage.server.game; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -180,11 +177,11 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public TableView getTable(UUID tableId) { + public Optional getTable(UUID tableId) { if (tables.containsKey(tableId)) { - return new TableView(tables.get(tableId)); + return Optional.of(new TableView(tables.get(tableId))); } - return null; + return Optional.empty(); } @Override diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoomManager.java b/Mage.Server/src/main/java/mage/server/game/GamesRoomManager.java index 9c392ed707..88db75c7c3 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomManager.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomManager.java @@ -28,6 +28,7 @@ package mage.server.game; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -57,8 +58,12 @@ public enum GamesRoomManager { return mainRoomId; } - public GamesRoom getRoom(UUID roomId) { - return rooms.get(roomId); + public Optional getRoom(UUID roomId) { + if(rooms.containsKey(roomId)) { + return Optional.of(rooms.get(roomId)); + } + return Optional.empty(); + } public void removeTable(UUID tableId) { 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 e3c26f57b9..d8ec2b52ba 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -249,16 +249,21 @@ public class TournamentController { table.setState(TableState.WAITING); TournamentPlayer player1 = pair.getPlayer1(); TournamentPlayer player2 = pair.getPlayer2(); - tableManager.addPlayer(getPlayerUserId(player1.getPlayer().getId()), table.getId(), player1.getPlayer(), player1.getPlayerType(), player1.getDeck()); - tableManager.addPlayer(getPlayerUserId(player2.getPlayer().getId()), table.getId(), player2.getPlayer(), player2.getPlayerType(), player2.getDeck()); - table.setState(TableState.STARTING); - tableManager.startTournamentSubMatch(null, table.getId()); - Match match = tableManager.getMatch(table.getId()); - match.setTableId(tableId); - pair.setMatch(match); - pair.setTableId(table.getId()); - player1.setState(TournamentPlayerState.DUELING); - player2.setState(TournamentPlayerState.DUELING); + Optional user1Id = getPlayerUserId(player1.getPlayer().getId()); + Optional user2Id = getPlayerUserId(player2.getPlayer().getId()); + if (user1Id.isPresent() && user2Id.isPresent()) { + tableManager.addPlayer(getPlayerUserId(player1.getPlayer().getId()).get(), table.getId(), player1); + tableManager.addPlayer(getPlayerUserId(player2.getPlayer().getId()).get(), table.getId(), player2); + table.setState(TableState.STARTING); + tableManager.startTournamentSubMatch(null, table.getId()); + tableManager.getMatch(table.getId()).ifPresent(match -> { + match.setTableId(tableId); + pair.setMatch(match); + pair.setTableId(table.getId()); + player1.setState(TournamentPlayerState.DUELING); + player2.setState(TournamentPlayerState.DUELING); + }); + } } catch (GameException ex) { logger.fatal("TournamentController startMatch error", ex); } @@ -271,18 +276,20 @@ public class TournamentController { table.setTournamentSubTable(true); table.setTournament(tournament); table.setState(TableState.WAITING); - - for (TournamentPlayer player : round.getAllPlayers()) { - tableManager.addPlayer(getPlayerUserId(player.getPlayer().getId()), table.getId(), player.getPlayer(), player.getPlayerType(), player.getDeck()); - } - table.setState(TableState.STARTING); - tableManager.startTournamentSubMatch(null, table.getId()); - Match match = tableManager.getMatch(table.getId()); - match.setTableId(tableId); - round.setMatch(match); - round.setTableId(table.getId()); - for (TournamentPlayer player : round.getAllPlayers()) { - player.setState(TournamentPlayerState.DUELING); + if (round.getAllPlayers().stream().allMatch(tournamentPlayer -> getPlayerUserId(tournamentPlayer.getPlayer().getId()).isPresent())) { + for (TournamentPlayer player : round.getAllPlayers()) { + tableManager.addPlayer(getPlayerUserId(player.getPlayer().getId()).get(), table.getId(), player); + } + table.setState(TableState.STARTING); + tableManager.startTournamentSubMatch(null, table.getId()); + tableManager.getMatch(table.getId()).ifPresent(match -> { + match.setTableId(tableId); + round.setMatch(match); + round.setTableId(table.getId()); + for (TournamentPlayer player : round.getAllPlayers()) { + player.setState(TournamentPlayerState.DUELING); + } + }); } } catch (GameException ex) { logger.fatal("TournamentController startMatch error", ex); @@ -307,9 +314,13 @@ public class TournamentController { if (tournamentSessions.containsKey(playerId)) { TournamentSession tournamentSession = tournamentSessions.get(playerId); tournamentSession.construct(timeout); - UserManager.instance.getUser(getPlayerUserId(playerId)).get().addConstructing(playerId, tournamentSession); - TournamentPlayer player = tournament.getPlayer(playerId); - player.setState(TournamentPlayerState.CONSTRUCTING); + getPlayerUserId(playerId).ifPresent(userId -> { + UserManager.instance.getUser(userId).ifPresent(user -> { + user.addConstructing(playerId, tournamentSession); + TournamentPlayer player = tournament.getPlayer(playerId); + player.setState(TournamentPlayerState.CONSTRUCTING); + }); + }); } } @@ -385,13 +396,11 @@ public class TournamentController { if (!checkToReplaceDraftPlayerByAi(userId, tournamentPlayer)) { this.abortDraftTournament(); } else { - DraftController draftController = DraftManager.instance.getController(tableId); - if (draftController != null) { - DraftSession draftSession = draftController.getDraftSession(playerId); - if (draftSession != null) { - DraftManager.instance.kill(draftSession.getDraftId(), userId); - } - } + DraftManager.instance.getController(tableId).ifPresent(draftController -> { + draftController.getDraftSession(playerId).ifPresent(draftSession -> + DraftManager.instance.kill(draftSession.getDraftId(), userId)); + + }); } status = TourneyQuitStatus.DURING_DRAFTING; } else if (tournamentPlayer.getState() == TournamentPlayerState.CONSTRUCTING) { @@ -419,8 +428,8 @@ public class TournamentController { // replace player that quits with draft bot if (humans > 1) { Optional user = UserManager.instance.getUser(userId); - TableController tableController = TableManager.instance.getController(tableId); - if (tableController != null) { + TableManager.instance.getController(tableId).ifPresent(tableController -> { + String replacePlayerName = "Draftbot"; if (user.isPresent()) { replacePlayerName = "Draftbot (" + user.get().getName() + ')'; @@ -432,19 +441,14 @@ public class TournamentController { user.get().removeTournament(leavingPlayer.getPlayer().getId()); } ChatManager.instance.broadcast(chatId, "", leavingPlayer.getPlayer().getLogName() + " was replaced by draftbot", MessageColor.BLACK, true, MessageType.STATUS, null); - } + }); return true; } return false; } - private UUID getPlayerUserId(UUID playerId) { - for (Entry entry : userPlayerMap.entrySet()) { - if (entry.getValue().equals(playerId)) { - return entry.getKey(); - } - } - return null; + private Optional getPlayerUserId(UUID playerId) { + return userPlayerMap.entrySet().stream().filter(entry -> entry.getValue().equals(playerId)).map(Entry::getKey).findFirst(); } public TournamentView getTournamentView() { @@ -453,7 +457,7 @@ public class TournamentController { private void abortDraftTournament() { tournament.setAbort(true); - DraftManager.instance.getController(tableId).abortDraft(); + DraftManager.instance.getController(tableId).ifPresent(DraftController::abortDraft); } public boolean isAbort() { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java index 8015e52615..58e8669207 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java @@ -28,6 +28,7 @@ package mage.server.tournament; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -85,10 +86,14 @@ public enum TournamentManager { return null; } - public UUID getChatId(UUID tournamentId) { - return controllers.get(tournamentId).getChatId(); + public Optional getChatId(UUID tournamentId) { + if(controllers.containsKey(tournamentId)) { + return Optional.of(controllers.get(tournamentId).getChatId()); + } + return Optional.empty(); } + public void removeTournament(UUID tournamentId) { TournamentController tournamentController = controllers.get(tournamentId); if (tournamentController != null) { diff --git a/Mage.Tests/src/test/java/org/mage/test/load/LoadTest.java b/Mage.Tests/src/test/java/org/mage/test/load/LoadTest.java index 5e551f1874..09a96fe007 100644 --- a/Mage.Tests/src/test/java/org/mage/test/load/LoadTest.java +++ b/Mage.Tests/src/test/java/org/mage/test/load/LoadTest.java @@ -107,7 +107,7 @@ public class LoadTest { if (!session.joinTable(roomId, table.getTableId(), TEST_USER_NAME + i, "Human", 1, deckList,"")) { log.error("Error while joining table"); - Assert.assertTrue("Error while joining table", false); + Assert.fail("Error while joining table"); return; } @@ -121,7 +121,7 @@ public class LoadTest { // connect to the table with the same deck if (!session2.joinTable(roomId2, table.getTableId(), TEST_USER_NAME_2 + i, "Human", 1, deckList,"")) { log.error("Error while joining table"); - Assert.assertTrue("Error while joining table", false); + Assert.fail("Error while joining table"); return; } @@ -179,7 +179,7 @@ public class LoadTest { if (!session.joinTable(roomId, table.getTableId(), TEST_USER_NAME + i, "Human", 1, deckList,"")) { log.error("Error while joining table"); - Assert.assertTrue("Error while joining table", false); + Assert.fail("Error while joining table"); return true; } @@ -195,7 +195,7 @@ public class LoadTest { // connect to the table with the same deck if (!session2.joinTable(roomId2, table.getTableId(), TEST_USER_NAME_2 + i, "Human", 1, deckList,"")) { log.error("Error while joining table"); - Assert.assertTrue("Error while joining table", false); + Assert.fail("Error while joining table"); return true; }