From e45345d87a01ddfec627d42d2df6be97b10f00af Mon Sep 17 00:00:00 2001 From: betasteward Date: Sat, 23 May 2015 10:18:36 -0400 Subject: [PATCH] initial commit - only table pane chat is working atm --- .gitignore | 3 +- Mage.Client/pom.xml | 5 + .../src/main/java/mage/client/MageFrame.java | 138 +- .../src/main/java/mage/client/cards/Card.java | 8 +- .../main/java/mage/client/chat/ChatPanel.java | 82 +- .../components/ability/AbilityPicker.java | 13 +- .../client/deckeditor/DeckEditorPanel.java | 19 +- .../mage/client/dialog/ConnectDialog.java | 6 +- .../mage/client/dialog/FeedbackDialog.java | 2 +- .../mage/client/dialog/JoinTableDialog.java | 11 +- .../mage/client/dialog/NewTableDialog.java | 27 +- .../client/dialog/NewTournamentDialog.java | 32 +- .../mage/client/dialog/PreferencesDialog.java | 4 +- .../client/dialog/TableWaitingDialog.java | 33 +- .../mage/client/dialog/UserRequestDialog.java | 7 +- .../java/mage/client/draft/DraftPanel.java | 15 +- .../java/mage/client/game/AbilityPicker.java | 13 +- .../java/mage/client/game/FeedbackPanel.java | 17 +- .../main/java/mage/client/game/GamePanel.java | 73 +- .../java/mage/client/game/PlayAreaPanel.java | 32 +- .../java/mage/client/game/PlayerPanelExt.java | 17 +- .../plugins/adapters/MageActionCallback.java | 17 +- .../client/remote/CallbackClientImpl.java | 128 +- .../mage/client/table/TablePlayerPanel.java | 11 +- .../java/mage/client/table/TablesPane.java | 2 +- .../java/mage/client/table/TablesPanel.java | 95 +- .../client/table/TournamentPlayerPanel.java | 11 +- .../client/tournament/TournamentPanel.java | 29 +- .../mage/client/unusedFiles/PlayerPanel.java | 9 +- .../client/util/DefaultActionCallback.java | 9 +- .../mage/client/game/MultiConnectTest.java | 59 +- .../src/mage/interfaces/MageServer.java | 316 +- .../src/mage/interfaces/ServerState.java | 11 +- Mage.Common/src/mage/remote/Session.java | 98 +- Mage.Common/src/mage/remote/SessionImpl.java | 2915 ++++++++--------- Mage.Network/pom.xml | 37 + .../main/java/org/mage/network/Client.java | 388 +++ .../main/java/org/mage/network/Server.java | 137 + .../network/handlers/HeartbeatHandler.java | 35 + .../network/handlers/PingMessageHandler.java | 26 + .../handlers/client/ChatMessageHandler.java | 37 + .../handlers/client/ChatRoomHandler.java | 46 + .../ClientRegisteredMessageHandler.java | 25 + .../client/InformClientMessageHandler.java | 25 + .../handlers/client/MessageHandler.java | 12 + .../handlers/server/ChatMessageHandler.java | 38 + .../handlers/server/ChatRoomIdHandler.java | 39 + .../handlers/server/ConnectionHandler.java | 19 + .../server/JoinChatMessageHandler.java | 37 + .../server/LeaveChatMessageHandler.java | 38 + .../server/RegisterClientMessageHandler.java | 43 + .../mage/network/interfaces/MageClient.java | 24 + .../mage/network/interfaces/MageServer.java | 23 + .../mage/network/model/ChatRoomIdMessage.java | 22 + .../mage/network/model/ChatRoomIdRequest.java | 22 + .../model/ClientRegisteredMessage.java | 21 + .../network/model/InformClientMessage.java | 26 + .../mage/network/model/JoinChatMessage.java | 22 + .../mage/network/model/LeaveChatMessage.java | 22 + .../org/mage/network/model/MessageType.java | 11 + .../org/mage/network/model/PingMessage.java | 11 + .../org/mage/network/model/PongMessage.java | 11 + .../network/model/ReceiveChatMessage.java | 29 + .../network/model/RegisterClientMessage.java | 27 + .../mage/network/model/SendChatMessage.java | 28 + Mage.Server.Console/pom.xml | 5 + .../mage/server/console/ConsoleFrame.java | 80 +- .../mage/server/console/ConsolePanel.java | 29 +- Mage.Server/pom.xml | 5 + .../main/java/mage/server/ChatManager.java | 86 +- .../main/java/mage/server/ChatSession.java | 55 +- .../main/java/mage/server/MageServerImpl.java | 1127 ------- .../src/main/java/mage/server/Main.java | 1309 +++++++- .../src/main/java/mage/server/Session.java | 55 +- .../main/java/mage/server/SessionManager.java | 30 +- .../java/mage/server/TableController.java | 8 +- .../src/main/java/mage/server/User.java | 3 +- .../java/mage/server/game/GameController.java | 16 +- .../tournament/TournamentController.java | 12 +- Mage.Tests/pom.xml | 6 +- .../mage/test/load/LoadCallbackClient.java | 252 +- .../java/org/mage/test/load/LoadTest.java | 600 ++-- .../org/mage/test/load/SimpleMageClient.java | 135 +- pom.xml | 1 + 84 files changed, 5370 insertions(+), 3992 deletions(-) create mode 100644 Mage.Network/pom.xml create mode 100644 Mage.Network/src/main/java/org/mage/network/Client.java create mode 100644 Mage.Network/src/main/java/org/mage/network/Server.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/HeartbeatHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/PingMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/client/ChatMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/client/ChatRoomHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/client/ClientRegisteredMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/client/InformClientMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/client/MessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/server/ChatMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/server/ChatRoomIdHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/server/ConnectionHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/server/JoinChatMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/server/LeaveChatMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/handlers/server/RegisterClientMessageHandler.java create mode 100644 Mage.Network/src/main/java/org/mage/network/interfaces/MageClient.java create mode 100644 Mage.Network/src/main/java/org/mage/network/interfaces/MageServer.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdRequest.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/ClientRegisteredMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/InformClientMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/JoinChatMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/LeaveChatMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/MessageType.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/PingMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/PongMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/ReceiveChatMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/RegisterClientMessage.java create mode 100644 Mage.Network/src/main/java/org/mage/network/model/SendChatMessage.java delete mode 100644 Mage.Server/src/main/java/mage/server/MageServerImpl.java diff --git a/.gitignore b/.gitignore index 2d4ddf9ef24..1e1aa9de62a 100644 --- a/.gitignore +++ b/.gitignore @@ -87,4 +87,5 @@ Mage.Server.Plugins/Mage.Draft.8PlayerBooster/target /Utils/*_unimplemented.txt *.netbeans_automatic_build *.txt -Mage.Client/serverlist.txt \ No newline at end of file +Mage.Client/serverlist.txt +/Mage.Network/target/ \ No newline at end of file diff --git a/Mage.Client/pom.xml b/Mage.Client/pom.xml index e0387aecee3..6ec734e24b6 100644 --- a/Mage.Client/pom.xml +++ b/Mage.Client/pom.xml @@ -25,6 +25,11 @@ mage-common ${project.version} + + ${project.groupId} + mage-network + ${project.version} + com.googlecode.jspf jspf-core diff --git a/Mage.Client/src/main/java/mage/client/MageFrame.java b/Mage.Client/src/main/java/mage/client/MageFrame.java index 785715924c4..365358c9c1a 100644 --- a/Mage.Client/src/main/java/mage/client/MageFrame.java +++ b/Mage.Client/src/main/java/mage/client/MageFrame.java @@ -58,13 +58,13 @@ import mage.client.util.audio.MusicPlayer; import mage.client.util.gui.ArrowBuilder; import mage.client.util.stats.UpdateMemUsageTask; import mage.components.ImagePanel; -import mage.interfaces.MageClient; +//import mage.interfaces.MageClient; import mage.interfaces.callback.CallbackClient; import mage.interfaces.callback.ClientCallback; import mage.remote.Connection; import mage.remote.Connection.ProxyType; -import mage.remote.Session; -import mage.remote.SessionImpl; +//import mage.remote.Session; +//import mage.remote.SessionImpl; import mage.utils.MageVersion; import mage.view.GameEndView; import org.apache.log4j.Logger; @@ -92,10 +92,16 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; +import mage.client.util.audio.AudioManager; +import mage.interfaces.ServerState; +import mage.view.ChatMessage; import mage.view.UserRequestMessage; import net.java.truevfs.access.TArchiveDetector; import net.java.truevfs.access.TConfig; import net.java.truevfs.kernel.spec.FsAccessOption; +import org.mage.network.Client; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.MessageType; /** * @author BetaSteward_at_googlemail.com @@ -111,10 +117,13 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private static MageFrame instance; - private static Session session; +// private static Session session; +// public static MageClient client; + private static Client client; + private ServerState serverState; private ConnectDialog connectDialog; private final ErrorDialog errorDialog; - private static CallbackClient callbackClient; +// private static CallbackClient callbackClient; private static final Preferences prefs = Preferences.userNodeForPackage(MageFrame.class); private JLabel title; private Rectangle titleRectangle; @@ -136,13 +145,17 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private static long startTime; - /** - * @return the session - */ - public static Session getSession() { - return session; - } +// /** +// * @return the session +// */ +// public static Session getSession() { +// return session; +// } + public static Client getClient() { + return client; + } + public static JDesktopPane getDesktop() { return desktopPane; } @@ -159,7 +172,6 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { return grayMode; } - @Override public MageVersion getVersion() { return version; } @@ -203,8 +215,8 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { DialogManager.updateParams(768, 1024, false); this.setExtendedState(JFrame.MAXIMIZED_BOTH); - session = new SessionImpl(this); - callbackClient = new CallbackClientImpl(this); +// session = new SessionImpl(this); +// callbackClient = new CallbackClientImpl(this); connectDialog = new ConnectDialog(); desktopPane.add(connectDialog, JLayeredPane.POPUP_LAYER); errorDialog = new ErrorDialog(); @@ -212,12 +224,12 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { desktopPane.add(errorDialog, JLayeredPane.POPUP_LAYER); ui.addComponent(MageComponents.DESKTOP_PANE, desktopPane); - pingTaskExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - session.ping(); - } - }, 60, 60, TimeUnit.SECONDS); +// pingTaskExecutor.scheduleAtFixedRate(new Runnable() { +// @Override +// public void run() { +// session.ping(); +// } +// }, 60, 60, TimeUnit.SECONDS); updateMemUsageTask = new UpdateMemUsageTask(jMemUsageLabel); @@ -330,7 +342,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { public void setWindowTitle() { setTitle(TITLE_NAME + " Client: " + version == null ? "" : version.toString() + " Server: " - + ((session != null && session.isConnected()) ? session.getVersionInfo():"")); + + ((client != null && client.isConnected()) ? serverState.getVersion().toString():"")); } private void addTooltipContainer() { @@ -682,15 +694,14 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { tableWaitingDialog.showDialog(roomId, tableId, isTournament); } - public static boolean connect(Connection connection) { - boolean result = session.connect(connection); - MageFrame.getInstance().setWindowTitle(); + public boolean connect(Connection connection) { + boolean result = client.connect(connection.getUsername(), connection.getHost(), connection.getPort(), version); return result; } - public static boolean stopConnecting() { - return session.stopConnecting(); - } +// public static boolean stopConnecting() { +// return session.stopConnecting(); +// } public boolean autoConnect() { boolean autoConnectParamValue = Boolean.parseBoolean(prefs.get("autoConnect", "false")); @@ -730,8 +741,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { connection.setAllowRequestShowHandCards(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, "true").equals("true")); connection.setUserSkipPrioritySteps(PreferencesDialog.getUserSkipPrioritySteps()); logger.debug("connecting (auto): " + proxyType + " " + proxyServer + " " + proxyPort + " " + proxyUsername); - if (MageFrame.connect(connection)) { - showGames(false); + if (connect(connection)) { return true; } else { showMessage("Unable to connect to server"); @@ -915,9 +925,9 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { }//GEN-LAST:event_btnExitActionPerformed private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed - if (session.isConnected()) { + if (client.isConnected()) { if (JOptionPane.showConfirmDialog(this, "Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - session.disconnect(false); + client.disconnect(); tablesPane.clearChat(); setWindowTitle(); showMessage("You have disconnected"); @@ -949,7 +959,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { }//GEN-LAST:event_btnPreferencesActionPerformed public void btnSendFeedbackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendFeedbackActionPerformed - if (!session.isConnected()) { + if (!client.isConnected()) { JOptionPane.showMessageDialog(null, "You may send us feedback only when connected to server.", "Information", JOptionPane.INFORMATION_MESSAGE); return; } @@ -957,11 +967,11 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { }//GEN-LAST:event_btnSendFeedbackActionPerformed public void exitApp() { - if (session.isConnected()) { + if (client.isConnected()) { if (JOptionPane.showConfirmDialog(this, "You are currently connected. Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } - session.disconnect(false); + client.disconnect(); } else { if (JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?", "Confirm exit", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; @@ -1167,6 +1177,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { } } instance = new MageFrame(); + client = new Client(instance); instance.setVisible(true); } @@ -1266,7 +1277,6 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { } } - @Override public void disconnected(final boolean errorCall) { if (SwingUtilities.isEventDispatchThread()) { // Returns true if the current thread is an AWT event dispatching thread. logger.info("DISCONNECTED (Event Dispatch Thread)"); @@ -1288,14 +1298,13 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { enableButtons(); } } else { - session.disconnect(false); + client.disconnect(); } } }); } } - @Override public void showMessage(final String message) { if (SwingUtilities.isEventDispatchThread()) { JOptionPane.showMessageDialog(desktopPane, message); @@ -1309,7 +1318,6 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { } } - @Override public void showError(final String message) { if (SwingUtilities.isEventDispatchThread()) { JOptionPane.showMessageDialog(desktopPane, message, "Error", JOptionPane.ERROR_MESSAGE); @@ -1323,9 +1331,59 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { } } +// @Override +// public void processCallback(ClientCallback callback) { +// callbackClient.processCallback(callback); +// } + @Override - public void processCallback(ClientCallback callback) { - callbackClient.processCallback(callback); + public void inform(String message, MessageType type) { + if (type == MessageType.ERROR) { + showError(message); + } + else { + showMessage(message); + } + } + + @Override + public void receiveChatMessage(final UUID chatId, final ChatMessage message) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + ChatPanel panel = MageFrame.getChat(chatId); + if (panel != null) { + // send the message to subchat if exists and it's not a game message + if (!message.getMessageType().equals(ChatMessage.MessageType.GAME) && panel.getConnectedChat() != null) { + panel.getConnectedChat().receiveMessage(message); + } else { + panel.receiveMessage(message); + } + } + } + }); + } + + @Override + public void receiveBroadcastMessage(String message) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void clientRegistered(ServerState state) { + this.serverState = state; + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + setWindowTitle(); + showGames(false); + } + }); + } + + @Override + public ServerState getServerState() { + return serverState; } } diff --git a/Mage.Client/src/main/java/mage/client/cards/Card.java b/Mage.Client/src/main/java/mage/client/cards/Card.java index ca322655e8c..f48e8b57f64 100644 --- a/Mage.Client/src/main/java/mage/client/cards/Card.java +++ b/Mage.Client/src/main/java/mage/client/cards/Card.java @@ -47,7 +47,7 @@ import mage.client.util.ImageHelper; import mage.client.util.gui.ArrowBuilder; import mage.constants.CardType; import mage.constants.EnlargeMode; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.*; import javax.swing.*; @@ -60,6 +60,7 @@ import java.util.List; import java.util.UUID; import static mage.client.constants.Constants.*; +import org.mage.network.Client; /** * @@ -68,7 +69,8 @@ import static mage.client.constants.Constants.*; @SuppressWarnings("serial") public class Card extends MagePermanent implements MouseMotionListener, MouseListener, FocusListener, ComponentListener { - protected static Session session = MageFrame.getSession(); +// protected static Session session = MageFrame.getSession(); + protected static Client client = MageFrame.getClient(); protected static DefaultActionCallback callback = DefaultActionCallback.getInstance(); protected Point p; @@ -353,7 +355,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis @Override public void mousePressed(MouseEvent e) { requestFocusInWindow(); - callback.mouseClicked(e, gameId, session, card); + callback.mouseClicked(e, gameId, client, card); } @Override diff --git a/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java b/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java index c078527ebd1..d3ae8b6012c 100644 --- a/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java +++ b/Mage.Client/src/main/java/mage/client/chat/ChatPanel.java @@ -45,13 +45,16 @@ import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import mage.client.MageFrame; import mage.client.util.MageTableRowSorter; +import mage.client.util.audio.AudioManager; import mage.remote.MageRemoteException; -import mage.remote.Session; +import mage.view.ChatMessage; +//import mage.remote.Session; import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageType; import mage.view.RoomUsersView; import mage.view.UsersView; import org.mage.card.arcane.ManaSymbols; +import org.mage.network.Client; /** * @@ -60,7 +63,7 @@ import org.mage.card.arcane.ManaSymbols; public class ChatPanel extends javax.swing.JPanel { private UUID chatId; - private Session session; + private Client client; private final List players = new ArrayList<>(); private final TableModel tableModel; /** @@ -174,20 +177,44 @@ public class ChatPanel extends javax.swing.JPanel { } public void connect(UUID chatId) { - session = MageFrame.getSession(); + client = MageFrame.getClient(); this.chatId = chatId; - if (session.joinChat(chatId)) { - MageFrame.addChat(chatId, this); - } + client.joinChat(chatId); + MageFrame.addChat(chatId, this); } public void disconnect() { - if (session != null) { - session.leaveChat(chatId); + if (client != null) { + client.leaveChat(chatId); MageFrame.removeChat(chatId); } } + public void receiveMessage(ChatMessage message) { + // play the to the message connected sound + if (message.getSoundToPlay() != null) { + switch (message.getSoundToPlay()) { + case PlayerLeft: + AudioManager.playPlayerLeft(); + break; + case PlayerQuitTournament: + AudioManager.playPlayerQuitTournament(); + break; + case PlayerSubmittedDeck: + AudioManager.playPlayerSubmittedDeck(); + break; + case PlayerWhispered: + AudioManager.playPlayerWhispered(); + break; + } + } + // send start message to chat if not done yet + if (!isStartMessageDone()) { + createChatStartMessage(); + } + receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), message.getColor()); + } + /** * Display message in the chat. Use different colors for timestamp, username * and message. @@ -198,7 +225,7 @@ public class ChatPanel extends javax.swing.JPanel { * @param messageType * @param color Preferred color. Not used. */ - public void receiveMessage(String username, String message, String time, MessageType messageType, MessageColor color) { + private void receiveMessage(String username, String message, String time, MessageType messageType, MessageColor color) { StringBuilder text = new StringBuilder(); if (time != null) { text.append(getColoredText(TIMESTAMP_COLOR, time + ": ")); @@ -218,9 +245,9 @@ public class ChatPanel extends javax.swing.JPanel { break; default: if (parentChatRef != null) { - userColor = parentChatRef.session.getUserName().equals(username) ? MY_COLOR : OPPONENT_COLOR; + userColor = parentChatRef.client.getUserName().equals(username) ? MY_COLOR : OPPONENT_COLOR; } else { - userColor = session.getUserName().equals(username) ? MY_COLOR : OPPONENT_COLOR; + userColor = client.getUserName().equals(username) ? MY_COLOR : OPPONENT_COLOR; } textColor = MESSAGE_COLOR; userSeparator = ": "; @@ -238,6 +265,35 @@ public class ChatPanel extends javax.swing.JPanel { this.txtConversation.append(text.toString()); } + private void createChatStartMessage() { + setStartMessageDone(true); + switch (getChatType()) { + case GAME: + receiveMessage("", new StringBuilder("You may use hot keys to play faster:") + .append("
Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over") + .append("
Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over") + .append("
F2 - Confirm \"Ok\", \"Yes\" or \"Done\" button") + .append("
F4 - Skip current turn but stop on declare attackers/blockers and something on the stack") + .append("
F5 - Skip to next end step but stop on declare attackers/blockers and something on the stack") + .append("
F7 - Skip to next main phase but stop on declare attackers/blockers and something on the stack") + .append("
F9 - Skip everything until your next turn") + .append("
F3 - Undo F4/F5/F7/F9").toString(), + null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); + break; + case TOURNAMENT: + receiveMessage("", new StringBuilder("On this panel you can see the players, their state and the results of the games of the tournament. Also you can chat with the competitors of the tournament.").toString(), + null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); + break; + case TABLES: + receiveMessage("", new StringBuilder("Download card images by using the \"Images\" menu to the top right .") + .append("
Download icons and symbols by using the \"Symbols\" menu to the top right.") + .append("
\\list - Show a list of available chat commands.").toString(), + null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); + break; + + } + } + private String getColoredText(String color, String text) { StringBuilder sb = new StringBuilder(); sb.append(" { private static final Logger logger = Logger.getLogger(UpdateDeckTask.class); - private final Session session; + private final Client client; private final UUID tableId; private final Deck deck; - UpdateDeckTask(Session session, UUID tableId, Deck deck) { - this.session = session; + UpdateDeckTask(Client client, UUID tableId, Deck deck) { + this.client = client; this.tableId = tableId; this.deck = deck; } @@ -889,7 +890,7 @@ class UpdateDeckTask extends SwingWorker { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - session.updateDeck(tableId, deck.getDeckCardLists()); + client.updateDeck(tableId, deck.getDeckCardLists()); Thread.sleep(5000); } return null; diff --git a/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java b/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java index 4c72ed3535e..1c738cc50bf 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/ConnectDialog.java @@ -354,7 +354,7 @@ public class ConnectDialog extends MageDialog { protected Boolean doInBackground() throws Exception { lblStatus.setText("Connecting..."); btnConnect.setEnabled(false); - result = MageFrame.connect(connection); + result = MageFrame.getInstance().connect(connection); return result; } @@ -366,7 +366,7 @@ public class ConnectDialog extends MageDialog { if (result) { lblStatus.setText(""); connected(); - MageFrame.getInstance().showGames(false); +// MageFrame.getInstance().showGames(false); } else { lblStatus.setText("Could not connect"); } @@ -380,7 +380,7 @@ public class ConnectDialog extends MageDialog { } catch (TimeoutException ex) { logger.fatal("Connection timeout: ", ex); } finally { - MageFrame.stopConnecting(); +// MageFrame.stopConnecting(); btnConnect.setEnabled(true); } } diff --git a/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java b/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java index dc3c892658e..69dd5dd1e36 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/FeedbackDialog.java @@ -254,7 +254,7 @@ public class FeedbackDialog extends javax.swing.JDialog { if (email.length() > 100) { email = email.substring(0, 100); } - if (MageFrame.getSession().sendFeedback(title, type, message, email)) { + if (MageFrame.getClient().sendFeedback(title, type, message, email)) { JOptionPane.showMessageDialog(null, "Feedback was sent. Thank you!", "Success", JOptionPane.INFORMATION_MESSAGE); reset(); dialog.setVisible(false); diff --git a/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java b/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java index 5413b8fc176..871d6f99a41 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/JoinTableDialog.java @@ -31,8 +31,9 @@ import java.util.UUID; import javax.swing.JOptionPane; import mage.cards.decks.importer.DeckImporterUtil; import mage.client.MageFrame; -import mage.remote.Session; +//import mage.remote.Session; import org.apache.log4j.Logger; +import org.mage.network.Client; /** * @@ -58,7 +59,7 @@ public class JoinTableDialog extends MageDialog { this.roomId = roomId; this.tableId = tableId; this.isTournament = isTournament; - this.newPlayerPanel.setPlayerName(MageFrame.getSession().getUserName()); + this.newPlayerPanel.setPlayerName(MageFrame.getClient().getUserName()); this.newPlayerPanel.showDeckElements(!isLimited); this.setModal(true); this.setLocation(100, 100); @@ -146,13 +147,13 @@ public class JoinTableDialog extends MageDialog { }//GEN-LAST:event_btnCancelActionPerformed private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed - Session session = MageFrame.getSession(); + Client client = MageFrame.getClient(); try { PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_PASSWORD, txtPassword.getText()); if (isTournament) { - joined = session.joinTournamentTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), "Human", 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText()); + joined = client.joinTournamentTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), "Human", 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText()); } else { - joined = session.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), "Human", 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText()); + joined = client.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), "Human", 1, DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()), this.txtPassword.getText()); } } catch (Exception ex) { diff --git a/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java b/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java index a3f45cffdee..d98e94a693d 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/NewTableDialog.java @@ -48,10 +48,11 @@ import mage.constants.MultiplayerAttackOption; import mage.constants.RangeOfInfluence; import mage.constants.SkillLevel; import mage.game.match.MatchOptions; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.GameTypeView; import mage.view.TableView; import org.apache.log4j.Logger; +import org.mage.network.Client; /** * @@ -64,7 +65,7 @@ public class NewTableDialog extends MageDialog { private TableView table; private UUID playerId; private UUID roomId; - private final Session session; + private final Client client; private String lastSessionId; private final List players = new ArrayList<>(); private final List prefPlayerTypes = new ArrayList<>(); @@ -73,7 +74,7 @@ public class NewTableDialog extends MageDialog { /** Creates new form NewTableDialog */ public NewTableDialog() { - session = MageFrame.getSession(); + client = MageFrame.getClient(); lastSessionId = ""; initComponents(); player1Panel.showLevel(false); @@ -370,13 +371,13 @@ public class NewTableDialog extends MageDialog { } saveGameSettingsToPrefs(options, this.player1Panel.getDeckFile()); - table = session.createTable(roomId, options); + table = client.createTable(roomId, options); if (table == null) { JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Error creating table.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { - if (session.joinTable( + if (client.joinTable( roomId, table.getTableId(), this.player1Panel.getPlayerName(), @@ -388,7 +389,7 @@ public class NewTableDialog extends MageDialog { if (!player.getPlayerType().equals("Human")) { if (!player.joinTable(roomId, table.getTableId())) { // error message must be send by the server - session.removeTable(roomId, table.getTableId()); + client.removeTable(roomId, table.getTableId()); table = null; return; } @@ -405,7 +406,7 @@ public class NewTableDialog extends MageDialog { handleError(ex); } // JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Error joining table.", "Error", JOptionPane.ERROR_MESSAGE); - session.removeTable(roomId, table.getTableId()); + client.removeTable(roomId, table.getTableId()); table = null; }//GEN-LAST:event_btnOKActionPerformed @@ -523,11 +524,11 @@ public class NewTableDialog extends MageDialog { public void showDialog(UUID roomId) { this.roomId = roomId; - if (!lastSessionId.equals(MageFrame.getSession().getSessionId())) { - lastSessionId = session.getSessionId(); - this.player1Panel.setPlayerName(session.getUserName()); - cbGameType.setModel(new DefaultComboBoxModel(session.getGameTypes().toArray())); - cbDeckType.setModel(new DefaultComboBoxModel(session.getDeckTypes())); + if (!lastSessionId.equals(MageFrame.getClient().getSessionId())) { + lastSessionId = client.getSessionId(); + this.player1Panel.setPlayerName(client.getUserName()); + cbGameType.setModel(new DefaultComboBoxModel(client.getServerState().getGameTypes().toArray())); + cbDeckType.setModel(new DefaultComboBoxModel(client.getServerState().getDeckTypes())); selectLimitedByDefault(); cbTimeLimit.setModel(new DefaultComboBoxModel(MatchTimeLimit.values())); cbRange.setModel(new DefaultComboBoxModel(RangeOfInfluence.values())); @@ -578,7 +579,7 @@ public class NewTableDialog extends MageDialog { String gameTypeName = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_GAME_TYPE, "Two Player Duel"); - for (GameTypeView gtv : session.getGameTypes()) { + for (GameTypeView gtv : client.getServerState().getGameTypes()) { if (gtv.getName().equals(gameTypeName)) { cbGameType.setSelectedItem(gtv); break; diff --git a/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java b/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java index ca6a30b6f66..475164206b9 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/NewTournamentDialog.java @@ -55,11 +55,12 @@ import mage.game.draft.DraftOptions; import mage.game.draft.DraftOptions.TimingOption; import mage.game.tournament.LimitedOptions; import mage.game.tournament.TournamentOptions; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.GameTypeView; import mage.view.TableView; import mage.view.TournamentTypeView; import org.apache.log4j.Logger; +import org.mage.network.Client; /** @@ -73,7 +74,7 @@ public class NewTournamentDialog extends MageDialog { private TableView table; private UUID playerId; private UUID roomId; - private final Session session; + private final Client client; private String lastSessionId; private final List players = new ArrayList<>(); private final List packs = new ArrayList<>(); @@ -85,7 +86,7 @@ public class NewTournamentDialog extends MageDialog { /** Creates new form NewTournamentDialog */ public NewTournamentDialog() { initComponents(); - session = MageFrame.getSession(); + client = MageFrame.getClient(); lastSessionId = ""; txtName.setText("Tournament"); this.spnNumWins.setModel(new SpinnerNumberModel(2, 1, 5, 1)); @@ -96,18 +97,17 @@ public class NewTournamentDialog extends MageDialog { public void showDialog(UUID roomId) { this.roomId = roomId; - if (!lastSessionId.equals(MageFrame.getSession().getSessionId())) { - lastSessionId = session.getSessionId(); - this.player1Panel.setPlayerName(session.getUserName()); + if (!lastSessionId.equals(MageFrame.getClient().getSessionId())) { + lastSessionId = client.getSessionId(); + this.player1Panel.setPlayerName(client.getUserName()); this.player1Panel.showLevel(false); // no computer - cbTournamentType.setModel(new DefaultComboBoxModel(session.getTournamentTypes().toArray())); + cbTournamentType.setModel(new DefaultComboBoxModel(client.getServerState().getTournamentTypes().toArray())); - cbGameType.setModel(new DefaultComboBoxModel(session.getTournamentGameTypes().toArray())); - cbDeckType.setModel(new DefaultComboBoxModel(session.getDeckTypes())); + cbGameType.setModel(new DefaultComboBoxModel(client.getServerState().getTournamentGameTypes().toArray())); + cbDeckType.setModel(new DefaultComboBoxModel(client.getServerState().getDeckTypes())); cbTimeLimit.setModel(new DefaultComboBoxModel(MatchTimeLimit.values())); - cbSkillLevel.setModel(new DefaultComboBoxModel(SkillLevel.values())); - cbDraftCube.setModel(new DefaultComboBoxModel(session.getDraftCubes())); + cbDraftCube.setModel(new DefaultComboBoxModel(client.getServerState().getDraftCubes())); cbDraftTiming.setModel(new DefaultComboBoxModel(DraftOptions.TimingOption.values())); // update player types int i=2; @@ -537,12 +537,12 @@ public class NewTournamentDialog extends MageDialog { tOptions.getMatchOptions().setRange(RangeOfInfluence.ALL); saveTournamentSettingsToPrefs(tOptions); - table = session.createTournamentTable(roomId, tOptions); + table = client.createTournamentTable(roomId, tOptions); if (table == null) { // message must be send by server! return; } - if (session.joinTournamentTable( + if (client.joinTournamentTable( roomId, table.getTableId(), this.player1Panel.getPlayerName(), @@ -553,7 +553,7 @@ public class NewTournamentDialog extends MageDialog { if (!player.getPlayerType().toString().equals("Human")) { if (!player.joinTournamentTable(roomId, table.getTableId(), DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()))) { // error message must be send by sever - session.removeTable(roomId, table.getTableId()); + client.removeTable(roomId, table.getTableId()); table = null; return; } @@ -563,7 +563,7 @@ public class NewTournamentDialog extends MageDialog { return; } JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Error joining tournament.", "Error", JOptionPane.ERROR_MESSAGE); - session.removeTable(roomId, table.getTableId()); + client.removeTable(roomId, table.getTableId()); table = null; }//GEN-LAST:event_btnOkActionPerformed @@ -799,7 +799,7 @@ public class NewTournamentDialog extends MageDialog { } this.spnConstructTime.setValue(constructionTime); String tournamentTypeName = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_TYPE, "Sealed Elimination"); - for (TournamentTypeView tournamentTypeView : session.getTournamentTypes()) { + for (TournamentTypeView tournamentTypeView : client.getServerState().getTournamentTypes()) { if (tournamentTypeView.getName().equals(tournamentTypeName)) { cbTournamentType.setSelectedItem(tournamentTypeView); break; diff --git a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java index 3d9b563e14b..96d9776e547 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java @@ -1686,7 +1686,7 @@ public class PreferencesDialog extends javax.swing.JDialog { } try { - MageFrame.getSession().updatePreferencesForServer( + MageFrame.getClient().updatePreferencesForServer( getSelectedAvatar(), dialog.showAbilityPickerForced.isSelected(), dialog.cbAllowRequestToShowHandCards.isSelected(), @@ -2357,7 +2357,7 @@ public class PreferencesDialog extends javax.swing.JDialog { public void mousePressed(MouseEvent e) { if (selectedAvatarId != id) { setSelectedId(id); - MageFrame.getSession().updatePreferencesForServer( + MageFrame.getClient().updatePreferencesForServer( id, PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_TOOLTIPS_ANY_ZONE, "true").equals("true"), PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, "true").equals("true"), 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 c2166b34d4b..70cdeca91ba 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/TableWaitingDialog.java @@ -45,10 +45,11 @@ import mage.client.chat.ChatPanel; import mage.client.components.MageComponents; import mage.client.components.tray.MageTray; import mage.client.util.audio.AudioManager; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.SeatView; import mage.view.TableView; import org.apache.log4j.Logger; +import org.mage.network.Client; /** * @@ -61,14 +62,14 @@ public class TableWaitingDialog extends MageDialog { private UUID tableId; private UUID roomId; private boolean isTournament; - private Session session; + private Client client; private final TableWaitModel tableWaitModel; private UpdateSeatsTask updateTask; /** Creates new form TableWaitingDialog */ public TableWaitingDialog() { - session = MageFrame.getSession(); + client = MageFrame.getClient(); tableWaitModel = new TableWaitModel(); initComponents(); @@ -113,9 +114,9 @@ public class TableWaitingDialog extends MageDialog { this.roomId = roomId; this.tableId = tableId; this.isTournament = isTournament; - session = MageFrame.getSession(); - updateTask = new UpdateSeatsTask(session, roomId, tableId, this); - if (session.isTableOwner(roomId, tableId)) { + client = MageFrame.getClient(); + updateTask = new UpdateSeatsTask(client, roomId, tableId, this); + if (client.isTableOwner(roomId, tableId)) { this.btnStart.setVisible(true); this.btnMoveDown.setVisible(true); this.btnMoveUp.setVisible(true); @@ -124,7 +125,7 @@ public class TableWaitingDialog extends MageDialog { this.btnMoveDown.setVisible(false); this.btnMoveUp.setVisible(false); } - UUID chatId = session.getTableChatId(tableId); + UUID chatId = client.getTableChatId(tableId); if (chatId != null) { this.chatPanel.connect(chatId); updateTask.execute(); @@ -245,12 +246,12 @@ public class TableWaitingDialog extends MageDialog { private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed if (!isTournament) { - if (session.startMatch(roomId, tableId)) { + if (client.startMatch(roomId, tableId)) { closeDialog(); } } else { - if (session.startTournament(roomId, tableId)) { + if (client.startTournament(roomId, tableId)) { closeDialog(); } } @@ -258,7 +259,7 @@ public class TableWaitingDialog extends MageDialog { private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed try { - if (!session.leaveTable(roomId, tableId)) { + if (!client.leaveTable(roomId, tableId)) { return; // already started, so leave no more possible } } catch (Exception e) { @@ -271,7 +272,7 @@ public class TableWaitingDialog extends MageDialog { private void btnMoveDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMoveDownActionPerformed int row = this.tableSeats.getSelectedRow(); if (row < this.tableSeats.getRowCount() - 1) { - session.swapSeats(roomId, tableId, row, row + 1); + client.swapSeats(roomId, tableId, row, row + 1); this.tableSeats.getSelectionModel().setSelectionInterval(row + 1, row + 1); } @@ -280,7 +281,7 @@ public class TableWaitingDialog extends MageDialog { private void btnMoveUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMoveUpActionPerformed int row = this.tableSeats.getSelectedRow(); if (row > 0) { - session.swapSeats(roomId, tableId, row, row - 1); + client.swapSeats(roomId, tableId, row, row - 1); this.tableSeats.getSelectionModel().setSelectionInterval(row - 1, row - 1); } }//GEN-LAST:event_btnMoveUpActionPerformed @@ -363,7 +364,7 @@ class TableWaitModel extends AbstractTableModel { class UpdateSeatsTask extends SwingWorker { - private final Session session; + private final Client client; private final UUID roomId; private final UUID tableId; private final TableWaitingDialog dialog; @@ -371,8 +372,8 @@ class UpdateSeatsTask extends SwingWorker { private static final Logger logger = Logger.getLogger(TableWaitingDialog.class); - UpdateSeatsTask(Session session, UUID roomId, UUID tableId, TableWaitingDialog dialog) { - this.session = session; + UpdateSeatsTask(Client client, UUID roomId, UUID tableId, TableWaitingDialog dialog) { + this.client = client; this.roomId = roomId; this.tableId = tableId; this.dialog = dialog; @@ -381,7 +382,7 @@ class UpdateSeatsTask extends SwingWorker { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - this.publish(session.getTable(roomId, tableId)); + this.publish(client.getTable(roomId, tableId)); Thread.sleep(1000); } return null; diff --git a/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java b/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java index 2b859be4df2..ce8e0661026 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/UserRequestDialog.java @@ -37,8 +37,9 @@ package mage.client.dialog; import mage.client.MageFrame; import mage.constants.PlayerAction; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.UserRequestMessage; +import org.mage.network.Client; /** * @@ -176,10 +177,10 @@ public class UserRequestDialog extends MageDialog { }//GEN-LAST:event_btn3ActionPerformed private void sendUserReplay(PlayerAction playerAction) { - Session session = MageFrame.getSession(); + Client client = MageFrame.getClient(); switch(playerAction) { case ADD_PERMISSION_TO_SEE_HAND_CARDS: - session.sendPlayerAction(playerAction, userRequestMessage.getGameId(), userRequestMessage.getRelatedUserId()); + client.sendPlayerAction(playerAction, userRequestMessage.getGameId(), userRequestMessage.getRelatedUserId()); break; default: // not supported action diff --git a/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java b/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java index 573a1b8be86..41c6a66348d 100644 --- a/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java +++ b/Mage.Client/src/main/java/mage/client/draft/DraftPanel.java @@ -63,12 +63,13 @@ import mage.client.util.ImageHelper; import mage.client.util.Listener; import mage.client.util.audio.AudioManager; import mage.client.util.gui.BufferedImageBuilder; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.CardsView; import mage.view.DraftPickView; import mage.view.DraftView; import mage.view.SimpleCardView; import mage.view.SimpleCardsView; +import org.mage.network.Client; /** * @@ -77,7 +78,7 @@ import mage.view.SimpleCardsView; public class DraftPanel extends javax.swing.JPanel { private UUID draftId; - private Session session; + private Client client; private Timer countdown; private int timeout; @@ -144,9 +145,9 @@ public class DraftPanel extends javax.swing.JPanel { public synchronized void showDraft(UUID draftId) { this.draftId = draftId; - session = MageFrame.getSession(); + client = MageFrame.getClient(); MageFrame.addDraft(draftId, this); - if (!session.joinDraft(draftId)) { + if (!client.joinDraft(draftId)) { hideDraft(); } } @@ -270,7 +271,7 @@ public class DraftPanel extends javax.swing.JPanel { public void event(Event event) { if (event.getEventName().equals("pick-a-card")) { SimpleCardView source = (SimpleCardView) event.getSource(); - DraftPickView view = session.sendCardPick(draftId, source.getId(), cardsHidden); + DraftPickView view = client.sendCardPick(draftId, source.getId(), cardsHidden); if (view != null) { loadCardsToPickedCardsArea(view.getPicks()); draftBooster.loadBooster(emptyView, bigCard); @@ -280,7 +281,7 @@ public class DraftPanel extends javax.swing.JPanel { } if (event.getEventName().equals("mark-a-card")) { SimpleCardView source = (SimpleCardView) event.getSource(); - session.sendCardMark(draftId, source.getId()); + client.sendCardMark(draftId, source.getId()); } } } @@ -764,7 +765,7 @@ public class DraftPanel extends javax.swing.JPanel { private void btnQuitTournamentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitTournamentActionPerformed if (JOptionPane.showConfirmDialog(this, "Are you sure you want to quit the tournament?", "Confirm quit tournament", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - MageFrame.getSession().quitDraft(draftId); + MageFrame.getClient().quitDraft(draftId); MageFrame.removeDraft(draftId); } }//GEN-LAST:event_btnQuitTournamentActionPerformed diff --git a/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java b/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java index d8937a35b1c..4e02dee9431 100644 --- a/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java +++ b/Mage.Client/src/main/java/mage/client/game/AbilityPicker.java @@ -30,7 +30,7 @@ package mage.client.game; import mage.client.MageFrame; import mage.client.util.gui.GuiDisplayUtil; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.AbilityPickerView; import javax.swing.*; @@ -40,6 +40,7 @@ import java.awt.*; import java.awt.event.ActionEvent; import java.util.Map.Entry; import java.util.UUID; +import org.mage.network.Client; /** * ************************ U N U S E D ********************************* @@ -49,15 +50,15 @@ import java.util.UUID; */ public class AbilityPicker extends JPopupMenu implements PopupMenuListener { - private Session session; + private Client client; private UUID gameId; public AbilityPicker(String ThisIsnotUsedAnymore) { this.addPopupMenuListener(this); } - public void init(Session session, UUID gameId) { - this.session = session; + public void init(Client client, UUID gameId) { + this.client = client; this.gameId = gameId; } @@ -85,7 +86,7 @@ public class AbilityPicker extends JPopupMenu implements PopupMenuListener { @Override public void popupMenuCanceled(PopupMenuEvent e) { - session.sendPlayerBoolean(gameId, false); + client.sendPlayerBoolean(gameId, false); } private class AbilityPickerAction extends AbstractAction { @@ -99,7 +100,7 @@ public class AbilityPicker extends JPopupMenu implements PopupMenuListener { @Override public void actionPerformed(ActionEvent e) { - session.sendPlayerUUID(gameId, id); + client.sendPlayerUUID(gameId, id); setVisible(false); } diff --git a/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java b/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java index fdd97d9b35c..3c69d897d64 100644 --- a/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/FeedbackPanel.java @@ -49,8 +49,9 @@ import mage.client.dialog.MageDialog; import mage.client.util.audio.AudioManager; import mage.client.util.gui.ArrowBuilder; import mage.constants.PlayerAction; -import mage.remote.Session; +//import mage.remote.Session; import org.apache.log4j.Logger; +import org.mage.network.Client; /** * @@ -65,7 +66,7 @@ public class FeedbackPanel extends javax.swing.JPanel { } private UUID gameId; - private Session session; + private Client client; private FeedbackMode mode; private MageDialog connectedDialog; private ChatPanel connectedChatPanel; @@ -81,7 +82,7 @@ public class FeedbackPanel extends javax.swing.JPanel { public void init(UUID gameId) { this.gameId = gameId; - session = MageFrame.getSession(); + client = MageFrame.getClient(); } public void getFeedback(FeedbackMode mode, String message, boolean special, Map options, int messageId) { @@ -273,29 +274,29 @@ public class FeedbackPanel extends javax.swing.JPanel { connectedDialog = null; } if (mode == FeedbackMode.SELECT && (evt.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { - session.sendPlayerInteger(gameId, 0); + client.sendPlayerInteger(gameId, 0); } else if (mode == FeedbackMode.END) { GamePanel gamePanel = MageFrame.getGame(gameId); if (gamePanel != null) { gamePanel.removeGame(); } } else { - session.sendPlayerBoolean(gameId, false); + client.sendPlayerBoolean(gameId, false); } //AudioManager.playButtonOk(); }//GEN-LAST:event_btnRightActionPerformed private void btnLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLeftActionPerformed - session.sendPlayerBoolean(gameId, true); + client.sendPlayerBoolean(gameId, true); AudioManager.playButtonCancel(); }//GEN-LAST:event_btnLeftActionPerformed private void btnSpecialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSpecialActionPerformed - session.sendPlayerString(gameId, "special"); + client.sendPlayerString(gameId, "special"); }//GEN-LAST:event_btnSpecialActionPerformed private void btnUndoActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.UNDO, gameId, null); + client.sendPlayerAction(PlayerAction.UNDO, gameId, null); } public void setHelperPanel(HelperPanel helper) { 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 6021b18fbe2..8c3dbdca93d 100644 --- a/Mage.Client/src/main/java/mage/client/game/GamePanel.java +++ b/Mage.Client/src/main/java/mage/client/game/GamePanel.java @@ -115,7 +115,7 @@ import static mage.constants.PhaseStep.UNTAP; import static mage.constants.PhaseStep.UPKEEP; import mage.constants.PlayerAction; import mage.constants.Zone; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.AbilityPickerView; import mage.view.CardView; import mage.view.CardsView; @@ -127,6 +127,7 @@ import mage.view.PlayerView; import mage.view.RevealedView; import mage.view.SimpleCardsView; import org.apache.log4j.Logger; +import org.mage.network.Client; import org.mage.plugins.card.utils.impl.ImageManagerImpl; @@ -147,7 +148,7 @@ public final class GamePanel extends javax.swing.JPanel { private final ArrayList pickTarget = new ArrayList<>(); private UUID gameId; private UUID playerId; // playerId of the player - private Session session; + private Client client; GamePane gamePane; private ReplayTask replayTask; private final PickNumberDialog pickNumber; @@ -359,11 +360,11 @@ public final class GamePanel extends javax.swing.JPanel { this.gameId = gameId; this.gamePane = gamePane; this.playerId = playerId; - session = MageFrame.getSession(); + client = MageFrame.getClient(); MageFrame.addGame(gameId, this); this.feedbackPanel.init(gameId); this.feedbackPanel.clear(); - this.abilityPicker.init(session, gameId); + this.abilityPicker.init(client, gameId); this.btnConcede.setVisible(true); this.btnStopWatching.setVisible(false); @@ -379,8 +380,8 @@ public final class GamePanel extends javax.swing.JPanel { this.pnlReplay.setVisible(false); this.gameChatPanel.clear(); - this.gameChatPanel.connect(session.getGameChatId(gameId)); - if (!session.joinGame(gameId)) { + this.gameChatPanel.connect(client.getGameChatId(gameId)); + if (!client.joinGame(gameId)) { removeGame(); } else { AudioManager.playYourGameStarted(); @@ -391,7 +392,7 @@ public final class GamePanel extends javax.swing.JPanel { this.gameId = gameId; this.gamePane = gamePane; this.playerId = null; - session = MageFrame.getSession(); + client = MageFrame.getClient(); MageFrame.addGame(gameId, this); this.feedbackPanel.init(gameId); this.feedbackPanel.clear(); @@ -411,8 +412,8 @@ public final class GamePanel extends javax.swing.JPanel { this.pnlReplay.setVisible(false); this.gameChatPanel.clear(); - this.gameChatPanel.connect(session.getGameChatId(gameId)); - if (!session.watchGame(gameId)) { + this.gameChatPanel.connect(client.getGameChatId(gameId)); + if (!client.watchGame(gameId)) { removeGame(); } for (PlayAreaPanel panel : getPlayers().values()) { @@ -423,7 +424,7 @@ public final class GamePanel extends javax.swing.JPanel { public synchronized void replayGame(UUID gameId) { this.gameId = gameId; this.playerId = null; - session = MageFrame.getSession(); + client = MageFrame.getClient(); MageFrame.addGame(gameId, this); this.feedbackPanel.init(gameId); this.feedbackPanel.clear(); @@ -433,7 +434,7 @@ public final class GamePanel extends javax.swing.JPanel { this.btnStopWatching.setVisible(false); this.pnlReplay.setVisible(true); this.gameChatPanel.clear(); - if (!session.startReplay(gameId)) { + if (!client.startReplay(gameId)) { removeGame(); } for (PlayAreaPanel panel : getPlayers().values()) { @@ -950,10 +951,10 @@ public final class GamePanel extends javax.swing.JPanel { public void getAmount(int min, int max, String message) { pickNumber.showDialog(min, max, message); if (pickNumber.isCancel()) { - session.sendPlayerBoolean(gameId, false); + client.sendPlayerBoolean(gameId, false); } else { - session.sendPlayerInteger(gameId, pickNumber.getAmount()); + client.sendPlayerInteger(gameId, pickNumber.getAmount()); } } @@ -963,12 +964,12 @@ public final class GamePanel extends javax.swing.JPanel { pickChoice.showDialog(choice, objectId,choiceWindowState); if (choice.isKeyChoice()) { if (pickChoice.isAutoSelect()) { - session.sendPlayerString(gameId, "#" + choice.getChoiceKey()); + client.sendPlayerString(gameId, "#" + choice.getChoiceKey()); } else { - session.sendPlayerString(gameId, choice.getChoiceKey()); + client.sendPlayerString(gameId, choice.getChoiceKey()); } } else { - session.sendPlayerString(gameId, choice.getChoice()); + client.sendPlayerString(gameId, choice.getChoice()); } choiceWindowState = new MageDialogState(pickChoice); pickChoice.removeDialog(); @@ -978,7 +979,7 @@ public final class GamePanel extends javax.swing.JPanel { hideAll(); PickPileDialog pickPileDialog = new PickPileDialog(); pickPileDialog.loadCards(message, pile1, pile2, bigCard, Config.dimensions, gameId); - session.sendPlayerBoolean(gameId, pickPileDialog.isPickedPile1()); + client.sendPlayerBoolean(gameId, pickPileDialog.isPickedPile1()); pickPileDialog.cleanUp(); pickPileDialog.removeDialog(); } @@ -1696,42 +1697,42 @@ public final class GamePanel extends javax.swing.JPanel { private void btnConcedeActionPerformed(java.awt.event.ActionEvent evt) { if (modalQuestion("Are you sure you want to concede?", "Confirm concede") == JOptionPane.YES_OPTION) { - session.sendPlayerAction(PlayerAction.CONCEDE, gameId, null); + client.sendPlayerAction(PlayerAction.CONCEDE, gameId, null); } } private void btnEndTurnActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN, gameId, null); + client.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN, gameId, null); AudioManager.playOnSkipButton(); updateSkipButtons(true, false, false, false, false); } private void btnUntilEndOfTurnActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_TURN_END_STEP, gameId, null); + client.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_TURN_END_STEP, gameId, null); AudioManager.playOnSkipButton(); updateSkipButtons(false, true, false, false, false); } private void btnUntilNextMainPhaseActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_MAIN_PHASE, gameId, null); + client.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_MAIN_PHASE, gameId, null); AudioManager.playOnSkipButton(); updateSkipButtons(false, false, true, false, false); } private void btnPassPriorityUntilNextYourTurnActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); + client.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); AudioManager.playOnSkipButton(); updateSkipButtons(false, false, false, true, false); } private void btnPassPriorityUntilStackResolvedActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_STACK_RESOLVED, gameId, null); + client.sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_STACK_RESOLVED, gameId, null); AudioManager.playOnSkipButton(); updateSkipButtons(false, false, false, false, true); } private void restorePriorityActionPerformed(java.awt.event.ActionEvent evt) { - session.sendPlayerAction(PlayerAction.PASS_PRIORITY_CANCEL_ALL_ACTIONS, gameId, null); + client.sendPlayerAction(PlayerAction.PASS_PRIORITY_CANCEL_ALL_ACTIONS, gameId, null); AudioManager.playOnSkipButtonCancel(); updateSkipButtons(false, false, false, false, false); } @@ -1762,7 +1763,7 @@ public final class GamePanel extends javax.swing.JPanel { private void btnStopWatchingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopWatchingActionPerformed if (modalQuestion("Are you sure you want to stop watching?", "Stop watching") == JOptionPane.YES_OPTION) { - session.stopWatching(gameId); + client.stopWatching(gameId); this.removeGame(); } }//GEN-LAST:event_btnStopWatchingActionPerformed @@ -1772,27 +1773,27 @@ public final class GamePanel extends javax.swing.JPanel { replayTask.cancel(true); } else if (modalQuestion("Are you sure you want to stop replay?", "Stop replay") == JOptionPane.YES_OPTION) { - session.stopReplay(gameId); + client.stopReplay(gameId); } }//GEN-LAST:event_btnStopReplayActionPerformed private void btnNextPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextPlayActionPerformed - session.nextPlay(gameId); + client.nextPlay(gameId); }//GEN-LAST:event_btnNextPlayActionPerformed private void btnPreviousPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviousPlayActionPerformed - session.previousPlay(gameId); + client.previousPlay(gameId); }//GEN-LAST:event_btnPreviousPlayActionPerformed private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayActionPerformed if (replayTask == null || replayTask.isDone()) { - replayTask = new ReplayTask(session, gameId); + replayTask = new ReplayTask(client, gameId); replayTask.execute(); } }//GEN-LAST:event_btnPlayActionPerformed private void btnSkipForwardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSkipForwardActionPerformed - session.skipForward(gameId, 10); + client.skipForward(gameId, 10); }//GEN-LAST:event_btnSkipForwardActionPerformed public void setJLayeredPane(JLayeredPane jLayeredPane) { @@ -1822,8 +1823,8 @@ public final class GamePanel extends javax.swing.JPanel { return gameChatPanel.getText(); } - public Session getSession() { - return session; + public Client getClient() { + return client; } public Map getLoadedCards() { @@ -1898,20 +1899,20 @@ public final class GamePanel extends javax.swing.JPanel { } class ReplayTask extends SwingWorker> { - private final Session session; + private final Client client; private final UUID gameId; private static final Logger logger = Logger.getLogger(ReplayTask.class); - ReplayTask(Session session, UUID gameId) { - this.session = session; + ReplayTask(Client client, UUID gameId) { + this.client = client; this.gameId = gameId; } @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - session.nextPlay(gameId); + client.nextPlay(gameId); Thread.sleep(1000); } return null; diff --git a/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java b/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java index cc92819b86c..e82c03595e2 100644 --- a/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java +++ b/Mage.Client/src/main/java/mage/client/game/PlayAreaPanel.java @@ -159,7 +159,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.PASS_PRIORITY_CANCEL_ALL_ACTIONS, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.PASS_PRIORITY_CANCEL_ALL_ACTIONS, gameId, null); } }); @@ -172,7 +172,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_TURN, gameId, null); } }); @@ -183,7 +183,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_TURN_END_STEP, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_TURN_END_STEP, gameId, null); } }); @@ -194,7 +194,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_MAIN_PHASE, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_NEXT_MAIN_PHASE, gameId, null); } }); menuItem = new JMenuItem("F9 - Skip everything until own next turn (stop on attack/block)"); @@ -204,7 +204,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.PASS_PRIORITY_UNTIL_MY_NEXT_TURN, gameId, null); } }); @@ -221,7 +221,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { public void actionPerformed(ActionEvent e) { boolean manaPoolAutomatic = ((JCheckBoxMenuItem)e.getSource()).getState(); gamePanel.setMenuStates(manaPoolAutomatic); - gamePanel.getSession().sendPlayerAction(manaPoolAutomatic ? PlayerAction.MANA_AUTO_PAYMENT_ON: PlayerAction.MANA_AUTO_PAYMENT_OFF, gameId, null); + gamePanel.getClient().sendPlayerAction(manaPoolAutomatic ? PlayerAction.MANA_AUTO_PAYMENT_ON: PlayerAction.MANA_AUTO_PAYMENT_OFF, gameId, null); } }); @@ -234,7 +234,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.RESET_AUTO_SELECT_REPLACEMENT_EFFECTS, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.RESET_AUTO_SELECT_REPLACEMENT_EFFECTS, gameId, null); } }); @@ -248,7 +248,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId); + gamePanel.getClient().sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId); } }); } else { @@ -263,7 +263,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { public void actionPerformed(ActionEvent e) { boolean requestsAllowed = ((JCheckBoxMenuItem)e.getSource()).getState(); PreferencesDialog.setPrefValue(KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, requestsAllowed); - gamePanel.getSession().sendPlayerAction(requestsAllowed ? PlayerAction.PERMISSION_REQUESTS_ALLOWED_ON: PlayerAction.PERMISSION_REQUESTS_ALLOWED_OFF, gameId, null); + gamePanel.getClient().sendPlayerAction(requestsAllowed ? PlayerAction.PERMISSION_REQUESTS_ALLOWED_ON: PlayerAction.PERMISSION_REQUESTS_ALLOWED_OFF, gameId, null); } }); @@ -276,7 +276,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.REVOKE_PERMISSIONS_TO_SEE_HAND_CARDS, gameId, null); + gamePanel.getClient().sendPlayerAction(PlayerAction.REVOKE_PERMISSIONS_TO_SEE_HAND_CARDS, gameId, null); } }); } @@ -290,7 +290,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { @Override public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(PlayAreaPanel.this, "Are you sure you want to concede the game?", "Confirm concede game", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - MageFrame.getSession().sendPlayerAction(PlayerAction.CONCEDE, gameId, null); + MageFrame.getClient().sendPlayerAction(PlayerAction.CONCEDE, gameId, null); } } }); @@ -305,7 +305,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { @Override public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(PlayAreaPanel.this, "Are you sure you want to concede the complete match?", "Confirm concede match", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - MageFrame.getSession().quitMatch(gameId); + MageFrame.getClient().quitMatch(gameId); } } }); @@ -343,7 +343,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { @Override public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(PlayAreaPanel.this, "Are you sure you want to stop watching the game?", "Confirm stop watching game", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - gamePanel.getSession().stopWatching(gameId); + gamePanel.getClient().stopWatching(gameId); gamePanel.removeGame(); } } @@ -356,7 +356,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - gamePanel.getSession().sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId); + gamePanel.getClient().sendPlayerAction(PlayerAction.REQUEST_PERMISSION_TO_SEE_HAND_CARDS, gameId, playerId); } }); @@ -384,7 +384,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { this.playerPanel.init(gameId, player.getPlayerId(), bigCard, priorityTime); this.battlefieldPanel.init(gameId, bigCard); this.gameId = gameId; - if (MageFrame.getSession().isTestMode()) { + if (MageFrame.getClient().getServerState().isTestMode()) { this.playerId = player.getPlayerId(); this.btnCheat.setVisible(true); } @@ -461,7 +461,7 @@ public class PlayAreaPanel extends javax.swing.JPanel { } private void btnCheatActionPerformed(java.awt.event.ActionEvent evt) { - MageFrame.getSession().cheat(gameId, playerId, DeckImporterUtil.importDeck("cheat.dck")); + MageFrame.getClient().cheat(gameId, playerId, DeckImporterUtil.importDeck("cheat.dck")); } public boolean isSmallMode() { diff --git a/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java b/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java index 47b9f520489..5976d58646b 100644 --- a/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java +++ b/Mage.Client/src/main/java/mage/client/game/PlayerPanelExt.java @@ -53,7 +53,7 @@ import mage.client.util.ImageHelper; import mage.client.util.gui.BufferedImageBuilder; import mage.components.ImagePanel; import mage.constants.ManaType; -import mage.remote.Session; +//import mage.remote.Session; import mage.utils.timer.PriorityTimer; import mage.view.CardView; import mage.view.ManaPoolView; @@ -73,6 +73,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; +import org.mage.network.Client; /** * Enhanced player pane. @@ -83,7 +84,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { private UUID playerId; private UUID gameId; - private Session session; + private Client client; private PlayerView player; private BigCard bigCard; @@ -118,8 +119,8 @@ public class PlayerPanelExt extends javax.swing.JPanel { this.gameId = gameId; this.playerId = playerId; this.bigCard = bigCard; - session = MageFrame.getSession(); - cheat.setVisible(session.isTestMode()); + client = MageFrame.getClient(); + cheat.setVisible(client.getServerState().isTestMode()); cheat.setFocusable(false); if (priorityTime > 0) { @@ -347,7 +348,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { avatar.setObserver(new Command() { @Override public void execute() { - session.sendPlayerUUID(gameId, playerId); + client.sendPlayerUUID(gameId, playerId); } }); // timer area /small layout) @@ -467,7 +468,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { btnPlayer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - session.sendPlayerUUID(gameId, playerId); + client.sendPlayerUUID(gameId, playerId); } }); @@ -783,7 +784,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { } private void btnManaActionPerformed(ManaType manaType) { - session.sendPlayerManaType(gameId, player.getPlayerId(), manaType); + client.sendPlayerManaType(gameId, player.getPlayerId(), manaType); } private void btnGraveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGraveActionPerformed @@ -804,7 +805,7 @@ public class PlayerPanelExt extends javax.swing.JPanel { private void btnCheatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheatActionPerformed DckDeckImporter deckImporter = new DckDeckImporter(); - session.cheat(gameId, playerId, deckImporter.importDeck("cheat.dck")); + client.cheat(gameId, playerId, deckImporter.importDeck("cheat.dck")); } public PlayerView getPlayer() { diff --git a/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java b/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java index 6a7f024aec2..dfde668c372 100644 --- a/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java +++ b/Mage.Client/src/main/java/mage/client/plugins/adapters/MageActionCallback.java @@ -15,7 +15,7 @@ import mage.client.util.gui.ArrowUtil; import mage.client.util.gui.GuiDisplayUtil; import mage.components.CardInfoPane; import mage.constants.EnlargeMode; -import mage.remote.Session; +//import mage.remote.Session; import mage.utils.ThreadUtils; import mage.view.CardView; import mage.view.PermanentView; @@ -35,6 +35,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import org.mage.network.Client; /** * Class that handles the callbacks from the card panels to mage to display big card @@ -57,7 +58,7 @@ public class MageActionCallback implements ActionCallback { private JPopupMenu jPopupMenu; private BigCard bigCard; protected static final DefaultActionCallback defaultCallback = DefaultActionCallback.getInstance(); - protected static Session session = MageFrame.getSession(); + protected static Client client = MageFrame.getClient(); private CardView popupCard; private TransferData popupData; private JComponent cardInfoPane; @@ -89,8 +90,8 @@ public class MageActionCallback implements ActionCallback { } public synchronized void refreshSession() { - if (session == null) { - session = MageFrame.getSession(); + if (client == null) { + client = MageFrame.getClient(); } if (cardInfoPane == null) { cardInfoPane = Plugins.getInstance().getCardInfoPane(); @@ -157,7 +158,7 @@ public class MageActionCallback implements ActionCallback { public void run() { ThreadUtils.sleep(300); - if (popupCard == null || !popupCard.equals(data.card) || session == null || !popupTextWindowOpen || !enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { + if (popupCard == null || !popupCard.equals(data.card) || client == null || !popupTextWindowOpen || !enlargedWindowState.equals(EnlargedWindowState.CLOSED)) { return; } @@ -234,13 +235,13 @@ public class MageActionCallback implements ActionCallback { this.startedDragging = false; if (maxXOffset < MIN_X_OFFSET_REQUIRED) { // we need this for protection from small card movements transferData.component.requestFocusInWindow(); - defaultCallback.mouseClicked(e, transferData.gameId, session, transferData.card); + defaultCallback.mouseClicked(e, transferData.gameId, client, transferData.card); // Closes popup & enlarged view if a card/Permanent is selected hidePopup(); } } else { transferData.component.requestFocusInWindow(); - defaultCallback.mouseClicked(e, transferData.gameId, session, transferData.card); + defaultCallback.mouseClicked(e, transferData.gameId, client, transferData.card); // Closes popup & enlarged view if a card/Permanent is selected hidePopup(); } @@ -400,7 +401,7 @@ public class MageActionCallback implements ActionCallback { jPopupMenu.setVisible(false); } try { - if (session == null) { + if (client == null) { return; } // set enlarged card display to visible = false diff --git a/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java b/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java index 01869c84ba0..f706deffd71 100644 --- a/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java +++ b/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java @@ -119,38 +119,38 @@ public class CallbackClientImpl implements CallbackClient { break; case "chatMessage": { - ChatMessage message = (ChatMessage) callback.getData(); - ChatPanel panel = MageFrame.getChat(callback.getObjectId()); - if (panel != null) { - // play the to the message connected sound - if (message.getSoundToPlay() != null) { - switch (message.getSoundToPlay()) { - case PlayerLeft: - AudioManager.playPlayerLeft(); - break; - case PlayerQuitTournament: - AudioManager.playPlayerQuitTournament(); - break; - case PlayerSubmittedDeck: - AudioManager.playPlayerSubmittedDeck(); - break; - case PlayerWhispered: - AudioManager.playPlayerWhispered(); - break; - } - } - // send start message to chat if not done yet - if (!panel.isStartMessageDone()) { - createChatStartMessage(panel); - } - // send the message to subchat if exists and it's not a game message - if (!message.getMessageType().equals(MessageType.GAME) && panel.getConnectedChat() != null) { - panel.getConnectedChat().receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), ChatMessage.MessageColor.BLACK); - } else { - panel.receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), message.getColor()); - } - - } break; +// ChatMessage message = (ChatMessage) callback.getData(); +// ChatPanel panel = MageFrame.getChat(callback.getObjectId()); +// if (panel != null) { +// // play the to the message connected sound +// if (message.getSoundToPlay() != null) { +// switch (message.getSoundToPlay()) { +// case PlayerLeft: +// AudioManager.playPlayerLeft(); +// break; +// case PlayerQuitTournament: +// AudioManager.playPlayerQuitTournament(); +// break; +// case PlayerSubmittedDeck: +// AudioManager.playPlayerSubmittedDeck(); +// break; +// case PlayerWhispered: +// AudioManager.playPlayerWhispered(); +// break; +// } +// } +// // send start message to chat if not done yet +// if (!panel.isStartMessageDone()) { +// createChatStartMessage(panel); +// } +// // send the message to subchat if exists and it's not a game message +// if (!message.getMessageType().equals(MessageType.GAME) && panel.getConnectedChat() != null) { +// panel.getConnectedChat().receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), ChatMessage.MessageColor.BLACK); +// } else { +// panel.receiveMessage(message.getUsername(), message.getMessage(), message.getTime(), message.getMessageType(), message.getColor()); +// } +// +// } break; } case "serverMessage": if (callback.getData() != null) { @@ -392,38 +392,38 @@ public class CallbackClientImpl implements CallbackClient { }); } - private void createChatStartMessage(ChatPanel chatPanel) { - chatPanel.setStartMessageDone(true); - ChatPanel usedPanel = chatPanel; - if (chatPanel.getConnectedChat() != null) { - usedPanel = chatPanel.getConnectedChat(); - } - switch (usedPanel.getChatType()) { - case GAME: - usedPanel.receiveMessage("", new StringBuilder("You may use hot keys to play faster:") - .append("
Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over") - .append("
Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over") - .append("
F2 - Confirm \"Ok\", \"Yes\" or \"Done\" button") - .append("
F4 - Skip current turn but stop on declare attackers/blockers and something on the stack") - .append("
F5 - Skip to next end step but stop on declare attackers/blockers and something on the stack") - .append("
F7 - Skip to next main phase but stop on declare attackers/blockers and something on the stack") - .append("
F9 - Skip everything until your next turn") - .append("
F3 - Undo F4/F5/F7/F9").toString(), - null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); - break; - case TOURNAMENT: - usedPanel.receiveMessage("", new StringBuilder("On this panel you can see the players, their state and the results of the games of the tournament. Also you can chat with the competitors of the tournament.").toString(), - null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); - break; - case TABLES: - usedPanel.receiveMessage("", new StringBuilder("Download card images by using the \"Images\" menu to the top right .") - .append("
Download icons and symbols by using the \"Symbols\" menu to the top right.") - .append("
\\list - Show a list of available chat commands.").toString(), - null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); - break; - - } - } +// private void createChatStartMessage(ChatPanel chatPanel) { +// chatPanel.setStartMessageDone(true); +// ChatPanel usedPanel = chatPanel; +// if (chatPanel.getConnectedChat() != null) { +// usedPanel = chatPanel.getConnectedChat(); +// } +// switch (usedPanel.getChatType()) { +// case GAME: +// usedPanel.receiveMessage("", new StringBuilder("You may use hot keys to play faster:") +// .append("
Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over") +// .append("
Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over") +// .append("
F2 - Confirm \"Ok\", \"Yes\" or \"Done\" button") +// .append("
F4 - Skip current turn but stop on declare attackers/blockers and something on the stack") +// .append("
F5 - Skip to next end step but stop on declare attackers/blockers and something on the stack") +// .append("
F7 - Skip to next main phase but stop on declare attackers/blockers and something on the stack") +// .append("
F9 - Skip everything until your next turn") +// .append("
F3 - Undo F4/F5/F7/F9").toString(), +// null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); +// break; +// case TOURNAMENT: +// usedPanel.receiveMessage("", new StringBuilder("On this panel you can see the players, their state and the results of the games of the tournament. Also you can chat with the competitors of the tournament.").toString(), +// null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); +// break; +// case TABLES: +// usedPanel.receiveMessage("", new StringBuilder("Download card images by using the \"Images\" menu to the top right .") +// .append("
Download icons and symbols by using the \"Symbols\" menu to the top right.") +// .append("
\\list - Show a list of available chat commands.").toString(), +// null, MessageType.USER_INFO, ChatMessage.MessageColor.BLUE); +// break; +// +// } +// } private void joinedTable(UUID roomId, UUID tableId, boolean isTournament) { try { diff --git a/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java b/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java index 99f0bed4253..a450981d761 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TablePlayerPanel.java @@ -43,7 +43,8 @@ import mage.client.MageFrame; import mage.client.util.Config; import mage.client.util.Event; import mage.client.util.Listener; -import mage.remote.Session; +import org.mage.network.Client; +//import mage.remote.Session; /** * @@ -53,7 +54,7 @@ public class TablePlayerPanel extends javax.swing.JPanel { protected PlayerTypeEventSource playerTypeEventSource = new PlayerTypeEventSource(); - private Session session; + private Client client; /** Creates new form TablePlayerPanel */ public TablePlayerPanel() { @@ -62,8 +63,8 @@ public class TablePlayerPanel extends javax.swing.JPanel { } public void init(int playerNum, String playerType) { - session = MageFrame.getSession(); - cbPlayerType.setModel(new DefaultComboBoxModel(session.getPlayerTypes())); + client = MageFrame.getClient(); + cbPlayerType.setModel(new DefaultComboBoxModel(client.getServerState().getPlayerTypes())); this.lblPlayerNum.setText("Player " + playerNum); if (Config.defaultOtherPlayerIndex != null) { if (Integer.valueOf(Config.defaultOtherPlayerIndex) >= cbPlayerType.getItemCount()) { @@ -81,7 +82,7 @@ public class TablePlayerPanel extends javax.swing.JPanel { public boolean joinTable(UUID roomId, UUID tableId) throws FileNotFoundException, IOException, ClassNotFoundException { if (!this.cbPlayerType.getSelectedItem().equals("Human")) { - return session.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), (String)this.cbPlayerType.getSelectedItem(), this.newPlayerPanel.getLevel(), DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()),""); + return client.joinTable(roomId, tableId, this.newPlayerPanel.getPlayerName(), (String)this.cbPlayerType.getSelectedItem(), this.newPlayerPanel.getLevel(), DeckImporterUtil.importDeck(this.newPlayerPanel.getDeckFile()),""); } return true; } diff --git a/Mage.Client/src/main/java/mage/client/table/TablesPane.java b/Mage.Client/src/main/java/mage/client/table/TablesPane.java index cb2e3b0c578..4f20e5a1565 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablesPane.java +++ b/Mage.Client/src/main/java/mage/client/table/TablesPane.java @@ -62,7 +62,7 @@ public class TablesPane extends MagePane { } public void showTables() { - UUID roomId = MageFrame.getSession().getMainRoomId(); + UUID roomId = MageFrame.getClient().getServerState().getMainRoomId(); if (roomId != null) { this.setTitle("Tables"); tablesPanel.showTables(roomId); 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 d553b6d3241..91325a1ba72 100644 --- a/Mage.Client/src/main/java/mage/client/table/TablesPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TablesPanel.java @@ -88,12 +88,13 @@ import mage.constants.RangeOfInfluence; import mage.constants.SkillLevel; import mage.game.match.MatchOptions; import mage.remote.MageRemoteException; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.MatchView; import mage.view.RoomUsersView; import mage.view.TableView; import org.apache.log4j.Logger; import org.mage.card.arcane.Util; +import org.mage.network.Client; /** * @@ -113,7 +114,7 @@ public class TablesPanel extends javax.swing.JPanel { private NewTableDialog newTableDialog; private NewTournamentDialog newTournamentDialog; private GameChooser gameChooser; - private Session session; + private Client client; private List messages; private int currentMessage; private MageTableRowSorter activeTablesSorter; @@ -128,7 +129,7 @@ public class TablesPanel extends javax.swing.JPanel { gameChooser = new GameChooser(); initComponents(); - tableModel.setSession(session); + tableModel.setClient(client); tableTables.createDefaultColumnsFromModel(); @@ -174,7 +175,7 @@ public class TablesPanel extends javax.swing.JPanel { String owner = (String)tableModel.getValueAt(modelRow, TableTableModel.COLUMN_OWNER); switch (action) { case "Join": - if (owner.equals(session.getUserName()) || owner.startsWith(session.getUserName() + ",")) { + if (owner.equals(client.getUserName())) { try { JDesktopPane desktopPane = (JDesktopPane) MageFrame.getUI().getComponent(MageComponents.DESKTOP_PANE); JInternalFrame[] windows = desktopPane.getAllFramesInLayer(javax.swing.JLayeredPane.DEFAULT_LAYER); @@ -199,7 +200,7 @@ public class TablesPanel extends javax.swing.JPanel { logger.info("Joining tournament " + tableId); if (deckType.startsWith("Limited")) { if (!status.endsWith("PW")) { - session.joinTournamentTable(roomId, tableId, session.getUserName(), "Human", 1, null, ""); + client.joinTournamentTable(roomId, tableId, client.getUserName(), "Human", 1, null, ""); } else { joinTableDialog.showDialog(roomId, tableId, true, deckType.startsWith("Limited")); } @@ -213,24 +214,24 @@ public class TablesPanel extends javax.swing.JPanel { break; case "Remove": if (JOptionPane.showConfirmDialog(null, "Are you sure you want to remove table?", "Removing table", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - session.removeTable(roomId, tableId); + client.removeTable(roomId, tableId); } break; case "Show": if (isTournament) { logger.info("Showing tournament table " + tableId); - session.watchTable(roomId, tableId); + client.watchTable(roomId, tableId); } break; case "Watch": if (!isTournament) { logger.info("Watching table " + tableId); - session.watchTable(roomId, tableId); + client.watchTable(roomId, tableId); } break; case "Replay": logger.info("Replaying game " + gameId); - session.replayGame(gameId); + client.replayGame(gameId); break; } } @@ -249,7 +250,7 @@ public class TablesPanel extends javax.swing.JPanel { List gameList = matchesModel.getListofGames(modelRow); if (gameList != null && gameList.size() > 0) { if (gameList.size() == 1) { - session.replayGame(gameList.get(0)); + client.replayGame(gameList.get(0)); } else { gameChooser.show(gameList, MageFrame.getDesktop().getMousePosition()); @@ -260,7 +261,7 @@ public class TablesPanel extends javax.swing.JPanel { case "Show":; if (matchesModel.isTournament(modelRow)) { logger.info("Showing tournament table " + matchesModel.getTableId(modelRow)); - session.watchTable(roomId, matchesModel.getTableId(modelRow)); + client.watchTable(roomId, matchesModel.getTableId(modelRow)); } break; } @@ -387,18 +388,18 @@ public class TablesPanel extends javax.swing.JPanel { } public void startTasks() { - if (session != null) { + if (client != null) { if (updateTablesTask == null || updateTablesTask.isDone()) { - updateTablesTask = new UpdateTablesTask(session, roomId, this); + updateTablesTask = new UpdateTablesTask(client, roomId, this); updateTablesTask.execute(); } if (updatePlayersTask == null || updatePlayersTask.isDone()) { - updatePlayersTask = new UpdatePlayersTask(session, roomId, this.chatPanel); + updatePlayersTask = new UpdatePlayersTask(client, roomId, this.chatPanel); updatePlayersTask.execute(); } if (this.btnStateFinished.isSelected()) { if (updateMatchesTask == null || updateMatchesTask.isDone()) { - updateMatchesTask = new UpdateMatchesTask(session, roomId, this); + updateMatchesTask = new UpdateMatchesTask(client, roomId, this); updateMatchesTask.execute(); } } @@ -424,12 +425,12 @@ public class TablesPanel extends javax.swing.JPanel { public void showTables(UUID roomId) { this.roomId = roomId; - session = MageFrame.getSession(); + client = MageFrame.getClient(); UUID chatRoomId = null; - if (session != null) { - btnQuickStart.setVisible(session.isTestMode()); - gameChooser.init(session); - chatRoomId = session.getRoomChatId(roomId); + if (client != null) { + btnQuickStart.setVisible(client.getServerState().isTestMode()); + gameChooser.init(client); + chatRoomId = client.getRoomChatId(roomId); } if (newTableDialog == null) { newTableDialog = new NewTableDialog(); @@ -451,7 +452,7 @@ public class TablesPanel extends javax.swing.JPanel { } else { hideTables(); } - tableModel.setSession(session); + tableModel.setClient(client); reloadMessages(); @@ -469,7 +470,7 @@ public class TablesPanel extends javax.swing.JPanel { protected void reloadMessages() { // reload server messages - List serverMessages = session.getServerMessages(); + List serverMessages = client.getServerMessages(); synchronized (this) { this.messages = serverMessages; this.currentMessage = 0; @@ -1156,11 +1157,11 @@ public class TablesPanel extends javax.swing.JPanel { options.setWinsNeeded(1); options.setMatchTimeLimit(MatchTimeLimit.NONE); options.setFreeMulligans(2); - table = session.createTable(roomId, options); + table = client.createTable(roomId, options); - session.joinTable(roomId, table.getTableId(), "Human", "Human", 1, DeckImporterUtil.importDeck("test.dck"),""); - session.joinTable(roomId, table.getTableId(), "Computer", "Computer - mad", 5, DeckImporterUtil.importDeck("test.dck"),""); - session.startMatch(roomId, table.getTableId()); + client.joinTable(roomId, table.getTableId(), "Human", "Human", 1, DeckImporterUtil.importDeck("test.dck"),""); + client.joinTable(roomId, table.getTableId(), "Computer", "Computer - mad", 5, DeckImporterUtil.importDeck("test.dck"),""); + client.startMatch(roomId, table.getTableId()); } catch (HeadlessException ex) { handleError(ex); } @@ -1266,7 +1267,7 @@ class TableTableModel extends AbstractTableModel { private TableView[] tables = new TableView[0]; private static final DateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");; - private Session session; + private Client client; public void loadData(Collection tables) throws MageRemoteException { this.tables = tables.toArray(new TableView[0]); @@ -1308,8 +1309,8 @@ class TableTableModel extends AbstractTableModel { return columnNames.length; } - public void setSession(Session session) { - this.session = session; + public void setClient(Client client) { + this.client = client; } @Override @@ -1336,7 +1337,7 @@ class TableTableModel extends AbstractTableModel { case WAITING: String owner = tables[arg0].getControllerName(); - if (session != null && owner.equals(session.getUserName())) { + if (client != null && owner.equals(client.getUserName())) { return ""; } return "Join"; @@ -1350,7 +1351,7 @@ class TableTableModel extends AbstractTableModel { return "Show"; } else { owner = tables[arg0].getControllerName(); - if (session != null && owner.equals(session.getUserName())) { + if (client != null && owner.equals(client.getUserName())) { return ""; } return "Watch"; @@ -1403,7 +1404,7 @@ class TableTableModel extends AbstractTableModel { class UpdateTablesTask extends SwingWorker> { - private final Session session; + private final Client client; private final UUID roomId; private final TablesPanel panel; @@ -1411,8 +1412,8 @@ class UpdateTablesTask extends SwingWorker> { private int count = 0; - UpdateTablesTask(Session session, UUID roomId, TablesPanel panel) { - this.session = session; + UpdateTablesTask(Client client, UUID roomId, TablesPanel panel) { + this.client = client; this.roomId = roomId; this.panel = panel; } @@ -1420,7 +1421,7 @@ class UpdateTablesTask extends SwingWorker> { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - Collection tables = session.getTables(roomId); + Collection tables = client.getTables(roomId); if (tables != null) { this.publish(tables); } @@ -1452,14 +1453,14 @@ class UpdateTablesTask extends SwingWorker> { class UpdatePlayersTask extends SwingWorker> { - private final Session session; + private final Client client; private final UUID roomId; private final ChatPanel chat; private static final Logger logger = Logger.getLogger(UpdatePlayersTask.class); - UpdatePlayersTask(Session session, UUID roomId, ChatPanel chat) { - this.session = session; + UpdatePlayersTask(Client client, UUID roomId, ChatPanel chat) { + this.client = client; this.roomId = roomId; this.chat = chat; } @@ -1467,7 +1468,7 @@ class UpdatePlayersTask extends SwingWorker> { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - this.publish(session.getRoomUsers(roomId)); + this.publish(client.getRoomUsers(roomId)); Thread.sleep(3000); } return null; @@ -1593,14 +1594,14 @@ class MatchesTableModel extends AbstractTableModel { class UpdateMatchesTask extends SwingWorker> { - private final Session session; + private final Client client; private final UUID roomId; private final TablesPanel panel; private static final Logger logger = Logger.getLogger(UpdateTablesTask.class); - UpdateMatchesTask(Session session, UUID roomId, TablesPanel panel) { - this.session = session; + UpdateMatchesTask(Client client, UUID roomId, TablesPanel panel) { + this.client = client; this.roomId = roomId; this.panel = panel; } @@ -1608,7 +1609,7 @@ class UpdateMatchesTask extends SwingWorker> { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - Collection matches = session.getFinishedMatches(roomId); + Collection matches = client.getFinishedMatches(roomId); if (matches != null) { this.publish(matches); } @@ -1635,10 +1636,10 @@ class UpdateMatchesTask extends SwingWorker> { class GameChooser extends JPopupMenu { - private Session session; + private Client client; - public void init(Session session) { - this.session = session; + public void init(Client client) { + this.client = client; } public void show(List games, Point p) { @@ -1664,7 +1665,7 @@ class GameChooser extends JPopupMenu { @Override public void actionPerformed(ActionEvent e) { - session.replayGame(id); + client.replayGame(id); setVisible(false); } diff --git a/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java b/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java index ada1fe1f034..2d2e69be2e8 100644 --- a/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/table/TournamentPlayerPanel.java @@ -40,7 +40,8 @@ import javax.swing.JComboBox; import mage.cards.decks.DeckCardLists; import mage.cards.decks.importer.DeckImporterUtil; import mage.client.MageFrame; -import mage.remote.Session; +import org.mage.network.Client; +//import mage.remote.Session; /** * @@ -48,7 +49,7 @@ import mage.remote.Session; */ public class TournamentPlayerPanel extends javax.swing.JPanel { - private Session session; + private Client client; /** Creates new form TournamentPlayerPanel */ public TournamentPlayerPanel() { @@ -57,8 +58,8 @@ public class TournamentPlayerPanel extends javax.swing.JPanel { } public void init(int playerNum) { - session = MageFrame.getSession(); - cbPlayerType.setModel(new DefaultComboBoxModel(session.getPlayerTypes())); + client = MageFrame.getClient(); + cbPlayerType.setModel(new DefaultComboBoxModel(client.getServerState().getPlayerTypes())); this.lblPlayerNum.setText("Player " + playerNum); } @@ -68,7 +69,7 @@ public class TournamentPlayerPanel extends javax.swing.JPanel { public boolean joinTournamentTable(UUID roomId, UUID tableId, DeckCardLists deckCardLists) { if (!this.cbPlayerType.getSelectedItem().equals("Human")) { - return session.joinTournamentTable( + return client.joinTournamentTable( roomId, tableId, this.txtPlayerName.getText(), 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 6b681fc17d3..a8895dbc4e4 100644 --- a/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java +++ b/Mage.Client/src/main/java/mage/client/tournament/TournamentPanel.java @@ -53,12 +53,13 @@ import mage.client.chat.ChatPanel; import mage.client.dialog.PreferencesDialog; import mage.client.util.ButtonColumn; import mage.client.util.Format; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.RoundView; import mage.view.TournamentGameView; import mage.view.TournamentPlayerView; import mage.view.TournamentView; import org.apache.log4j.Logger; +import org.mage.network.Client; /** * @@ -70,7 +71,7 @@ public class TournamentPanel extends javax.swing.JPanel { private UUID tournamentId; private boolean firstInitDone = false; - private Session session; + private Client client; private final TournamentPlayersTableModel playersModel; private TournamentMatchesTableModel matchesModel; private UpdateTournamentTask updateTask; @@ -112,7 +113,7 @@ public class TournamentPanel extends javax.swing.JPanel { // } if (state.startsWith("Dueling") && actionText.equals("Watch")) { logger.info("Watching game " + gameId); - session.watchTournamentTable(tableId); + client.watchTournamentTable(tableId); } } }; @@ -159,10 +160,10 @@ public class TournamentPanel extends javax.swing.JPanel { public synchronized void showTournament(UUID tournamentId) { this.tournamentId = tournamentId; - session = MageFrame.getSession(); + client = MageFrame.getClient(); // MageFrame.addTournament(tournamentId, this); - UUID chatRoomId = session.getTournamentChatId(tournamentId); - if (session.joinTournament(tournamentId) && chatRoomId != null) { + UUID chatRoomId = client.getTournamentChatId(tournamentId); + if (client.joinTournament(tournamentId) && chatRoomId != null) { this.chatPanel1.connect(chatRoomId); startTasks(); this.setVisible(true); @@ -248,7 +249,7 @@ public class TournamentPanel extends javax.swing.JPanel { btnQuitTournament.setVisible(false); if (tournament.getEndTime() == null) { for (TournamentPlayerView player : tournament.getPlayers()) { - if (player.getName().equals(session.getUserName())) { + if (player.getName().equals(client.getUserName())) { if (!player.hasQuit()) { btnQuitTournament.setVisible(true); } @@ -260,9 +261,9 @@ public class TournamentPanel extends javax.swing.JPanel { } public void startTasks() { - if (session != null) { + if (client != null) { if (updateTask == null || updateTask.isDone()) { - updateTask = new UpdateTournamentTask(session, tournamentId, this); + updateTask = new UpdateTournamentTask(client, tournamentId, this); updateTask.execute(); } } @@ -496,7 +497,7 @@ public class TournamentPanel extends javax.swing.JPanel { private void btnQuitTournamentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitTournamentActionPerformed if (JOptionPane.showConfirmDialog(this, "Are you sure you want to quit the tournament?", "Confirm quit tournament", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - MageFrame.getSession().quitTournament(tournamentId); + MageFrame.getClient().quitTournament(tournamentId); } }//GEN-LAST:event_btnQuitTournamentActionPerformed @@ -673,14 +674,14 @@ class TournamentMatchesTableModel extends AbstractTableModel { class UpdateTournamentTask extends SwingWorker { - private final Session session; + private final Client client; private final UUID tournamentId; private final TournamentPanel panel; private static final Logger logger = Logger.getLogger(UpdateTournamentTask.class); - UpdateTournamentTask(Session session, UUID tournamentId, TournamentPanel panel) { - this.session = session; + UpdateTournamentTask(Client client, UUID tournamentId, TournamentPanel panel) { + this.client = client; this.tournamentId = tournamentId; this.panel = panel; } @@ -688,7 +689,7 @@ class UpdateTournamentTask extends SwingWorker { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - this.publish(session.getTournament(tournamentId)); + this.publish(client.getTournament(tournamentId)); Thread.sleep(2000); } return null; diff --git a/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java b/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java index 6e35211152e..6527ed7d22a 100644 --- a/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java +++ b/Mage.Client/src/main/java/mage/client/unusedFiles/PlayerPanel.java @@ -41,8 +41,9 @@ import mage.client.MageFrame; import mage.client.cards.BigCard; import mage.client.dialog.ShowCardsDialog; import mage.client.util.Config; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.PlayerView; +import org.mage.network.Client; /** * @@ -52,7 +53,7 @@ public class PlayerPanel extends javax.swing.JPanel { private UUID playerId; private UUID gameId; - private Session session; + private Client client; private PlayerView player; private ShowCardsDialog graveyard; @@ -67,7 +68,7 @@ public class PlayerPanel extends javax.swing.JPanel { this.gameId = gameId; this.playerId = playerId; this.bigCard = bigCard; - session = MageFrame.getSession(); + client = MageFrame.getClient(); } public void update(PlayerView player) { @@ -194,7 +195,7 @@ public class PlayerPanel extends javax.swing.JPanel { }// //GEN-END:initComponents private void btnPlayerNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayerNameActionPerformed - session.sendPlayerUUID(gameId, playerId); + client.sendPlayerUUID(gameId, playerId); }//GEN-LAST:event_btnPlayerNameActionPerformed private void btnGraveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGraveActionPerformed diff --git a/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java b/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java index c2fe64b6b03..eb969f293ff 100644 --- a/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java +++ b/Mage.Client/src/main/java/mage/client/util/DefaultActionCallback.java @@ -3,8 +3,9 @@ package mage.client.util; import java.awt.event.MouseEvent; import java.util.UUID; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.CardView; +import org.mage.network.Client; public class DefaultActionCallback { @@ -17,12 +18,12 @@ public class DefaultActionCallback { return INSTANCE; } - public void mouseClicked(MouseEvent e, UUID gameId, Session session, CardView card) { + public void mouseClicked(MouseEvent e, UUID gameId, Client client, CardView card) { if (gameId != null) { if (card.isAbility() && card.getAbility() != null) { - session.sendPlayerUUID(gameId, card.getAbility().getId()); + client.sendPlayerUUID(gameId, card.getAbility().getId()); } else { - session.sendPlayerUUID(gameId, card.getId()); + client.sendPlayerUUID(gameId, card.getId()); } } } diff --git a/Mage.Client/src/test/java/mage/client/game/MultiConnectTest.java b/Mage.Client/src/test/java/mage/client/game/MultiConnectTest.java index 3207e33122d..d54a08287d1 100644 --- a/Mage.Client/src/test/java/mage/client/game/MultiConnectTest.java +++ b/Mage.Client/src/test/java/mage/client/game/MultiConnectTest.java @@ -1,17 +1,23 @@ package mage.client.game; +import java.util.UUID; import mage.client.components.MageUI; -import mage.interfaces.MageClient; -import mage.interfaces.callback.ClientCallback; +//import mage.interfaces.MageClient; +//import mage.interfaces.callback.ClientCallback; import mage.remote.Connection; -import mage.remote.Session; -import mage.remote.SessionImpl; +//import mage.remote.Session; +//import mage.remote.SessionImpl; import mage.utils.MageVersion; import org.apache.log4j.Logger; import org.junit.Ignore; import javax.swing.*; import java.util.concurrent.CountDownLatch; +import mage.interfaces.ServerState; +import mage.view.ChatMessage; +import org.mage.network.Client; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.MessageType; /** * Test for emulating the connection from multi mage clients. @@ -39,25 +45,25 @@ public class MultiConnectTest { private class ClientMock implements MageClient { - private Session session; + private Client client; private final String username; + private ServerState serverState; public ClientMock(String username) { this.username = username; } public void connect() { - session = new SessionImpl(this); + client = new Client(this); Connection connection = new Connection(); connection.setUsername(username); connection.setHost("localhost"); connection.setPort(17171); connection.setProxyType(Connection.ProxyType.NONE); - session.connect(connection); + client.connect(username, "localhost", 17171, version); } - @Override public MageVersion getVersion() { logger.info("getVersion"); return version; @@ -69,24 +75,51 @@ public class MultiConnectTest { connected++; } - @Override public void disconnected(boolean errorCall) { logger.info("disconnected"); } - @Override public void showMessage(String message) { logger.info("showMessage: " + message); } - @Override public void showError(String message) { logger.info("showError: " + message); } +// @Override +// public void processCallback(ClientCallback callback) { +// logger.info("processCallback"); +// } + @Override - public void processCallback(ClientCallback callback) { - logger.info("processCallback"); + public void inform(String message, MessageType type) { + if (type == MessageType.ERROR) { + showError(message); + } + else { + showMessage(message); + } + } + + @Override + public void receiveChatMessage(UUID chatId, ChatMessage message) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void receiveBroadcastMessage(String message) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void clientRegistered(ServerState state) { + this.serverState = state; + } + + @Override + public ServerState getServerState() { + return serverState; } } diff --git a/Mage.Common/src/mage/interfaces/MageServer.java b/Mage.Common/src/mage/interfaces/MageServer.java index fd86ee26645..1719435ca22 100644 --- a/Mage.Common/src/mage/interfaces/MageServer.java +++ b/Mage.Common/src/mage/interfaces/MageServer.java @@ -1,158 +1,158 @@ -/* -* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without modification, are -* permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, this list of -* conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright notice, this list -* of conditions and the following disclaimer in the documentation and/or other materials -* provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR -* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* The views and conclusions contained in the software and documentation are those of the -* authors and should not be interpreted as representing official policies, either expressed -* or implied, of BetaSteward_at_googlemail.com. -*/ - -package mage.interfaces; - -import java.util.List; -import java.util.Set; -import java.util.UUID; -import mage.MageException; -import mage.cards.decks.DeckCardLists; -import mage.cards.repository.CardInfo; -import mage.cards.repository.ExpansionInfo; -import mage.constants.ManaType; -import mage.constants.PlayerAction; -import mage.game.GameException; -import mage.game.match.MatchOptions; -import mage.game.tournament.TournamentOptions; -import mage.utils.MageVersion; -import mage.view.DraftPickView; -import mage.view.GameView; -import mage.view.MatchView; -import mage.view.TableView; -import mage.view.TournamentView; -import mage.view.UserDataView; -import mage.view.RoomUsersView; -import mage.view.UserView; - -/** - * - * @author BetaSteward_at_googlemail.com - */ -public interface MageServer { - - // connection methods - boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException; - boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException; -// Not used -// void deregisterClient(String sessionId) throws MageException; - - // update methods - List getMissingExpansionData(List codes); - List getMissingCardsData(List classNames); - - // user methods - boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException; - void sendFeedbackMessage(String sessionId, String username, String title, String type, String message, String email) throws MageException; - - // server state methods - ServerState getServerState() throws MageException; - List getRoomUsers(UUID roomId) throws MageException; - List getFinishedMatches(UUID roomId) throws MageException; - Object getServerMessagesCompressed(String sessionId) throws MageException; // messages of the day - - // ping - extends session - boolean ping(String sessionId, String pingInfo) throws MageException; - - //table methods - TableView createTable(String sessionId, UUID roomId, MatchOptions matchOptions) throws MageException; - TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions tournamentOptions) throws MageException; - boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException; - boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException; - boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; - void updateDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; - boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException; - boolean watchTournamentTable(String sessionId, UUID tableId) throws MageException; - boolean leaveTable(String sessionId, UUID roomId, UUID tableId) throws MageException; - void swapSeats(String sessionId, UUID roomId, UUID tableId, int seatNum1, int seatNum2) throws MageException; - void removeTable(String sessionId, UUID roomId, UUID tableId) throws MageException; - boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException; - TableView getTable(UUID roomId, UUID tableId) throws MageException; - List getTables(UUID roomId) throws MageException; - - //chat methods - void sendChatMessage(UUID chatId, String userName, String message) throws MageException; - void joinChat(UUID chatId, String sessionId, String userName) throws MageException; - void leaveChat(UUID chatId, String sessionId) throws MageException; - UUID getTableChatId(UUID tableId) throws MageException; - UUID getGameChatId(UUID gameId) throws MageException; - UUID getRoomChatId(UUID roomId) throws MageException; - UUID getTournamentChatId(UUID tournamentId) throws MageException; - - //room methods - UUID getMainRoomId() throws MageException; - - //game methods - boolean startMatch(String sessionId, UUID roomId, UUID tableId) throws MageException; - void joinGame(UUID gameId, String sessionId) throws MageException; - void watchGame(UUID gameId, String sessionId) throws MageException; - void stopWatching(UUID gameId, String sessionId) throws MageException; - void sendPlayerUUID(UUID gameId, String sessionId, UUID data) throws MageException; - void sendPlayerString(UUID gameId, String sessionId, String data) throws MageException; - void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data) throws MageException; - void sendPlayerInteger(UUID gameId, String sessionId, Integer data) throws MageException; - void sendPlayerManaType(UUID gameId, UUID playerId, String sessionId, ManaType data) throws MageException; - void quitMatch(UUID gameId, String sessionId) throws MageException; - GameView getGameView(UUID gameId, String sessionId, UUID playerId) throws MageException; - // priority, undo, concede, mana pool - void sendPlayerAction(PlayerAction playerAction, UUID gameId, String sessionId, Object data) throws MageException; - - //tournament methods - boolean startTournament(String sessionId, UUID roomId, UUID tableId) throws MageException; - void joinTournament(UUID draftId, String sessionId) throws MageException; - void quitTournament(UUID tournamentId, String sessionId) throws MageException; - TournamentView getTournament(UUID tournamentId) throws MageException; - - //draft methods - void joinDraft(UUID draftId, String sessionId) throws MageException; - void quitDraft(UUID draftId, String sessionId) throws MageException; - DraftPickView sendCardPick(UUID draftId, String sessionId, UUID cardId, Set hiddenCards) throws MageException; - void sendCardMark(UUID draftId, String sessionId, UUID cardId) throws MageException; - - //challenge methods - // void startChallenge(String sessionId, UUID roomId, UUID tableId, UUID challengeId) throws MageException; - - //replay methods - void replayGame(UUID gameId, String sessionId) throws MageException; - void startReplay(UUID gameId, String sessionId) throws MageException; - void stopReplay(UUID gameId, String sessionId) throws MageException; - void nextPlay(UUID gameId, String sessionId) throws MageException; - void previousPlay(UUID gameId, String sessionId) throws MageException; - void skipForward(UUID gameId, String sessionId, int moves) throws MageException; - - //test methods - void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList) throws MageException; - boolean cheat(UUID gameId, String sessionId, UUID playerId, String cardName) throws MageException; - - //admin methods - List getUsers(String sessionId) throws MageException; - void disconnectUser(String sessionId, String userSessionId) throws MageException; - void endUserSession(String sessionId, String userSessionId) throws MageException; - void removeTable(String sessionId, UUID tableId) throws MageException; - void sendBroadcastMessage(String sessionId, String message) throws MageException; -} +///* +//* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. +//* +//* Redistribution and use in source and binary forms, with or without modification, are +//* permitted provided that the following conditions are met: +//* +//* 1. Redistributions of source code must retain the above copyright notice, this list of +//* conditions and the following disclaimer. +//* +//* 2. Redistributions in binary form must reproduce the above copyright notice, this list +//* of conditions and the following disclaimer in the documentation and/or other materials +//* provided with the distribution. +//* +//* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED +//* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +//* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR +//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +//* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +//* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +//* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +//* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +//* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//* +//* The views and conclusions contained in the software and documentation are those of the +//* authors and should not be interpreted as representing official policies, either expressed +//* or implied, of BetaSteward_at_googlemail.com. +//*/ +// +//package mage.interfaces; +// +//import java.util.List; +//import java.util.Set; +//import java.util.UUID; +//import mage.MageException; +//import mage.cards.decks.DeckCardLists; +//import mage.cards.repository.CardInfo; +//import mage.cards.repository.ExpansionInfo; +//import mage.constants.ManaType; +//import mage.constants.PlayerAction; +//import mage.game.GameException; +//import mage.game.match.MatchOptions; +//import mage.game.tournament.TournamentOptions; +//import mage.utils.MageVersion; +//import mage.view.DraftPickView; +//import mage.view.GameView; +//import mage.view.MatchView; +//import mage.view.TableView; +//import mage.view.TournamentView; +//import mage.view.UserDataView; +//import mage.view.RoomUsersView; +//import mage.view.UserView; +// +///** +// * +// * @author BetaSteward_at_googlemail.com +// */ +//public interface MageServer { +// +// // connection methods +// boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException; +// boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException; +//// Not used +//// void deregisterClient(String sessionId) throws MageException; +// +// // update methods +// List getMissingExpansionData(List codes); +// List getMissingCardsData(List classNames); +// +// // user methods +// boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException; +// void sendFeedbackMessage(String sessionId, String username, String title, String type, String message, String email) throws MageException; +// +// // server state methods +// ServerState getServerState() throws MageException; +// List getRoomUsers(UUID roomId) throws MageException; +// List getFinishedMatches(UUID roomId) throws MageException; +// Object getServerMessagesCompressed(String sessionId) throws MageException; // messages of the day +// +// // ping - extends session +// boolean ping(String sessionId, String pingInfo) throws MageException; +// +// //table methods +// TableView createTable(String sessionId, UUID roomId, MatchOptions matchOptions) throws MageException; +// TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions tournamentOptions) throws MageException; +// boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException; +// boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException, GameException; +// boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; +// void updateDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException; +// boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException; +// boolean watchTournamentTable(String sessionId, UUID tableId) throws MageException; +// boolean leaveTable(String sessionId, UUID roomId, UUID tableId) throws MageException; +// void swapSeats(String sessionId, UUID roomId, UUID tableId, int seatNum1, int seatNum2) throws MageException; +// void removeTable(String sessionId, UUID roomId, UUID tableId) throws MageException; +// boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException; +// TableView getTable(UUID roomId, UUID tableId) throws MageException; +// List getTables(UUID roomId) throws MageException; +// +// //chat methods +// void sendChatMessage(UUID chatId, String userName, String message) throws MageException; +// void joinChat(UUID chatId, String sessionId, String userName) throws MageException; +// void leaveChat(UUID chatId, String sessionId) throws MageException; +// UUID getTableChatId(UUID tableId) throws MageException; +// UUID getGameChatId(UUID gameId) throws MageException; +// UUID getRoomChatId(UUID roomId) throws MageException; +// UUID getTournamentChatId(UUID tournamentId) throws MageException; +// +// //room methods +// UUID getMainRoomId() throws MageException; +// +// //game methods +// boolean startMatch(String sessionId, UUID roomId, UUID tableId) throws MageException; +// void joinGame(UUID gameId, String sessionId) throws MageException; +// void watchGame(UUID gameId, String sessionId) throws MageException; +// void stopWatching(UUID gameId, String sessionId) throws MageException; +// void sendPlayerUUID(UUID gameId, String sessionId, UUID data) throws MageException; +// void sendPlayerString(UUID gameId, String sessionId, String data) throws MageException; +// void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data) throws MageException; +// void sendPlayerInteger(UUID gameId, String sessionId, Integer data) throws MageException; +// void sendPlayerManaType(UUID gameId, UUID playerId, String sessionId, ManaType data) throws MageException; +// void quitMatch(UUID gameId, String sessionId) throws MageException; +// GameView getGameView(UUID gameId, String sessionId, UUID playerId) throws MageException; +// // priority, undo, concede, mana pool +// void sendPlayerAction(PlayerAction playerAction, UUID gameId, String sessionId, Object data) throws MageException; +// +// //tournament methods +// boolean startTournament(String sessionId, UUID roomId, UUID tableId) throws MageException; +// void joinTournament(UUID draftId, String sessionId) throws MageException; +// void quitTournament(UUID tournamentId, String sessionId) throws MageException; +// TournamentView getTournament(UUID tournamentId) throws MageException; +// +// //draft methods +// void joinDraft(UUID draftId, String sessionId) throws MageException; +// void quitDraft(UUID draftId, String sessionId) throws MageException; +// DraftPickView sendCardPick(UUID draftId, String sessionId, UUID cardId, Set hiddenCards) throws MageException; +// void sendCardMark(UUID draftId, String sessionId, UUID cardId) throws MageException; +// +// //challenge methods +// // void startChallenge(String sessionId, UUID roomId, UUID tableId, UUID challengeId) throws MageException; +// +// //replay methods +// void replayGame(UUID gameId, String sessionId) throws MageException; +// void startReplay(UUID gameId, String sessionId) throws MageException; +// void stopReplay(UUID gameId, String sessionId) throws MageException; +// void nextPlay(UUID gameId, String sessionId) throws MageException; +// void previousPlay(UUID gameId, String sessionId) throws MageException; +// void skipForward(UUID gameId, String sessionId, int moves) throws MageException; +// +// //test methods +// void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList) throws MageException; +// boolean cheat(UUID gameId, String sessionId, UUID playerId, String cardName) throws MageException; +// +// //admin methods +// List getUsers(String sessionId) throws MageException; +// void disconnectUser(String sessionId, String userSessionId) throws MageException; +// void endUserSession(String sessionId, String userSessionId) throws MageException; +// void removeTable(String sessionId, UUID tableId) throws MageException; +// void sendBroadcastMessage(String sessionId, String message) throws MageException; +//} diff --git a/Mage.Common/src/mage/interfaces/ServerState.java b/Mage.Common/src/mage/interfaces/ServerState.java index 83e0ddbbf4e..abf7fc00677 100644 --- a/Mage.Common/src/mage/interfaces/ServerState.java +++ b/Mage.Common/src/mage/interfaces/ServerState.java @@ -31,6 +31,7 @@ package mage.interfaces; import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import mage.utils.MageVersion; import mage.view.GameTypeView; import mage.view.TournamentTypeView; @@ -50,10 +51,12 @@ public class ServerState implements Serializable { private final MageVersion version; private final long cardsContentVersion; private final long expansionsContentVersion; + private final UUID mainRoomId; public ServerState(List gameTypes, List tournamentTypes, String[] playerTypes, String[] deckTypes, String[] draftCubes, boolean testMode, - MageVersion version, long cardsContentVersion, long expansionsContentVersion) { + MageVersion version, long cardsContentVersion, long expansionsContentVersion, + UUID mainRoomId) { this.gameTypes = gameTypes; this.tournamentTypes = tournamentTypes; this.playerTypes = playerTypes; @@ -63,7 +66,7 @@ public class ServerState implements Serializable { this.version = version; this.cardsContentVersion = cardsContentVersion; this.expansionsContentVersion = expansionsContentVersion; - + this.mainRoomId = mainRoomId; } public List getGameTypes() { @@ -112,4 +115,8 @@ public class ServerState implements Serializable { return expansionsContentVersion; } + public UUID getMainRoomId() { + return mainRoomId; + } + } diff --git a/Mage.Common/src/mage/remote/Session.java b/Mage.Common/src/mage/remote/Session.java index 8cb062c63ef..dc1e5c55a2a 100644 --- a/Mage.Common/src/mage/remote/Session.java +++ b/Mage.Common/src/mage/remote/Session.java @@ -1,49 +1,49 @@ -/* -* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without modification, are -* permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, this list of -* conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright notice, this list -* of conditions and the following disclaimer in the documentation and/or other materials -* provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR -* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* The views and conclusions contained in the software and documentation are those of the -* authors and should not be interpreted as representing official policies, either expressed -* or implied, of BetaSteward_at_googlemail.com. -*/ - -package mage.remote; - -import mage.remote.interfaces.ChatSession; -import mage.remote.interfaces.ClientData; -import mage.remote.interfaces.Connect; -import mage.remote.interfaces.Feedback; -import mage.remote.interfaces.GamePlay; -import mage.remote.interfaces.GameTypes; -import mage.remote.interfaces.PlayerActions; -import mage.remote.interfaces.Replays; -import mage.remote.interfaces.ServerState; -import mage.remote.interfaces.Testable; - -/** - * Extracted interface for SessionImpl class. - * - * @author noxx - */ -public interface Session extends ClientData, Connect, GamePlay, GameTypes, ServerState, ChatSession, Feedback, PlayerActions, Replays, Testable { - -} +///* +//* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. +//* +//* Redistribution and use in source and binary forms, with or without modification, are +//* permitted provided that the following conditions are met: +//* +//* 1. Redistributions of source code must retain the above copyright notice, this list of +//* conditions and the following disclaimer. +//* +//* 2. Redistributions in binary form must reproduce the above copyright notice, this list +//* of conditions and the following disclaimer in the documentation and/or other materials +//* provided with the distribution. +//* +//* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED +//* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +//* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR +//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +//* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +//* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +//* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +//* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +//* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//* +//* The views and conclusions contained in the software and documentation are those of the +//* authors and should not be interpreted as representing official policies, either expressed +//* or implied, of BetaSteward_at_googlemail.com. +//*/ +// +//package mage.remote; +// +//import mage.remote.interfaces.ChatSession; +//import mage.remote.interfaces.ClientData; +//import mage.remote.interfaces.Connect; +//import mage.remote.interfaces.Feedback; +//import mage.remote.interfaces.GamePlay; +//import mage.remote.interfaces.GameTypes; +//import mage.remote.interfaces.PlayerActions; +//import mage.remote.interfaces.Replays; +//import mage.remote.interfaces.ServerState; +//import mage.remote.interfaces.Testable; +// +///** +// * Extracted interface for SessionImpl class. +// * +// * @author noxx +// */ +//public interface Session extends ClientData, Connect, GamePlay, GameTypes, ServerState, ChatSession, Feedback, PlayerActions, Replays, Testable { +// +//} diff --git a/Mage.Common/src/mage/remote/SessionImpl.java b/Mage.Common/src/mage/remote/SessionImpl.java index 3ae7e622083..2263f5152a7 100644 --- a/Mage.Common/src/mage/remote/SessionImpl.java +++ b/Mage.Common/src/mage/remote/SessionImpl.java @@ -1,1107 +1,606 @@ -/* -* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without modification, are -* permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, this list of -* conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright notice, this list -* of conditions and the following disclaimer in the documentation and/or other materials -* provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR -* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* The views and conclusions contained in the software and documentation are those of the -* authors and should not be interpreted as representing official policies, either expressed -* or implied, of BetaSteward_at_googlemail.com. -*/ - -package mage.remote; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.Authenticator; -import java.net.ConnectException; -import java.net.MalformedURLException; -import java.net.PasswordAuthentication; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import mage.MageException; -import mage.cards.decks.DeckCardLists; -import mage.cards.decks.InvalidDeckException; -import mage.cards.repository.CardInfo; -import mage.cards.repository.CardRepository; -import mage.cards.repository.ExpansionInfo; -import mage.cards.repository.ExpansionRepository; -import mage.constants.Constants.SessionState; -import mage.constants.ManaType; -import mage.constants.PlayerAction; -import mage.game.GameException; -import mage.game.match.MatchOptions; -import mage.game.tournament.TournamentOptions; -import mage.interfaces.MageClient; -import mage.interfaces.MageServer; -import mage.interfaces.ServerState; -import mage.interfaces.callback.ClientCallback; -import mage.utils.CompressUtil; -import mage.players.net.UserSkipPrioritySteps; -import mage.view.DraftPickView; -import mage.view.GameTypeView; -import mage.view.MatchView; -import mage.view.RoomUsersView; -import mage.view.TableView; -import mage.view.TournamentTypeView; -import mage.view.TournamentView; -import mage.view.UserDataView; -import mage.view.UserView; -import org.apache.log4j.Logger; -import org.jboss.remoting.CannotConnectException; -import org.jboss.remoting.Client; -import org.jboss.remoting.ConnectionListener; -import org.jboss.remoting.ConnectionValidator; -import org.jboss.remoting.InvocationFailureException; -import org.jboss.remoting.InvokerLocator; -import org.jboss.remoting.Remoting; -import org.jboss.remoting.callback.Callback; -import org.jboss.remoting.callback.HandleCallbackException; -import org.jboss.remoting.callback.InvokerCallbackHandler; -import org.jboss.remoting.transport.bisocket.Bisocket; -import org.jboss.remoting.transport.socket.SocketWrapper; -import org.jboss.remoting.transporter.TransporterClient; - -/** - * - * @author BetaSteward_at_googlemail.com - */ -public class SessionImpl implements Session { - - private static final Logger logger = Logger.getLogger(SessionImpl.class); - - private final MageClient client; - - private String sessionId; - private MageServer server; - private Client callbackClient; - private CallbackHandler callbackHandler; - private ServerState serverState; - private SessionState sessionState = SessionState.DISCONNECTED; - private Connection connection; - private final static int PING_CYCLES = 10; - private final LinkedList pingTime = new LinkedList<>(); - private String pingInfo = ""; - private static boolean debugMode = false; - - private boolean canceled = false; - - static { - debugMode = System.getProperty("debug.mage") != null; - } - - public SessionImpl(MageClient client) { - this.client = client; - } - - @Override - public String getSessionId() { - return sessionId; - } - - @Override - public synchronized boolean connect(Connection connection) { - if (isConnected()) { - disconnect(true); - } - this.connection = connection; - this.canceled = false; - return connect(); - } - - @Override - public boolean stopConnecting() { - canceled = true; - return true; - } - - @Override - public boolean connect() { - sessionState = SessionState.CONNECTING; - try { - System.setProperty("http.nonProxyHosts", "code.google.com"); - System.setProperty("socksNonProxyHosts", "code.google.com"); - - // clear previous values - System.clearProperty("socksProxyHost"); - System.clearProperty("socksProxyPort"); - System.clearProperty("http.proxyHost"); - System.clearProperty("http.proxyPort"); - - switch (connection.getProxyType()) { - case SOCKS: - System.setProperty("socksProxyHost", connection.getProxyHost()); - System.setProperty("socksProxyPort", Integer.toString(connection.getProxyPort())); - break; - case HTTP: - System.setProperty("http.proxyHost", connection.getProxyHost()); - System.setProperty("http.proxyPort", Integer.toString(connection.getProxyPort())); - Authenticator.setDefault(new MageAuthenticator(connection.getProxyUsername(), connection.getProxyPassword())); - break; - } - InvokerLocator clientLocator = new InvokerLocator(connection.getURI()); - - Map metadata = new HashMap<>(); - /* - 5.8.3.1.1. Write timeouts - The socket timeout facility offered by the JDK applies only to read operations on the socket. As of release 2.5.2, - the socket and bisocket (and also sslsocket and sslbisocket) transports offer a write timeout facility. When a client - or server is configured, in any of the usual ways, with the parameter org.jboss.remoting.transport.socket.SocketWrapper.WRITE_TIMEOUT - (actual value "writeTimeout") set to a positive value (in milliseconds), all write operations will time out if they do - not complete within the configured period. When a write operation times out, the socket upon which the write was invoked - will be closed, which is likely to result in a java.net.SocketException. - Note. A SocketException is considered to be a "retriable" exception, so, if the parameter "numberOfCallRetries" is set - to a value greater than 1, an invocation interrupted by a write timeout can be retried. - Note. The write timeout facility applies to writing of both invocations and responses. It applies to push callbacks as well. - */ - metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); - metadata.put("generalizeSocketException", "true"); - server = (MageServer) TransporterClient.createTransporterClient(clientLocator.getLocatorURI(), MageServer.class, metadata); - - // http://docs.jboss.org/jbossremoting/docs/guide/2.5/html_single/#d0e1057 - Map clientMetadata = new HashMap<>(); - - clientMetadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); - /* generalizeSocketException - * If set to false, a failed invocation will be retried in the case of - * SocketExceptions. If set to true, a failed invocation will be retried in the case of - * SocketExceptions and also any IOException - * whose message matches the regular expression - * ^.*(?:connection.*reset|connection.*closed|broken.*pipe).*$. - * See also the "numberOfCallRetries" parameter, above. The default value is false.*/ - clientMetadata.put("generalizeSocketException", "true"); - - /* A remoting server also has the capability to detect when a client is no longer available. - * This is done by estabilishing a lease with the remoting clients that connect to a server. - * On the client side, an org.jboss.remoting.LeasePinger periodically sends PING messages to - * the server, and on the server side an org.jboss.remoting.Lease informs registered listeners - * if the PING doesn't arrive withing the specified timeout period. */ - clientMetadata.put(Client.ENABLE_LEASE, "true"); - /* - When the socket client invoker makes its first invocation, it will check to see if there is an available - socket connection in its pool. Since is the first invocation, there will not be and will create a new socket - connection and use it for making the invocation. Then when finished making invocation, will return the still - active socket connection to the pool. As more client invocations are made, is possible for the number of - socket connections to reach the maximum allowed (which is controlled by 'clientMaxPoolSize' property). At this - point, when the next client invocation is made, it will wait up to some configured number of milliseconds, at - which point it will throw an org.jboss.remoting.CannotConnectException. The number of milliseconds is given by - the parameter MicroSocketClientInvoker.CONNECTION_WAIT (actual value "connectionWait"), with a default of - 30000 milliseconds. Note that if more than one call retry is configured (see next paragraph), - the CannotConnectException will be swallowed. - Once the socket client invoker get an available socket connection from the pool, are not out of the woods yet. - For example, a network problem could cause a java.net.SocketException. There is also a possibility that the socket - connection, while still appearing to be valid, has "gone stale" while sitting in the pool. For example, a ServerThread - on the other side of the connection could time out and close its socket. If the attempt to complete an invocation - fails, then MicroSocketClientInvoker will make a number of attempts, according to the parameter "numberOfCallRetries", - with a default value of 3. Once the configured number of retries has been exhausted, - an org.jboss.remoting.InvocationFailureException will be thrown. - */ - clientMetadata.put("numberOfCallRetries", "1"); - - - /** - * I'll explain the meaning of "secondaryBindPort" and "secondaryConnectPort", and maybe that will help. - * The Remoting bisocket transport creates two ServerSockets on the server. The "primary" ServerSocket is used to create - * connections used for ordinary invocations, e.g., a request to create a JMS consumer, and the "secondary" ServerSocket - * is used to create "control" connections for internal Remoting messages. The port for the primary ServerSocket is configured - * by the "serverBindPort" parameter, and the port for the secondary ServerSocket is, by default, chosen randomly. - * The "secondaryBindPort" parameter can be used to assign a specific port to the secondary ServerSocket. Now, if there is a - * translating firewall between the client and server, the client should be given the value of the port that is translated - * to the actual binding port of the secondary ServerSocket. - * For example, your configuration will tell the secondary ServerSocket to bind to port 14000, and it will tell the client to - * connect to port 14001. It assumes that there is a firewall which will translate 14001 to 14000. Apparently, that's not happening. - */ - // secondaryBindPort - the port to which the secondary server socket is to be bound. By default, an arbitrary port is selected. - - // secondaryConnectPort - the port clients are to use to connect to the secondary server socket. - // By default, the value of secondaryBindPort is used. secondaryConnectPort is useful if the server is behind a translating firewall. - - // Indicated the max number of threads used within oneway thread pool. - clientMetadata.put(Client.MAX_NUM_ONEWAY_THREADS, "10"); - clientMetadata.put(Remoting.USE_CLIENT_CONNECTION_IDENTITY, "true"); - callbackClient = new Client(clientLocator, "callback", clientMetadata); - - Map listenerMetadata = new HashMap<>(); - if (debugMode) { - // prevent client from disconnecting while debugging - listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_PERIOD, "1000000"); - listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_TIMEOUT, "900000"); - } else { - listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_PERIOD, "15000"); - listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_TIMEOUT, "13000"); - } - callbackClient.connect(new ClientConnectionListener(), listenerMetadata); - - Map callbackMetadata = new HashMap<>(); - callbackMetadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); - if (callbackHandler == null) { - callbackHandler = new CallbackHandler(); - } - callbackClient.addListener(callbackHandler, callbackMetadata); - - Set callbackConnectors = callbackClient.getCallbackConnectors(callbackHandler); - if (callbackConnectors.size() != 1) { - logger.warn("There should be one callback Connector (number existing = " + callbackConnectors.size() + ")"); - } - - logger.info("Trying to connect as " + (this.getUserName() == null ? "":this.getUserName()) + " to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); - callbackClient.invoke(null); - - this.sessionId = callbackClient.getSessionId(); - boolean registerResult; - if (connection.getPassword() == null) { - UserDataView userDataView = new UserDataView(connection.getAvatarId(), - connection.isShowAbilityPickerForced(), - connection.allowRequestShowHandCards(), - connection.getUserSkipPrioritySteps()); - // for backward compatibility. don't remove twice call - first one does nothing but for version checking - registerResult = server.registerClient(connection.getUsername(), sessionId, client.getVersion()); - if (registerResult) { - server.setUserData(connection.getUsername(), sessionId, userDataView); - } - } else { - registerResult = server.registerAdmin(connection.getPassword(), sessionId, client.getVersion()); - } - if (registerResult) { - sessionState = SessionState.CONNECTED; - serverState = server.getServerState(); - if (!connection.getUsername().equals("Admin")) { - updateDatabase(connection.isForceDBComparison(), serverState); - } - logger.info("Connected as " + (this.getUserName() == null ? "":this.getUserName()) + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); - client.connected(this.getUserName() == null ? "":this.getUserName() +"@" + connection.getHost() + ":" + connection.getPort() +" "); - return true; - } - disconnect(false); - // client.showMessage("Unable to connect to server."); - } catch (MalformedURLException ex) { - logger.fatal("", ex); - client.showMessage("Unable to connect to server. " + ex.getMessage()); - } catch (UndeclaredThrowableException ex) { - String addMessage = ""; - if (ex.getCause() instanceof InvocationFailureException) { - InvocationFailureException exep = (InvocationFailureException) ex.getCause(); - if (exep.getCause() instanceof IOException) { - if (exep.getCause().getMessage().startsWith("Field hash null is not available on current")) { - addMessage = "Probabaly the server version is not compatible to the client. "; - } - } - } - if (addMessage.isEmpty()) { - logger.fatal("", ex); - } - client.showMessage("Unable to connect to server. " + addMessage + (ex.getMessage() != null ? ex.getMessage():"")); - } catch (IOException ex) { - logger.fatal("", ex); - String addMessage = ""; - if (ex.getMessage() != null && ex.getMessage().startsWith("Unable to perform invocation")) { - addMessage = "Maybe the server version is not compatible. "; - } - client.showMessage("Unable to connect to server. " + addMessage + ex.getMessage() != null ? ex.getMessage():""); - } catch (MageVersionException ex) { - if (!canceled) { - client.showMessage("Unable to connect to server. " + ex.getMessage()); - } - disconnect(false); - } catch (CannotConnectException ex) { - if (!canceled) { - handleCannotConnectException(ex); - } - } catch (Throwable t) { - logger.fatal("Unable to connect to server - ", t); - if (!canceled) { - disconnect(false); - StringBuilder sb = new StringBuilder(); - sb.append("Unable to connect to server.\n"); - for (StackTraceElement element :t.getStackTrace()) { - sb.append(element.toString()).append("\n"); - } - client.showMessage(sb.toString()); - } - } - return false; - } - - private void updateDatabase(boolean forceDBComparison, ServerState serverState) { - long cardDBVersion = CardRepository.instance.getContentVersionFromDB(); - if (forceDBComparison || serverState.getCardsContentVersion() > cardDBVersion) { - List classNames = CardRepository.instance.getClassNames(); - List cards = server.getMissingCardsData(classNames); - CardRepository.instance.addCards(cards); - CardRepository.instance.setContentVersion(serverState.getCardsContentVersion()); - logger.info("Updating client cards DB - existing cards: " + classNames.size() + " new cards: " + cards.size() + - " content versions - server: " + serverState.getCardsContentVersion() + " client: " + cardDBVersion); - } - - long expansionDBVersion = ExpansionRepository.instance.getContentVersionFromDB(); - if (forceDBComparison || serverState.getExpansionsContentVersion() > expansionDBVersion) { - List setCodes = ExpansionRepository.instance.getSetCodes(); - List expansions = server.getMissingExpansionData(setCodes); - for (ExpansionInfo expansion : expansions) { - ExpansionRepository.instance.add(expansion); - } - ExpansionRepository.instance.setContentVersion(serverState.getExpansionsContentVersion()); - logger.info("Updating client expansions DB - existing sets: " + setCodes.size() + " new sets: " + expansions.size()+ - " content versions - server: " + serverState.getExpansionsContentVersion() + " client: " + expansionDBVersion); - } - } - - private void handleCannotConnectException(CannotConnectException ex) { - logger.warn("Cannot connect", ex); - Throwable t = ex.getCause(); - String message = ""; - while (t != null) { - if (t instanceof ConnectException) { - message = "Server is likely offline." + message; - break; - } - if (t instanceof SocketException) { - message = "Check your internet connection." + message; - break; - } - if (t instanceof SocketTimeoutException) { - message = "Server is not responding." + message; - break; - } - if (t.getCause() != null && logger.isDebugEnabled()) { - message = "\n" + t.getCause().getMessage() + message; - logger.debug(t.getCause().getMessage()); - } - - t = t.getCause(); - } - client.showMessage("Unable to connect to server. " + message); - if (logger.isTraceEnabled()) { - logger.trace("StackTrace", t); - } - } - - /** - * - * @param askForReconnect - true = connection was lost because of error and ask the user if he want to try to reconnect - */ - @Override - public synchronized void disconnect(boolean askForReconnect) { - if (isConnected()) { - logger.info("DISCONNECT (still connected)"); - sessionState = SessionState.DISCONNECTING; - } - if (connection == null || sessionState == SessionState.DISCONNECTED) { - return; - } - - try { - callbackClient.removeListener(callbackHandler); - callbackClient.disconnect(); - TransporterClient.destroyTransporterClient(server); - } catch (Throwable ex) { - logger.fatal("Error disconnecting ...", ex); - } - - if (sessionState == SessionState.DISCONNECTING || sessionState == SessionState.CONNECTING) { - sessionState = SessionState.DISCONNECTED; - logger.info("Disconnected ... "); - if (askForReconnect) { - client.showError("Network error. You have been disconnected"); - } - client.disconnected(askForReconnect); // MageFrame with check to reconnect - pingTime.clear(); - } - } - - @Override - public synchronized void reconnect(Throwable throwable) { - logger.info("RECONNECT - Connected: " + isConnected()); - client.disconnected(true); - } - - @Override - public synchronized boolean sendFeedback(String title, String type, String message, String email) { - if (isConnected()) { - try { - server.sendFeedbackMessage(sessionId, connection.getUsername(), title, type, message, email); - return true; - } catch (MageException e) { - logger.error(e); - } - } - return false; - } - - class CallbackHandler implements InvokerCallbackHandler { - @Override - public void handleCallback(Callback callback) throws HandleCallbackException { - //logger.info("callback handler"); - client.processCallback((ClientCallback)callback.getCallbackObject()); - } - } - - class ClientConnectionListener implements ConnectionListener { - // http://docs.jboss.org/jbossremoting/2.5.3.SP1/html/chapter-connection-failure.html - - @Override - public void handleConnectionException(Throwable throwable, Client client) { - logger.info("connection to server lost - " + throwable.getMessage()); - throwable.printStackTrace(); - - reconnect(throwable); - } - } - - @Override - public boolean isConnected() { - if (callbackClient == null) { - return false; - } - return callbackClient.isConnected(); - } - - @Override - public String[] getPlayerTypes() { - return serverState.getPlayerTypes(); - } - - @Override - public List getGameTypes() { - return serverState.getGameTypes(); - } - - @Override - public List getTournamentGameTypes() { - return serverState.getTournamentGameTypes(); - } - - @Override - public String[] getDeckTypes() { - return serverState.getDeckTypes(); - } - - @Override - public String[] getDraftCubes() { - return serverState.getDraftCubes(); - } - - - @Override - public List getTournamentTypes() { - return serverState.getTournamentTypes(); - } - - @Override - public boolean isTestMode() { - if (serverState != null) { - return serverState.isTestMode(); - } - return false; - } - - @Override - public UUID getMainRoomId() { - try { - if (isConnected()) { - return server.getMainRoomId(); - } - } catch (MageException ex) { - handleMageException(ex); - } - return null; - } - - @Override - public UUID getRoomChatId(UUID roomId) { - try { - if (isConnected()) { - return server.getRoomChatId(roomId); - } - } catch (MageException ex) { - handleMageException(ex); - } - return null; - } - - @Override - public UUID getTableChatId(UUID tableId) { - try { - if (isConnected()) { - return server.getTableChatId(tableId); - } - } catch (MageException ex) { - handleMageException(ex); - } - return null; - } - - @Override - public UUID getGameChatId(UUID gameId) { - try { - if (isConnected()) { - return server.getGameChatId(gameId); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public TableView getTable(UUID roomId, UUID tableId) { - try { - if (isConnected()) { - return server.getTable(roomId, tableId); - } - } catch (MageException ex) { - handleMageException(ex); - } - return null; - } - - @Override - public boolean watchTable(UUID roomId, UUID tableId) { - try { - if (isConnected()) { - server.watchTable(sessionId, roomId, tableId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean watchTournamentTable(UUID tableId) { - try { - if (isConnected()) { - server.watchTournamentTable(sessionId, tableId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password) { - try { - if (isConnected()) { - return server.joinTable(sessionId, roomId, tableId, playerName, playerType, skill, deckList, password); - } - } catch (InvalidDeckException iex) { - handleInvalidDeckException(iex); - } catch (GameException ex) { - handleGameException(ex); - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password) { - try { - if (isConnected()) { - return server.joinTournamentTable(sessionId, roomId, tableId, playerName, playerType, skill, deckList, password); - } - } catch (GameException ex) { - handleGameException(ex); - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public Collection getTables(UUID roomId) throws MageRemoteException { - try { - if (isConnected()) { - return server.getTables(roomId); - } - } catch (MageException ex) { - handleMageException(ex); - throw new MageRemoteException(); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public Collection getFinishedMatches(UUID roomId) throws MageRemoteException { - try { - if (isConnected()) { - return server.getFinishedMatches(roomId); - } - } catch (MageException ex) { - handleMageException(ex); - throw new MageRemoteException(); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public Collection getRoomUsers(UUID roomId) throws MageRemoteException { - try { - if (isConnected()) { - return server.getRoomUsers(roomId); - } - } catch (MageException ex) { - handleMageException(ex); - throw new MageRemoteException(); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public TournamentView getTournament(UUID tournamentId) throws MageRemoteException { - try { - if (isConnected()) { - return server.getTournament(tournamentId); - } - } catch (MageException ex) { - handleMageException(ex); - throw new MageRemoteException(); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public UUID getTournamentChatId(UUID tournamentId) { - try { - if (isConnected()) { - return server.getTournamentChatId(tournamentId); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public boolean sendPlayerUUID(UUID gameId, UUID data) { - try { - if (isConnected()) { - server.sendPlayerUUID(gameId, sessionId, data); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean sendPlayerBoolean(UUID gameId, boolean data) { - try { - if (isConnected()) { - server.sendPlayerBoolean(gameId, sessionId, data); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean sendPlayerInteger(UUID gameId, int data) { - try { - if (isConnected()) { - server.sendPlayerInteger(gameId, sessionId, data); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean sendPlayerString(UUID gameId, String data) { - try { - if (isConnected()) { - server.sendPlayerString(gameId, sessionId, data); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean sendPlayerManaType(UUID gameId, UUID playerId, ManaType data) { - try { - if (isConnected()) { - server.sendPlayerManaType(gameId, playerId, sessionId, data); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public DraftPickView sendCardPick(UUID draftId, UUID cardId, Set hiddenCards) { - try { - if (isConnected()) { - return server.sendCardPick(draftId, sessionId, cardId, hiddenCards); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public DraftPickView sendCardMark(UUID draftId, UUID cardId) { - try { - if (isConnected()) { - server.sendCardMark(draftId, sessionId, cardId); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public boolean joinChat(UUID chatId) { - try { - if (isConnected()) { - server.joinChat(chatId, sessionId, connection.getUsername()); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean leaveChat(UUID chatId) { -// lock.readLock().lock(); - try { - if (isConnected()) { - server.leaveChat(chatId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); -// } finally { -// lock.readLock().unlock(); - } - return false; - } - - @Override - public boolean sendChatMessage(UUID chatId, String message) { -// lock.readLock().lock(); - try { - if (isConnected()) { - server.sendChatMessage(chatId, connection.getUsername(), message); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); -// } finally { -// lock.readLock().unlock(); - } - return false; - } - - @Override - public boolean sendBroadcastMessage(String message) { - try { - if (isConnected()) { - server.sendBroadcastMessage(sessionId, message); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean joinGame(UUID gameId) { - try { - if (isConnected()) { - server.joinGame(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean joinDraft(UUID draftId) { - try { - if (isConnected()) { - server.joinDraft(draftId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean joinTournament(UUID tournamentId) { - try { - if (isConnected()) { - server.joinTournament(tournamentId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean watchGame(UUID gameId) { - try { - if (isConnected()) { - server.watchGame(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean replayGame(UUID gameId) { - try { - if (isConnected()) { - server.replayGame(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public TableView createTable(UUID roomId, MatchOptions matchOptions) { - try { - if (isConnected()) { - return server.createTable(sessionId, roomId, matchOptions); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public TableView createTournamentTable(UUID roomId, TournamentOptions tournamentOptions) { - try { - if (isConnected()) { - return server.createTournamentTable(sessionId, roomId, tournamentOptions); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public boolean isTableOwner(UUID roomId, UUID tableId) { - try { - if (isConnected()) { - return server.isTableOwner(sessionId, roomId, tableId); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean removeTable(UUID roomId, UUID tableId) { - try { - if (isConnected()) { - server.removeTable(sessionId, roomId, tableId); - - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - /** - * Remove table - called from admin console - * @param tableId - * @return - */ - @Override - public boolean removeTable(UUID tableId) { - try { - if (isConnected()) { - server.removeTable(sessionId, tableId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean swapSeats(UUID roomId, UUID tableId, int seatNum1, int seatNum2) { - try { - if (isConnected()) { - server.swapSeats(sessionId, roomId, tableId, seatNum1, seatNum2); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean leaveTable(UUID roomId, UUID tableId) { - try { - if (isConnected() && server.leaveTable(sessionId, roomId, tableId)) { - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean startMatch(UUID roomId, UUID tableId) { - try { - if (isConnected()) { - return (server.startMatch(sessionId, roomId, tableId)); - } - } catch (MageException ex) { - handleMageException(ex); - } - return false; - } - - @Override - public boolean startTournament(UUID roomId, UUID tableId) { - try { - if (isConnected() && server.startTournament(sessionId, roomId, tableId)) { - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - +///* +//* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. +//* +//* Redistribution and use in source and binary forms, with or without modification, are +//* permitted provided that the following conditions are met: +//* +//* 1. Redistributions of source code must retain the above copyright notice, this list of +//* conditions and the following disclaimer. +//* +//* 2. Redistributions in binary form must reproduce the above copyright notice, this list +//* of conditions and the following disclaimer in the documentation and/or other materials +//* provided with the distribution. +//* +//* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED +//* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +//* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR +//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +//* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +//* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +//* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +//* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +//* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//* +//* The views and conclusions contained in the software and documentation are those of the +//* authors and should not be interpreted as representing official policies, either expressed +//* or implied, of BetaSteward_at_googlemail.com. +//*/ +// +//package mage.remote; +// +//import java.io.IOException; +//import java.lang.reflect.UndeclaredThrowableException; +//import java.net.Authenticator; +//import java.net.ConnectException; +//import java.net.MalformedURLException; +//import java.net.PasswordAuthentication; +//import java.net.SocketException; +//import java.net.SocketTimeoutException; +//import java.util.Collection; +//import java.util.HashMap; +//import java.util.LinkedList; +//import java.util.List; +//import java.util.Map; +//import java.util.Set; +//import java.util.UUID; +//import java.util.concurrent.TimeUnit; +//import mage.MageException; +//import mage.cards.decks.DeckCardLists; +//import mage.cards.decks.InvalidDeckException; +//import mage.cards.repository.CardInfo; +//import mage.cards.repository.CardRepository; +//import mage.cards.repository.ExpansionInfo; +//import mage.cards.repository.ExpansionRepository; +//import mage.constants.Constants.SessionState; +//import mage.constants.ManaType; +//import mage.constants.PlayerAction; +//import mage.game.GameException; +//import mage.game.match.MatchOptions; +//import mage.game.tournament.TournamentOptions; +//import mage.interfaces.MageClient; +//import mage.interfaces.MageServer; +//import mage.interfaces.ServerState; +//import mage.interfaces.callback.ClientCallback; +//import mage.utils.CompressUtil; +//import mage.players.net.UserSkipPrioritySteps; +//import mage.view.DraftPickView; +//import mage.view.GameTypeView; +//import mage.view.MatchView; +//import mage.view.RoomUsersView; +//import mage.view.TableView; +//import mage.view.TournamentTypeView; +//import mage.view.TournamentView; +//import mage.view.UserDataView; +//import mage.view.UserView; +//import org.apache.log4j.Logger; +//import org.jboss.remoting.CannotConnectException; +//import org.jboss.remoting.Client; +//import org.jboss.remoting.ConnectionListener; +//import org.jboss.remoting.ConnectionValidator; +//import org.jboss.remoting.InvocationFailureException; +//import org.jboss.remoting.InvokerLocator; +//import org.jboss.remoting.Remoting; +//import org.jboss.remoting.callback.Callback; +//import org.jboss.remoting.callback.HandleCallbackException; +//import org.jboss.remoting.callback.InvokerCallbackHandler; +//import org.jboss.remoting.transport.bisocket.Bisocket; +//import org.jboss.remoting.transport.socket.SocketWrapper; +//import org.jboss.remoting.transporter.TransporterClient; +// +///** +// * +// * @author BetaSteward_at_googlemail.com +// */ +//public class SessionImpl implements Session { +// +// private static final Logger logger = Logger.getLogger(SessionImpl.class); +// +// private final MageClient client; +// +// private String sessionId; +// private MageServer server; +// private Client callbackClient; +// private CallbackHandler callbackHandler; +// private ServerState serverState; +// private SessionState sessionState = SessionState.DISCONNECTED; +// private Connection connection; +// private final static int PING_CYCLES = 10; +// private final LinkedList pingTime = new LinkedList<>(); +// private String pingInfo = ""; +// private static boolean debugMode = false; +// +// private boolean canceled = false; +// +// static { +// debugMode = System.getProperty("debug.mage") != null; +// } +// +// public SessionImpl(MageClient client) { +// this.client = client; +// } +// // @Override -// public boolean startChallenge(UUID roomId, UUID tableId, UUID challengeId) { +// public String getSessionId() { +// return sessionId; +// } +// +// @Override +// public synchronized boolean connect(Connection connection) { +// if (isConnected()) { +// disconnect(true); +// } +// this.connection = connection; +// this.canceled = false; +// return connect(); +// } +// +// @Override +// public boolean stopConnecting() { +// canceled = true; +// return true; +// } +// +// @Override +// public boolean connect() { +// sessionState = SessionState.CONNECTING; +// try { +// System.setProperty("http.nonProxyHosts", "code.google.com"); +// System.setProperty("socksNonProxyHosts", "code.google.com"); +// +// // clear previous values +// System.clearProperty("socksProxyHost"); +// System.clearProperty("socksProxyPort"); +// System.clearProperty("http.proxyHost"); +// System.clearProperty("http.proxyPort"); +// +// switch (connection.getProxyType()) { +// case SOCKS: +// System.setProperty("socksProxyHost", connection.getProxyHost()); +// System.setProperty("socksProxyPort", Integer.toString(connection.getProxyPort())); +// break; +// case HTTP: +// System.setProperty("http.proxyHost", connection.getProxyHost()); +// System.setProperty("http.proxyPort", Integer.toString(connection.getProxyPort())); +// Authenticator.setDefault(new MageAuthenticator(connection.getProxyUsername(), connection.getProxyPassword())); +// break; +// } +// InvokerLocator clientLocator = new InvokerLocator(connection.getURI()); +// +// Map metadata = new HashMap<>(); +// /* +// 5.8.3.1.1. Write timeouts +// The socket timeout facility offered by the JDK applies only to read operations on the socket. As of release 2.5.2, +// the socket and bisocket (and also sslsocket and sslbisocket) transports offer a write timeout facility. When a client +// or server is configured, in any of the usual ways, with the parameter org.jboss.remoting.transport.socket.SocketWrapper.WRITE_TIMEOUT +// (actual value "writeTimeout") set to a positive value (in milliseconds), all write operations will time out if they do +// not complete within the configured period. When a write operation times out, the socket upon which the write was invoked +// will be closed, which is likely to result in a java.net.SocketException. +// Note. A SocketException is considered to be a "retriable" exception, so, if the parameter "numberOfCallRetries" is set +// to a value greater than 1, an invocation interrupted by a write timeout can be retried. +// Note. The write timeout facility applies to writing of both invocations and responses. It applies to push callbacks as well. +// */ +// metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); +// metadata.put("generalizeSocketException", "true"); +// server = (MageServer) TransporterClient.createTransporterClient(clientLocator.getLocatorURI(), MageServer.class, metadata); +// +// // http://docs.jboss.org/jbossremoting/docs/guide/2.5/html_single/#d0e1057 +// Map clientMetadata = new HashMap<>(); +// +// clientMetadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); +// /* generalizeSocketException +// * If set to false, a failed invocation will be retried in the case of +// * SocketExceptions. If set to true, a failed invocation will be retried in the case of +// * SocketExceptions and also any IOException +// * whose message matches the regular expression +// * ^.*(?:connection.*reset|connection.*closed|broken.*pipe).*$. +// * See also the "numberOfCallRetries" parameter, above. The default value is false.*/ +// clientMetadata.put("generalizeSocketException", "true"); +// +// /* A remoting server also has the capability to detect when a client is no longer available. +// * This is done by estabilishing a lease with the remoting clients that connect to a server. +// * On the client side, an org.jboss.remoting.LeasePinger periodically sends PING messages to +// * the server, and on the server side an org.jboss.remoting.Lease informs registered listeners +// * if the PING doesn't arrive withing the specified timeout period. */ +// clientMetadata.put(Client.ENABLE_LEASE, "true"); +// /* +// When the socket client invoker makes its first invocation, it will check to see if there is an available +// socket connection in its pool. Since is the first invocation, there will not be and will create a new socket +// connection and use it for making the invocation. Then when finished making invocation, will return the still +// active socket connection to the pool. As more client invocations are made, is possible for the number of +// socket connections to reach the maximum allowed (which is controlled by 'clientMaxPoolSize' property). At this +// point, when the next client invocation is made, it will wait up to some configured number of milliseconds, at +// which point it will throw an org.jboss.remoting.CannotConnectException. The number of milliseconds is given by +// the parameter MicroSocketClientInvoker.CONNECTION_WAIT (actual value "connectionWait"), with a default of +// 30000 milliseconds. Note that if more than one call retry is configured (see next paragraph), +// the CannotConnectException will be swallowed. +// Once the socket client invoker get an available socket connection from the pool, are not out of the woods yet. +// For example, a network problem could cause a java.net.SocketException. There is also a possibility that the socket +// connection, while still appearing to be valid, has "gone stale" while sitting in the pool. For example, a ServerThread +// on the other side of the connection could time out and close its socket. If the attempt to complete an invocation +// fails, then MicroSocketClientInvoker will make a number of attempts, according to the parameter "numberOfCallRetries", +// with a default value of 3. Once the configured number of retries has been exhausted, +// an org.jboss.remoting.InvocationFailureException will be thrown. +// */ +// clientMetadata.put("numberOfCallRetries", "1"); +// +// +// /** +// * I'll explain the meaning of "secondaryBindPort" and "secondaryConnectPort", and maybe that will help. +// * The Remoting bisocket transport creates two ServerSockets on the server. The "primary" ServerSocket is used to create +// * connections used for ordinary invocations, e.g., a request to create a JMS consumer, and the "secondary" ServerSocket +// * is used to create "control" connections for internal Remoting messages. The port for the primary ServerSocket is configured +// * by the "serverBindPort" parameter, and the port for the secondary ServerSocket is, by default, chosen randomly. +// * The "secondaryBindPort" parameter can be used to assign a specific port to the secondary ServerSocket. Now, if there is a +// * translating firewall between the client and server, the client should be given the value of the port that is translated +// * to the actual binding port of the secondary ServerSocket. +// * For example, your configuration will tell the secondary ServerSocket to bind to port 14000, and it will tell the client to +// * connect to port 14001. It assumes that there is a firewall which will translate 14001 to 14000. Apparently, that's not happening. +// */ +// // secondaryBindPort - the port to which the secondary server socket is to be bound. By default, an arbitrary port is selected. +// +// // secondaryConnectPort - the port clients are to use to connect to the secondary server socket. +// // By default, the value of secondaryBindPort is used. secondaryConnectPort is useful if the server is behind a translating firewall. +// +// // Indicated the max number of threads used within oneway thread pool. +// clientMetadata.put(Client.MAX_NUM_ONEWAY_THREADS, "10"); +// clientMetadata.put(Remoting.USE_CLIENT_CONNECTION_IDENTITY, "true"); +// callbackClient = new Client(clientLocator, "callback", clientMetadata); +// +// Map listenerMetadata = new HashMap<>(); +// if (debugMode) { +// // prevent client from disconnecting while debugging +// listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_PERIOD, "1000000"); +// listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_TIMEOUT, "900000"); +// } else { +// listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_PERIOD, "15000"); +// listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_TIMEOUT, "13000"); +// } +// callbackClient.connect(new ClientConnectionListener(), listenerMetadata); +// +// Map callbackMetadata = new HashMap<>(); +// callbackMetadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); +// if (callbackHandler == null) { +// callbackHandler = new CallbackHandler(); +// } +// callbackClient.addListener(callbackHandler, callbackMetadata); +// +// Set callbackConnectors = callbackClient.getCallbackConnectors(callbackHandler); +// if (callbackConnectors.size() != 1) { +// logger.warn("There should be one callback Connector (number existing = " + callbackConnectors.size() + ")"); +// } +// +// callbackClient.invoke(null); +// +// this.sessionId = callbackClient.getSessionId(); +// boolean registerResult; +// if (connection.getPassword() == null) { +// UserDataView userDataView = new UserDataView(connection.getAvatarId(), +// connection.isShowAbilityPickerForced(), +// connection.allowRequestShowHandCards(), +// connection.getUserSkipPrioritySteps()); +// // for backward compatibility. don't remove twice call - first one does nothing but for version checking +// registerResult = server.registerClient(connection.getUsername(), sessionId, client.getVersion()); +// if (registerResult) { +// server.setUserData(connection.getUsername(), sessionId, userDataView); +// } +// } else { +// registerResult = server.registerAdmin(connection.getPassword(), sessionId, client.getVersion()); +// } +// if (registerResult) { +// sessionState = SessionState.CONNECTED; +// serverState = server.getServerState(); +// if (!connection.getUsername().equals("Admin")) { +// updateDatabase(connection.isForceDBComparison(), serverState); +// } +// logger.info("Connected as " + (this.getUserName() == null ? "":this.getUserName()) + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); +// client.connected(this.getUserName() == null ? "":this.getUserName() +"@" + connection.getHost() + ":" + connection.getPort() +" "); +// return true; +// } +// disconnect(false); +// // client.showMessage("Unable to connect to server."); +// } catch (MalformedURLException ex) { +// logger.fatal("", ex); +// client.showMessage("Unable to connect to server. " + ex.getMessage()); +// } catch (UndeclaredThrowableException ex) { +// String addMessage = ""; +// if (ex.getCause() instanceof InvocationFailureException) { +// InvocationFailureException exep = (InvocationFailureException) ex.getCause(); +// if (exep.getCause() instanceof IOException) { +// if (exep.getCause().getMessage().startsWith("Field hash null is not available on current")) { +// addMessage = "Probabaly the server version is not compatible to the client. "; +// } +// } +// } +// if (addMessage.isEmpty()) { +// logger.fatal("", ex); +// } +// client.showMessage("Unable to connect to server. " + addMessage + (ex.getMessage() != null ? ex.getMessage():"")); +// } catch (IOException ex) { +// logger.fatal("", ex); +// String addMessage = ""; +// if (ex.getMessage() != null && ex.getMessage().startsWith("Unable to perform invocation")) { +// addMessage = "Maybe the server version is not compatible. "; +// } +// client.showMessage("Unable to connect to server. " + addMessage + ex.getMessage() != null ? ex.getMessage():""); +// } catch (MageVersionException ex) { +// if (!canceled) { +// client.showMessage("Unable to connect to server. " + ex.getMessage()); +// } +// disconnect(false); +// } catch (CannotConnectException ex) { +// if (!canceled) { +// handleCannotConnectException(ex); +// } +// } catch (Throwable t) { +// logger.fatal("Unable to connect to server - ", t); +// if (!canceled) { +// disconnect(false); +// StringBuilder sb = new StringBuilder(); +// sb.append("Unable to connect to server.\n"); +// for (StackTraceElement element :t.getStackTrace()) { +// sb.append(element.toString()).append("\n"); +// } +// client.showMessage(sb.toString()); +// } +// } +// return false; +// } +// +// private void updateDatabase(boolean forceDBComparison, ServerState serverState) { +// long cardDBVersion = CardRepository.instance.getContentVersionFromDB(); +// if (forceDBComparison || serverState.getCardsContentVersion() > cardDBVersion) { +// List classNames = CardRepository.instance.getClassNames(); +// List cards = server.getMissingCardsData(classNames); +// CardRepository.instance.addCards(cards); +// CardRepository.instance.setContentVersion(serverState.getCardsContentVersion()); +// logger.info("Updating client cards DB - existing cards: " + classNames.size() + " new cards: " + cards.size() + +// " content versions - server: " + serverState.getCardsContentVersion() + " client: " + cardDBVersion); +// } +// +// long expansionDBVersion = ExpansionRepository.instance.getContentVersionFromDB(); +// if (forceDBComparison || serverState.getExpansionsContentVersion() > expansionDBVersion) { +// List setCodes = ExpansionRepository.instance.getSetCodes(); +// List expansions = server.getMissingExpansionData(setCodes); +// for (ExpansionInfo expansion : expansions) { +// ExpansionRepository.instance.add(expansion); +// } +// ExpansionRepository.instance.setContentVersion(serverState.getExpansionsContentVersion()); +// logger.info("Updating client expansions DB - existing sets: " + setCodes.size() + " new sets: " + expansions.size()+ +// " content versions - server: " + serverState.getExpansionsContentVersion() + " client: " + expansionDBVersion); +// } +// } +// +// private void handleCannotConnectException(CannotConnectException ex) { +// logger.warn("Cannot connect", ex); +// Throwable t = ex.getCause(); +// String message = ""; +// while (t != null) { +// if (t instanceof ConnectException) { +// message = "Server is likely offline." + message; +// break; +// } +// if (t instanceof SocketException) { +// message = "Check your internet connection." + message; +// break; +// } +// if (t instanceof SocketTimeoutException) { +// message = "Server is not responding." + message; +// break; +// } +// if (t.getCause() != null && logger.isDebugEnabled()) { +// message = "\n" + t.getCause().getMessage() + message; +// logger.debug(t.getCause().getMessage()); +// } +// +// t = t.getCause(); +// } +// client.showMessage("Unable to connect to server. " + message); +// if (logger.isTraceEnabled()) { +// logger.trace("StackTrace", t); +// } +// } +// +// /** +// * +// * @param askForReconnect - true = connection was lost because of error and ask the user if he want to try to reconnect +// */ +// @Override +// public synchronized void disconnect(boolean askForReconnect) { +// if (isConnected()) { +// logger.info("DISCONNECT (still connected)"); +// sessionState = SessionState.DISCONNECTING; +// } +// if (connection == null || sessionState == SessionState.DISCONNECTED) { +// return; +// } +// +// try { +// callbackClient.removeListener(callbackHandler); +// callbackClient.disconnect(); +// TransporterClient.destroyTransporterClient(server); +// } catch (Throwable ex) { +// logger.fatal("Error disconnecting ...", ex); +// } +// +// if (sessionState == SessionState.DISCONNECTING || sessionState == SessionState.CONNECTING) { +// sessionState = SessionState.DISCONNECTED; +// logger.info("Disconnected ... "); +// if (askForReconnect) { +// client.showError("Network error. You have been disconnected"); +// } +// client.disconnected(askForReconnect); // MageFrame with check to reconnect +// pingTime.clear(); +// } +// } +// +// @Override +// public synchronized void reconnect(Throwable throwable) { +// logger.info("RECONNECT - Connected: " + isConnected()); +// client.disconnected(true); +// } +// +// @Override +// public synchronized boolean sendFeedback(String title, String type, String message, String email) { +// if (isConnected()) { +// try { +// server.sendFeedbackMessage(sessionId, connection.getUsername(), title, type, message, email); +// return true; +// } catch (MageException e) { +// logger.error(e); +// } +// } +// return false; +// } +// +// class CallbackHandler implements InvokerCallbackHandler { +// @Override +// public void handleCallback(Callback callback) throws HandleCallbackException { +// //logger.info("callback handler"); +// client.processCallback((ClientCallback)callback.getCallbackObject()); +// } +// } +// +// class ClientConnectionListener implements ConnectionListener { +// // http://docs.jboss.org/jbossremoting/2.5.3.SP1/html/chapter-connection-failure.html +// +// @Override +// public void handleConnectionException(Throwable throwable, Client client) { +// logger.info("connection to server lost - " + throwable.getMessage()); +// throwable.printStackTrace(); +// +// reconnect(throwable); +// } +// } +// +// @Override +// public boolean isConnected() { +// if (callbackClient == null) { +// return false; +// } +// return callbackClient.isConnected(); +// } +// +// @Override +// public String[] getPlayerTypes() { +// return serverState.getPlayerTypes(); +// } +// +// @Override +// public List getGameTypes() { +// return serverState.getGameTypes(); +// } +// +// @Override +// public List getTournamentGameTypes() { +// return serverState.getTournamentGameTypes(); +// } +// +// @Override +// public String[] getDeckTypes() { +// return serverState.getDeckTypes(); +// } +// +// @Override +// public String[] getDraftCubes() { +// return serverState.getDraftCubes(); +// } +// +// +// @Override +// public List getTournamentTypes() { +// return serverState.getTournamentTypes(); +// } +// +// @Override +// public boolean isTestMode() { +// if (serverState != null) { +// return serverState.isTestMode(); +// } +// return false; +// } +// +// @Override +// public UUID getMainRoomId() { // try { // if (isConnected()) { -// server.startChallenge(sessionId, roomId, tableId, challengeId); +// return server.getMainRoomId(); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } +// return null; +// } +// +// @Override +// public UUID getRoomChatId(UUID roomId) { +// try { +// if (isConnected()) { +// return server.getRoomChatId(roomId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } +// return null; +// } +// +// @Override +// public UUID getTableChatId(UUID tableId) { +// try { +// if (isConnected()) { +// return server.getTableChatId(tableId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } +// return null; +// } +// +// @Override +// public UUID getGameChatId(UUID gameId) { +// try { +// if (isConnected()) { +// return server.getGameChatId(gameId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public TableView getTable(UUID roomId, UUID tableId) { +// try { +// if (isConnected()) { +// return server.getTable(roomId, tableId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } +// return null; +// } +// +// @Override +// public boolean watchTable(UUID roomId, UUID tableId) { +// try { +// if (isConnected()) { +// server.watchTable(sessionId, roomId, tableId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean watchTournamentTable(UUID tableId) { +// try { +// if (isConnected()) { +// server.watchTournamentTable(sessionId, tableId); // return true; // } // } catch (MageException ex) { @@ -1111,361 +610,859 @@ public class SessionImpl implements Session { // } // return false; // } - - @Override - public boolean submitDeck(UUID tableId, DeckCardLists deck) { - try { - if (isConnected()) { - return server.submitDeck(sessionId, tableId, deck); - } - } catch (GameException ex) { - handleGameException(ex); - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean updateDeck(UUID tableId, DeckCardLists deck) { - try { - if (isConnected()) { - server.updateDeck(sessionId, tableId, deck); - return true; - } - } catch (GameException ex) { - handleGameException(ex); - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean quitMatch(UUID gameId) { - try { - if (isConnected()) { - server.quitMatch(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean quitTournament(UUID tournamentId) { - try { - if (isConnected()) { - server.quitTournament(tournamentId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean quitDraft(UUID draftId) { - try { - if (isConnected()) { - server.quitDraft(draftId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } - return false; - } - - @Override - public boolean sendPlayerAction(PlayerAction passPriorityAction, UUID gameId, Object data) { - try { - if (isConnected()) { - server.sendPlayerAction(passPriorityAction, gameId, sessionId, data); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean stopWatching(UUID gameId) { - try { - if (isConnected()) { - server.stopWatching(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean startReplay(UUID gameId) { - try { - if (isConnected()) { - server.startReplay(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean stopReplay(UUID gameId) { - try { - if (isConnected()) { - server.stopReplay(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean nextPlay(UUID gameId) { - try { - if (isConnected()) { - server.nextPlay(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean previousPlay(UUID gameId) { - try { - if (isConnected()) { - server.previousPlay(gameId, sessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean skipForward(UUID gameId, int moves) { - try { - if (isConnected()) { - server.skipForward(gameId, sessionId, moves); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean cheat(UUID gameId, UUID playerId, DeckCardLists deckList) { - try { - if (isConnected()) { - server.cheat(gameId, sessionId, playerId, deckList); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public List getUsers() { - try { - if (isConnected()) { - return server.getUsers(sessionId); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public List getServerMessages() { - try { - if (isConnected()) { - return (List) CompressUtil.decompress(server.getServerMessagesCompressed(sessionId)); - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return null; - } - - @Override - public boolean disconnectUser(String userSessionId) { - try { - if (isConnected()) { - server.disconnectUser(sessionId, userSessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean endUserSession(String userSessionId) { - try { - if (isConnected()) { - server.endUserSession(sessionId, userSessionId); - return true; - } - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - private void handleThrowable(Throwable t) { - logger.fatal("Communication error", t); - // Probably this can cause hanging the client under certain circumstances as the disconnect method is synchronized - // so check if it's needed - // disconnect(true); - } - - private void handleMageException(MageException ex) { - logger.fatal("Server error", ex); - client.showError(ex.getMessage()); - } - - private void handleInvalidDeckException(InvalidDeckException iex) { - logger.warn(iex.getMessage() + "\n" + iex.getInvalid()); - client.showError(iex.getMessage() + "\n" + iex.getInvalid()); - } - - private void handleGameException(GameException ex) { - logger.warn(ex.getMessage()); - client.showError(ex.getMessage()); - } - - - @Override - public String getUserName() { - return connection.getUsername(); - } - - @Override - public boolean updatePreferencesForServer(int avatarId, boolean showAbilityPickerForced, boolean allowRequestShowHandCards, UserSkipPrioritySteps userSkipPrioritySteps) { - try { - if (isConnected()) { - UserDataView userDataView = new UserDataView(avatarId, showAbilityPickerForced, allowRequestShowHandCards, userSkipPrioritySteps); - server.setUserData(connection.getUsername(), sessionId, userDataView); - } - return true; - } catch (MageException ex) { - handleMageException(ex); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public boolean ping() { - try { - if (isConnected()) { - long startTime = System.nanoTime(); - if (!server.ping(sessionId, pingInfo)) { - logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() +":" + connection.getPort()); - throw new MageException("Ping failed"); - } - pingTime.add(System.nanoTime() - startTime); - long milliSeconds = TimeUnit.MILLISECONDS.convert(pingTime.getLast(), TimeUnit.NANOSECONDS); - String lastPing = milliSeconds > 0 ? milliSeconds+"ms" : "<1ms"; - if (pingTime.size() > PING_CYCLES) { - pingTime.poll(); - } - long sum = 0; - for (Long time :pingTime) { - sum += time; - } - milliSeconds = TimeUnit.MILLISECONDS.convert(sum / pingTime.size(), TimeUnit.NANOSECONDS); - pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms":"<1ms")+")"; - } - return true; - } catch (MageException ex) { - handleMageException(ex); - disconnect(true); - } catch (Throwable t) { - handleThrowable(t); - } - return false; - } - - @Override - public String getVersionInfo() { - if (serverState != null) { - return serverState.getVersion().toString(); - } else { - return ""; - } - } - -} - - -class MageAuthenticator extends Authenticator { - - private final String username; - private final String password; - - public MageAuthenticator(String username, String password) { - this.username = username; - this.password = password; - } - - @Override - public PasswordAuthentication getPasswordAuthentication () { - return new PasswordAuthentication (username, password.toCharArray()); - } -} +// +// @Override +// public boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password) { +// try { +// if (isConnected()) { +// return server.joinTable(sessionId, roomId, tableId, playerName, playerType, skill, deckList, password); +// } +// } catch (InvalidDeckException iex) { +// handleInvalidDeckException(iex); +// } catch (GameException ex) { +// handleGameException(ex); +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList, String password) { +// try { +// if (isConnected()) { +// return server.joinTournamentTable(sessionId, roomId, tableId, playerName, playerType, skill, deckList, password); +// } +// } catch (GameException ex) { +// handleGameException(ex); +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public Collection getTables(UUID roomId) throws MageRemoteException { +// try { +// if (isConnected()) { +// return server.getTables(roomId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// throw new MageRemoteException(); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public Collection getFinishedMatches(UUID roomId) throws MageRemoteException { +// try { +// if (isConnected()) { +// return server.getFinishedMatches(roomId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// throw new MageRemoteException(); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public Collection getRoomUsers(UUID roomId) throws MageRemoteException { +// try { +// if (isConnected()) { +// return server.getRoomUsers(roomId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// throw new MageRemoteException(); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public TournamentView getTournament(UUID tournamentId) throws MageRemoteException { +// try { +// if (isConnected()) { +// return server.getTournament(tournamentId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// throw new MageRemoteException(); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public UUID getTournamentChatId(UUID tournamentId) { +// try { +// if (isConnected()) { +// return server.getTournamentChatId(tournamentId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public boolean sendPlayerUUID(UUID gameId, UUID data) { +// try { +// if (isConnected()) { +// server.sendPlayerUUID(gameId, sessionId, data); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean sendPlayerBoolean(UUID gameId, boolean data) { +// try { +// if (isConnected()) { +// server.sendPlayerBoolean(gameId, sessionId, data); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean sendPlayerInteger(UUID gameId, int data) { +// try { +// if (isConnected()) { +// server.sendPlayerInteger(gameId, sessionId, data); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean sendPlayerString(UUID gameId, String data) { +// try { +// if (isConnected()) { +// server.sendPlayerString(gameId, sessionId, data); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean sendPlayerManaType(UUID gameId, UUID playerId, ManaType data) { +// try { +// if (isConnected()) { +// server.sendPlayerManaType(gameId, playerId, sessionId, data); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public DraftPickView sendCardPick(UUID draftId, UUID cardId, Set hiddenCards) { +// try { +// if (isConnected()) { +// return server.sendCardPick(draftId, sessionId, cardId, hiddenCards); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public DraftPickView sendCardMark(UUID draftId, UUID cardId) { +// try { +// if (isConnected()) { +// server.sendCardMark(draftId, sessionId, cardId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public boolean joinChat(UUID chatId) { +// try { +// if (isConnected()) { +// server.joinChat(chatId, sessionId, connection.getUsername()); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean leaveChat(UUID chatId) { +//// lock.readLock().lock(); +// try { +// if (isConnected()) { +// server.leaveChat(chatId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +//// } finally { +//// lock.readLock().unlock(); +// } +// return false; +// } +// +// @Override +// public boolean sendChatMessage(UUID chatId, String message) { +//// lock.readLock().lock(); +// try { +// if (isConnected()) { +// server.sendChatMessage(chatId, connection.getUsername(), message); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +//// } finally { +//// lock.readLock().unlock(); +// } +// return false; +// } +// +// @Override +// public boolean sendBroadcastMessage(String message) { +// try { +// if (isConnected()) { +// server.sendBroadcastMessage(sessionId, message); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean joinGame(UUID gameId) { +// try { +// if (isConnected()) { +// server.joinGame(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean joinDraft(UUID draftId) { +// try { +// if (isConnected()) { +// server.joinDraft(draftId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean joinTournament(UUID tournamentId) { +// try { +// if (isConnected()) { +// server.joinTournament(tournamentId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean watchGame(UUID gameId) { +// try { +// if (isConnected()) { +// server.watchGame(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean replayGame(UUID gameId) { +// try { +// if (isConnected()) { +// server.replayGame(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public TableView createTable(UUID roomId, MatchOptions matchOptions) { +// try { +// if (isConnected()) { +// return server.createTable(sessionId, roomId, matchOptions); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public TableView createTournamentTable(UUID roomId, TournamentOptions tournamentOptions) { +// try { +// if (isConnected()) { +// return server.createTournamentTable(sessionId, roomId, tournamentOptions); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public boolean isTableOwner(UUID roomId, UUID tableId) { +// try { +// if (isConnected()) { +// return server.isTableOwner(sessionId, roomId, tableId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean removeTable(UUID roomId, UUID tableId) { +// try { +// if (isConnected()) { +// server.removeTable(sessionId, roomId, tableId); +// +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// /** +// * Remove table - called from admin console +// * @param tableId +// * @return +// */ +// @Override +// public boolean removeTable(UUID tableId) { +// try { +// if (isConnected()) { +// server.removeTable(sessionId, tableId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean swapSeats(UUID roomId, UUID tableId, int seatNum1, int seatNum2) { +// try { +// if (isConnected()) { +// server.swapSeats(sessionId, roomId, tableId, seatNum1, seatNum2); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean leaveTable(UUID roomId, UUID tableId) { +// try { +// if (isConnected() && server.leaveTable(sessionId, roomId, tableId)) { +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean startMatch(UUID roomId, UUID tableId) { +// try { +// if (isConnected()) { +// return (server.startMatch(sessionId, roomId, tableId)); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } +// return false; +// } +// +// @Override +// public boolean startTournament(UUID roomId, UUID tableId) { +// try { +// if (isConnected() && server.startTournament(sessionId, roomId, tableId)) { +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +//// @Override +//// public boolean startChallenge(UUID roomId, UUID tableId, UUID challengeId) { +//// try { +//// if (isConnected()) { +//// server.startChallenge(sessionId, roomId, tableId, challengeId); +//// return true; +//// } +//// } catch (MageException ex) { +//// handleMageException(ex); +//// } catch (Throwable t) { +//// handleThrowable(t); +//// } +//// return false; +//// } +// +// @Override +// public boolean submitDeck(UUID tableId, DeckCardLists deck) { +// try { +// if (isConnected()) { +// return server.submitDeck(sessionId, tableId, deck); +// } +// } catch (GameException ex) { +// handleGameException(ex); +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean updateDeck(UUID tableId, DeckCardLists deck) { +// try { +// if (isConnected()) { +// server.updateDeck(sessionId, tableId, deck); +// return true; +// } +// } catch (GameException ex) { +// handleGameException(ex); +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean quitMatch(UUID gameId) { +// try { +// if (isConnected()) { +// server.quitMatch(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean quitTournament(UUID tournamentId) { +// try { +// if (isConnected()) { +// server.quitTournament(tournamentId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean quitDraft(UUID draftId) { +// try { +// if (isConnected()) { +// server.quitDraft(draftId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } +// return false; +// } +// +// @Override +// public boolean sendPlayerAction(PlayerAction passPriorityAction, UUID gameId, Object data) { +// try { +// if (isConnected()) { +// server.sendPlayerAction(passPriorityAction, gameId, sessionId, data); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean stopWatching(UUID gameId) { +// try { +// if (isConnected()) { +// server.stopWatching(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean startReplay(UUID gameId) { +// try { +// if (isConnected()) { +// server.startReplay(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean stopReplay(UUID gameId) { +// try { +// if (isConnected()) { +// server.stopReplay(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean nextPlay(UUID gameId) { +// try { +// if (isConnected()) { +// server.nextPlay(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean previousPlay(UUID gameId) { +// try { +// if (isConnected()) { +// server.previousPlay(gameId, sessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean skipForward(UUID gameId, int moves) { +// try { +// if (isConnected()) { +// server.skipForward(gameId, sessionId, moves); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean cheat(UUID gameId, UUID playerId, DeckCardLists deckList) { +// try { +// if (isConnected()) { +// server.cheat(gameId, sessionId, playerId, deckList); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public List getUsers() { +// try { +// if (isConnected()) { +// return server.getUsers(sessionId); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public List getServerMessages() { +// try { +// if (isConnected()) { +// return (List) CompressUtil.decompress(server.getServerMessagesCompressed(sessionId)); +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return null; +// } +// +// @Override +// public boolean disconnectUser(String userSessionId) { +// try { +// if (isConnected()) { +// server.disconnectUser(sessionId, userSessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean endUserSession(String userSessionId) { +// try { +// if (isConnected()) { +// server.endUserSession(sessionId, userSessionId); +// return true; +// } +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// private void handleThrowable(Throwable t) { +// logger.fatal("Communication error", t); +// disconnect(true); +// } +// +// private void handleMageException(MageException ex) { +// logger.fatal("Server error", ex); +// client.showError(ex.getMessage()); +// } +// +// private void handleInvalidDeckException(InvalidDeckException iex) { +// logger.warn(iex.getMessage() + "\n" + iex.getInvalid()); +// client.showError(iex.getMessage() + "\n" + iex.getInvalid()); +// } +// +// private void handleGameException(GameException ex) { +// logger.warn(ex.getMessage()); +// client.showError(ex.getMessage()); +// } +// +// +// @Override +// public String getUserName() { +// return connection.getUsername(); +// } +// +// @Override +// public boolean updatePreferencesForServer(int avatarId, boolean showAbilityPickerForced, boolean allowRequestShowHandCards, UserSkipPrioritySteps userSkipPrioritySteps) { +// try { +// if (isConnected()) { +// UserDataView userDataView = new UserDataView(avatarId, showAbilityPickerForced, allowRequestShowHandCards, userSkipPrioritySteps); +// server.setUserData(connection.getUsername(), sessionId, userDataView); +// } +// return true; +// } catch (MageException ex) { +// handleMageException(ex); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public boolean ping() { +// try { +// if (isConnected()) { +// long startTime = System.nanoTime(); +// if (!server.ping(sessionId, pingInfo)) { +// logger.error(new StringBuilder("Ping failed: ").append(this.getUserName()).append(" Session: ").append(sessionId).append(" to MAGE server at ").append(connection.getHost()).append(":").append(connection.getPort()).toString()); +// throw new MageException("Ping failed"); +// } +// pingTime.add(System.nanoTime() - startTime); +// long milliSeconds = TimeUnit.MILLISECONDS.convert(pingTime.getLast(), TimeUnit.NANOSECONDS); +// String lastPing = milliSeconds > 0 ? milliSeconds+"ms" : "<1ms"; +// if (pingTime.size() > PING_CYCLES) { +// pingTime.poll(); +// } +// long sum = 0; +// for (Long time :pingTime) { +// sum += time; +// } +// milliSeconds = TimeUnit.MILLISECONDS.convert(sum / pingTime.size(), TimeUnit.NANOSECONDS); +// pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms":"<1ms")+")"; +// } +// return true; +// } catch (MageException ex) { +// handleMageException(ex); +// disconnect(true); +// } catch (Throwable t) { +// handleThrowable(t); +// } +// return false; +// } +// +// @Override +// public String getVersionInfo() { +// if (serverState != null) { +// return serverState.getVersion().toString(); +// } else { +// return ""; +// } +// } +// +//} +// +// +//class MageAuthenticator extends Authenticator { +// +// private final String username; +// private final String password; +// +// public MageAuthenticator(String username, String password) { +// this.username = username; +// this.password = password; +// } +// +// @Override +// public PasswordAuthentication getPasswordAuthentication () { +// return new PasswordAuthentication (username, password.toCharArray()); +// } +//} diff --git a/Mage.Network/pom.xml b/Mage.Network/pom.xml new file mode 100644 index 00000000000..56cfba07642 --- /dev/null +++ b/Mage.Network/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + + + org.mage + mage-root + 1.4.0 + + + mage-network + jar + Mage Network + + + + io.netty + netty-all + 5.0.0.Alpha2 + + + log4j + log4j + jar + + + ${project.groupId} + mage + ${project.version} + + + ${project.groupId} + mage-common + ${project.version} + + + \ No newline at end of file diff --git a/Mage.Network/src/main/java/org/mage/network/Client.java b/Mage.Network/src/main/java/org/mage/network/Client.java new file mode 100644 index 00000000000..a530261d676 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/Client.java @@ -0,0 +1,388 @@ +package org.mage.network; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.serialization.ClassResolvers; +import io.netty.handler.codec.serialization.ObjectDecoder; +import io.netty.handler.codec.serialization.ObjectEncoder; +import io.netty.handler.timeout.IdleStateHandler; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Level; +import mage.cards.decks.DeckCardLists; +import mage.constants.ManaType; +import mage.constants.PlayerAction; +import mage.game.match.MatchOptions; +import mage.game.tournament.TournamentOptions; +import mage.interfaces.ServerState; +import mage.players.net.UserSkipPrioritySteps; +import mage.utils.MageVersion; +import mage.view.DraftPickView; +import mage.view.MatchView; +import mage.view.RoomUsersView; +import mage.view.TableView; +import mage.view.TournamentView; +import mage.view.UserView; +import org.apache.log4j.Logger; +import org.mage.network.handlers.HeartbeatHandler; +import org.mage.network.handlers.PingMessageHandler; +import org.mage.network.handlers.client.ChatMessageHandler; +import org.mage.network.handlers.client.ChatRoomHandler; +import org.mage.network.handlers.client.ClientRegisteredMessageHandler; +import org.mage.network.handlers.client.InformClientMessageHandler; +import org.mage.network.handlers.client.MessageHandler; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.JoinChatMessage; +import org.mage.network.model.LeaveChatMessage; +import org.mage.network.model.MessageType; +import org.mage.network.model.RegisterClientMessage; +import org.mage.network.model.SendChatMessage; + +/** + * + * @author BetaSteward + */ +public class Client { + + private static final Logger logger = Logger.getLogger(Client.class); + + private static final int IDLE_PING_TIME = 30; + private static final int IDLE_TIMEOUT = 60; + + private final MageClient client; +// private final MessageHandler h; + private final ChatRoomHandler chatRoomHandler; + private final ChatMessageHandler chatMessageHandler; + private final InformClientMessageHandler informClientMessageHandler; + private final ClientRegisteredMessageHandler clientRegisteredMessageHandler; + + private Channel channel; + private EventLoopGroup group; + private String username; + + public Client(MageClient client) { + this.client = client; +// h = new MessageHandler(); + chatRoomHandler = new ChatRoomHandler(); + chatMessageHandler = new ChatMessageHandler(client); + informClientMessageHandler = new InformClientMessageHandler(client); + clientRegisteredMessageHandler = new ClientRegisteredMessageHandler(client); + } + + public boolean connect(String userName, String host, int port, MageVersion version) { + + this.username = userName; + + group = new NioEventLoopGroup(); + try { + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioSocketChannel.class) + .handler(new ClientInitializer()); + + channel = b.connect(host, port).sync().channel(); + channel.writeAndFlush(new RegisterClientMessage(userName, version)); + client.connected(userName + "@" + host + ":" + port + " "); + return true; + } catch (InterruptedException ex) { + logger.fatal("Error connecting", ex); + client.inform("Error connecting", MessageType.ERROR); + group.shutdownGracefully(); + } + return false; + } + + private class ClientInitializer extends ChannelInitializer { + + @Override + public void initChannel(SocketChannel ch) throws Exception { + + ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); + ch.pipeline().addLast(new ObjectEncoder()); + + ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(IDLE_TIMEOUT, IDLE_PING_TIME, 0)); + ch.pipeline().addLast("heartbeatHandler", new HeartbeatHandler()); + ch.pipeline().addLast("pingMessageHandler", new PingMessageHandler()); + +// ch.pipeline().addLast("h", h); + ch.pipeline().addLast("chatMessageHandler", chatMessageHandler); + ch.pipeline().addLast("informClientMessageHandler", informClientMessageHandler); + ch.pipeline().addLast("clientRegisteredMessageHandler", clientRegisteredMessageHandler); + ch.pipeline().addLast("chatRoomHandler", chatRoomHandler); + + } + } + + public void disconnect() { + + try { + channel.closeFuture().sync(); + } catch (InterruptedException ex) { + logger.fatal("Error disconnecting", ex); + } finally { + group.shutdownGracefully(); + } + } + + public boolean isConnected() { + if (channel != null) + return channel.isActive(); + return false; + } + + public void sendChatMessage(UUID chatId, String message) { + chatMessageHandler.sendMessage(chatId, message); + } + + public void joinChat(UUID chatId) { + chatRoomHandler.joinChat(chatId); + } + + public void leaveChat(UUID chatId) { + chatRoomHandler.leaveChat(chatId); + } + + public void sendPlayerUUID(UUID gameId, UUID id) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendPlayerBoolean(UUID gameId, boolean b) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public String getUserName() { + return username; + } + + public ServerState getServerState() { + return client.getServerState(); + } + + public boolean submitDeck(UUID tableId, DeckCardLists deckCardLists) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void updateDeck(UUID tableId, DeckCardLists deckCardLists) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean sendFeedback(String title, String type, String message, String email) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String human, int i, DeckCardLists importDeck, String text) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean joinTable(UUID roomId, UUID tableId, String playerName, String human, int i, DeckCardLists importDeck, String text) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public TableView createTable(UUID roomId, MatchOptions options) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void removeTable(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public String getSessionId() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public TableView createTournamentTable(UUID roomId, TournamentOptions tOptions) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void updatePreferencesForServer(int selectedAvatar, boolean selected, boolean selected0, UserSkipPrioritySteps userSkipPrioritySteps) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean isTableOwner(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public UUID getTableChatId(UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean startMatch(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean startTournament(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean leaveTable(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void swapSeats(UUID roomId, UUID tableId, int row, int i) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendPlayerAction(PlayerAction playerAction, UUID gameId, UUID relatedUserId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public TableView getTable(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void watchTournamentTable(UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public UUID getTournamentChatId(UUID tournamentId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean joinTournament(UUID tournamentId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void quitTournament(UUID tournamentId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public TournamentView getTournament(UUID tournamentId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public UUID getMainRoomId() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void watchTable(UUID roomId, UUID tableId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void replayGame(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public UUID getRoomChatId(UUID roomId) { + try { + return chatRoomHandler.getChatRoomId(roomId); + } catch (Exception ex) { + logger.error("Error getting chat room id", ex); + } + return null; + } + + public List getServerMessages() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public Collection getTables(UUID roomId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public Collection getFinishedMatches(UUID roomId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public Collection getRoomUsers(UUID roomId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendPlayerInteger(UUID gameId, int i) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendPlayerString(UUID gameId, String special) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendPlayerManaType(UUID gameId, UUID playerId, ManaType manaType) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void cheat(UUID gameId, UUID playerId, DeckCardLists importDeck) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public UUID getGameChatId(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean joinGame(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean watchGame(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean startReplay(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void stopWatching(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void stopReplay(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void nextPlay(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void previousPlay(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void skipForward(UUID gameId, int i) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void quitMatch(UUID gameId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public boolean joinDraft(UUID draftId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public DraftPickView sendCardPick(UUID draftId, UUID id, Set cardsHidden) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendCardMark(UUID draftId, UUID id) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void quitDraft(UUID draftId) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void sendBroadcastMessage(String message) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void disconnectUser(String string) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void removeTable(UUID uuid) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public void endUserSession(String string) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + public List getUsers() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/Server.java b/Mage.Network/src/main/java/org/mage/network/Server.java new file mode 100644 index 00000000000..ca481cb3630 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/Server.java @@ -0,0 +1,137 @@ +package org.mage.network; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.group.ChannelGroup; +import io.netty.channel.group.DefaultChannelGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.serialization.ClassResolvers; +import io.netty.handler.codec.serialization.ObjectDecoder; +import io.netty.handler.codec.serialization.ObjectEncoder; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import io.netty.handler.timeout.IdleStateHandler; +import io.netty.util.concurrent.DefaultEventExecutorGroup; +import io.netty.util.concurrent.EventExecutorGroup; +import io.netty.util.concurrent.GlobalEventExecutor; +import java.util.UUID; +import mage.view.ChatMessage; +import org.apache.log4j.Logger; +import org.mage.network.handlers.HeartbeatHandler; +import org.mage.network.handlers.PingMessageHandler; +import org.mage.network.handlers.server.ChatMessageHandler; +import org.mage.network.handlers.server.ChatRoomIdHandler; +import org.mage.network.handlers.server.ConnectionHandler; +import org.mage.network.handlers.server.JoinChatMessageHandler; +import org.mage.network.handlers.server.LeaveChatMessageHandler; +import org.mage.network.handlers.server.RegisterClientMessageHandler; +import org.mage.network.interfaces.MageServer; +import org.mage.network.model.InformClientMessage; +import org.mage.network.model.MessageType; +import org.mage.network.model.ReceiveChatMessage; + +/** + * + * @author BetaSteward + */ +public class Server { + + private static final Logger logger = Logger.getLogger(Server.class); + + private static final int IDLE_PING_TIME = 30; + private static final int IDLE_TIMEOUT = 60; + + public static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); + + private final HeartbeatHandler heartbeatHandler = new HeartbeatHandler(); + private final PingMessageHandler pingMessageHandler = new PingMessageHandler(); + private final EventExecutorGroup handlersExecutor = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2); + private final RegisterClientMessageHandler registerClientMessageHandler; + + private final ChatRoomIdHandler chatRoomIdHandler; + private final ChatMessageHandler chatMessageHandler; + private final JoinChatMessageHandler joinChatMessageHandler; + private final LeaveChatMessageHandler leaveChatMessageHandler; + + public Server(MageServer server) { + registerClientMessageHandler = new RegisterClientMessageHandler(server); + chatMessageHandler = new ChatMessageHandler(server); + joinChatMessageHandler = new JoinChatMessageHandler(server); + leaveChatMessageHandler = new LeaveChatMessageHandler(server); + chatRoomIdHandler = new ChatRoomIdHandler(server); + } + + public void start(int port) { + EventLoopGroup bossGroup = new NioEventLoopGroup(); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + ServerBootstrap b = new ServerBootstrap(); + b.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ServerInitializer()); + + b.bind(port).sync().channel().closeFuture().sync(); + } catch (InterruptedException ex) { + logger.fatal("Error starting server", ex); + } finally { + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + + } + + private class ServerInitializer extends ChannelInitializer { + + @Override + public void initChannel(SocketChannel ch) throws Exception { + + ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); + ch.pipeline().addLast(new ObjectEncoder()); + + ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(IDLE_TIMEOUT, IDLE_PING_TIME, 0)); + ch.pipeline().addLast("heartbeatHandler", heartbeatHandler); + ch.pipeline().addLast("pingMessageHandler", pingMessageHandler); + + ch.pipeline().addLast("connectionHandler", new ConnectionHandler()); + ch.pipeline().addLast(handlersExecutor, registerClientMessageHandler); + + ch.pipeline().addLast(handlersExecutor, chatRoomIdHandler); + ch.pipeline().addLast(handlersExecutor, chatMessageHandler); + ch.pipeline().addLast(handlersExecutor, joinChatMessageHandler); + ch.pipeline().addLast(handlersExecutor, leaveChatMessageHandler); + } + + } + + private Channel findChannel(String sessionId) { + for (Channel channel: clients) { + if (channel.id().asLongText().equals(sessionId)) { + return channel; + } + } + return null; + } + + public void sendChatMessage(String sessionId, UUID chatId, ChatMessage message) { + Channel ch = findChannel(sessionId); + if (ch != null) + ch.writeAndFlush(new ReceiveChatMessage(chatId, message)); + } + + public void informClient(String sessionId, String message, MessageType type) { + Channel ch = findChannel(sessionId); + if (ch != null) + ch.writeAndFlush(new InformClientMessage(message, type)); + } + + public void informClients(String message, MessageType type) { + clients.writeAndFlush(new InformClientMessage(message, type)); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/HeartbeatHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/HeartbeatHandler.java new file mode 100644 index 00000000000..7c44738ea75 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/HeartbeatHandler.java @@ -0,0 +1,35 @@ +package org.mage.network.handlers; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.timeout.IdleState; +import io.netty.handler.timeout.IdleStateEvent; +import org.apache.log4j.Logger; +import org.mage.network.model.PingMessage; + +/** + * + * @author BetaSteward + */ +@Sharable +public class HeartbeatHandler extends ChannelHandlerAdapter { + + private static final Logger logger = Logger.getLogger(HeartbeatHandler.class); + + private static PingMessage ping = new PingMessage(); + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof IdleStateEvent) { + IdleStateEvent e = (IdleStateEvent) evt; + if (e.state() == IdleState.READER_IDLE) { + ctx.close(); + logger.info("Disconnected due to extended idle"); + } else if (e.state() == IdleState.WRITER_IDLE) { + ctx.writeAndFlush(ping); + logger.info("Sending ping"); + } + } + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/PingMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/PingMessageHandler.java new file mode 100644 index 00000000000..c8414cac869 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/PingMessageHandler.java @@ -0,0 +1,26 @@ +package org.mage.network.handlers; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.apache.log4j.Logger; +import org.mage.network.model.PingMessage; +import org.mage.network.model.PongMessage; + +/** + * + * @author BetaSteward + */ +@Sharable +public class PingMessageHandler extends SimpleChannelInboundHandler { + + private static final Logger logger = Logger.getLogger(HeartbeatHandler.class); + private static PongMessage pong = new PongMessage(); + + @Override + protected void messageReceived(ChannelHandlerContext ctx, PingMessage msg) throws Exception { + ctx.writeAndFlush(pong); + logger.info("Received ping. Sending pong"); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/client/ChatMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/client/ChatMessageHandler.java new file mode 100644 index 00000000000..6734df232e4 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/client/ChatMessageHandler.java @@ -0,0 +1,37 @@ +package org.mage.network.handlers.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import java.util.UUID; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.ReceiveChatMessage; +import org.mage.network.model.SendChatMessage; + +/** + * + * @author BetaSteward + */ +public class ChatMessageHandler extends SimpleChannelInboundHandler { + + private final MageClient client; + private ChannelHandlerContext ctx; + + public ChatMessageHandler (MageClient client) { + this.client = client; + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + this.ctx = ctx; + super.channelActive(ctx); + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, ReceiveChatMessage msg) throws Exception { + client.receiveChatMessage(msg.getChatId(), msg.getMessage()); + } + + public void sendMessage(UUID chatId, String message) { + ctx.writeAndFlush(new SendChatMessage(chatId, message)); + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/client/ChatRoomHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/client/ChatRoomHandler.java new file mode 100644 index 00000000000..2b02f75781e --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/client/ChatRoomHandler.java @@ -0,0 +1,46 @@ +package org.mage.network.handlers.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import java.util.UUID; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import org.mage.network.model.ChatRoomIdMessage; +import org.mage.network.model.ChatRoomIdRequest; +import org.mage.network.model.JoinChatMessage; +import org.mage.network.model.LeaveChatMessage; + +/** + * + * @author BetaSteward + */ +public class ChatRoomHandler extends SimpleChannelInboundHandler { + + private ChannelHandlerContext ctx; + private final BlockingQueue queue = new LinkedBlockingQueue<>(); + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + this.ctx = ctx; + super.channelActive(ctx); + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, ChatRoomIdMessage msg) { + queue.offer(msg.getId()); + } + + public UUID getChatRoomId(UUID id) throws Exception { + ctx.writeAndFlush(new ChatRoomIdRequest(id)); + return queue.take(); + } + + public void joinChat(UUID chatId) { + ctx.writeAndFlush(new JoinChatMessage(chatId)); + } + + public void leaveChat(UUID chatId) { + ctx.writeAndFlush(new LeaveChatMessage(chatId)); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientRegisteredMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientRegisteredMessageHandler.java new file mode 100644 index 00000000000..c0ce45acfd7 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientRegisteredMessageHandler.java @@ -0,0 +1,25 @@ +package org.mage.network.handlers.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.ClientRegisteredMessage; + +/** + * + * @author BetaSteward + */ +public class ClientRegisteredMessageHandler extends SimpleChannelInboundHandler { + + private final MageClient client; + + public ClientRegisteredMessageHandler (MageClient client) { + this.client = client; + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, ClientRegisteredMessage msg) throws Exception { + client.clientRegistered(msg.getServerState()); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/client/InformClientMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/client/InformClientMessageHandler.java new file mode 100644 index 00000000000..8d0aaf26539 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/client/InformClientMessageHandler.java @@ -0,0 +1,25 @@ +package org.mage.network.handlers.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.InformClientMessage; + +/** + * + * @author BetaSteward + */ +public class InformClientMessageHandler extends SimpleChannelInboundHandler { + + private final MageClient client; + + public InformClientMessageHandler (MageClient client) { + this.client = client; + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, InformClientMessage msg) throws Exception { + client.inform(msg.getMessage(), msg.getType()); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/client/MessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/client/MessageHandler.java new file mode 100644 index 00000000000..af865011d87 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/client/MessageHandler.java @@ -0,0 +1,12 @@ +package org.mage.network.handlers.client; + +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; + +public class MessageHandler extends ChannelHandlerAdapter { + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ctx.fireChannelRead(msg); + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/server/ChatMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/server/ChatMessageHandler.java new file mode 100644 index 00000000000..d09844b8969 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/server/ChatMessageHandler.java @@ -0,0 +1,38 @@ +package org.mage.network.handlers.server; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageServer; +import org.mage.network.model.SendChatMessage; + +/** + * + * @author BetaSteward + */ +@Sharable +public class ChatMessageHandler extends SimpleChannelInboundHandler { + + private final MageServer server; + + public ChatMessageHandler (MageServer server) { + this.server = server; + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, SendChatMessage msg) throws Exception { + server.receiveChatMessage(msg.getChatId(), ctx.channel().id().asLongText(), msg.getMessage()); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/server/ChatRoomIdHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/server/ChatRoomIdHandler.java new file mode 100644 index 00000000000..f1db4834ce7 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/server/ChatRoomIdHandler.java @@ -0,0 +1,39 @@ +package org.mage.network.handlers.server; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageServer; +import org.mage.network.model.ChatRoomIdMessage; +import org.mage.network.model.ChatRoomIdRequest; + +/** + * + * @author BetaSteward + */ +@Sharable +public class ChatRoomIdHandler extends SimpleChannelInboundHandler { + + private final MageServer server; + + public ChatRoomIdHandler (MageServer server) { + this.server = server; + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, ChatRoomIdRequest msg) { + ctx.writeAndFlush(new ChatRoomIdMessage(server.getRoomChatId(msg.getId()))); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/server/ConnectionHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/server/ConnectionHandler.java new file mode 100644 index 00000000000..964a8fcf938 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/server/ConnectionHandler.java @@ -0,0 +1,19 @@ +package org.mage.network.handlers.server; + +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; +import org.mage.network.Server; + +/** + * + * @author BetaSteward + */ +public class ConnectionHandler extends ChannelHandlerAdapter { + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + Server.clients.add(ctx.channel()); + super.channelActive(ctx); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/server/JoinChatMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/server/JoinChatMessageHandler.java new file mode 100644 index 00000000000..ee597524a3d --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/server/JoinChatMessageHandler.java @@ -0,0 +1,37 @@ +package org.mage.network.handlers.server; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageServer; +import org.mage.network.model.JoinChatMessage; + +/** + * + * @author BetaSteward + */ +@Sharable +public class JoinChatMessageHandler extends SimpleChannelInboundHandler { + + private final MageServer server; + + public JoinChatMessageHandler (MageServer server) { + this.server = server; + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, JoinChatMessage msg) throws Exception { + server.joinChat(msg.getChatId(), ctx.channel().id().asLongText()); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/server/LeaveChatMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/server/LeaveChatMessageHandler.java new file mode 100644 index 00000000000..d38b810a2ae --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/server/LeaveChatMessageHandler.java @@ -0,0 +1,38 @@ +package org.mage.network.handlers.server; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageServer; +import org.mage.network.model.JoinChatMessage; + +/** + * + * @author BetaSteward + */ +@Sharable +public class LeaveChatMessageHandler extends SimpleChannelInboundHandler { + + private final MageServer server; + + public LeaveChatMessageHandler (MageServer server) { + this.server = server; + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, JoinChatMessage msg) throws Exception { + server.leaveChat(msg.getChatId(), ctx.channel().id().asLongText()); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/server/RegisterClientMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/server/RegisterClientMessageHandler.java new file mode 100644 index 00000000000..efbce7ab6a1 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/handlers/server/RegisterClientMessageHandler.java @@ -0,0 +1,43 @@ +package org.mage.network.handlers.server; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import org.mage.network.interfaces.MageServer; +import org.mage.network.model.RegisterClientMessage; +import org.mage.network.model.ClientRegisteredMessage; + +/** + * + * @author BetaSteward + */ +@Sharable +public class RegisterClientMessageHandler extends SimpleChannelInboundHandler { + + private final MageServer server; + + public RegisterClientMessageHandler (MageServer server) { + this.server = server; + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, RegisterClientMessage msg) throws Exception { + if (!server.registerClient(msg.getUserName(), ctx.channel().id().asLongText(), msg.getMageVersion())) { + ctx.disconnect(); + } + else { + ctx.writeAndFlush(new ClientRegisteredMessage(server.getServerState())); + } + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/interfaces/MageClient.java b/Mage.Network/src/main/java/org/mage/network/interfaces/MageClient.java new file mode 100644 index 00000000000..e57f0c55a3d --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/interfaces/MageClient.java @@ -0,0 +1,24 @@ +package org.mage.network.interfaces; + +import java.util.UUID; +import mage.interfaces.ServerState; +import mage.view.ChatMessage; +import org.mage.network.model.MessageType; + +/** + * + * @author BetaSteward + */ +public interface MageClient { + + void connected(String message); + + void inform(String message, MessageType type); + + void receiveChatMessage(UUID chatId, ChatMessage message); + void receiveBroadcastMessage(String message); + + void clientRegistered(ServerState state); + ServerState getServerState(); + +} diff --git a/Mage.Network/src/main/java/org/mage/network/interfaces/MageServer.java b/Mage.Network/src/main/java/org/mage/network/interfaces/MageServer.java new file mode 100644 index 00000000000..3029cf4e7c3 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/interfaces/MageServer.java @@ -0,0 +1,23 @@ +package org.mage.network.interfaces; + +import java.util.UUID; +import mage.interfaces.ServerState; +import mage.utils.MageVersion; + +/** + * + * @author BetaSteward + */ +public interface MageServer { + + boolean registerClient(String userName, String sessionId, MageVersion version); + + void receiveChatMessage(UUID chatId, String sessionId, String message); + void joinChat(UUID chatId, String sessionId); + void leaveChat(UUID chatId, String sessionId); + UUID getRoomChatId(UUID roomId); + void receiveBroadcastMessage(String message, String sessionId); + + ServerState getServerState(); + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdMessage.java b/Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdMessage.java new file mode 100644 index 00000000000..b7afba6615e --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdMessage.java @@ -0,0 +1,22 @@ +package org.mage.network.model; + +import java.io.Serializable; +import java.util.UUID; + +/** + * + * @author BetaSteward + */ +public class ChatRoomIdMessage implements Serializable { + + private UUID id; + + public ChatRoomIdMessage(UUID id) { + this.id = id; + } + + public UUID getId() { + return id; + } + +} \ No newline at end of file diff --git a/Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdRequest.java b/Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdRequest.java new file mode 100644 index 00000000000..6a83cdadcca --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/ChatRoomIdRequest.java @@ -0,0 +1,22 @@ +package org.mage.network.model; + +import java.io.Serializable; +import java.util.UUID; + +/** + * + * @author BetaSteward + */ +public class ChatRoomIdRequest implements Serializable { + + private UUID id; + + public ChatRoomIdRequest(UUID id) { + this.id = id; + } + + public UUID getId() { + return id; + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/ClientRegisteredMessage.java b/Mage.Network/src/main/java/org/mage/network/model/ClientRegisteredMessage.java new file mode 100644 index 00000000000..4cbc2fad672 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/ClientRegisteredMessage.java @@ -0,0 +1,21 @@ +package org.mage.network.model; + +import java.io.Serializable; +import mage.interfaces.ServerState; + +/** + * + * @author BetaSteward + */ +public class ClientRegisteredMessage implements Serializable { + + private ServerState state; + + public ClientRegisteredMessage(ServerState state) { + this.state = state; + } + + public ServerState getServerState() { + return state; + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/InformClientMessage.java b/Mage.Network/src/main/java/org/mage/network/model/InformClientMessage.java new file mode 100644 index 00000000000..aef3c176b9c --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/InformClientMessage.java @@ -0,0 +1,26 @@ +package org.mage.network.model; + +import java.io.Serializable; + +/** + * + * @author BetaSteward + */ +public class InformClientMessage implements Serializable { + + private String message; + private MessageType type; + + public InformClientMessage(String message, MessageType type) { + this.message = message; + this.type = type; + } + + public String getMessage() { + return message; + } + + public MessageType getType() { + return type; + } +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/JoinChatMessage.java b/Mage.Network/src/main/java/org/mage/network/model/JoinChatMessage.java new file mode 100644 index 00000000000..d5ccc69e4ba --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/JoinChatMessage.java @@ -0,0 +1,22 @@ +package org.mage.network.model; + +import java.io.Serializable; +import java.util.UUID; + +/** + * + * @author BetaSteward + */ +public class JoinChatMessage implements Serializable { + + private UUID chatId; + + public JoinChatMessage(UUID chatId) { + this.chatId = chatId; + } + + public UUID getChatId() { + return chatId; + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/LeaveChatMessage.java b/Mage.Network/src/main/java/org/mage/network/model/LeaveChatMessage.java new file mode 100644 index 00000000000..c8b56b40c33 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/LeaveChatMessage.java @@ -0,0 +1,22 @@ +package org.mage.network.model; + +import java.io.Serializable; +import java.util.UUID; + +/** + * + * @author BetaSteward + */ +public class LeaveChatMessage implements Serializable { + + private UUID chatId; + + public LeaveChatMessage(UUID chatId) { + this.chatId = chatId; + } + + public UUID getChatId() { + return chatId; + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/MessageType.java b/Mage.Network/src/main/java/org/mage/network/model/MessageType.java new file mode 100644 index 00000000000..a50f2139b3b --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/MessageType.java @@ -0,0 +1,11 @@ +package org.mage.network.model; + +/** + * + * @author BetaSteward + */ +public enum MessageType { + INFORMATION, + WARNING, + ERROR +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/PingMessage.java b/Mage.Network/src/main/java/org/mage/network/model/PingMessage.java new file mode 100644 index 00000000000..24eb9b1480e --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/PingMessage.java @@ -0,0 +1,11 @@ +package org.mage.network.model; + +import java.io.Serializable; + +/** + * + * @author BetaSteward + */ +public class PingMessage implements Serializable { + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/PongMessage.java b/Mage.Network/src/main/java/org/mage/network/model/PongMessage.java new file mode 100644 index 00000000000..5d81dc77c44 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/PongMessage.java @@ -0,0 +1,11 @@ +package org.mage.network.model; + +import java.io.Serializable; + +/** + * + * @author BetaSteward + */ +public class PongMessage implements Serializable { + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/ReceiveChatMessage.java b/Mage.Network/src/main/java/org/mage/network/model/ReceiveChatMessage.java new file mode 100644 index 00000000000..ad07e780635 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/ReceiveChatMessage.java @@ -0,0 +1,29 @@ +package org.mage.network.model; + +import java.io.Serializable; +import java.util.UUID; +import mage.view.ChatMessage; + +/** + * + * @author BetaSteward + */ +public class ReceiveChatMessage implements Serializable { + + private UUID chatId; + private ChatMessage message; + + public ReceiveChatMessage(UUID chatId, ChatMessage message) { + this.chatId = chatId; + this.message = message; + } + + public UUID getChatId() { + return chatId; + } + + public ChatMessage getMessage() { + return message; + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/RegisterClientMessage.java b/Mage.Network/src/main/java/org/mage/network/model/RegisterClientMessage.java new file mode 100644 index 00000000000..158dac036fb --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/RegisterClientMessage.java @@ -0,0 +1,27 @@ +package org.mage.network.model; + +import java.io.Serializable; +import mage.utils.MageVersion; + +/** + * + * @author BetaSteward + */ +public class RegisterClientMessage implements Serializable { + private String userName; + private MageVersion version; + + public RegisterClientMessage(String userName, MageVersion version) { + this.userName = userName; + this.version = version; + } + + public String getUserName() { + return userName; + } + + public MageVersion getMageVersion() { + return version; + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/model/SendChatMessage.java b/Mage.Network/src/main/java/org/mage/network/model/SendChatMessage.java new file mode 100644 index 00000000000..b5b63681b0f --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/model/SendChatMessage.java @@ -0,0 +1,28 @@ +package org.mage.network.model; + +import java.io.Serializable; +import java.util.UUID; + +/** + * + * @author BetaSteward + */ +public class SendChatMessage implements Serializable { + + private UUID chatId; + private String message; + + public SendChatMessage(UUID chatId, String message) { + this.chatId = chatId; + this.message = message; + } + + public UUID getChatId() { + return chatId; + } + + public String getMessage() { + return message; + } + +} diff --git a/Mage.Server.Console/pom.xml b/Mage.Server.Console/pom.xml index 89711b9d918..be3f68f1555 100644 --- a/Mage.Server.Console/pom.xml +++ b/Mage.Server.Console/pom.xml @@ -30,5 +30,10 @@ junit test
+ + ${project.groupId} + mage-network + ${project.version} + diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java index 346e98260cd..cb9d7cd7e77 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java @@ -36,6 +36,7 @@ package mage.server.console; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -44,13 +45,17 @@ import javax.swing.Box; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; -import mage.interfaces.MageClient; -import mage.interfaces.callback.ClientCallback; +import mage.interfaces.ServerState; +//import mage.interfaces.MageClient; +//import mage.interfaces.callback.ClientCallback; import mage.remote.Connection; -import mage.remote.Session; -import mage.remote.SessionImpl; +//import mage.remote.Session; +//import mage.remote.SessionImpl; import mage.utils.MageVersion; import org.apache.log4j.Logger; +import org.mage.network.Client; +import org.mage.network.interfaces.MageClient; +import org.mage.network.model.MessageType; /** * @@ -60,7 +65,7 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { private static final Logger logger = Logger.getLogger(ConsoleFrame.class); - private static Session session; + private static Client client; private ConnectDialog connectDialog; private static final Preferences prefs = Preferences.userNodeForPackage(ConsoleFrame.class); private static final MageVersion version = new MageVersion(MageVersion.MAGE_VERSION_MAJOR, MageVersion.MAGE_VERSION_MINOR, MageVersion.MAGE_VERSION_PATCH, MageVersion.MAGE_VERSION_MINOR_PATCH, MageVersion.MAGE_VERSION_INFO); @@ -69,15 +74,14 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { /** * @return the session */ - public static Session getSession() { - return session; + public static Client getClient() { + return client; } public static Preferences getPreferences() { return prefs; } - @Override public MageVersion getVersion() { return version; } @@ -95,22 +99,22 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { initComponents(); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); - session = new SessionImpl(this); + client = new Client(); connectDialog = new ConnectDialog(); } catch (Exception ex) { logger.fatal("", ex); } - pingTaskExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - session.ping(); - } - }, 60, 60, TimeUnit.SECONDS); +// pingTaskExecutor.scheduleAtFixedRate(new Runnable() { +// @Override +// public void run() { +// session.ping(); +// } +// }, 60, 60, TimeUnit.SECONDS); } public boolean connect(Connection connection) { - if (session.connect(connection)) { + if (client.connect(connection.getUsername(), connection.getHost(), connection.getPort(), version, this)) { this.consolePanel1.start(); return true; } @@ -200,10 +204,10 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { }// //GEN-END:initComponents private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed - if (session.isConnected()) { + if (client.isConnected()) { if (JOptionPane.showConfirmDialog(this, "Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { this.consolePanel1.stop(); - session.disconnect(false); + client.disconnect(); } } else { connectDialog.showDialog(this); @@ -213,7 +217,7 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { private void btnSendMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendMessageActionPerformed String message = JOptionPane.showInputDialog(null, "Type message to send", "Broadcast message", JOptionPane.INFORMATION_MESSAGE); if (message != null) { - session.sendBroadcastMessage(message); + client.sendBroadcastMessage(message); } }//GEN-LAST:event_btnSendMessageActionPerformed @@ -262,7 +266,6 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { } } - @Override public void disconnected(boolean errorCall) { if (SwingUtilities.isEventDispatchThread()) { consolePanel1.stop(); @@ -281,7 +284,6 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { } } - @Override public void showMessage(final String message) { if (SwingUtilities.isEventDispatchThread()) { JOptionPane.showMessageDialog(this, message); @@ -296,7 +298,6 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { } } - @Override public void showError(final String message) { if (SwingUtilities.isEventDispatchThread()) { JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE); @@ -311,16 +312,16 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { } } - @Override - public void processCallback(ClientCallback callback) { - } +// @Override +// public void processCallback(ClientCallback callback) { +// } public void exitApp() { - if (session.isConnected()) { + if (client.isConnected()) { if (JOptionPane.showConfirmDialog(this, "You are currently connected. Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } - session.disconnect(false); + client.disconnect(); } else { if (JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?", "Confirm exit", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; @@ -329,4 +330,29 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { dispose(); System.exit(0); } + + @Override + public void inform(String message, MessageType type) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void receiveChatMessage(UUID chatId, String user, String message) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void receiveBroadcastMessage(String message) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void setServerState(ServerState state) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public ServerState getServerState() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } } 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 7f9c21e3d08..cfcfb052d2b 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 @@ -45,10 +45,11 @@ import static javax.swing.JTable.AUTO_RESIZE_OFF; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableRowSorter; -import mage.remote.Session; +//import mage.remote.Session; import mage.view.TableView; import mage.view.UserView; import org.apache.log4j.Logger; +import org.mage.network.Client; /** * @@ -93,8 +94,8 @@ public class ConsolePanel extends javax.swing.JPanel { public void start() { - updateUsersTask = new UpdateUsersTask(ConsoleFrame.getSession(), this); - updateTablesTask = new UpdateTablesTask(ConsoleFrame.getSession(), ConsoleFrame.getSession().getMainRoomId(), this); + updateUsersTask = new UpdateUsersTask(ConsoleFrame.getClient(), this); + updateTablesTask = new UpdateTablesTask(ConsoleFrame.getClient(), ConsoleFrame.getClient().getMainRoomId(), this); updateUsersTask.execute(); updateTablesTask.execute(); } @@ -268,17 +269,17 @@ public class ConsolePanel extends javax.swing.JPanel { private void btnDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDisconnectActionPerformed int row = this.tblUsers.convertRowIndexToModel(tblUsers.getSelectedRow()); - ConsoleFrame.getSession().disconnectUser((String)tableUserModel.getValueAt(row, 3)); + ConsoleFrame.getClient().disconnectUser((String)tableUserModel.getValueAt(row, 3)); }//GEN-LAST:event_btnDisconnectActionPerformed private void btnRemoveTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveTableActionPerformed int row = this.tblTables.convertRowIndexToModel(tblTables.getSelectedRow()); - ConsoleFrame.getSession().removeTable((UUID)tableTableModel.getValueAt(row, 7)); + ConsoleFrame.getClient().removeTable((UUID)tableTableModel.getValueAt(row, 7)); }//GEN-LAST:event_btnRemoveTableActionPerformed private void btnEndSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEndSessionActionPerformed int row = this.tblUsers.convertRowIndexToModel(tblUsers.getSelectedRow()); - ConsoleFrame.getSession().endUserSession((String) tableUserModel.getValueAt(row, 3)); + ConsoleFrame.getClient().endUserSession((String) tableUserModel.getValueAt(row, 3)); }//GEN-LAST:event_btnEndSessionActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables @@ -433,21 +434,21 @@ class TableTableModel extends AbstractTableModel { class UpdateUsersTask extends SwingWorker> { - private final Session session; + private final Client client; private final ConsolePanel panel; private List previousUsers; private static final Logger logger = Logger.getLogger(UpdateUsersTask.class); - UpdateUsersTask(Session session, ConsolePanel panel) { - this.session = session; + UpdateUsersTask(Client client, ConsolePanel panel) { + this.client = client; this.panel = panel; } @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - List users = session.getUsers(); + List users = client.getUsers(); if (previousUsers == null || checkUserListChanged(users)) { logger.debug("Need to update the user list"); @@ -503,14 +504,14 @@ class UpdateUsersTask extends SwingWorker> { class UpdateTablesTask extends SwingWorker> { - private final Session session; + private final Client client; private final UUID roomId; private final ConsolePanel panel; private static final Logger logger = Logger.getLogger(UpdateTablesTask.class); - UpdateTablesTask(Session session, UUID roomId, ConsolePanel panel) { - this.session = session; + UpdateTablesTask(Client client, UUID roomId, ConsolePanel panel) { + this.client = client; this.roomId = roomId; this.panel = panel; } @@ -518,7 +519,7 @@ class UpdateTablesTask extends SwingWorker> { @Override protected Void doInBackground() throws Exception { while (!isCancelled()) { - this.publish(session.getTables(roomId)); + this.publish(client.getTables(roomId)); Thread.sleep(3000); } return null; diff --git a/Mage.Server/pom.xml b/Mage.Server/pom.xml index 8ca875326bd..e9dff70ca1b 100644 --- a/Mage.Server/pom.xml +++ b/Mage.Server/pom.xml @@ -29,6 +29,11 @@ mage-common ${mage-version} + + ${project.groupId} + mage-network + ${project.version} + ${project.groupId} mage-sets diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index f5a5c945cf7..7acc476911e 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -94,93 +94,59 @@ public class ChatManager { } } - public void broadcast(UUID chatId, String userName, String message, MessageColor color) { - this.broadcast(chatId, userName, message, color, true); + public void broadcast(UUID chatId, User user, String message, MessageColor color) { + this.broadcast(chatId, user, message, color, true); } - public void broadcast(UUID chatId, String userName, String message, MessageColor color, boolean withTime) { - this.broadcast(chatId, userName, message, color, withTime, MessageType.TALK); + public void broadcast(UUID chatId, User user, String message, MessageColor color, boolean withTime) { + this.broadcast(chatId, user, message, color, withTime, MessageType.TALK); } - public void broadcast(UUID chatId, String userName, String message, MessageColor color, boolean withTime, MessageType messageType) { - this.broadcast(chatId, userName, message, color, withTime, messageType, null); + public void broadcast(UUID chatId, User user, String message, MessageColor color, boolean withTime, MessageType messageType) { + this.broadcast(chatId, user, message, color, withTime, messageType, null); } - public void broadcast(UUID chatId, String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { + public void broadcast(UUID chatId, User user, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { ChatSession chatSession = chatSessions.get(chatId); if (chatSession != null) { if (message.startsWith("\\") || message.startsWith("/")) { - User user = UserManager.getInstance().findUser(userName); - if (user != null && performUserCommand(user, message, chatId)) { +// User user = UserManager.getInstance().findUser(userName); + if (chatSession.performUserCommand(user, message, chatId)) { return; } } - chatSession.broadcast(userName, message, color, withTime, messageType, soundToPlay); + chatSession.broadcast(user.getName(), message, color, withTime, messageType, soundToPlay); } } - - private boolean performUserCommand(User user, String message, UUID chatId) { - String command = message.substring(1).trim().toUpperCase(Locale.ENGLISH); - if (command.equals("I") || command.equals("INFO")) { - user.setInfo(""); - chatSessions.get(chatId).broadcastInfoToUser(user,message); - return true; - } - if (command.startsWith("I ") || command.startsWith("INFO ")) { - user.setInfo(message.substring(command.startsWith("I ") ? 3 : 6)); - chatSessions.get(chatId).broadcastInfoToUser(user,message); - return true; - } - if (command.startsWith("W ") || command.startsWith("WHISPER ")) { - String rest = message.substring(command.startsWith("W ")? 3 : 9); - int first = rest.indexOf(" "); - if (first > 1) { - String userToName = rest.substring(0,first); - rest = rest.substring(first + 1).trim(); - User userTo = UserManager.getInstance().findUser(userToName); - if (userTo != null) { - if (!chatSessions.get(chatId).broadcastWhisperToUser(user, userTo, rest)) { - message += new StringBuilder("
User ").append(userToName).append(" not found").toString(); - chatSessions.get(chatId).broadcastInfoToUser(user,message); - } - } else { - message += new StringBuilder("
User ").append(userToName).append(" not found").toString(); - chatSessions.get(chatId).broadcastInfoToUser(user,message); - } - return true; - } - } - if (command.equals("L") || command.equals("LIST")) { - message += new StringBuilder("
List of commands:") - .append("
\\info [text] - set a info text to your player") - .append("
\\list - Show a list of commands") - .append("
\\whisper [player name] [text] - whisper to the player with the given name").toString(); - chatSessions.get(chatId).broadcastInfoToUser(user,message); - return true; - } - return false; + public void inform(UUID chatId, String message, MessageColor color, boolean withTime, MessageType messageType) { + inform(chatId, message, color, withTime, messageType, null); } - - - + + public void inform(UUID chatId, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { + ChatSession chatSession = chatSessions.get(chatId); + if (chatSession != null) { + chatSession.broadcast("", message, color, withTime, messageType, soundToPlay); + } + } + /** * * use mainly for announcing that a user connection was lost or that a user has reconnected * - * @param userId + * @param user * @param message * @param color */ - public void broadcast(UUID userId, String message, MessageColor color) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { + public void broadcast(User user, String message, MessageColor color) { +// User user = UserManager.getInstance().getUser(userId); +// if (user != null) { for (ChatSession chat: chatSessions.values()) { - if (chat.hasUser(userId)) { + if (chat.hasUser(user.getId())) { chat.broadcast(user.getName(), message, color); } } - } +// } } public void sendReconnectMessage(UUID userId) { diff --git a/Mage.Server/src/main/java/mage/server/ChatSession.java b/Mage.Server/src/main/java/mage/server/ChatSession.java index bfd7ccef0c2..b72b1d6e593 100644 --- a/Mage.Server/src/main/java/mage/server/ChatSession.java +++ b/Mage.Server/src/main/java/mage/server/ChatSession.java @@ -32,6 +32,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; +import java.util.Locale; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mage.interfaces.callback.ClientCallback; @@ -152,14 +153,13 @@ public class ChatSession { public void broadcast(String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { if (!message.isEmpty()) { boolean remove = false; - final String msg = message; final String time = (withTime ? timeFormatter.format(new Date()):""); - final String username = userName; - logger.trace("Broadcasting '" + msg + "' for " + chatId); + logger.trace("Broadcasting '" + message + "' for " + chatId); for (UUID userId: clients.keySet()) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - user.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color, messageType, soundToPlay))); + User chatUser = UserManager.getInstance().getUser(userId); + if (chatUser != null) { + Main.getInstance().sendChatMessage(chatUser.getSessionId(), chatId, new ChatMessage(userName, message, time, color, messageType, soundToPlay)); +// user.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color, messageType, soundToPlay))); } else { logger.error("User not found but connected to chat - userId: " + userId + " chatId: " + chatId); @@ -176,6 +176,49 @@ public class ChatSession { } } + public boolean performUserCommand(User user, String message, UUID chatId) { + String command = message.substring(1).trim().toUpperCase(Locale.ENGLISH); + if (command.equals("I") || command.equals("INFO")) { + user.setInfo(""); + broadcastInfoToUser(user,message); + return true; + } + if (command.startsWith("I ") || command.startsWith("INFO ")) { + user.setInfo(message.substring(command.startsWith("I ") ? 3 : 6)); + broadcastInfoToUser(user,message); + return true; + } + if (command.startsWith("W ") || command.startsWith("WHISPER ")) { + String rest = message.substring(command.startsWith("W ")? 3 : 9); + int first = rest.indexOf(" "); + if (first > 1) { + String userToName = rest.substring(0,first); + rest = rest.substring(first + 1).trim(); + User userTo = UserManager.getInstance().findUser(userToName); + if (userTo != null) { + if (!broadcastWhisperToUser(user, userTo, rest)) { + message += new StringBuilder("
User ").append(userToName).append(" not found").toString(); + broadcastInfoToUser(user,message); + } + } else { + message += new StringBuilder("
User ").append(userToName).append(" not found").toString(); + broadcastInfoToUser(user,message); + } + return true; + } + } + if (command.equals("L") || command.equals("LIST")) { + message += new StringBuilder("
List of commands:") + .append("
\\info [text] - set a info text to your player") + .append("
\\list - Show a list of commands") + .append("
\\whisper [player name] [text] - whisper to the player with the given name").toString(); + broadcastInfoToUser(user,message); + return true; + } + return false; + } + + /** * @return the chatId */ diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java deleted file mode 100644 index 7ddf83a1530..00000000000 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ /dev/null @@ -1,1127 +0,0 @@ -/* -* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without modification, are -* permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, this list of -* conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright notice, this list -* of conditions and the following disclaimer in the documentation and/or other materials -* provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR -* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* The views and conclusions contained in the software and documentation are those of the -* authors and should not be interpreted as representing official policies, either expressed -* or implied, of BetaSteward_at_googlemail.com. -*/ - -package mage.server; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ExecutorService; -import mage.MageException; -import mage.cards.decks.DeckCardLists; -import mage.cards.repository.CardInfo; -import mage.cards.repository.CardRepository; -import mage.cards.repository.ExpansionInfo; -import mage.cards.repository.ExpansionRepository; -import mage.constants.ManaType; -import mage.constants.PlayerAction; -import mage.constants.TableState; -import mage.game.GameException; -import mage.game.Table; -import mage.game.match.MatchOptions; -import mage.game.tournament.TournamentOptions; -import mage.interfaces.Action; -import mage.interfaces.ActionWithResult; -import mage.interfaces.MageServer; -import mage.interfaces.ServerState; -import mage.interfaces.callback.ClientCallback; -import mage.remote.MageVersionException; -import mage.server.draft.CubeFactory; -import mage.server.draft.DraftManager; -import mage.server.game.DeckValidatorFactory; -import mage.server.game.GameFactory; -import mage.server.game.GameManager; -import mage.server.game.GamesRoom; -import mage.server.game.GamesRoomManager; -import mage.server.game.PlayerFactory; -import mage.server.game.ReplayManager; -import mage.server.services.LogKeys; -import mage.server.services.impl.FeedbackServiceImpl; -import mage.server.services.impl.LogServiceImpl; -import mage.server.tournament.TournamentFactory; -import mage.server.tournament.TournamentManager; -import mage.server.util.ConfigSettings; -import mage.server.util.ServerMessagesUtil; -import mage.server.util.ThreadExecutor; -import mage.utils.ActionWithBooleanResult; -import mage.utils.ActionWithNullNegativeResult; -import mage.utils.ActionWithTableViewResult; -import mage.utils.CompressUtil; -import mage.utils.MageVersion; -import mage.view.ChatMessage; -import mage.view.ChatMessage.MessageColor; -import mage.view.DraftPickView; -import mage.view.GameView; -import mage.view.MatchView; -import mage.view.RoomUsersView; -import mage.view.TableView; -import mage.view.TournamentView; -import mage.view.UserDataView; -import mage.view.UserView; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.log4j.Logger; - -/** - * - * @author BetaSteward_at_googlemail.com, noxx - */ -public class MageServerImpl implements MageServer { - - private static final Logger logger = Logger.getLogger(MageServerImpl.class); - private static final ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); - - private final String password; - private final boolean testMode; - - public MageServerImpl(String password, boolean testMode) { - this.password = password; - this.testMode = testMode; - ServerMessagesUtil.getInstance().getMessages(); - } - - @Override - public boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException { - try { - if (version.compareTo(Main.getVersion()) != 0) { - logger.info("MageVersionException: userName=" + userName + ", version=" + version); - LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, userName, version.toString(), Main.getVersion().toString(), sessionId); - throw new MageVersionException(version, Main.getVersion()); - } - return SessionManager.getInstance().registerUser(sessionId, userName); - } catch (MageException ex) { - if (ex instanceof MageVersionException) { - throw (MageVersionException)ex; - } - handleException(ex); - } - return false; - } - - @Override - public boolean setUserData(final String userName, final String sessionId, final UserDataView userDataView) throws MageException { - return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() throws MageException { - return SessionManager.getInstance().setUserData(userName, sessionId, userDataView); - } - }); - } - - @Override - public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException { - try { - if (version.compareTo(Main.getVersion()) != 0) { - throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); - } - if (!password.equals(this.password)) { - throw new MageException("Wrong password"); - } - return SessionManager.getInstance().registerAdmin(sessionId); - } catch (Exception ex) { - handleException(ex); - } - return false; - } - - @Override - public TableView createTable(final String sessionId, final UUID roomId, final MatchOptions options) throws MageException { - return executeWithResult("createTable", sessionId, new ActionWithTableViewResult() { - @Override - public TableView execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options); - if (logger.isDebugEnabled()) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - logger.debug("TABLE created - tableId: " + table.getTableId() + " " + table.getTableName()); - logger.debug("- " + user.getName() + " userId: " + user.getId()); - logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); - } - } - LogServiceImpl.instance.log(LogKeys.KEY_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); - return table; - } - }); - } - - @Override - public TableView createTournamentTable(final String sessionId, final UUID roomId, final TournamentOptions options) throws MageException { - return executeWithResult("createTournamentTable", sessionId, new ActionWithTableViewResult() { - @Override - public TableView execute() throws MageException { - try { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - // check AI players max - String maxAiOpponents = ConfigSettings.getInstance().getMaxAiOpponents(); - if (maxAiOpponents != null) { - int max = Integer.parseInt(maxAiOpponents); - int aiPlayers = 0; - for (String playerType : options.getPlayerTypes()) { - if (!playerType.equals("Human")) { - aiPlayers++; - } - } - if (aiPlayers > max) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - user.showUserMessage("Create tournament", "It's only allowed to use a maximum of " + max + " AI players."); - } - throw new MageException("No message"); - } - } - TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(userId, options); - logger.debug("Tournament table " + table.getTableId() + " created"); - LogServiceImpl.instance.log(LogKeys.KEY_TOURNAMENT_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); - return table; - } catch (Exception ex) { - handleException(ex); - } - return null; - } - }); - } - - @Override - public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - execute("removeTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } - }); - } - - @Override - public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException { - return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - logger.debug(name + " joins tableId: " + tableId); - if (userId == null) { - logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); - return false; - } - boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); - return ret; - } - }); - } - - @Override - public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException { - return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - if (logger.isTraceEnabled()) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - logger.trace("join tourn. tableId: " + tableId + " " + name); - } - } - if (userId == null) { - logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); - return false; - } - boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); - return ret; - } - }); - } - - @Override - public boolean submitDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { - return executeWithResult("submitDeck", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList); - logger.debug("Session " + sessionId + " submitted deck"); - return ret; - } - }); - } - - @Override - public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { - execute("updateDeck", sessionId, new Action() { - @Override - public void execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().updateDeck(userId, tableId, deckList); - logger.trace("Session " + sessionId + " updated deck"); - } - }); - } - - @Override - //FIXME: why no sessionId here??? - public List getTables(UUID roomId) throws MageException { - try { - GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); - if (room != null) { - return room.getTables(); - } else { - return null; - } - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - //FIXME: why no sessionId here??? - public List getFinishedMatches(UUID roomId) throws MageException { - try { - GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); - if (room != null) { - return room.getFinished(); - } else { - return null; - } - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - public List getRoomUsers(UUID roomId) throws MageException { - try { - GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); - if (room != null) { - return room.getRoomUsersInfo(); - } else { - return null; - } - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - //FIXME: why no sessionId here??? - public TableView getTable(UUID roomId, UUID tableId) throws MageException { - try { - GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); - if (room != null) { - return room.getTable(tableId); - } else { - return null; - } - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - public boolean ping(String sessionId, String pingInfo) { - return SessionManager.getInstance().extendUserSession(sessionId, pingInfo); - } - -// @Override -// public void deregisterClient(final String sessionId) throws MageException { -// execute("deregisterClient", sessionId, new Action() { -// @Override -// public void execute() { -// SessionManager.getInstance().disconnect(sessionId, true); -// logger.debug("Client deregistered ..."); -// } -// }); -// } - - @Override - public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { - return false; - } - execute("startMatch", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startMatch(userId, roomId, tableId); - } - }); - return true; - } - -// @Override -// public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException { -// execute("startChallenge", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId); -// } -// }); -// } - - @Override - public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { - return false; - } - execute("startTournament", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startTournament(userId, roomId, tableId); - } - }); - return true; - } - - @Override - //FIXME: why no sessionId here??? - public TournamentView getTournament(UUID tournamentId) throws MageException { - try { - return TournamentManager.getInstance().getTournamentView(tournamentId); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - //FIXME: why no sessionId here??? - public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { - try { - callExecutor.execute( - new Runnable() { - @Override - public void run() { - ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); - } - } - ); - } - catch (Exception ex) { - handleException(ex); - } - } - - @Override - public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException { - execute("joinChat", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ChatManager.getInstance().joinChat(chatId, userId); - } - }); - } - - @Override - public void leaveChat(final UUID chatId, final String sessionId) throws MageException { - execute("leaveChat", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ChatManager.getInstance().leaveChat(chatId, userId); - } - }); - } - - @Override - //FIXME: why no sessionId here??? - public UUID getMainRoomId() throws MageException { - try { - return GamesRoomManager.getInstance().getMainRoomId(); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - //FIXME: why no sessionId here??? - public UUID getRoomChatId(UUID roomId) throws MageException { - try { - return GamesRoomManager.getInstance().getRoom(roomId).getChatId(); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - public boolean isTableOwner(final String sessionId, UUID roomId, final UUID tableId) throws MageException { - return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - return TableManager.getInstance().isTableOwner(tableId, userId); - } - }); - } - - @Override - public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException { - execute("swapSeats", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); - } - }); - } - - @Override - public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - TableState tableState = TableManager.getInstance().getController(tableId).getTableState(); - if (!tableState.equals(TableState.WAITING) && !tableState.equals(TableState.READY_TO_START)) { - // table was already started, so player can't leave anymore now - return false; - } - execute("leaveTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); - } - }); - return true; - } - - @Override - //FIXME: why no sessionId here??? - public UUID getTableChatId(UUID tableId) throws MageException { - try { - return TableManager.getInstance().getChatId(tableId); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - public void joinGame(final UUID gameId, final String sessionId) throws MageException { - execute("joinGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().joinGame(gameId, userId); - } - }); - } - - @Override - public void joinDraft(final UUID draftId, final String sessionId) throws MageException { - execute("joinDraft", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - DraftManager.getInstance().joinDraft(draftId, userId); - } - }); - } - - @Override - public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { - execute("joinTournament", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TournamentManager.getInstance().joinTournament(tournamentId, userId); - } - }); - } - - @Override - //FIXME: why no sessionId here??? - public UUID getGameChatId(UUID gameId) throws MageException { - try { - return GameManager.getInstance().getChatId(gameId); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - //FIXME: why no sessionId here??? - public UUID getTournamentChatId(UUID tournamentId) throws MageException { - try { - return TournamentManager.getInstance().getChatId(tournamentId); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException { - execute("sendPlayerUUID", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { -// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); - user.sendPlayerUUID(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - }); - } - - @Override - public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException { - execute("sendPlayerString", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerString(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - }); - } - - @Override - public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException { - execute("sendPlayerManaType", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerManaType(gameId, playerId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - }); - } - - @Override - public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException { - execute("sendPlayerBoolean", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerBoolean(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - }); - } - - @Override - public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException { - execute("sendPlayerInteger", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerInteger(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - }); - } - - @Override - public DraftPickView sendCardPick(final UUID draftId, final String sessionId, final UUID cardPick, final Set hiddenCards) throws MageException { - return executeWithResult("sendCardPick", sessionId, new ActionWithNullNegativeResult() { - @Override - public DraftPickView execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - return DraftManager.getInstance().sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); - } - return null; - } - }); - } - - @Override - public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { - execute("sendCardMark", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); - } - } - }); - } - - @Override - public void quitMatch(final UUID gameId, final String sessionId) throws MageException { - execute("quitMatch", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - GameManager.getInstance().quitMatch(gameId, session.getUserId()); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " gameId:" +gameId); - } - } - }); - } - - @Override - public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { - execute("quitTournament", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - }else{ - logger.error("Session not found sessionId: "+ sessionId + " tournamentId:" + tournamentId); - } - } - }); - } - - @Override - public void quitDraft(final UUID draftId, final String sessionId) throws MageException { - execute("quitDraft", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); - return; - } - UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); - Table table = TableManager.getInstance().getTable(tableId); - if (table.isTournament()) { - UUID tournamentId = table.getTournament().getId(); - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - } - } - }); - } - - @Override - public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException { - execute("sendPlayerAction", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: "+ sessionId + " gameId:" + gameId); - return; - } - GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); - } - }); - } - - @Override - public boolean watchTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - return GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId); - } - }); - } - - @Override - public boolean watchTournamentTable(final String sessionId, final UUID tableId) throws MageException { - return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - return TableManager.getInstance().watchTable(userId, tableId); - } - }); - } - - @Override - public void watchGame(final UUID gameId, final String sessionId) throws MageException { - execute("watchGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().watchGame(gameId, userId); - } - }); - } - - @Override - public void stopWatching(final UUID gameId, final String sessionId) throws MageException { - execute("stopWatching", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - GameManager.getInstance().stopWatching(gameId, userId); - user.removeGameWatchInfo(gameId); - } - - } - }); - } - - @Override - public void replayGame(final UUID gameId, final String sessionId) throws MageException { - execute("replayGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().replayGame(gameId, userId); - } - }); - } - - @Override - public void startReplay(final UUID gameId, final String sessionId) throws MageException { - execute("startReplay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().startReplay(gameId, userId); - } - }); - } - - @Override - public void stopReplay(final UUID gameId, final String sessionId) throws MageException { - execute("stopReplay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().stopReplay(gameId, userId); - } - }); - } - - @Override - public void nextPlay(final UUID gameId, final String sessionId) throws MageException { - execute("nextPlay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().nextPlay(gameId, userId); - } - }); - } - - @Override - public void previousPlay(final UUID gameId, final String sessionId) throws MageException { - execute("previousPlay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().previousPlay(gameId, userId); - } - }); - } - - @Override - public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { - execute("skipForward", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().skipForward(gameId, userId, moves); - } - }); - } - - @Override - //TODO: check how often it is used - public ServerState getServerState() throws MageException { - try { - return new ServerState( - GameFactory.getInstance().getGameTypes(), - TournamentFactory.getInstance().getTournamentTypes(), - PlayerFactory.getInstance().getPlayerTypes().toArray(new String[PlayerFactory.getInstance().getPlayerTypes().size()]), - DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[DeckValidatorFactory.getInstance().getDeckTypes().size()]), - CubeFactory.getInstance().getDraftCubes().toArray(new String[CubeFactory.getInstance().getDraftCubes().size()]), - testMode, - Main.getVersion(), - CardRepository.instance.getContentVersionConstant(), - ExpansionRepository.instance.getContentVersionConstant() - ); - } - catch (Exception ex) { - handleException(ex); - } - return null; - } - - @Override - public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { - execute("cheat", sessionId, new Action() { - @Override - public void execute() { - if (testMode) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().cheat(gameId, userId, playerId, deckList); - } - } - }); - } - - @Override - public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException { - return executeWithResult("cheatOne", sessionId, new ActionWithBooleanResult() { - @Override - public Boolean execute() { - if (testMode) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - return GameManager.getInstance().cheat(gameId, userId, playerId, cardName); - } - return false; - } - }); - } - - public void handleException(Exception ex) throws MageException { - if (!ex.getMessage().equals("No message")) { - logger.fatal("", ex); - throw new MageException("Server error: " + ex.getMessage()); - } - } - - @Override - public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) throws MageException { - return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { - @Override - public GameView execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - return GameManager.getInstance().getGameView(gameId, userId, playerId); - } - }); - } - - /** - * Get user data for admin console - * - * @param sessionId - * @return - * @throws MageException - */ - @Override - public List getUsers(String sessionId) throws MageException { - return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult>() { - @Override - public List execute() throws MageException { - List users = new ArrayList<>(); - for (User user : UserManager.getInstance().getUsers()) { - - users.add(new UserView(user.getName(), user.getHost(), user.getSessionId(), user.getConnectionTime(), user.getGameInfo())); - } - return users; - } - }, true); - } - - @Override - public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { - execute("disconnectUser", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().disconnectUser(sessionId, userSessionId); - } - }); - } - - @Override - public void endUserSession(final String sessionId, final String userSessionId) throws MageException { - execute("endUserSession", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().endUserSession(sessionId, userSessionId); - } - }); - } - - /** - * Admin console - Remove table - * - * @param sessionId - * @param tableId - * @throws MageException - */ - @Override - public void removeTable(final String sessionId, final UUID tableId) throws MageException { - execute("removeTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } - }); - } - - @Override - public Object getServerMessagesCompressed(String sessionId) throws MageException { - return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { - @Override - public Object execute() throws MageException { - return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); - } - }); - } - - @Override - 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, new Action() { - @Override - public void execute() { - String host = SessionManager.getInstance().getSession(sessionId).getHost(); - FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); - LogServiceImpl.instance.log(LogKeys.KEY_FEEDBACK_ADDED, sessionId, username, host); - } - }); - } - } - - @Override - public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { - if (message != null) { - execute("sendBroadcastMessage", sessionId, new Action() { - @Override - public void execute() { - for (User user : UserManager.getInstance().getUsers()) { - if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { - user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); - } else { - user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); - } - } - } - }, true); - } - } - - protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { - if (checkAdminRights) { - if (!SessionManager.getInstance().isAdmin(sessionId)) { - LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); - return; - } - } - execute(actionName, sessionId, action); - } - - protected void execute(final String actionName, final String sessionId, final Action action) throws MageException { - if (SessionManager.getInstance().isValidSession(sessionId)) { - try { - callExecutor.execute( - new Runnable() { - @Override - public void run() { - if (SessionManager.getInstance().isValidSession(sessionId)) { - try { - action.execute(); - } catch (MageException me) { - throw new RuntimeException(me); - } - } else { - LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId); - } - } - } - ); - } - catch (Exception ex) { - handleException(ex); - } - } else { - LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); - } - } - - protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action, boolean checkAdminRights) throws MageException { - if (checkAdminRights) { - if (!SessionManager.getInstance().isAdmin(sessionId)) { - LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); - return action.negativeResult(); - } - } - return executeWithResult(actionName, sessionId, action); - } - - //TODO: also run in threads with future task - protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action) throws MageException { - if (SessionManager.getInstance().isValidSession(sessionId)) { - try { - return action.execute(); - } catch (Exception ex) { - handleException(ex); - } - } else { - LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); - } - return action.negativeResult(); - } - - @Override - public List getMissingExpansionData(List codes) { - List result = new ArrayList<>(); - for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) { - if (!codes.contains(expansionInfo.getCode())) { - result.add(expansionInfo); - } - } - return result; - } - - @Override - public List getMissingCardsData(List classNames) { - return CardRepository.instance.getMissingCards(classNames); - } -} diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index d9f8aec6c2b..8268674c41f 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -28,51 +28,88 @@ package mage.server; +import io.netty.channel.ChannelId; +import java.io.File; +import java.io.FilenameFilter; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import mage.MageException; +import mage.cards.decks.DeckCardLists; +import mage.cards.repository.CardInfo; +import mage.cards.repository.CardRepository; import mage.cards.repository.CardScanner; +import mage.cards.repository.ExpansionInfo; +import mage.cards.repository.ExpansionRepository; +import mage.constants.ManaType; +import mage.constants.PlayerAction; +import mage.constants.TableState; +import mage.game.GameException; +import mage.game.Table; +import mage.game.match.MatchOptions; import mage.game.match.MatchType; +import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentType; -import mage.interfaces.MageServer; -import mage.remote.Connection; +import mage.interfaces.Action; +import mage.interfaces.ActionWithResult; +//import mage.interfaces.MageServer; +import org.mage.network.interfaces.MageServer; +import mage.interfaces.ServerState; +import mage.interfaces.callback.ClientCallback; +import mage.remote.MageVersionException; import mage.server.draft.CubeFactory; +import mage.server.draft.DraftManager; import mage.server.game.DeckValidatorFactory; import mage.server.game.GameFactory; +import mage.server.game.GameManager; +import mage.server.game.GamesRoom; +import mage.server.game.GamesRoomManager; import mage.server.game.PlayerFactory; +import mage.server.game.ReplayManager; +import mage.server.services.LogKeys; +import mage.server.services.impl.FeedbackServiceImpl; +import mage.server.services.impl.LogServiceImpl; import mage.server.tournament.TournamentFactory; +import mage.server.tournament.TournamentManager; import mage.server.util.ConfigSettings; import mage.server.util.PluginClassLoader; import mage.server.util.ServerMessagesUtil; import mage.server.util.SystemUtil; +import mage.server.util.ThreadExecutor; import mage.server.util.config.GamePlugin; import mage.server.util.config.Plugin; +import mage.utils.ActionWithBooleanResult; +import mage.utils.ActionWithNullNegativeResult; +import mage.utils.ActionWithTableViewResult; +import mage.utils.CompressUtil; import mage.utils.MageVersion; +import mage.view.ChatMessage; +import mage.view.ChatMessage.MessageColor; +import mage.view.DraftPickView; +import mage.view.GameView; +import mage.view.MatchView; +import mage.view.RoomUsersView; +import mage.view.TableView; +import mage.view.TournamentView; +import mage.view.UserDataView; +import mage.view.UserView; +import org.apache.commons.lang3.StringEscapeUtils; import org.apache.log4j.Logger; -import org.jboss.remoting.*; -import org.jboss.remoting.callback.InvokerCallbackHandler; -import org.jboss.remoting.callback.ServerInvokerCallbackHandler; -import org.jboss.remoting.transport.Connector; -import org.jboss.remoting.transport.socket.SocketWrapper; -import org.jboss.remoting.transporter.TransporterClient; -import org.jboss.remoting.transporter.TransporterServer; -import org.w3c.dom.Element; - -import javax.management.MBeanServer; -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.net.InetAddress; -import java.net.MalformedURLException; -import java.util.HashMap; -import java.util.Map; -import org.jboss.remoting.transport.bisocket.BisocketServerInvoker; - +import org.mage.network.Server; +import org.mage.network.model.MessageType; /** * - * @author BetaSteward_at_googlemail.com + * @author BetaSteward_at_googlemail.com, noxx */ -public class Main { +public class Main implements MageServer { - private static final Logger logger = Logger.getLogger(Main.class); + private static final Logger logger = Logger.getLogger(MageServer.class); + private static final ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); private static final MageVersion version = new MageVersion(MageVersion.MAGE_VERSION_MAJOR, MageVersion.MAGE_VERSION_MINOR, MageVersion.MAGE_VERSION_PATCH, MageVersion.MAGE_VERSION_MINOR_PATCH, MageVersion.MAGE_VERSION_INFO); private static final String testModeArg = "-testMode="; @@ -80,21 +117,42 @@ public class Main { private static final String adminPasswordArg = "-adminPassword="; private static final String pluginFolder = "plugins"; + public static final PluginClassLoader classLoader = new PluginClassLoader(); - public static PluginClassLoader classLoader = new PluginClassLoader(); - public static TransporterServer server; - protected static boolean testMode; - protected static boolean fastDbMode; + private final ServerState state; + private final String password; + private final boolean testMode; - /** - * @param args the command line arguments - */ + private static Main instance; + private static Server server; + + public Main(String password, boolean testMode) { + this.password = password; + this.testMode = testMode; + ServerMessagesUtil.getInstance().getMessages(); + state = new ServerState( + GameFactory.getInstance().getGameTypes(), + TournamentFactory.getInstance().getTournamentTypes(), + PlayerFactory.getInstance().getPlayerTypes().toArray(new String[PlayerFactory.getInstance().getPlayerTypes().size()]), + DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[DeckValidatorFactory.getInstance().getDeckTypes().size()]), + CubeFactory.getInstance().getDraftCubes().toArray(new String[CubeFactory.getInstance().getDraftCubes().size()]), + testMode, + Main.getVersion(), + CardRepository.instance.getContentVersionConstant(), + ExpansionRepository.instance.getContentVersionConstant(), + GamesRoomManager.getInstance().getMainRoomId() + ); + } + public static void main(String[] args) { System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); logger.info("Starting MAGE server version " + version); logger.info("Logging level: " + logger.getEffectiveLevel()); String adminPassword = ""; + boolean testMode = false; + boolean fastDbMode = false; + for (String arg: args) { if (arg.startsWith(testModeArg)) { testMode = Boolean.valueOf(arg.replace(testModeArg, "")); @@ -147,160 +205,1088 @@ public class Main { logger.info("Config - num accp.threads: " + config.getNumAcceptThreads()); logger.info("Config - second.bind port: " + config.getSecondaryBindPort()); - Connection connection = new Connection("&maxPoolSize=" + config.getMaxPoolSize()); - connection.setHost(config.getServerAddress()); - connection.setPort(config.getPort()); +// Connection connection = new Connection("&maxPoolSize=" + config.getMaxPoolSize()); +// connection.setHost(config.getServerAddress()); +// connection.setPort(config.getPort()); try { + instance = new Main(adminPassword, testMode); + server = new Server(instance); + server.start(config.getPort()); // Parameter: serializationtype => jboss - InvokerLocator serverLocator = new InvokerLocator(connection.getURI()); - if (!isAlreadyRunning(serverLocator)) { - server = new MageTransporterServer(serverLocator, new MageServerImpl(adminPassword, testMode), MageServer.class.getName(), new MageServerInvocationHandler()); - server.start(); - logger.info("Started MAGE server - listening on " + connection.toString()); - - if (testMode) { - logger.info("MAGE server running in test mode"); - } - initStatistics(); - } - else { - logger.fatal("Unable to start MAGE server - another server is already started"); - } - } catch (IOException ex) { - logger.fatal("Failed to start server - " + connection.toString(), ex); +// InvokerLocator serverLocator = new InvokerLocator(connection.getURI()); +// if (!isAlreadyRunning(serverLocator)) { +// server = new MageTransporterServer(serverLocator, new MageServerImpl(adminPassword, testMode), MageServer.class.getName(), new MageServerInvocationHandler()); +// server.start(); +// logger.info("Started MAGE server - listening on " + connection.toString()); +// +// if (testMode) { +// logger.info("MAGE server running in test mode"); +// } +// initStatistics(); +// } +// else { +// logger.fatal("Unable to start MAGE server - another server is already started"); +// } +// } catch (IOException ex) { +// logger.fatal("Failed to start server - " + connection.toString(), ex); } catch (Exception ex) { - logger.fatal("Failed to start server - " + connection.toString(), ex); + logger.fatal("Failed to start server - " + config.getServerAddress(), ex); } } - static void initStatistics() { - ServerMessagesUtil.getInstance().setStartDate(System.currentTimeMillis()); + public static Main getInstance() { + return instance; } - - static boolean isAlreadyRunning(InvokerLocator serverLocator) { - Map metadata = new HashMap<>(); - metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); - metadata.put("generalizeSocketException", "true"); + + @Override + public boolean registerClient(String userName, String sessionId, MageVersion version) { try { - MageServer testServer = (MageServer) TransporterClient.createTransporterClient(serverLocator.getLocatorURI(), MageServer.class, metadata); - if (testServer != null) { - testServer.getServerState(); - return true; + if (version.compareTo(Main.getVersion()) != 0) { + logger.info("MageVersionException: userName=" + userName + ", version=" + version); + LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, userName, version.toString(), Main.getVersion().toString(), sessionId); + server.informClient(sessionId, "Wrong version", MessageType.ERROR); + return false; +// throw new MageVersionException(version, Main.getVersion()); } - } catch (Throwable t) { - // assume server is not running + return SessionManager.getInstance().registerUser(sessionId, userName); + } catch (MageException ex) { +// if (ex instanceof MageVersionException) { +// throw (MageVersionException)ex; +// } + handleException(sessionId, ex); } return false; } - static class ClientConnectionListener implements ConnectionListener { - @Override - public void handleConnectionException(Throwable throwable, Client client) { - Session session = SessionManager.getInstance().getSession(client.getSessionId()); - if (session != null) { - StringBuilder sessionInfo = new StringBuilder(); - User user = UserManager.getInstance().getUser(session.getUserId()); - if (user != null) { - sessionInfo.append(user.getName()); - } else { - sessionInfo.append("[user missing] "); - } - sessionInfo.append(" at ").append(session.getHost()).append(" sessionId: ").append(session.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 - //SessionManager.getInstance().disconnect(client.getSessionId(), DisconnectReason.Disconnected); - SessionManager.getInstance().disconnect(client.getSessionId(), DisconnectReason.LostConnection); - logger.info("CLIENT DISCONNECTED - " + sessionInfo); - logger.debug("Stack Trace", throwable); - } else { - SessionManager.getInstance().disconnect(client.getSessionId(), DisconnectReason.LostConnection); - logger.info("LOST CONNECTION - " + sessionInfo); - if (logger.isDebugEnabled()) { - if (throwable == null) { - logger.debug("- cause: Lease expired"); - } else { - logger.debug(" - cause: " + Session.getBasicCause(throwable).toString()); - } - } - } +// @Override +// public boolean setUserData(final String userName, final String sessionId, final UserDataView userDataView) throws MageException { +// return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() throws MageException { +// return SessionManager.getInstance().setUserData(userName, sessionId, userDataView); +// } +// }); +// } +// +// @Override +// public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException { +// try { +// if (version.compareTo(Main.getVersion()) != 0) { +// throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); +// } +// if (!password.equals(this.password)) { +// throw new MageException("Wrong password"); +// } +// return SessionManager.getInstance().registerAdmin(sessionId); +// } catch (Exception ex) { +// handleException(ex); +// } +// return false; +// } +// +// @Override +// public TableView createTable(final String sessionId, final UUID roomId, final MatchOptions options) throws MageException { +// return executeWithResult("createTable", sessionId, new ActionWithTableViewResult() { +// @Override +// public TableView execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options); +// if (logger.isDebugEnabled()) { +// User user = UserManager.getInstance().getUser(userId); +// if (user != null) { +// logger.debug("TABLE created - tableId: " + table.getTableId() + " " + table.getTableName()); +// logger.debug("- " + user.getName() + " userId: " + user.getId()); +// logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); +// } +// } +// LogServiceImpl.instance.log(LogKeys.KEY_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); +// return table; +// } +// }); +// } +// +// @Override +// public TableView createTournamentTable(final String sessionId, final UUID roomId, final TournamentOptions options) throws MageException { +// return executeWithResult("createTournamentTable", sessionId, new ActionWithTableViewResult() { +// @Override +// public TableView execute() throws MageException { +// try { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// // check AI players max +// String maxAiOpponents = ConfigSettings.getInstance().getMaxAiOpponents(); +// if (maxAiOpponents != null) { +// int max = Integer.parseInt(maxAiOpponents); +// int aiPlayers = 0; +// for (String playerType : options.getPlayerTypes()) { +// if (!playerType.equals("Human")) { +// aiPlayers++; +// } +// } +// if (aiPlayers > max) { +// User user = UserManager.getInstance().getUser(userId); +// if (user != null) { +// user.showUserMessage("Create tournament", "It's only allowed to use a maximum of " + max + " AI players."); +// } +// throw new MageException("No message"); +// } +// } +// TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(userId, options); +// logger.debug("Tournament table " + table.getTableId() + " created"); +// LogServiceImpl.instance.log(LogKeys.KEY_TOURNAMENT_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); +// return table; +// } catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// }); +// } +// +// @Override +// public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { +// execute("removeTable", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().removeTable(userId, tableId); +// } +// }); +// } +// +// @Override +// public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException { +// return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// logger.debug(name + " joins tableId: " + tableId); +// if (userId == null) { +// logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); +// return false; +// } +// boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); +// return ret; +// } +// }); +// } +// +// @Override +// public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) throws MageException, GameException { +// return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// if (logger.isTraceEnabled()) { +// User user = UserManager.getInstance().getUser(userId); +// if (user != null) { +// logger.trace("join tourn. tableId: " + tableId + " " + name); +// } +// } +// if (userId == null) { +// logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); +// return false; +// } +// boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); +// return ret; +// } +// }); +// } +// +// @Override +// public boolean submitDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { +// return executeWithResult("submitDeck", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList); +// logger.debug("Session " + sessionId + " submitted deck"); +// return ret; +// } +// }); +// } +// +// @Override +// public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { +// execute("updateDeck", sessionId, new Action() { +// @Override +// public void execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().updateDeck(userId, tableId, deckList); +// logger.trace("Session " + sessionId + " updated deck"); +// } +// }); +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public List getTables(UUID roomId) throws MageException { +// try { +// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); +// if (room != null) { +// return room.getTables(); +// } else { +// return null; +// } +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public List getFinishedMatches(UUID roomId) throws MageException { +// try { +// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); +// if (room != null) { +// return room.getFinished(); +// } else { +// return null; +// } +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// public List getRoomUsers(UUID roomId) throws MageException { +// try { +// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); +// if (room != null) { +// return room.getRoomUsersInfo(); +// } else { +// return null; +// } +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public TableView getTable(UUID roomId, UUID tableId) throws MageException { +// try { +// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); +// if (room != null) { +// return room.getTable(tableId); +// } else { +// return null; +// } +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// public boolean ping(String sessionId, String pingInfo) { +// return SessionManager.getInstance().extendUserSession(sessionId, pingInfo); +// } +// +// @Override +// public void deregisterClient(final String sessionId) throws MageException { +// execute("deregisterClient", sessionId, new Action() { +// @Override +// public void execute() { +// SessionManager.getInstance().disconnect(sessionId, true); +// logger.debug("Client deregistered ..."); +// } +// }); +// } +// +// @Override +// public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { +// if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { +// return false; +// } +// execute("startMatch", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().startMatch(userId, roomId, tableId); +// } +// }); +// return true; +// } +// +// @Override +// public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException { +// execute("startChallenge", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId); +// } +// }); +// } +// +// @Override +// public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { +// if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { +// return false; +// } +// execute("startTournament", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().startTournament(userId, roomId, tableId); +// } +// }); +// return true; +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public TournamentView getTournament(UUID tournamentId) throws MageException { +// try { +// return TournamentManager.getInstance().getTournamentView(tournamentId); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { +// try { +// callExecutor.execute( +// new Runnable() { +// @Override +// public void run() { +// ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); +// } +// } +// ); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// } + + @Override + public void receiveChatMessage(final UUID chatId, final String sessionId, final String message) { + execute("receiveChatMessage", sessionId, new Action() { + @Override + public void execute() { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) + ChatManager.getInstance().broadcast(chatId, user, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); } + }); +// } +// catch (Exception ex) { +// handleException(sessionId, ex); +// } + } + + public void sendChatMessage(String sessionId, UUID chatId, ChatMessage message) { + server.sendChatMessage(sessionId, chatId, message); + } + + @Override + public void joinChat(final UUID chatId, final String sessionId) { +// execute("joinChat", sessionId, new Action() { +// @Override +// public void execute() { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) + ChatManager.getInstance().joinChat(chatId, session.getUserId()); +// } +// }); + } + + @Override + public void leaveChat(final UUID chatId, final String sessionId) { +// execute("leaveChat", sessionId, new Action() { +// @Override +// public void execute() { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) + ChatManager.getInstance().leaveChat(chatId, session.getUserId()); +// } +// }); + } + +// @Override +// //FIXME: why no sessionId here??? +// public UUID getMainRoomId() throws MageException { +// try { +// return GamesRoomManager.getInstance().getMainRoomId(); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// + @Override +// //FIXME: why no sessionId here??? + public UUID getRoomChatId(UUID roomId) { +// try { + return GamesRoomManager.getInstance().getRoom(roomId).getChatId(); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; + } +// +// @Override +// public boolean isTableOwner(final String sessionId, UUID roomId, final UUID tableId) throws MageException { +// return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return TableManager.getInstance().isTableOwner(tableId, userId); +// } +// }); +// } +// +// @Override +// public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException { +// execute("swapSeats", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); +// } +// }); +// } +// +// @Override +// public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { +// TableState tableState = TableManager.getInstance().getController(tableId).getTableState(); +// if (!tableState.equals(TableState.WAITING) && !tableState.equals(TableState.READY_TO_START)) { +// // table was already started, so player can't leave anymore now +// return false; +// } +// execute("leaveTable", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); +// } +// }); +// return true; +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public UUID getTableChatId(UUID tableId) throws MageException { +// try { +// return TableManager.getInstance().getChatId(tableId); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// public void joinGame(final UUID gameId, final String sessionId) throws MageException { +// execute("joinGame", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// GameManager.getInstance().joinGame(gameId, userId); +// } +// }); +// } +// +// @Override +// public void joinDraft(final UUID draftId, final String sessionId) throws MageException { +// execute("joinDraft", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// DraftManager.getInstance().joinDraft(draftId, userId); +// } +// }); +// } +// +// @Override +// public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { +// execute("joinTournament", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TournamentManager.getInstance().joinTournament(tournamentId, userId); +// } +// }); +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public UUID getGameChatId(UUID gameId) throws MageException { +// try { +// return GameManager.getInstance().getChatId(gameId); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// //FIXME: why no sessionId here??? +// public UUID getTournamentChatId(UUID tournamentId) throws MageException { +// try { +// return TournamentManager.getInstance().getChatId(tournamentId); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException { +// execute("sendPlayerUUID", sessionId, new Action() { +// @Override +// public void execute() { +// User user = SessionManager.getInstance().getUser(sessionId); +// if (user != null) { +//// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); +// user.sendPlayerUUID(gameId, data); +// } else { +// logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); +// } +// } +// }); +// } +// +// @Override +// public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException { +// execute("sendPlayerString", sessionId, new Action() { +// @Override +// public void execute() { +// User user = SessionManager.getInstance().getUser(sessionId); +// if (user != null) { +// user.sendPlayerString(gameId, data); +// } else { +// logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); +// } +// } +// }); +// } +// +// @Override +// public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException { +// execute("sendPlayerManaType", sessionId, new Action() { +// @Override +// public void execute() { +// User user = SessionManager.getInstance().getUser(sessionId); +// if (user != null) { +// user.sendPlayerManaType(gameId, playerId, data); +// } else { +// logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); +// } +// } +// }); +// } +// +// @Override +// public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException { +// execute("sendPlayerBoolean", sessionId, new Action() { +// @Override +// public void execute() { +// User user = SessionManager.getInstance().getUser(sessionId); +// if (user != null) { +// user.sendPlayerBoolean(gameId, data); +// } else { +// logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); +// } +// } +// }); +// } +// +// @Override +// public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException { +// execute("sendPlayerInteger", sessionId, new Action() { +// @Override +// public void execute() { +// User user = SessionManager.getInstance().getUser(sessionId); +// if (user != null) { +// user.sendPlayerInteger(gameId, data); +// } else { +// logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); +// } +// } +// }); +// } +// +// @Override +// public DraftPickView sendCardPick(final UUID draftId, final String sessionId, final UUID cardPick, final Set hiddenCards) throws MageException { +// return executeWithResult("sendCardPick", sessionId, new ActionWithNullNegativeResult() { +// @Override +// public DraftPickView execute() { +// Session session = SessionManager.getInstance().getSession(sessionId); +// if (session != null) { +// return DraftManager.getInstance().sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); +// } else{ +// logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); +// } +// return null; +// } +// }); +// } +// +// @Override +// public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { +// execute("sendCardMark", sessionId, new Action() { +// @Override +// public void execute() { +// Session session = SessionManager.getInstance().getSession(sessionId); +// if (session != null) { +// DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); +// } else{ +// logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); +// } +// } +// }); +// } +// +// @Override +// public void quitMatch(final UUID gameId, final String sessionId) throws MageException { +// execute("quitMatch", sessionId, new Action() { +// @Override +// public void execute() { +// Session session = SessionManager.getInstance().getSession(sessionId); +// if (session != null) { +// GameManager.getInstance().quitMatch(gameId, session.getUserId()); +// } else{ +// logger.error("Session not found sessionId: "+ sessionId + " gameId:" +gameId); +// } +// } +// }); +// } +// +// @Override +// public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { +// execute("quitTournament", sessionId, new Action() { +// @Override +// public void execute() { +// Session session = SessionManager.getInstance().getSession(sessionId); +// if (session != null) { +// TournamentManager.getInstance().quit(tournamentId, session.getUserId()); +// }else{ +// logger.error("Session not found sessionId: "+ sessionId + " tournamentId:" + tournamentId); +// } +// } +// }); +// } +// +// @Override +// public void quitDraft(final UUID draftId, final String sessionId) throws MageException { +// execute("quitDraft", sessionId, new Action() { +// @Override +// public void execute() { +// Session session = SessionManager.getInstance().getSession(sessionId); +// if (session == null) { +// logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); +// return; +// } +// UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); +// Table table = TableManager.getInstance().getTable(tableId); +// if (table.isTournament()) { +// UUID tournamentId = table.getTournament().getId(); +// TournamentManager.getInstance().quit(tournamentId, session.getUserId()); +// } +// } +// }); +// } +// +// @Override +// public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException { +// execute("sendPlayerAction", sessionId, new Action() { +// @Override +// public void execute() { +// Session session = SessionManager.getInstance().getSession(sessionId); +// if (session == null) { +// logger.error("Session not found sessionId: "+ sessionId + " gameId:" + gameId); +// return; +// } +// GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); +// } +// }); +// } +// +// @Override +// public boolean watchTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { +// return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId); +// } +// }); +// } +// +// @Override +// public boolean watchTournamentTable(final String sessionId, final UUID tableId) throws MageException { +// return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return TableManager.getInstance().watchTable(userId, tableId); +// } +// }); +// } +// +// @Override +// public void watchGame(final UUID gameId, final String sessionId) throws MageException { +// execute("watchGame", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// GameManager.getInstance().watchGame(gameId, userId); +// } +// }); +// } +// +// @Override +// public void stopWatching(final UUID gameId, final String sessionId) throws MageException { +// execute("stopWatching", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// User user = UserManager.getInstance().getUser(userId); +// if (user != null) { +// GameManager.getInstance().stopWatching(gameId, userId); +// user.removeGameWatchInfo(gameId); +// } +// +// } +// }); +// } +// +// @Override +// public void replayGame(final UUID gameId, final String sessionId) throws MageException { +// execute("replayGame", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().replayGame(gameId, userId); +// } +// }); +// } +// +// @Override +// public void startReplay(final UUID gameId, final String sessionId) throws MageException { +// execute("startReplay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().startReplay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void stopReplay(final UUID gameId, final String sessionId) throws MageException { +// execute("stopReplay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().stopReplay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void nextPlay(final UUID gameId, final String sessionId) throws MageException { +// execute("nextPlay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().nextPlay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void previousPlay(final UUID gameId, final String sessionId) throws MageException { +// execute("previousPlay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().previousPlay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { +// execute("skipForward", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().skipForward(gameId, userId, moves); +// } +// }); +// } +// + @Override + public ServerState getServerState() { +// try { + return state; +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; + } +// +// @Override +// public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { +// execute("cheat", sessionId, new Action() { +// @Override +// public void execute() { +// if (testMode) { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// GameManager.getInstance().cheat(gameId, userId, playerId, deckList); +// } +// } +// }); +// } +// +// @Override +// public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException { +// return executeWithResult("cheatOne", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() { +// if (testMode) { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return GameManager.getInstance().cheat(gameId, userId, playerId, cardName); +// } +// return false; +// } +// }); +// } + + public void handleException(String sessionId, Exception ex) { + if (!ex.getMessage().equals("No message")) { + logger.fatal("", ex); + server.informClient(sessionId, "Server error: " + ex.getMessage(), MessageType.ERROR); +// throw new MageException("Server error: " + ex.getMessage()); } } - static class MageTransporterServer extends TransporterServer { +// @Override +// public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) throws MageException { +// return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { +// @Override +// public GameView execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return GameManager.getInstance().getGameView(gameId, userId, playerId); +// } +// }); +// } - protected Connector connector; +// /** +// * Get user data for admin console +// * +// * @param sessionId +// * @return +// * @throws MageException +// */ +// @Override +// public List getUsers(String sessionId) throws MageException { +// return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult>() { +// @Override +// public List execute() throws MageException { +// List users = new ArrayList<>(); +// for (User user : UserManager.getInstance().getUsers()) { +// +// users.add(new UserView(user.getName(), user.getHost(), user.getSessionId(), user.getConnectionTime(), user.getGameInfo())); +// } +// return users; +// } +// }, true); +// } +// +// @Override +// public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { +// execute("disconnectUser", sessionId, new Action() { +// @Override +// public void execute() { +// SessionManager.getInstance().disconnectUser(sessionId, userSessionId); +// } +// }); +// } +// +// @Override +// public void endUserSession(final String sessionId, final String userSessionId) throws MageException { +// execute("endUserSession", sessionId, new Action() { +// @Override +// public void execute() { +// SessionManager.getInstance().endUserSession(sessionId, userSessionId); +// } +// }); +// } - public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler callback) throws Exception { - super(locator, target, subsystem); - connector.addInvocationHandler("callback", callback); - connector.setLeasePeriod(ConfigSettings.getInstance().getLeasePeriod()); - connector.addConnectionListener(new ClientConnectionListener()); - } - - public Connector getConnector() throws Exception { - return connector; - } - - @Override - protected Connector getConnector(InvokerLocator locator, Map config, Element xmlConfig) throws Exception { - Connector c = super.getConnector(locator, config, xmlConfig); - this.connector = c; - return c; - } - } - - static class MageServerInvocationHandler implements ServerInvocationHandler { - - @Override - public void setMBeanServer(MBeanServer server) { - - } - - @Override - public void setInvoker(ServerInvoker invoker) { - ((BisocketServerInvoker) invoker).setSecondaryBindPort(ConfigSettings.getInstance().getSecondaryBindPort()); - ((BisocketServerInvoker) invoker).setBacklog(ConfigSettings.getInstance().getBacklogSize()); - ((BisocketServerInvoker) invoker).setNumAcceptThreads(ConfigSettings.getInstance().getNumAcceptThreads()); - } - - @Override - public Object invoke(final InvocationRequest invocation) throws Throwable { - String sessionId = invocation.getSessionId(); - Map map = invocation.getRequestPayload(); - String host; - if (map != null) { - InetAddress clientAddress = (InetAddress) invocation.getRequestPayload().get(Remoting.CLIENT_ADDRESS); - host = clientAddress.getHostAddress(); +// /** +// * Admin console - Remove table +// * +// * @param sessionId +// * @param tableId +// * @throws MageException +// */ +// @Override +// public void removeTable(final String sessionId, final UUID tableId) throws MageException { +// execute("removeTable", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().removeTable(userId, tableId); +// } +// }); +// } +// +// @Override +// public Object getServerMessagesCompressed(String sessionId) throws MageException { +// return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { +// @Override +// public Object execute() throws MageException { +// return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); +// } +// }); +// } +// +// @Override +// 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, new Action() { +// @Override +// public void execute() { +// String host = SessionManager.getInstance().getSession(sessionId).getHost(); +// FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); +// LogServiceImpl.instance.log(LogKeys.KEY_FEEDBACK_ADDED, sessionId, username, host); +// } +// }); +// } +// } +// +// @Override +// public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { +// if (message != null) { +// execute("sendBroadcastMessage", sessionId, new Action() { +// @Override +// public void execute() { +// for (User user : UserManager.getInstance().getUsers()) { +// if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { +// user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); +// } else { +// user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); +// } +// } +// } +// }, true); +// } +// } + + @Override + public void receiveBroadcastMessage(String message, String sessionId) { + if (SessionManager.getInstance().isAdmin(sessionId)) { + if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { + server.informClients(message, MessageType.WARNING); } else { - host = "localhost"; - } - SessionManager.getInstance().getSession(sessionId).setHost(host); - return null; - } - - @Override - public void addListener(InvokerCallbackHandler callbackHandler) { - ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; - try { - String sessionId = handler.getClientSessionId(); - SessionManager.getInstance().createSession(sessionId, callbackHandler); - } catch (Throwable ex) { - logger.fatal("", ex); + server.informClients(message, MessageType.INFORMATION); } } - - @Override - public void removeListener(InvokerCallbackHandler callbackHandler) { - ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; - String sessionId = handler.getClientSessionId(); - SessionManager.getInstance().disconnect(sessionId, DisconnectReason.Disconnected); - } - } + public void informClient(String sessionId, String mesage, MessageType type) { + server.informClient(sessionId, mesage, type); + } + + protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { + if (checkAdminRights) { + if (!SessionManager.getInstance().isAdmin(sessionId)) { + LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); + return; + } + } + execute(actionName, sessionId, action); + } + + protected void execute(final String actionName, final String sessionId, final Action action) { + if (SessionManager.getInstance().isValidSession(sessionId)) { + try { + callExecutor.execute( + new Runnable() { + @Override + public void run() { + if (SessionManager.getInstance().isValidSession(sessionId)) { + try { + action.execute(); + } catch (MageException me) { + throw new RuntimeException(me); + } + } else { + LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId); + } + } + } + ); + } + catch (Exception ex) { + handleException(sessionId, ex); + } + } else { + LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); + } + } + +// protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action, boolean checkAdminRights) throws MageException { +// if (checkAdminRights) { +// if (!SessionManager.getInstance().isAdmin(sessionId)) { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); +// return action.negativeResult(); +// } +// } +// return executeWithResult(actionName, sessionId, action); +// } + + //TODO: also run in threads with future task +// protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action) throws MageException { +// if (SessionManager.getInstance().isValidSession(sessionId)) { +// try { +// return action.execute(); +// } catch (Exception ex) { +// handleException(ex); +// } +// } else { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); +// } +// return action.negativeResult(); +// } + +// @Override +// public List getMissingExpansionData(List codes) { +// List result = new ArrayList<>(); +// for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) { +// if (!codes.contains(expansionInfo.getCode())) { +// result.add(expansionInfo); +// } +// } +// return result; +// } +// +// @Override +// public List getMissingCardsData(List classNames) { +// return CardRepository.instance.getMissingCards(classNames); +// } + private static Class loadPlugin(Plugin plugin) { try { classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); @@ -363,7 +1349,8 @@ public class Main { return version; } - public static boolean isTestMode() { + public boolean isTestMode() { return testMode; } + } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 2a4cee3daee..ff722981b5d 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -63,24 +63,25 @@ public class Session { private int messageId = 0; private final Date timeConnected; private boolean isAdmin = false; - private final AsynchInvokerCallbackHandler callbackHandler; +// private final AsynchInvokerCallbackHandler callbackHandler; private final ReentrantLock lock; - public Session(String sessionId, InvokerCallbackHandler callbackHandler) { + public Session(String sessionId) { this.sessionId = sessionId; - this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler; +// this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler; this.isAdmin = false; this.timeConnected = new Date(); this.lock = new ReentrantLock(); } public String registerUser(String userName) throws MageException { - String returnMessage = registerUserHandling(userName); - if (returnMessage != null) { - sendErrorMessageToClient(returnMessage); - } - return returnMessage; +// String returnMessage = registerUserHandling(userName); +// if (returnMessage != null) { +// sendErrorMessageToClient(returnMessage); +// } +// return returnMessage; + return registerUserHandling(userName); } public boolean isLocked() { @@ -271,19 +272,19 @@ public class Session { } - public void fireCallback(final ClientCallback call) { - try { - call.setMessageId(messageId++); - callbackHandler.handleCallbackOneway(new Callback(call)); - } catch (HandleCallbackException ex) { - User user = UserManager.getInstance().getUser(userId); - logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName():"") + " userId " + userId); - logger.warn(" - method: " + call.getMethod()); - logger.warn(" - cause: " + getBasicCause(ex).toString()); - logger.trace("Stack trace:", ex); - userLostConnection(); - } - } +// public void fireCallback(final ClientCallback call) { +// try { +// call.setMessageId(messageId++); +// callbackHandler.handleCallbackOneway(new Callback(call)); +// } catch (HandleCallbackException ex) { +// User user = UserManager.getInstance().getUser(userId); +// logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName():"") + " userId " + userId); +// logger.warn(" - method: " + call.getMethod()); +// logger.warn(" - cause: " + getBasicCause(ex).toString()); +// logger.trace("Stack trace:", ex); +// userLostConnection(); +// } +// } public UUID getUserId() { return userId; @@ -305,12 +306,12 @@ public class Session { this.host = hostAddress; } - void sendErrorMessageToClient(String message) { - List messageData = new LinkedList<>(); - messageData.add("Error while connecting to server"); - messageData.add(message); - fireCallback(new ClientCallback("showUserMessage", null, messageData)); - } +// void sendErrorMessageToClient(String message) { +// List messageData = new LinkedList<>(); +// messageData.add("Error while connecting to server"); +// messageData.add(message); +// fireCallback(new ClientCallback("showUserMessage", null, messageData)); +// } public static Throwable getBasicCause(Throwable cause) { Throwable t = cause; diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 2bf3e9e4fc7..e35f2f10e09 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -36,6 +36,8 @@ import mage.server.services.impl.LogServiceImpl; import mage.view.UserDataView; import org.apache.log4j.Logger; import org.jboss.remoting.callback.InvokerCallbackHandler; +import org.mage.network.Server; +import org.mage.network.model.MessageType; /** * @@ -65,15 +67,17 @@ public class SessionManager { return session; } - public void createSession(String sessionId, InvokerCallbackHandler callbackHandler) { - Session session = new Session(sessionId, callbackHandler); - sessions.put(sessionId, session); - } +// public void createSession(String sessionId) { +// Session session = new Session(sessionId); +// sessions.put(sessionId, session); +// } public boolean registerUser(String sessionId, String userName) throws MageException { - Session session = sessions.get(sessionId); - if (session != null) { - String returnMessage = session.registerUser(userName); + Session session = new Session(sessionId); + sessions.put(sessionId, session); +// Session session = sessions.get(sessionId); +// if (session != null) { + String returnMessage = session.registerUser(userName); if (returnMessage == null) { LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, userName, session.getHost(), sessionId); @@ -82,12 +86,14 @@ public class SessionManager { logger.debug("- sessionId: " + sessionId); logger.debug("- host: " + session.getHost()); return true; - } else { - logger.debug(userName + " not registered: " + returnMessage); } - } else { - logger.error(userName + " tried to join with no sessionId"); - } + logger.debug(userName + " not registered: " + returnMessage); + Main.getInstance().informClient(sessionId, returnMessage, MessageType.ERROR); +// Server.informClient(sessionId, returnMessage, MessageType.ERROR); + +// } else { +// logger.error(userName + " tried to join with no sessionId"); +// } return false; } diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index d9231e36a16..3a93ff9222a 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -182,7 +182,7 @@ public class TableController { user.showUserMessage("Join Table", "No valid deck selected!"); return false; } - if (!Main.isTestMode() && !table.getValidator().validate(deck)) { + if (!Main.getInstance().isTestMode() && !table.getValidator().validate(deck)) { StringBuilder sb = new StringBuilder("You (").append(name).append(") have an invalid deck for the selected ").append(table.getValidator().getName()).append(" Format. \n\n"); for (Map.Entry entry : table.getValidator().getInvalid().entrySet()) { sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); @@ -271,7 +271,7 @@ public class TableController { } Deck deck = Deck.load(deckList, false, false); - if (!Main.isTestMode() && !table.getValidator().validate(deck)) { + if (!Main.getInstance().isTestMode() && !table.getValidator().validate(deck)) { StringBuilder sb = new StringBuilder("You (").append(name).append(") have an invalid deck for the selected ").append(table.getValidator().getName()).append(" Format. \n\n"); for (Map.Entry entry : table.getValidator().getInvalid().entrySet()) { sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); @@ -357,7 +357,7 @@ public class TableController { deck.setName(mPlayer.getDeck().getName()); } } - if (!Main.isTestMode() && !table.getValidator().validate(deck)) { + if (!Main.getInstance().isTestMode() && !table.getValidator().validate(deck)) { throw new InvalidDeckException("Invalid deck for this format", table.getValidator().getInvalid()); } submitDeck(userId, playerId, deck); @@ -475,7 +475,7 @@ public class TableController { } User user = UserManager.getInstance().getUser(userId); if (user != null) { - ChatManager.getInstance().broadcast(chatId, user.getName(), "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft); + ChatManager.getInstance().broadcast(chatId, user, "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft); if (!table.isTournamentSubTable()) { user.removeTable(playerId); } diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index 183e0704ca9..14e0b0520e5 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -179,7 +179,8 @@ public class User { if (isConnected()) { Session session = SessionManager.getInstance().getSession(sessionId); if (session != null) { - session.fireCallback(call); + +// session.fireCallback(call); } } } diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index 39c87163cce..0b7beada630 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -159,11 +159,11 @@ public class GameController implements GameCallback { updateGame(); break; case INFO: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, ChatMessage.MessageType.GAME); + ChatManager.getInstance().inform(chatId, event.getMessage(), MessageColor.BLACK, true, ChatMessage.MessageType.GAME); logger.trace(game.getId() + " " + event.getMessage()); break; case STATUS: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), ChatMessage.MessageType.GAME); + ChatManager.getInstance().inform(chatId, event.getMessage(), MessageColor.ORANGE, event.getWithTime(), ChatMessage.MessageType.GAME); logger.trace(game.getId() + " " + event.getMessage()); break; case ERROR: @@ -337,7 +337,7 @@ public class GameController implements GameCallback { } user.addGame(playerId, gameSession); logger.debug("Player " + player.getName()+ " " + playerId + " has " + joinType + " gameId: " + game.getId()); - ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getLogName() + " has " + joinType + " the game", MessageColor.ORANGE, true, MessageType.GAME); + ChatManager.getInstance().inform(chatId, game.getPlayer(playerId).getName() + " has " + joinType + " the game", MessageColor.ORANGE, true, MessageType.GAME); checkStart(); } @@ -363,7 +363,7 @@ public class GameController implements GameCallback { GameManager.getInstance().joinGame(game.getId(), user.getId()); logger.debug("Player " + player.getLogName() + " (disconnected) has joined gameId: " +game.getId()); } - ChatManager.getInstance().broadcast(chatId, player.getName(), user.getPingInfo() + " is pending to join the game", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS); + ChatManager.getInstance().broadcast(chatId, user, user.getPingInfo() + " is pending to join the game", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS); if (user.getSecondsDisconnected() > 240) { // Cancel player join possibility lately after 4 minutes logger.debug("Player " + player.getLogName() + " - canceled game (after 240 seconds) gameId: " +game.getId()); @@ -436,7 +436,7 @@ public class GameController implements GameCallback { watchers.put(userId, gameWatcher); gameWatcher.init(); user.addGameWatchInfo(game.getId()); - ChatManager.getInstance().broadcast(chatId, user.getName(), " has started watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS); + ChatManager.getInstance().broadcast(chatId, user, " has started watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS); } } @@ -444,7 +444,7 @@ public class GameController implements GameCallback { watchers.remove(userId); User user = UserManager.getInstance().getUser(userId); if (user != null) { - ChatManager.getInstance().broadcast(chatId, user.getName(), " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS); + ChatManager.getInstance().broadcast(chatId, user, " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS); } } @@ -584,7 +584,7 @@ public class GameController implements GameCallback { String sb = player.getLogName() + " has timed out (player had priority and was not active for " + ConfigSettings.getInstance().getMaxSecondsIdle() + " seconds ) - Auto concede."; - ChatManager.getInstance().broadcast(chatId, "", sb, MessageColor.BLACK, true, MessageType.STATUS); + ChatManager.getInstance().inform(chatId, sb, MessageColor.BLACK, true, MessageType.STATUS); game.idleTimeout(playerId); } } @@ -980,7 +980,7 @@ public class GameController implements GameCallback { idleTimeout(playerId); } }, - Main.isTestMode() ? 3600 :ConfigSettings.getInstance().getMaxSecondsIdle(), + Main.getInstance().isTestMode() ? 3600 :ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS ); } 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 2136cd33465..17ffbea0467 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -97,7 +97,7 @@ public class TournamentController { checkPlayersState(); break; case INFO: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS); + ChatManager.getInstance().inform(chatId, event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS); logger.debug(tournament.getId() + " " + event.getMessage()); break; case START_DRAFT: @@ -143,7 +143,7 @@ public class TournamentController { if (!player.getPlayer().isHuman()) { player.setJoined(); logger.debug("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId()); - ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS); + ChatManager.getInstance().inform(chatId, player.getPlayer().getName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS); } } checkStart(); @@ -173,7 +173,7 @@ public class TournamentController { TournamentPlayer player = tournament.getPlayer(playerId); player.setJoined(); logger.debug("player " +player.getPlayer().getName() + " - client has joined tournament " + tournament.getId()); - ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS); + ChatManager.getInstance().inform(chatId, player.getPlayer().getName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS); checkStart(); } else { logger.error("User not found userId: " + userId + " tournamentId: " + tournament.getId()); @@ -296,7 +296,7 @@ public class TournamentController { TournamentPlayer player = tournament.getPlayer(playerId); if (player != null && !player.hasQuit()) { tournamentSessions.get(playerId).submitDeck(deck); - ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has submitted his tournament deck", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerSubmittedDeck); + ChatManager.getInstance().inform(chatId, player.getPlayer().getName() + " has submitted his tournament deck", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerSubmittedDeck); } } } @@ -380,7 +380,7 @@ public class TournamentController { tournamentPlayer.setQuit(info); tournament.quit(playerId); tournamentSession.quit(); - ChatManager.getInstance().broadcast(chatId, "", tournamentPlayer.getPlayer().getLogName() + " has quit the tournament", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerQuitTournament); + ChatManager.getInstance().inform(chatId, tournamentPlayer.getPlayer().getName() + " has quit the tournament", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerQuitTournament); } } @@ -407,7 +407,7 @@ public class TournamentController { user.removeTable(leavingPlayer.getPlayer().getId()); user.removeTournament(leavingPlayer.getPlayer().getId()); } - ChatManager.getInstance().broadcast(chatId, "", leavingPlayer.getPlayer().getLogName() + " was replaced by draftbot", MessageColor.BLACK, true, MessageType.STATUS); + ChatManager.getInstance().inform(chatId, leavingPlayer.getPlayer().getName() + " was replaced by draftbot", MessageColor.BLACK, true, MessageType.STATUS); } return true; } diff --git a/Mage.Tests/pom.xml b/Mage.Tests/pom.xml index 8b5be68e065..0384cada3c8 100644 --- a/Mage.Tests/pom.xml +++ b/Mage.Tests/pom.xml @@ -57,7 +57,11 @@ log4j jar - + + ${project.groupId} + mage-network + ${project.version} + diff --git a/Mage.Tests/src/test/java/org/mage/test/load/LoadCallbackClient.java b/Mage.Tests/src/test/java/org/mage/test/load/LoadCallbackClient.java index 7a4e7cfa9ee..b62b936f187 100644 --- a/Mage.Tests/src/test/java/org/mage/test/load/LoadCallbackClient.java +++ b/Mage.Tests/src/test/java/org/mage/test/load/LoadCallbackClient.java @@ -1,126 +1,126 @@ -package org.mage.test.load; - -import mage.interfaces.callback.CallbackClient; -import mage.interfaces.callback.ClientCallback; -import mage.remote.Session; -import mage.utils.CompressUtil; -import mage.view.GameClientMessage; -import mage.view.GameView; -import mage.view.SimpleCardView; -import mage.view.TableClientMessage; -import org.apache.log4j.Logger; - -import java.util.UUID; - -/** - * @author noxx - */ -public class LoadCallbackClient implements CallbackClient { - - private static final transient Logger log = Logger.getLogger(LoadCallbackClient.class); - - private Session session; - private UUID gameId; - private UUID playerId; - private boolean gameOver; - - private volatile int controlCount; - - private GameView gameView; - - @Override - public void processCallback(ClientCallback callback) { - //TODO - controlCount = 0; - log.info(callback.getMethod()); - callback.setData(CompressUtil.decompress(callback.getData())); - switch (callback.getMethod()) { - case "startGame": - { - TableClientMessage message = (TableClientMessage) callback.getData(); - gameId = message.getGameId(); - playerId = message.getPlayerId(); - session.joinGame(message.getGameId()); - startControlThread(); - break; - } - case "gameInform": - { - GameClientMessage message = (GameClientMessage) callback.getData(); - log.info("Inform: " + message.getMessage()); - gameView = message.getGameView(); - break; - } - case "gameInit": - break; - case "gameTarget": - { - GameClientMessage message = (GameClientMessage) callback.getData(); - log.info("Target: " + message.getMessage()); - switch (message.getMessage()) { - case "Select a starting player": - session.sendPlayerUUID(gameId, playerId); - break; - case "Select a card to discard": - log.info("hand size: " + gameView.getHand().size()); - SimpleCardView card = gameView.getHand().values().iterator().next(); - session.sendPlayerUUID(gameId, card.getId()); - break; - } - break; - } - case "gameAsk": - { - GameClientMessage message = (GameClientMessage) callback.getData(); - log.info("Ask: " + message.getMessage()); - if (message.getMessage().equals("Do you want to take a mulligan?")) { - session.sendPlayerBoolean(gameId, false); - } break; - } - case "gameSelect": - { - GameClientMessage message = (GameClientMessage) callback.getData(); - log.info("Select: " + message.getMessage()); - if (LoadPhaseManager.getInstance().isSkip(message.getGameView(), message.getMessage(), playerId)) { - log.info("Skipped: " + message.getMessage()); - session.sendPlayerBoolean(gameId, false); - } break; - } - case "gameOver": - log.info("Game over"); - gameOver = true; - break; - } - - } - - public void setSession(Session session) { - this.session = session; - } - - public boolean isGameOver() { - return gameOver; - } - - private void startControlThread() { - new Thread(new Runnable() { - @Override - public void run() { - while (true) { - controlCount++; - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (controlCount > 5) { - log.warn("Game seems freezed. Sending boolean message to server."); - session.sendPlayerBoolean(gameId, false); - controlCount = 0; - } - } - - } - }).start(); - } -} +//package org.mage.test.load; +// +//import mage.interfaces.callback.CallbackClient; +//import mage.interfaces.callback.ClientCallback; +//import mage.remote.Session; +//import mage.utils.CompressUtil; +//import mage.view.GameClientMessage; +//import mage.view.GameView; +//import mage.view.SimpleCardView; +//import mage.view.TableClientMessage; +//import org.apache.log4j.Logger; +// +//import java.util.UUID; +// +///** +// * @author noxx +// */ +//public class LoadCallbackClient implements CallbackClient { +// +// private static final transient Logger log = Logger.getLogger(LoadCallbackClient.class); +// +// private Session session; +// private UUID gameId; +// private UUID playerId; +// private boolean gameOver; +// +// private volatile int controlCount; +// +// private GameView gameView; +// +// @Override +// public void processCallback(ClientCallback callback) { +// //TODO +// controlCount = 0; +// log.info(callback.getMethod()); +// callback.setData(CompressUtil.decompress(callback.getData())); +// switch (callback.getMethod()) { +// case "startGame": +// { +// TableClientMessage message = (TableClientMessage) callback.getData(); +// gameId = message.getGameId(); +// playerId = message.getPlayerId(); +// session.joinGame(message.getGameId()); +// startControlThread(); +// break; +// } +// case "gameInform": +// { +// GameClientMessage message = (GameClientMessage) callback.getData(); +// log.info("Inform: " + message.getMessage()); +// gameView = message.getGameView(); +// break; +// } +// case "gameInit": +// break; +// case "gameTarget": +// { +// GameClientMessage message = (GameClientMessage) callback.getData(); +// log.info("Target: " + message.getMessage()); +// switch (message.getMessage()) { +// case "Select a starting player": +// session.sendPlayerUUID(gameId, playerId); +// break; +// case "Select a card to discard": +// log.info("hand size: " + gameView.getHand().size()); +// SimpleCardView card = gameView.getHand().values().iterator().next(); +// session.sendPlayerUUID(gameId, card.getId()); +// break; +// } +// break; +// } +// case "gameAsk": +// { +// GameClientMessage message = (GameClientMessage) callback.getData(); +// log.info("Ask: " + message.getMessage()); +// if (message.getMessage().equals("Do you want to take a mulligan?")) { +// session.sendPlayerBoolean(gameId, false); +// } break; +// } +// case "gameSelect": +// { +// GameClientMessage message = (GameClientMessage) callback.getData(); +// log.info("Select: " + message.getMessage()); +// if (LoadPhaseManager.getInstance().isSkip(message.getGameView(), message.getMessage(), playerId)) { +// log.info("Skipped: " + message.getMessage()); +// session.sendPlayerBoolean(gameId, false); +// } break; +// } +// case "gameOver": +// log.info("Game over"); +// gameOver = true; +// break; +// } +// +// } +// +// public void setSession(Session session) { +// this.session = session; +// } +// +// public boolean isGameOver() { +// return gameOver; +// } +// +// private void startControlThread() { +// new Thread(new Runnable() { +// @Override +// public void run() { +// while (true) { +// controlCount++; +// try { +// Thread.sleep(1000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// if (controlCount > 5) { +// log.warn("Game seems freezed. Sending boolean message to server."); +// session.sendPlayerBoolean(gameId, false); +// controlCount = 0; +// } +// } +// +// } +// }).start(); +// } +//} 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 4687365d313..bdd33a606a0 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 @@ -1,300 +1,300 @@ -package org.mage.test.load; - -import mage.cards.Card; -import mage.cards.decks.Deck; -import mage.cards.decks.DeckCardLists; -import mage.cards.repository.CardInfo; -import mage.cards.repository.CardRepository; -import mage.constants.ColoredManaSymbol; -import mage.constants.MultiplayerAttackOption; -import mage.constants.RangeOfInfluence; -import mage.game.match.MatchOptions; -import mage.player.ai.ComputerPlayer; -import mage.remote.Connection; -import mage.remote.Session; -import mage.remote.SessionImpl; -import mage.cards.Sets; -import mage.view.GameTypeView; -import mage.view.TableView; -import org.apache.log4j.Logger; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import mage.cards.decks.DeckCardInfo; - -/** - * Intended to test Mage server under different load patterns. - * - * These tests do use server started separately, so Mage server should be started before running them. - * In case you want to debug these tests, use -Ddebug.mage that would disable client-server request timeout. - * - * Then it's also better to use -Xms256M -Xmx512M JVM options for these stests. - * - * @author noxx - */ -public class LoadTest { - - /** - * Logger for tests - */ - private static final Logger log = Logger.getLogger(LoadTest.class); - - /** - * First player's username - */ - private static final String TEST_USER_NAME = "player"; - - /** - * Second player's username - */ - private static final String TEST_USER_NAME_2 = "opponent"; - - /** - * Server connection setting. - */ - private static final String TEST_SERVER = "localhost"; - - /** - * Server connection setting. - */ - private static final int TEST_PORT = 17171; - - /** - * Server connection setting. - */ - private static final String TEST_PROXY_TYPE = "None"; - - /** - * Determines how many times test will be executed in a row. - */ - private static final int EXECUTION_COUNT = 100; - - /** - * Determines how many times test will be executed in a row. - */ - private static final int EXECUTION_COUNT_PLAY_GAME = 100; - - /** - * Tests connecting with two players, creating game and starting it. - * - * Executes the test EXECUTION_COUNT times. - * - * @throws Exception - */ - @Test - @Ignore - public void testStartGame() throws Exception { - DeckCardLists deckList = createDeck(); - - for (int i = 0; i < EXECUTION_COUNT; i++) { - Connection connection = createConnection(TEST_USER_NAME + i); - - SimpleMageClient mageClient = new SimpleMageClient(); - Session session = new SessionImpl(mageClient); - - session.connect(connection); - UUID roomId = session.getMainRoomId(); - - GameTypeView gameTypeView = session.getGameTypes().get(0); - log.info("Game type view: " + gameTypeView.getName()); - MatchOptions options = createGameOptions(gameTypeView, session); - - TableView table = session.createTable(roomId, options); - - 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); - return; - } - - /*** Connect with a second player ***/ - Connection connection2 = createConnection(TEST_USER_NAME_2 + i); - SimpleMageClient mageClient2 = new SimpleMageClient(); - Session session2 = new SessionImpl(mageClient2); - session2.connect(connection2); - UUID roomId2 = session2.getMainRoomId(); - - // 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); - return; - } - - /*** Start game ***/ - session.startMatch(roomId, table.getTableId()); - - Thread.sleep(100); - } - } - - /** - * Tests 10 simple games played one after another. - */ - @Test - @Ignore - public void testSimpleGame() throws Exception { - final DeckCardLists deckList = createDeck(); - - for (int i = 0; i < EXECUTION_COUNT_PLAY_GAME; i++) { - final int j = i; - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - testSimpleGame0(deckList, j); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }); - t.start(); - t.join(); - } - } - - /** - * Tests simple game till the end (game over). - * Players do nothing but skip phases and discard cards at the end. - * - * This results in a game that lasts until there is no cards in library. - */ - private boolean testSimpleGame0(DeckCardLists deckList, int i) throws InterruptedException { - Connection connection = createConnection(TEST_USER_NAME + i); - - SimpleMageClient mageClient = new SimpleMageClient(); - Session session = new SessionImpl(mageClient); - - session.connect(connection); - - mageClient.setSession(session); - UUID roomId = session.getMainRoomId(); - - GameTypeView gameTypeView = session.getGameTypes().get(0); - log.info("Game type view: " + gameTypeView.getName()); - MatchOptions options = createGameOptions(gameTypeView, session); - - TableView table = session.createTable(roomId, options); - - 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); - return true; - } - - /*** Connect with a second player ***/ - Connection connection2 = createConnection(TEST_USER_NAME_2 + i); - SimpleMageClient mageClient2 = new SimpleMageClient(); - Session session2 = new SessionImpl(mageClient2); - session2.connect(connection2); - - mageClient2.setSession(session2); - UUID roomId2 = session2.getMainRoomId(); - - // 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); - return true; - } - - /*** Start game ***/ - session.startMatch(roomId, table.getTableId()); - - while (!mageClient.isGameOver()) { - Thread.sleep(1000); - } - return false; - } - - /** - * Tests playing the whole game. - * Player use cheat to add lands, creatures and other cards. - * Then play only lands, one of them plays 1 damage targeting player. - * - * This results in 40 turns of the game. - */ - @Test - @Ignore - public void testPlayGame() throws Exception { - //TODO: to be implemented - } - - /** - * Creates connection to the server. - * Server should run independently. - * - * @param username - * @return - */ - private Connection createConnection(String username) { - Connection connection = new Connection(); - connection.setUsername(username); - connection.setHost(TEST_SERVER); - connection.setPort(TEST_PORT); - Connection.ProxyType proxyType = Connection.ProxyType.valueByText(TEST_PROXY_TYPE); - connection.setProxyType(proxyType); - return connection; - } - - /** - * Returns random deck. - * Converts deck returned by {@link #generateRandomDeck} method to {@link DeckCardLists} format. - * - * @return - */ - private DeckCardLists createDeck() { - DeckCardLists deckList = new DeckCardLists(); - Deck deck = generateRandomDeck(); - for (Card card : deck.getCards()) { - CardInfo cardInfo = CardRepository.instance.findCard(card.getExpansionSetCode(), card.getCardNumber()); - if (cardInfo != null) { - deckList.getCards().add(new DeckCardInfo(cardInfo.getName(), cardInfo.getCardNumber(), cardInfo.getSetCode())); - } - } - return deckList; - } - - /** - * Creates game options with two human players. - * - * @param gameTypeView - * @param session - * @return - */ - private MatchOptions createGameOptions(GameTypeView gameTypeView, Session session) { - MatchOptions options = new MatchOptions("Test game", gameTypeView.getName()); - - options.getPlayerTypes().add("Human"); - options.getPlayerTypes().add("Human"); - - options.setDeckType(session.getDeckTypes()[0]); - options.setLimited(false); - options.setAttackOption(MultiplayerAttackOption.MULTIPLE); - options.setRange(RangeOfInfluence.ALL); - options.setWinsNeeded(1); - return options; - } - - /** - * Generates random deck in {@link Deck} format. - * Uses {B}{R} as deck colors. - * - * @return - */ - private Deck generateRandomDeck() { - String selectedColors = "BR"; - List allowedColors = new ArrayList(); - log.info("Building deck with colors: " + selectedColors); - for (int i = 0; i < selectedColors.length(); i++) { - char c = selectedColors.charAt(i); - allowedColors.add(ColoredManaSymbol.lookup(c)); - } - List cardPool = Sets.generateRandomCardPool(45, allowedColors); - return ComputerPlayer.buildDeck(cardPool, allowedColors); - } -} +//package org.mage.test.load; +// +//import mage.cards.Card; +//import mage.cards.decks.Deck; +//import mage.cards.decks.DeckCardLists; +//import mage.cards.repository.CardInfo; +//import mage.cards.repository.CardRepository; +//import mage.constants.ColoredManaSymbol; +//import mage.constants.MultiplayerAttackOption; +//import mage.constants.RangeOfInfluence; +//import mage.game.match.MatchOptions; +//import mage.player.ai.ComputerPlayer; +//import mage.remote.Connection; +////import mage.remote.Session; +////import mage.remote.SessionImpl; +//import mage.cards.Sets; +//import mage.view.GameTypeView; +//import mage.view.TableView; +//import org.apache.log4j.Logger; +//import org.junit.Assert; +//import org.junit.Ignore; +//import org.junit.Test; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.UUID; +//import mage.cards.decks.DeckCardInfo; +// +///** +// * Intended to test Mage server under different load patterns. +// * +// * These tests do use server started separately, so Mage server should be started before running them. +// * In case you want to debug these tests, use -Ddebug.mage that would disable client-server request timeout. +// * +// * Then it's also better to use -Xms256M -Xmx512M JVM options for these stests. +// * +// * @author noxx +// */ +//public class LoadTest { +// +// /** +// * Logger for tests +// */ +// private static final Logger log = Logger.getLogger(LoadTest.class); +// +// /** +// * First player's username +// */ +// private static final String TEST_USER_NAME = "player"; +// +// /** +// * Second player's username +// */ +// private static final String TEST_USER_NAME_2 = "opponent"; +// +// /** +// * Server connection setting. +// */ +// private static final String TEST_SERVER = "localhost"; +// +// /** +// * Server connection setting. +// */ +// private static final int TEST_PORT = 17171; +// +// /** +// * Server connection setting. +// */ +// private static final String TEST_PROXY_TYPE = "None"; +// +// /** +// * Determines how many times test will be executed in a row. +// */ +// private static final int EXECUTION_COUNT = 100; +// +// /** +// * Determines how many times test will be executed in a row. +// */ +// private static final int EXECUTION_COUNT_PLAY_GAME = 100; +// +// /** +// * Tests connecting with two players, creating game and starting it. +// * +// * Executes the test EXECUTION_COUNT times. +// * +// * @throws Exception +// */ +// @Test +// @Ignore +// public void testStartGame() throws Exception { +// DeckCardLists deckList = createDeck(); +// +// for (int i = 0; i < EXECUTION_COUNT; i++) { +// Connection connection = createConnection(TEST_USER_NAME + i); +// +// SimpleMageClient mageClient = new SimpleMageClient(); +// Session session = new SessionImpl(mageClient); +// +// session.connect(connection); +// UUID roomId = session.getMainRoomId(); +// +// GameTypeView gameTypeView = session.getGameTypes().get(0); +// log.info("Game type view: " + gameTypeView.getName()); +// MatchOptions options = createGameOptions(gameTypeView, session); +// +// TableView table = session.createTable(roomId, options); +// +// 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); +// return; +// } +// +// /*** Connect with a second player ***/ +// Connection connection2 = createConnection(TEST_USER_NAME_2 + i); +// SimpleMageClient mageClient2 = new SimpleMageClient(); +// Session session2 = new SessionImpl(mageClient2); +// session2.connect(connection2); +// UUID roomId2 = session2.getMainRoomId(); +// +// // 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); +// return; +// } +// +// /*** Start game ***/ +// session.startMatch(roomId, table.getTableId()); +// +// Thread.sleep(100); +// } +// } +// +// /** +// * Tests 10 simple games played one after another. +// */ +// @Test +// @Ignore +// public void testSimpleGame() throws Exception { +// final DeckCardLists deckList = createDeck(); +// +// for (int i = 0; i < EXECUTION_COUNT_PLAY_GAME; i++) { +// final int j = i; +// Thread t = new Thread(new Runnable() { +// @Override +// public void run() { +// try { +// testSimpleGame0(deckList, j); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// } +// }); +// t.start(); +// t.join(); +// } +// } +// +// /** +// * Tests simple game till the end (game over). +// * Players do nothing but skip phases and discard cards at the end. +// * +// * This results in a game that lasts until there is no cards in library. +// */ +// private boolean testSimpleGame0(DeckCardLists deckList, int i) throws InterruptedException { +// Connection connection = createConnection(TEST_USER_NAME + i); +// +// SimpleMageClient mageClient = new SimpleMageClient(); +// Session session = new SessionImpl(mageClient); +// +// session.connect(connection); +// +// mageClient.setSession(session); +// UUID roomId = session.getMainRoomId(); +// +// GameTypeView gameTypeView = session.getGameTypes().get(0); +// log.info("Game type view: " + gameTypeView.getName()); +// MatchOptions options = createGameOptions(gameTypeView, session); +// +// TableView table = session.createTable(roomId, options); +// +// 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); +// return true; +// } +// +// /*** Connect with a second player ***/ +// Connection connection2 = createConnection(TEST_USER_NAME_2 + i); +// SimpleMageClient mageClient2 = new SimpleMageClient(); +// Session session2 = new SessionImpl(mageClient2); +// session2.connect(connection2); +// +// mageClient2.setSession(session2); +// UUID roomId2 = session2.getMainRoomId(); +// +// // 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); +// return true; +// } +// +// /*** Start game ***/ +// session.startMatch(roomId, table.getTableId()); +// +// while (!mageClient.isGameOver()) { +// Thread.sleep(1000); +// } +// return false; +// } +// +// /** +// * Tests playing the whole game. +// * Player use cheat to add lands, creatures and other cards. +// * Then play only lands, one of them plays 1 damage targeting player. +// * +// * This results in 40 turns of the game. +// */ +// @Test +// @Ignore +// public void testPlayGame() throws Exception { +// //TODO: to be implemented +// } +// +// /** +// * Creates connection to the server. +// * Server should run independently. +// * +// * @param username +// * @return +// */ +// private Connection createConnection(String username) { +// Connection connection = new Connection(); +// connection.setUsername(username); +// connection.setHost(TEST_SERVER); +// connection.setPort(TEST_PORT); +// Connection.ProxyType proxyType = Connection.ProxyType.valueByText(TEST_PROXY_TYPE); +// connection.setProxyType(proxyType); +// return connection; +// } +// +// /** +// * Returns random deck. +// * Converts deck returned by {@link #generateRandomDeck} method to {@link DeckCardLists} format. +// * +// * @return +// */ +// private DeckCardLists createDeck() { +// DeckCardLists deckList = new DeckCardLists(); +// Deck deck = generateRandomDeck(); +// for (Card card : deck.getCards()) { +// CardInfo cardInfo = CardRepository.instance.findCard(card.getExpansionSetCode(), card.getCardNumber()); +// if (cardInfo != null) { +// deckList.getCards().add(new DeckCardInfo(cardInfo.getName(), cardInfo.getCardNumber(), cardInfo.getSetCode())); +// } +// } +// return deckList; +// } +// +// /** +// * Creates game options with two human players. +// * +// * @param gameTypeView +// * @param session +// * @return +// */ +// private MatchOptions createGameOptions(GameTypeView gameTypeView, Session session) { +// MatchOptions options = new MatchOptions("Test game", gameTypeView.getName()); +// +// options.getPlayerTypes().add("Human"); +// options.getPlayerTypes().add("Human"); +// +// options.setDeckType(session.getDeckTypes()[0]); +// options.setLimited(false); +// options.setAttackOption(MultiplayerAttackOption.MULTIPLE); +// options.setRange(RangeOfInfluence.ALL); +// options.setWinsNeeded(1); +// return options; +// } +// +// /** +// * Generates random deck in {@link Deck} format. +// * Uses {B}{R} as deck colors. +// * +// * @return +// */ +// private Deck generateRandomDeck() { +// String selectedColors = "BR"; +// List allowedColors = new ArrayList(); +// log.info("Building deck with colors: " + selectedColors); +// for (int i = 0; i < selectedColors.length(); i++) { +// char c = selectedColors.charAt(i); +// allowedColors.add(ColoredManaSymbol.lookup(c)); +// } +// List cardPool = Sets.generateRandomCardPool(45, allowedColors); +// return ComputerPlayer.buildDeck(cardPool, allowedColors); +// } +//} diff --git a/Mage.Tests/src/test/java/org/mage/test/load/SimpleMageClient.java b/Mage.Tests/src/test/java/org/mage/test/load/SimpleMageClient.java index 88f0532070a..155595eb549 100644 --- a/Mage.Tests/src/test/java/org/mage/test/load/SimpleMageClient.java +++ b/Mage.Tests/src/test/java/org/mage/test/load/SimpleMageClient.java @@ -1,67 +1,68 @@ -package org.mage.test.load; - -import java.util.UUID; -import mage.interfaces.MageClient; -import mage.interfaces.callback.CallbackClient; -import mage.interfaces.callback.ClientCallback; -import mage.remote.Session; -import mage.utils.MageVersion; -import org.apache.log4j.Logger; - -/** - * For tests only - * - * @author noxx - */ -public class SimpleMageClient implements MageClient { - - private final UUID clientId; - private static final MageVersion version = new MageVersion(MageVersion.MAGE_VERSION_MAJOR, MageVersion.MAGE_VERSION_MINOR, MageVersion.MAGE_VERSION_PATCH, MageVersion.MAGE_VERSION_MINOR_PATCH, MageVersion.MAGE_VERSION_INFO); - - private static final transient Logger log = Logger.getLogger(SimpleMageClient.class); - - private final CallbackClient callbackClient; - - public SimpleMageClient() { - clientId = UUID.randomUUID(); - callbackClient = new LoadCallbackClient(); - } - - @Override - public MageVersion getVersion() { - return version; - } - - @Override - public void connected(String message) { - // do nothing - } - - @Override - public void disconnected(boolean errorCall) { - // do nothing - } - - @Override - public void showMessage(String message) { - log.info(message); - } - - @Override - public void showError(String message) { - log.error(message); - } - - @Override - public void processCallback(ClientCallback callback) { - callbackClient.processCallback(callback); - } - - public void setSession(Session session) { - ((LoadCallbackClient)callbackClient).setSession(session); - } - - public boolean isGameOver() { - return ((LoadCallbackClient)callbackClient).isGameOver(); - } -} +//package org.mage.test.load; +// +//import java.util.UUID; +////import mage.interfaces.MageClient; +////import mage.interfaces.callback.CallbackClient; +////import mage.interfaces.callback.ClientCallback; +////import mage.remote.Session; +//import mage.utils.MageVersion; +//import org.apache.log4j.Logger; +//import org.mage.network.interfaces.MageClient; +// +///** +// * For tests only +// * +// * @author noxx +// */ +//public class SimpleMageClient implements MageClient { +// +// private final UUID clientId; +// private static final MageVersion version = new MageVersion(MageVersion.MAGE_VERSION_MAJOR, MageVersion.MAGE_VERSION_MINOR, MageVersion.MAGE_VERSION_PATCH, MageVersion.MAGE_VERSION_MINOR_PATCH, MageVersion.MAGE_VERSION_INFO); +// +// private static final transient Logger log = Logger.getLogger(SimpleMageClient.class); +// +//// private final CallbackClient callbackClient; +// +// public SimpleMageClient() { +// clientId = UUID.randomUUID(); +// callbackClient = new LoadCallbackClient(); +// } +// +// @Override +// public MageVersion getVersion() { +// return version; +// } +// +// @Override +// public void connected(String message) { +// // do nothing +// } +// +// @Override +// public void disconnected(boolean errorCall) { +// // do nothing +// } +// +// @Override +// public void showMessage(String message) { +// log.info(message); +// } +// +// @Override +// public void showError(String message) { +// log.error(message); +// } +// +// @Override +// public void processCallback(ClientCallback callback) { +// callbackClient.processCallback(callback); +// } +// +// public void setSession(Session session) { +// ((LoadCallbackClient)callbackClient).setSession(session); +// } +// +// public boolean isGameOver() { +// return ((LoadCallbackClient)callbackClient).isGameOver(); +// } +//} diff --git a/pom.xml b/pom.xml index c0468ace043..aa13a725d2a 100644 --- a/pom.xml +++ b/pom.xml @@ -61,6 +61,7 @@ Mage.Tests Mage.Updater Mage.Stats + Mage.Network