initial commit - only table pane chat is working atm

This commit is contained in:
betasteward 2015-05-23 10:18:36 -04:00
parent f9bad74ca7
commit e45345d87a
84 changed files with 5370 additions and 3992 deletions

3
.gitignore vendored
View file

@ -87,4 +87,5 @@ Mage.Server.Plugins/Mage.Draft.8PlayerBooster/target
/Utils/*_unimplemented.txt
*.netbeans_automatic_build
*.txt
Mage.Client/serverlist.txt
Mage.Client/serverlist.txt
/Mage.Network/target/

View file

@ -25,6 +25,11 @@
<artifactId>mage-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-network</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.jspf</groupId>
<artifactId>jspf-core</artifactId>

View file

@ -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 ? "<not available>" : version.toString() + " Server: "
+ ((session != null && session.isConnected()) ? session.getVersionInfo():"<not connected>"));
+ ((client != null && client.isConnected()) ? serverState.getVersion().toString():"<not connected>"));
}
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;
}
}

View file

@ -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

View file

@ -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<String> 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("<br/>Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over")
.append("<br/>Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over")
.append("<br/><b>F2</b> - Confirm \"Ok\", \"Yes\" or \"Done\" button")
.append("<br/><b>F4</b> - Skip current turn but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>F5</b> - Skip to next end step but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>F7</b> - Skip to next main phase but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>F9</b> - Skip everything until your next turn")
.append("<br/><b>F3</b> - 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("<br/>Download icons and symbols by using the \"Symbols\" menu to the top right.")
.append("<br/>\\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("<font color='");
@ -470,9 +526,9 @@ public class ChatPanel extends javax.swing.JPanel {
private void txtMessageKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMessageKeyTyped
if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
if (parentChatRef != null) {
parentChatRef.session.sendChatMessage(parentChatRef.chatId, this.txtMessage.getText());
parentChatRef.client.sendChatMessage(parentChatRef.chatId, this.txtMessage.getText());
} else {
session.sendChatMessage(chatId, this.txtMessage.getText());
client.sendChatMessage(chatId, this.txtMessage.getText());
}
this.txtMessage.setText("");
this.txtMessage.repaint();

View file

@ -3,7 +3,7 @@ package mage.client.components.ability;
import mage.client.util.ImageHelper;
import mage.client.util.SettingsManager;
import mage.client.util.gui.GuiDisplayUtil;
import mage.remote.Session;
//import mage.remote.Session;
import mage.view.AbilityPickerView;
import org.apache.log4j.Logger;
import org.jdesktop.layout.GroupLayout;
@ -17,6 +17,7 @@ import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import org.mage.network.Client;
/**
* Dialog for choosing abilities.
@ -35,7 +36,7 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener {
private List<Object> choices;
private String message = DEFAULT_MESSAGE;
private Session session;
private Client client;
private UUID gameId;
private BackgroundPainter mwPanelPainter;
@ -78,8 +79,8 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener {
jScrollPane2.getVerticalScrollBar().setUI(new MageScrollbarUI());
}
public void init(Session session, UUID gameId) {
this.session = session;
public void init(Client client, UUID gameId) {
this.client = client;
this.gameId = gameId;
}
@ -449,7 +450,7 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener {
if (id == null) {
cancel();
} else {
session.sendPlayerUUID(gameId, id);
client.sendPlayerUUID(gameId, id);
}
setVisible(false);
AbilityPicker.this.selected = true;
@ -464,7 +465,7 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener {
private void cancel() {
try {
session.sendPlayerBoolean(gameId, false);
client.sendPlayerBoolean(gameId, false);
} catch (Exception e) {
log.error("Couldn't cancel choose dialog: " + e, e);
}

View file

@ -70,10 +70,11 @@ import mage.client.util.Listener;
import mage.client.util.audio.AudioManager;
import mage.components.CardInfoPane;
import mage.game.GameException;
import mage.remote.Session;
//import mage.remote.Session;
import mage.view.CardView;
import mage.view.SimpleCardView;
import org.apache.log4j.Logger;
import org.mage.network.Client;
/**
*
@ -169,7 +170,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
this.btnExit.setVisible(false);
this.btnImport.setVisible(false);
if (!MageFrame.getSession().isTestMode()) {
if (!MageFrame.getClient().getServerState().isTestMode()) {
this.btnLoad.setVisible(false);
}
this.deckArea.showSideboard(false);
@ -179,7 +180,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
if (timeout != 0) {
countdown.start();
if (updateDeckTask == null || updateDeckTask.isDone()) {
updateDeckTask = new UpdateDeckTask(MageFrame.getSession(), tableId, deck);
updateDeckTask = new UpdateDeckTask(MageFrame.getClient(), tableId, deck);
updateDeckTask.execute();
}
}
@ -190,7 +191,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
//this.cardTableSelector.loadCards(this.bigCard);
this.btnExit.setVisible(true);
this.btnImport.setVisible(true);
if (!MageFrame.getSession().isTestMode()) {
if (!MageFrame.getClient().getServerState().isTestMode()) {
this.btnLoad.setVisible(true);
}
this.deckArea.showSideboard(true);
@ -789,7 +790,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
updateDeckTask.cancel(true);
}
if (MageFrame.getSession().submitDeck(tableId, deck.getDeckCardLists())) {
if (MageFrame.getClient().submitDeck(tableId, deck.getDeckCardLists())) {
removeDeckEditor();
}
}//GEN-LAST:event_btnSubmitActionPerformed
@ -876,12 +877,12 @@ class ImportFilter extends FileFilter {
class UpdateDeckTask extends SwingWorker<Void, Void> {
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<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
while (!isCancelled()) {
session.updateDeck(tableId, deck.getDeckCardLists());
client.updateDeck(tableId, deck.getDeckCardLists());
Thread.sleep(5000);
}
return null;

View file

@ -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);
}
}

View file

@ -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);

View file

@ -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) {

View file

@ -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<TablePlayerPanel> players = new ArrayList<>();
private final List<String> 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;

View file

@ -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<TournamentPlayerPanel> players = new ArrayList<>();
private final List<JComboBox> 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;

View file

@ -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"),

View file

@ -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<Void, TableView> {
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<Void, TableView> {
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<Void, TableView> {
@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;

View file

@ -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

View file

@ -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

View file

@ -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);
}

View file

@ -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<String, Serializable> 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) {

View file

@ -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<ShowCardsDialog> 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<String, Card> getLoadedCards() {
@ -1898,20 +1899,20 @@ public final class GamePanel extends javax.swing.JPanel {
}
class ReplayTask extends SwingWorker<Void, Collection<MatchView>> {
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;

View file

@ -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() {

View file

@ -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() {

View file

@ -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

View file

@ -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("<br/>Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over")
.append("<br/>Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over")
.append("<br/><b>F2</b> - Confirm \"Ok\", \"Yes\" or \"Done\" button")
.append("<br/><b>F4</b> - Skip current turn but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>F5</b> - Skip to next end step but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>F7</b> - Skip to next main phase but stop on declare attackers/blockers and something on the stack")
.append("<br/><b>F9</b> - Skip everything until your next turn")
.append("<br/><b>F3</b> - 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("<br/>Download icons and symbols by using the \"Symbols\" menu to the top right.")
.append("<br/>\\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("<br/>Turn mousewheel up (ALT-e) - enlarge image of card the mousepointer hovers over")
// .append("<br/>Turn mousewheel down (ALT-s) - enlarge original/alternate image of card the mousepointer hovers over")
// .append("<br/><b>F2</b> - Confirm \"Ok\", \"Yes\" or \"Done\" button")
// .append("<br/><b>F4</b> - Skip current turn but stop on declare attackers/blockers and something on the stack")
// .append("<br/><b>F5</b> - Skip to next end step but stop on declare attackers/blockers and something on the stack")
// .append("<br/><b>F7</b> - Skip to next main phase but stop on declare attackers/blockers and something on the stack")
// .append("<br/><b>F9</b> - Skip everything until your next turn")
// .append("<br/><b>F3</b> - 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("<br/>Download icons and symbols by using the \"Symbols\" menu to the top right.")
// .append("<br/>\\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 {

View file

@ -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;
}

View file

@ -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);

View file

@ -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<String> 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<UUID> 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<String> serverMessages = session.getServerMessages();
List<String> 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<TableView> 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<Void, Collection<TableView>> {
private final Session session;
private final Client client;
private final UUID roomId;
private final TablesPanel panel;
@ -1411,8 +1412,8 @@ class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> {
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<Void, Collection<TableView>> {
@Override
protected Void doInBackground() throws Exception {
while (!isCancelled()) {
Collection<TableView> tables = session.getTables(roomId);
Collection<TableView> tables = client.getTables(roomId);
if (tables != null) {
this.publish(tables);
}
@ -1452,14 +1453,14 @@ class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> {
class UpdatePlayersTask extends SwingWorker<Void, Collection<RoomUsersView>> {
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<Void, Collection<RoomUsersView>> {
@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<Void, Collection<MatchView>> {
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<Void, Collection<MatchView>> {
@Override
protected Void doInBackground() throws Exception {
while (!isCancelled()) {
Collection<MatchView> matches = session.getFinishedMatches(roomId);
Collection<MatchView> matches = client.getFinishedMatches(roomId);
if (matches != null) {
this.publish(matches);
}
@ -1635,10 +1636,10 @@ class UpdateMatchesTask extends SwingWorker<Void, Collection<MatchView>> {
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<UUID> 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);
}

View file

@ -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(),

View file

@ -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<Void, TournamentView> {
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<Void, TournamentView> {
@Override
protected Void doInBackground() throws Exception {
while (!isCancelled()) {
this.publish(session.getTournament(tournamentId));
this.publish(client.getTournament(tournamentId));
Thread.sleep(2000);
}
return null;

View file

@ -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 {
}// </editor-fold>//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

View file

@ -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());
}
}
}

View file

@ -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;
}
}

View file

@ -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<ExpansionInfo> getMissingExpansionData(List<String> codes);
List<CardInfo> getMissingCardsData(List<String> 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<RoomUsersView> getRoomUsers(UUID roomId) throws MageException;
List<MatchView> 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<TableView> 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<UUID> 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<UserView> 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<ExpansionInfo> getMissingExpansionData(List<String> codes);
// List<CardInfo> getMissingCardsData(List<String> 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<RoomUsersView> getRoomUsers(UUID roomId) throws MageException;
// List<MatchView> 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<TableView> 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<UUID> 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<UserView> 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;
//}

View file

@ -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<GameTypeView> gameTypes, List<TournamentTypeView> 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<GameTypeView> getGameTypes() {
@ -112,4 +115,8 @@ public class ServerState implements Serializable {
return expansionsContentVersion;
}
public UUID getMainRoomId() {
return mainRoomId;
}
}

View file

@ -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 {
//
//}

File diff suppressed because it is too large Load diff

37
Mage.Network/pom.xml Normal file
View file

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.mage</groupId>
<artifactId>mage-root</artifactId>
<version>1.4.0</version>
</parent>
<artifactId>mage-network</artifactId>
<packaging>jar</packaging>
<name>Mage Network</name>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<type>jar</type>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-common</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View file

@ -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<SocketChannel> {
@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<String> getServerMessages() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Collection<TableView> getTables(UUID roomId) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Collection<MatchView> getFinishedMatches(UUID roomId) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Collection<RoomUsersView> 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<UUID> 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<UserView> getUsers() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

View file

@ -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<SocketChannel> {
@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));
}
}

View file

@ -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");
}
}
}
}

View file

@ -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<PingMessage> {
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");
}
}

View file

@ -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<ReceiveChatMessage> {
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));
}
}

View file

@ -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<ChatRoomIdMessage> {
private ChannelHandlerContext ctx;
private final BlockingQueue<UUID> 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));
}
}

View file

@ -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<ClientRegisteredMessage> {
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());
}
}

View file

@ -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<InformClientMessage> {
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());
}
}

View file

@ -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);
}
}

View file

@ -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<SendChatMessage> {
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();
}
}

View file

@ -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<ChatRoomIdRequest> {
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();
}
}

View file

@ -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);
}
}

View file

@ -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<JoinChatMessage> {
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();
}
}

View file

@ -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<JoinChatMessage> {
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();
}
}

View file

@ -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<RegisterClientMessage> {
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();
}
}

View file

@ -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();
}

View file

@ -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();
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -0,0 +1,11 @@
package org.mage.network.model;
/**
*
* @author BetaSteward
*/
public enum MessageType {
INFORMATION,
WARNING,
ERROR
}

View file

@ -0,0 +1,11 @@
package org.mage.network.model;
import java.io.Serializable;
/**
*
* @author BetaSteward
*/
public class PingMessage implements Serializable {
}

View file

@ -0,0 +1,11 @@
package org.mage.network.model;
import java.io.Serializable;
/**
*
* @author BetaSteward
*/
public class PongMessage implements Serializable {
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -30,5 +30,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-network</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View file

@ -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 {
}// </editor-fold>//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.
}
}

View file

@ -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<Void, List<UserView>> {
private final Session session;
private final Client client;
private final ConsolePanel panel;
private List<UserView> 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<UserView> users = session.getUsers();
List<UserView> users = client.getUsers();
if (previousUsers == null || checkUserListChanged(users)) {
logger.debug("Need to update the user list");
@ -503,14 +504,14 @@ class UpdateUsersTask extends SwingWorker<Void, List<UserView>> {
class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> {
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<Void, Collection<TableView>> {
@Override
protected Void doInBackground() throws Exception {
while (!isCancelled()) {
this.publish(session.getTables(roomId));
this.publish(client.getTables(roomId));
Thread.sleep(3000);
}
return null;

View file

@ -29,6 +29,11 @@
<artifactId>mage-common</artifactId>
<version>${mage-version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-network</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-sets</artifactId>

View file

@ -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("<br/>User ").append(userToName).append(" not found").toString();
chatSessions.get(chatId).broadcastInfoToUser(user,message);
}
} else {
message += new StringBuilder("<br/>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("<br/>List of commands:")
.append("<br/>\\info [text] - set a info text to your player")
.append("<br/>\\list - Show a list of commands")
.append("<br/>\\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) {

View file

@ -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("<br/>User ").append(userToName).append(" not found").toString();
broadcastInfoToUser(user,message);
}
} else {
message += new StringBuilder("<br/>User ").append(userToName).append(" not found").toString();
broadcastInfoToUser(user,message);
}
return true;
}
}
if (command.equals("L") || command.equals("LIST")) {
message += new StringBuilder("<br/>List of commands:")
.append("<br/>\\info [text] - set a info text to your player")
.append("<br/>\\list - Show a list of commands")
.append("<br/>\\whisper [player name] [text] - whisper to the player with the given name").toString();
broadcastInfoToUser(user,message);
return true;
}
return false;
}
/**
* @return the chatId
*/

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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<String> messageData = new LinkedList<>();
messageData.add("Error while connecting to server");
messageData.add(message);
fireCallback(new ClientCallback("showUserMessage", null, messageData));
}
// void sendErrorMessageToClient(String message) {
// List<String> 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;

View file

@ -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;
}

View file

@ -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<String, String> 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<String, String> 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);
}

View file

@ -179,7 +179,8 @@ public class User {
if (isConnected()) {
Session session = SessionManager.getInstance().getSession(sessionId);
if (session != null) {
session.fireCallback(call);
// session.fireCallback(call);
}
}
}

View file

@ -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
);
}

View file

@ -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;
}

View file

@ -57,7 +57,11 @@
<artifactId>log4j</artifactId>
<type>jar</type>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mage-network</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>

View file

@ -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();
// }
//}

View file

@ -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<ColoredManaSymbol> allowedColors = new ArrayList<ColoredManaSymbol>();
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<Card> 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<ColoredManaSymbol> allowedColors = new ArrayList<ColoredManaSymbol>();
// 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<Card> cardPool = Sets.generateRandomCardPool(45, allowedColors);
// return ComputerPlayer.buildDeck(cardPool, allowedColors);
// }
//}

View file

@ -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();
// }
//}

View file

@ -61,6 +61,7 @@
<module>Mage.Tests</module>
<module>Mage.Updater</module>
<module>Mage.Stats</module>
<module>Mage.Network</module>
</modules>
<repositories>