This commit is contained in:
BetaSteward 2011-07-17 15:55:25 -04:00
commit 955e1c76b6
67 changed files with 2519 additions and 2658 deletions

View file

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
@ -88,7 +88,7 @@
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>Mage-Card-Plugin</artifactId> <artifactId>Mage-Card-Plugin</artifactId>
<version>0.6</version> <version>0.5</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -102,11 +102,6 @@
<artifactId>beansbinding</artifactId> <artifactId>beansbinding</artifactId>
<version>1.2.1</version> <version>1.2.1</version>
</dependency> </dependency>
<dependency>
<groupId>org.swinglabs</groupId>
<artifactId>swing-layout</artifactId>
<version>1.0.3</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View file

@ -47,7 +47,6 @@ import mage.client.deckeditor.collection.viewer.CollectionViewerPane;
import mage.client.dialog.*; import mage.client.dialog.*;
import mage.client.plugins.impl.Plugins; import mage.client.plugins.impl.Plugins;
import mage.client.util.EDTExceptionHandler; import mage.client.util.EDTExceptionHandler;
import mage.client.util.SettingsManager;
import mage.client.util.gui.ArrowBuilder; import mage.client.util.gui.ArrowBuilder;
import mage.components.ImagePanel; import mage.components.ImagePanel;
@ -109,7 +108,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
private static Preferences prefs = Preferences.userNodeForPackage(MageFrame.class); private static Preferences prefs = Preferences.userNodeForPackage(MageFrame.class);
private JLabel title; private JLabel title;
private Rectangle titleRectangle; private Rectangle titleRectangle;
private final static MageVersion version = new MageVersion(0, 7, 4, ""); private final static MageVersion version = new MageVersion(0, 8, 0, "");
private UUID clientId; private UUID clientId;
private static MagePane activeFrame; private static MagePane activeFrame;
private static boolean liteMode = false; private static boolean liteMode = false;
@ -174,7 +173,6 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
initComponents(); initComponents();
setSize(1024, 768); setSize(1024, 768);
SettingsManager.getInstance().setScreenWidthAndHeight(1024, 768);
this.setExtendedState(JFrame.MAXIMIZED_BOTH); this.setExtendedState(JFrame.MAXIMIZED_BOTH);
session = new Session(this); session = new Session(this);
@ -201,6 +199,11 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
addMageLabel(); addMageLabel();
setAppIcon(); setAppIcon();
//PlayerPanelNew n = new PlayerPanelNew();
//n.setBounds(100,100,100,300);
//n.setVisible(true);
//backgroundPane.add(n);
desktopPane.add(ArrowBuilder.getArrowsPanel(), JLayeredPane.DRAG_LAYER); desktopPane.add(ArrowBuilder.getArrowsPanel(), JLayeredPane.DRAG_LAYER);
desktopPane.addComponentListener(new ComponentAdapter() { desktopPane.addComponentListener(new ComponentAdapter() {
@ -208,13 +211,12 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
public void componentResized(ComponentEvent e) { public void componentResized(ComponentEvent e) {
int width = ((JComponent) e.getSource()).getWidth(); int width = ((JComponent) e.getSource()).getWidth();
int height = ((JComponent) e.getSource()).getHeight(); int height = ((JComponent) e.getSource()).getHeight();
SettingsManager.getInstance().setScreenWidthAndHeight(width, height); if (!liteMode)
if (!liteMode) {
backgroundPane.setSize(width, height); backgroundPane.setSize(width, height);
}
JPanel arrowsPanel = ArrowBuilder.getArrowsPanelRef(); JPanel arrowsPanel = ArrowBuilder.getArrowsPanelRef();
if (arrowsPanel != null) arrowsPanel.setSize(width, height); if (arrowsPanel != null) arrowsPanel.setSize(width, height);
if (title != null) { if (title != null) {
//title.setBorder(BorderFactory.createLineBorder(Color.red));
title.setBounds((int) (width - titleRectangle.getWidth()) / 2, (int) (height - titleRectangle.getHeight()) / 2, titleRectangle.width, titleRectangle.height); title.setBounds((int) (width - titleRectangle.getWidth()) / 2, (int) (height - titleRectangle.getHeight()) / 2, titleRectangle.width, titleRectangle.height);
} }
} }
@ -759,8 +761,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
}//GEN-LAST:event_btnCollectionViewerActionPerformed }//GEN-LAST:event_btnCollectionViewerActionPerformed
private void btnPreferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreferencesActionPerformed private void btnPreferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreferencesActionPerformed
//PhasesDialog.main(new String[]{}); PhasesDialog.main(new String[]{});
PreferencesDialog.main(new String[]{});
}//GEN-LAST:event_btnPreferencesActionPerformed }//GEN-LAST:event_btnPreferencesActionPerformed
public void exitApp() { public void exitApp() {

View file

@ -173,7 +173,6 @@ public class DeckEditorPanel extends javax.swing.JPanel {
if (cardInfoPane instanceof CardInfoPane) { if (cardInfoPane instanceof CardInfoPane) {
((CardInfoPane)cardInfoPane).setCard(new CardView(card)); ((CardInfoPane)cardInfoPane).setCard(new CardView(card));
} }
hidePopup();
} }
} else if (event.getEventName().equals("shift-double-click") && mode == DeckEditorMode.Constructed) { } else if (event.getEventName().equals("shift-double-click") && mode == DeckEditorMode.Constructed) {
@ -182,7 +181,6 @@ public class DeckEditorPanel extends javax.swing.JPanel {
if (cardInfoPane instanceof CardInfoPane) { if (cardInfoPane instanceof CardInfoPane) {
((CardInfoPane)cardInfoPane).setCard(new CardView(card)); ((CardInfoPane)cardInfoPane).setCard(new CardView(card));
} }
hidePopup();
} }
refreshDeck(); refreshDeck();
} }
@ -196,7 +194,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
public void event(Event event) { public void event(Event event) {
if (event.getEventName().equals("double-click")) { if (event.getEventName().equals("double-click")) {
for (Card card: deck.getCards()) { for (Card card: deck.getCards()) {
if (card.getId().equals(event.getSource())) { if (card.getId().equals((UUID)event.getSource())) {
deck.getCards().remove(card); deck.getCards().remove(card);
if (mode == DeckEditorMode.Limited || mode == DeckEditorMode.Sideboard) { if (mode == DeckEditorMode.Limited || mode == DeckEditorMode.Sideboard) {
deck.getSideboard().add(card); deck.getSideboard().add(card);
@ -205,18 +203,16 @@ public class DeckEditorPanel extends javax.swing.JPanel {
break; break;
} }
} }
hidePopup();
refreshDeck(); refreshDeck();
} }
else if (event.getEventName().equals("shift-double-click") && mode == DeckEditorMode.Constructed) { else if (event.getEventName().equals("shift-double-click") && mode == DeckEditorMode.Constructed) {
for (Card card: deck.getCards()) { for (Card card: deck.getCards()) {
if (card.getId().equals(event.getSource())) { if (card.getId().equals((UUID)event.getSource())) {
deck.getCards().remove(card); deck.getCards().remove(card);
deck.getSideboard().add(card); deck.getSideboard().add(card);
break; break;
} }
} }
hidePopup();
refreshDeck(); refreshDeck();
} }
} }
@ -227,14 +223,16 @@ public class DeckEditorPanel extends javax.swing.JPanel {
@Override @Override
public void event(Event event) { public void event(Event event) {
if (event.getEventName().equals("double-click")) { if (event.getEventName().equals("double-click")) {
//boolean isListView = cardSelector.getCardsList() instanceof TableModel;
for (Card card: deck.getSideboard()) { for (Card card: deck.getSideboard()) {
if (card.getId().equals(event.getSource())) { if (card.getId().equals((UUID)event.getSource())) {
deck.getSideboard().remove(card); deck.getSideboard().remove(card);
//if (!isListView) {
deck.getCards().add(card); deck.getCards().add(card);
//}
break; break;
} }
} }
hidePopup();
refreshDeck(); refreshDeck();
} }
} }
@ -245,10 +243,6 @@ public class DeckEditorPanel extends javax.swing.JPanel {
this.repaint(); this.repaint();
} }
private void hidePopup() {
Plugins.getInstance().getActionCallback().mouseExited(null, null);
}
public void hideDeckEditor() { public void hideDeckEditor() {
Component c = this.getParent(); Component c = this.getParent();
while (c != null && !(c instanceof DeckEditorPane)) { while (c != null && !(c instanceof DeckEditorPane)) {
@ -585,26 +579,27 @@ public class DeckEditorPanel extends javax.swing.JPanel {
int ret = fcImportDeck.showOpenDialog(this); int ret = fcImportDeck.showOpenDialog(this);
if (ret == JFileChooser.APPROVE_OPTION) { if (ret == JFileChooser.APPROVE_OPTION) {
File file = fcImportDeck.getSelectedFile(); File file = fcImportDeck.getSelectedFile();
try { if (file != null) {
setCursor(new Cursor(Cursor.WAIT_CURSOR)); try {
DeckImporter importer = getDeckImporter(file.getPath()); setCursor(new Cursor(Cursor.WAIT_CURSOR));
if (importer != null) { DeckImporter importer = getDeckImporter(file.getPath());
deck = Deck.load(importer.importDeck(file.getPath())); if (importer != null) {
deck = Deck.load(importer.importDeck(file.getPath()));
}
else {
JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Unknown deck format", "Error importing deck", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
Logger.getLogger(DeckEditorPanel.class.getName()).log(Level.SEVERE, null, ex);
} }
else { finally {
JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Unknown deck format", "Error importing deck", JOptionPane.ERROR_MESSAGE); setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
} }
} catch (Exception ex) { refreshDeck();
Logger.getLogger(DeckEditorPanel.class.getName()).log(Level.SEVERE, null, ex); try {
}
finally {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
refreshDeck();
try {
if (file != null)
MageFrame.getPreferences().put("lastImportFolder", file.getCanonicalPath()); MageFrame.getPreferences().put("lastImportFolder", file.getCanonicalPath());
} catch (IOException ex) { } } catch (IOException ex) { }
}
} }
fcImportDeck.setSelectedFile(null); fcImportDeck.setSelectedFile(null);
}//GEN-LAST:event_btnImportActionPerformed }//GEN-LAST:event_btnImportActionPerformed

View file

@ -80,9 +80,6 @@ public class CallbackClientImpl implements CallbackClient {
public void run() { public void run() {
try { try {
logger.info(callback.getMessageId() + " -- " + callback.getMethod()); logger.info(callback.getMessageId() + " -- " + callback.getMethod());
if (callback.getMethod() == null) { // may happen on disconnect
return;
}
if (callback.getMethod().equals("startGame")) { if (callback.getMethod().equals("startGame")) {
TableClientMessage message = (TableClientMessage) callback.getData(); TableClientMessage message = (TableClientMessage) callback.getData();
GameManager.getInstance().setCurrentPlayerUUID(message.getPlayerId()); GameManager.getInstance().setCurrentPlayerUUID(message.getPlayerId());
@ -247,7 +244,10 @@ public class CallbackClientImpl implements CallbackClient {
} }
} }
else if (callback.getMethod().equals("draftInit")) { else if (callback.getMethod().equals("draftInit")) {
DraftClientMessage message = (DraftClientMessage) callback.getData();
DraftPanel panel = frame.getDraft(callback.getObjectId());
if (panel != null)
panel.loadBooster(message.getDraftPickView());
} }
else if (callback.getMethod().equals("tournamentInit")) { else if (callback.getMethod().equals("tournamentInit")) {

View file

@ -1,5 +1,5 @@
#default levels #default levels
log4j.rootLogger=debug, console log4j.rootLogger=info, console
#console log #console log
log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console=org.apache.log4j.ConsoleAppender

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Common</artifactId> <artifactId>Mage-Common</artifactId>
@ -24,6 +24,31 @@
<groupId>com.googlecode.jspf</groupId> <groupId>com.googlecode.jspf</groupId>
<artifactId>jspf-core</artifactId> <artifactId>jspf-core</artifactId>
<version>${jspf-version}</version> <version>${jspf-version}</version>
</dependency>
<dependency>
<groupId>org.jboss.remoting</groupId>
<artifactId>jboss-remoting</artifactId>
<version>2.5.4.SP2</version>
</dependency>
<dependency>
<groupId>jboss</groupId>
<artifactId>jboss-common-core</artifactId>
<version>2.2.16.GA</version>
</dependency>
<dependency>
<groupId>jboss</groupId>
<artifactId>jboss-serialization</artifactId>
<version>1.0.3.GA</version>
</dependency>
<dependency>
<groupId>concurrent</groupId>
<artifactId>concurrent</artifactId>
<version>1.3.4</version>
</dependency>
<dependency>
<groupId>trove</groupId>
<artifactId>trove</artifactId>
<version>1.0.2</version>
</dependency> </dependency>
</dependencies> </dependencies>

View file

@ -0,0 +1,124 @@
/*
* 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 mage.game.match.MatchOptions;
import java.util.List;
import java.util.UUID;
import mage.MageException;
import mage.cards.decks.DeckCardLists;
import mage.game.GameException;
import mage.game.tournament.TournamentOptions;
import mage.utils.MageVersion;
import mage.view.DraftPickView;
import mage.view.TableView;
import mage.view.GameView;
import mage.view.TournamentView;
import mage.view.UserView;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public interface MageServer {
public boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException;
public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException;
public void deregisterClient(String sessionId) throws MageException;
public ServerState getServerState() throws MageException;
//table methods
public TableView createTable(String sessionId, UUID roomId, MatchOptions matchOptions) throws MageException;
public TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions tournamentOptions) throws MageException;
public boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException, GameException;
public boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill) throws MageException, GameException;
public boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException;
public boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException;
public void leaveTable(String sessionId, UUID roomId, UUID tableId) throws MageException;
public void swapSeats(String sessionId, UUID roomId, UUID tableId, int seatNum1, int seatNum2) throws MageException;
public void removeTable(String sessionId, UUID roomId, UUID tableId) throws MageException;
public boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException;
public TableView getTable(UUID roomId, UUID tableId) throws MageException;
public List<TableView> getTables(UUID roomId) throws MageException;
public List<String> getConnectedPlayers(UUID roomId) throws MageException;
//chat methods
public void sendChatMessage(UUID chatId, String userName, String message) throws MageException;
public void joinChat(UUID chatId, String sessionId, String userName) throws MageException;
public void leaveChat(UUID chatId, String sessionId) throws MageException;
public UUID getTableChatId(UUID tableId) throws MageException;
public UUID getGameChatId(UUID gameId) throws MageException;
public UUID getRoomChatId(UUID roomId) throws MageException;
public UUID getTournamentChatId(UUID tournamentId) throws MageException;
//room methods
public UUID getMainRoomId() throws MageException;
//game methods
public void startMatch(String sessionId, UUID roomId, UUID tableId) throws MageException;
public void joinGame(UUID gameId, String sessionId) throws MageException;
public void watchGame(UUID gameId, String sessionId) throws MageException;
public void stopWatching(UUID gameId, String sessionId) throws MageException;
public void sendPlayerUUID(UUID gameId, String sessionId, UUID data) throws MageException;
public void sendPlayerString(UUID gameId, String sessionId, String data) throws MageException;
public void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data) throws MageException;
public void sendPlayerInteger(UUID gameId, String sessionId, Integer data) throws MageException;
public void concedeGame(UUID gameId, String sessionId) throws MageException;
//tournament methods
public void startTournament(String sessionId, UUID roomId, UUID tableId) throws MageException;
public void joinTournament(UUID draftId, String sessionId) throws MageException;
public TournamentView getTournament(UUID tournamentId) throws MageException;
//draft methods
public void joinDraft(UUID draftId, String sessionId) throws MageException;
public DraftPickView sendCardPick(UUID draftId, String sessionId, UUID cardId) throws MageException;
//challenge methods
public void startChallenge(String sessionId, UUID roomId, UUID tableId, UUID challengeId) throws MageException;
//replay methods
public void replayGame(UUID gameId, String sessionId) throws MageException;
public void startReplay(UUID gameId, String sessionId) throws MageException;
public void stopReplay(UUID gameId, String sessionId) throws MageException;
public void nextPlay(UUID gameId, String sessionId) throws MageException;
public void previousPlay(UUID gameId, String sessionId) throws MageException;
//test methods
public void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList) throws MageException;
public boolean cheat(UUID gameId, String sessionId, UUID playerId, String cardName) throws MageException;
public GameView getGameView(UUID gameId, String sessionId, UUID playerId) throws MageException;
//admin methods
public List<UserView> getUsers(String sessionId) throws MageException;
public void disconnectUser(String sessionId, String userSessionId) throws MageException;
public void removeTable(String sessionId, UUID tableId) throws MageException;
}

View file

@ -1,129 +0,0 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.interfaces;
import mage.game.match.MatchOptions;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
import java.util.UUID;
import mage.MageException;
import mage.cards.decks.DeckCardLists;
import mage.game.GameException;
import mage.game.tournament.TournamentOptions;
import mage.interfaces.callback.CallbackServer;
import mage.utils.MageVersion;
import mage.view.DraftPickView;
import mage.view.TableView;
import mage.view.GameView;
import mage.view.TournamentView;
import mage.view.UserView;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public interface Server extends Remote, CallbackServer {
public UUID registerClient(String userName, UUID clientId, MageVersion version) throws RemoteException, MageException;
public UUID registerAdmin(String password, MageVersion version) throws RemoteException, MageException;
public void deregisterClient(UUID sessionId) throws RemoteException, MageException;
public void ack(String message, UUID sessionId) throws RemoteException, MageException;
public boolean ping(UUID sessionId) throws RemoteException, MageException;
public ServerState getServerState() throws RemoteException, MageException;
//table methods
public TableView createTable(UUID sessionId, UUID roomId, MatchOptions matchOptions) throws RemoteException, MageException;
public TableView createTournamentTable(UUID sessionId, UUID roomId, TournamentOptions tournamentOptions) throws RemoteException, MageException;
public boolean joinTable(UUID sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws RemoteException, MageException, GameException;
public boolean joinTournamentTable(UUID sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill) throws RemoteException, MageException, GameException;
public boolean submitDeck(UUID sessionId, UUID tableId, DeckCardLists deckList) throws RemoteException, MageException, GameException;
public boolean watchTable(UUID sessionId, UUID roomId, UUID tableId) throws RemoteException, MageException;
public void leaveTable(UUID sessionId, UUID roomId, UUID tableId) throws RemoteException, MageException;
public void swapSeats(UUID sessionId, UUID roomId, UUID tableId, int seatNum1, int seatNum2) throws RemoteException, MageException;
public void removeTable(UUID sessionId, UUID roomId, UUID tableId) throws RemoteException, MageException;
public boolean isTableOwner(UUID sessionId, UUID roomId, UUID tableId) throws RemoteException, MageException;
public TableView getTable(UUID roomId, UUID tableId) throws RemoteException, MageException;
public List<TableView> getTables(UUID roomId) throws RemoteException, MageException;
public List<String> getConnectedPlayers(UUID roomId) throws RemoteException, MageException;
//chat methods
public void sendChatMessage(UUID chatId, String userName, String message) throws RemoteException, MageException;
public void joinChat(UUID chatId, UUID sessionId, String userName) throws RemoteException, MageException;
public void leaveChat(UUID chatId, UUID sessionId) throws RemoteException, MageException;
public UUID getTableChatId(UUID tableId) throws RemoteException, MageException;
public UUID getGameChatId(UUID gameId) throws RemoteException, MageException;
public UUID getRoomChatId(UUID roomId) throws RemoteException, MageException;
public UUID getTournamentChatId(UUID tournamentId) throws RemoteException, MageException;
//room methods
public UUID getMainRoomId() throws RemoteException, MageException;
//game methods
public void startMatch(UUID sessionId, UUID roomId, UUID tableId) throws RemoteException, MageException;
public void joinGame(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void watchGame(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void stopWatching(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void sendPlayerUUID(UUID gameId, UUID sessionId, UUID data) throws RemoteException, MageException;
public void sendPlayerString(UUID gameId, UUID sessionId, String data) throws RemoteException, MageException;
public void sendPlayerBoolean(UUID gameId, UUID sessionId, Boolean data) throws RemoteException, MageException;
public void sendPlayerInteger(UUID gameId, UUID sessionId, Integer data) throws RemoteException, MageException;
public void concedeGame(UUID gameId, UUID sessionId) throws RemoteException, MageException;
//tournament methods
public void startTournament(UUID sessionId, UUID roomId, UUID tableId) throws RemoteException, MageException;
public void joinTournament(UUID draftId, UUID sessionId) throws RemoteException, MageException;
public TournamentView getTournament(UUID tournamentId) throws RemoteException, MageException;
//draft methods
public void joinDraft(UUID draftId, UUID sessionId) throws RemoteException, MageException;
public DraftPickView sendCardPick(UUID draftId, UUID sessionId, UUID cardId) throws RemoteException, MageException;
//challenge methods
public void startChallenge(UUID sessionId, UUID roomId, UUID tableId, UUID challengeId) throws RemoteException, MageException;
//replay methods
public void replayGame(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void startReplay(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void stopReplay(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void nextPlay(UUID gameId, UUID sessionId) throws RemoteException, MageException;
public void previousPlay(UUID gameId, UUID sessionId) throws RemoteException, MageException;
//test methods
public void cheat(UUID gameId, UUID sessionId, UUID playerId, DeckCardLists deckList) throws RemoteException, MageException;
public boolean cheat(UUID gameId, UUID sessionId, UUID playerId, String cardName) throws RemoteException, MageException;
public GameView getGameView(UUID gameId, UUID sessionId, UUID playerId) throws RemoteException, MageException;
//admin methods
public List<UserView> getUsers(UUID sessionId) throws RemoteException, MageException;
public void disconnectUser(UUID sessionId, UUID userSessionId) throws RemoteException, MageException;
public void removeTable(UUID sessionId, UUID tableId) throws RemoteException, MageException;
}

View file

@ -1,82 +0,0 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.interfaces.callback;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class CallbackClientDaemon extends Thread {
private final static Logger logger = Logger.getLogger(CallbackClientDaemon.class);
private static ExecutorService callbackExecutor = Executors.newCachedThreadPool();
private final CallbackClient client;
private final CallbackServer server;
private final UUID id;
public CallbackClientDaemon(UUID id, CallbackClient client, CallbackServer server) {
this.client = client;
this.server = server;
this.id = id;
setDaemon(true);
start();
}
@Override
public void run() {
try {
while(true) {
final ClientCallback callback = server.callback(id);
callbackExecutor.submit(
new Runnable() {
@Override
public void run() {
try {
if (callback != null) {
client.processCallback(callback);
}
}
catch (Exception ex) {
logger.fatal("CallbackClientDaemon error ", ex);
}
}
}
);
}
} catch(Exception ex) {
logger.fatal("CallbackClientDaemon error ", ex);
}
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright 2011 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.callback;
import mage.MageException;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class CallbackException extends MageException {
public CallbackException(String message) {
super(message);
}
public CallbackException(Throwable t) {
super(t);
}
}

View file

@ -1,42 +0,0 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.interfaces.callback;
import java.rmi.RemoteException;
import java.util.UUID;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public interface CallbackServer {
public ClientCallback callback(UUID clientId) throws RemoteException;
}

View file

@ -1,110 +0,0 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.interfaces.callback;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class CallbackServerSession {
private final static Logger logger = Logger.getLogger(CallbackServerSession.class);
private final ClientCallback callback = new ClientCallback();
private final ReentrantLock lock = new ReentrantLock();
private final Condition waiting = lock.newCondition();
private final Condition callbackCalled = lock.newCondition();
private boolean waitingForCallback;
private boolean threadAlive = true;
/**
*
* blocks the thread until a callback is requested
*
* @return ClientCallback - the callback requested
*/
public ClientCallback callback() throws InterruptedException {
callback.clear();
lock.lock();
try {
waitingForCallback = true;
waiting.signal();
while (callback.getMethod() == null && threadAlive) {
logger.trace("waiting for callback");
callbackCalled.await();
}
waitingForCallback = false;
logger.trace("callback called:" + callback.getMethod());
return callback;
}
finally {
lock.unlock();
}
}
/**
*
* requests a callback
*
* @param call - the callback to request
*/
public void setCallback(ClientCallback call) throws InterruptedException {
lock.lock();
try {
while (!waitingForCallback) {
logger.trace("waiting for callback state to call:" + call.getMethod());
waiting.await();
}
callback.setMethod(call.getMethod());
callback.setData(call.getData());
callback.setObjectId(call.getObjectId());
callback.setMessageId(call.getMessageId());
callbackCalled.signal();
}
finally {
lock.unlock();
}
}
public void destroy() {
lock.lock();
try {
threadAlive = false;
callbackCalled.signal();
}
finally {
lock.unlock();
}
}
}

View file

@ -28,9 +28,12 @@
package mage.remote; package mage.remote;
import java.rmi.registry.LocateRegistry; import java.net.Inet4Address;
import java.rmi.registry.Registry; import java.net.InetAddress;
import mage.interfaces.Server; import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/** /**
* *
@ -48,19 +51,12 @@ public class Connection {
private String proxyUsername; private String proxyUsername;
private String proxyPassword; private String proxyPassword;
// protected Server getServer() { private static final String serialization = "?serializationtype=jboss";
// Server server = null; private static final String transport = "bisocket";
// try {
// Registry reg = LocateRegistry.getRegistry(host, port);
// server = (Server) reg.lookup("mage-server");
// }
// catch (Exception ignored) {}
// return server;
// }
@Override @Override
public int hashCode() { public int hashCode() {
return (host + Integer.toString(port) + proxyType.toString()).hashCode(); return (transport + host + Integer.toString(port) + proxyType.toString()).hashCode();
} }
@Override @Override
@ -74,11 +70,18 @@ public class Connection {
@Override @Override
public String toString() { public String toString() {
return host + ":" + Integer.toString(port); return host + ":" + Integer.toString(port) + "/" + serialization;
} }
public String getURI() { public String getURI() {
return "bisocket://" + host + ":" + port; if (host.equals("localhost")) {
try {
return transport + "://" + getLocalAddress().getHostAddress() + ":" + port + "/" + serialization;
} catch (SocketException ex) {
// just use localhost if can't find local ip
}
}
return transport + "://" + host + ":" + port + "/" + serialization;
} }
public ProxyType getProxyType() { public ProxyType getProxyType() {
@ -175,4 +178,20 @@ public class Connection {
this.proxyPassword = proxyPassword; this.proxyPassword = proxyPassword;
} }
public static InetAddress getLocalAddress() throws SocketException {
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
NetworkInterface iface = interfaces.nextElement( );
if (iface.isLoopback())
continue;
for (InterfaceAddress addr: iface.getInterfaceAddresses())
{
InetAddress iaddr = addr.getAddress();
if (iaddr instanceof Inet4Address) {
return iaddr;
}
}
}
return null;
}
} }

File diff suppressed because it is too large Load diff

View file

@ -39,10 +39,10 @@ public class UserView implements Serializable {
private String userName; private String userName;
private String host; private String host;
private UUID sessionId; private String sessionId;
private Date timeConnected; private Date timeConnected;
public UserView(String userName, String host, UUID sessionId, Date timeConnected) { public UserView(String userName, String host, String sessionId, Date timeConnected) {
this.userName = userName; this.userName = userName;
this.host = host; this.host = host;
this.sessionId = sessionId; this.sessionId = sessionId;
@ -57,7 +57,7 @@ public class UserView implements Serializable {
return host; return host;
} }
public UUID getSessionId() { public String getSessionId() {
return sessionId; return sessionId;
} }

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Plugins</artifactId> <artifactId>Mage-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Card-Plugin</artifactId> <artifactId>Mage-Card-Plugin</artifactId>
@ -76,7 +76,7 @@
</build> </build>
<properties> <properties>
<plugin-version>0.6</plugin-version> <plugin-version>0.5</plugin-version>
<jspf-version>0.9.1</jspf-version> <jspf-version>0.9.1</jspf-version>
</properties> </properties>
</project> </project>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Plugins</artifactId> <artifactId>Mage-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Counter-Plugin</artifactId> <artifactId>Mage-Counter-Plugin</artifactId>

View file

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Plugins</artifactId> <artifactId>Mage-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>

View file

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Plugins</artifactId> <artifactId>Mage-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Theme-Plugin</artifactId> <artifactId>Mage-Theme-Plugin</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Plugins</artifactId> <artifactId>Mage-Plugins</artifactId>

View file

@ -1,33 +1,34 @@
<?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>mage-root</artifactId> <parent>
<groupId>org.mage</groupId>
<artifactId>mage-root</artifactId>
<version>0.8.0</version>
</parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<version>0.7.4</version> <artifactId>Mage.Server.Console</artifactId>
</parent> <packaging>jar</packaging>
<groupId>org.mage</groupId> <name>Mage Server Console</name>
<artifactId>Mage.Server.Console</artifactId>
<version>0.8</version> <dependencies>
<name>Mage Server Console</name> <dependency>
<url>http://maven.apache.org</url> <groupId>org.mage</groupId>
<dependencies> <artifactId>Mage-Common</artifactId>
<dependency> <version>${project.version}</version>
<groupId>junit</groupId> </dependency>
<artifactId>junit</artifactId> <dependency>
<version>3.8.1</version> <groupId>org.swinglabs</groupId>
<scope>test</scope> <artifactId>swingx</artifactId>
</dependency> <version>1.6.1</version>
<dependency> </dependency>
<groupId>${project.groupId}</groupId> <dependency>
<artifactId>Mage-Common</artifactId> <groupId>junit</groupId>
<version>0.7.4</version> <artifactId>junit</artifactId>
</dependency> <version>4.8.2</version>
<dependency> </dependency>
<groupId>org.swinglabs</groupId> </dependencies>
<artifactId>swingx</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</project> </project>

View file

@ -1,6 +1,6 @@
<?xml version="1.1" encoding="UTF-8" ?> <?xml version="1.1" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo"> <Form version="1.5" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
<Properties> <Properties>
<Property name="title" type="java.lang.String" value="Connect"/> <Property name="title" type="java.lang.String" value="Connect"/>
</Properties> </Properties>
@ -25,40 +25,45 @@
<Group type="102" attributes="0"> <Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0"> <Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0"> <Group type="102" alignment="1" attributes="0">
<Component id="lblStatus" pref="271" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnConnect" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnCancel" min="-2" max="-2" attributes="0"/>
</Group>
<Component id="pnlProxySettings" alignment="0" max="32767" attributes="0"/>
<Group type="102" alignment="0" attributes="0">
<Component id="lblProxyType" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="chkAutoConnect" alignment="0" pref="383" max="32767" attributes="0"/>
<Component id="cbProxyType" alignment="0" min="-2" pref="126" max="-2" attributes="0"/>
</Group>
</Group>
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="6" max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0"> <Group type="103" groupAlignment="1" attributes="0">
<Group type="102" alignment="1" attributes="0"> <Component id="lblPassword" alignment="1" min="-2" max="-2" attributes="0"/>
<Component id="btnConnect" min="-2" max="-2" attributes="0"/> <Component id="lblServer" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/> <Component id="lblPort" alignment="1" min="-2" max="-2" attributes="0"/>
<Component id="btnCancel" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<Group type="103" groupAlignment="1" attributes="0">
<Component id="lblPort" alignment="1" min="-2" max="-2" attributes="0"/>
<Component id="lblServer" min="-2" max="-2" attributes="0"/>
<Component id="lblUserName" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<Component id="txtPort" min="-2" pref="71" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="131" max="-2" attributes="0"/>
</Group>
<Component id="txtPassword" alignment="0" pref="276" max="32767" attributes="0"/>
<Component id="chkAutoConnect" alignment="0" pref="276" max="32767" attributes="0"/>
<Component id="chkUseProxy" alignment="0" pref="276" max="32767" attributes="0"/>
<Group type="102" alignment="1" attributes="0">
<Component id="txtServer" pref="205" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton1" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
</Group>
</Group> </Group>
<EmptySpace max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0">
<Component id="txtPassword" pref="359" max="32767" attributes="0"/>
<Group type="102" alignment="0" attributes="0">
<Component id="txtPort" min="-2" pref="71" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="131" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<Component id="txtServer" pref="288" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton1" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
</Group> </Group>
<Component id="pnlProxy" alignment="1" max="32767" attributes="0"/>
</Group> </Group>
<EmptySpace max="-2" attributes="0"/>
</Group> </Group>
</Group> </Group>
</DimensionLayout> </DimensionLayout>
@ -76,23 +81,27 @@
<Component id="txtPort" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="txtPort" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="lblPort" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="lblPort" alignment="3" min="-2" max="-2" attributes="0"/>
</Group> </Group>
<EmptySpace min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0"> <Group type="103" groupAlignment="3" attributes="0">
<Component id="txtPassword" min="-2" max="-2" attributes="0"/> <Component id="txtPassword" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="lblUserName" min="-2" max="-2" attributes="0"/> <Component id="lblPassword" alignment="3" min="-2" max="-2" attributes="0"/>
</Group> </Group>
<EmptySpace min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
<Component id="chkAutoConnect" min="-2" max="-2" attributes="0"/> <Component id="chkAutoConnect" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" max="-2" attributes="0"/> <EmptySpace min="-2" max="-2" attributes="0"/>
<Component id="chkUseProxy" min="-2" max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0">
<EmptySpace min="-2" max="-2" attributes="0"/> <Component id="cbProxyType" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="pnlProxy" max="32767" attributes="0"/> <Component id="lblProxyType" alignment="3" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" max="-2" attributes="0"/> </Group>
<EmptySpace max="-2" attributes="0"/>
<Component id="pnlProxySettings" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0"> <Group type="103" groupAlignment="3" attributes="0">
<Component id="btnCancel" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="btnCancel" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnConnect" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="btnConnect" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="lblStatus" alignment="3" min="-2" max="-2" attributes="0"/>
</Group> </Group>
<EmptySpace min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/>
</Group> </Group>
</Group> </Group>
</DimensionLayout> </DimensionLayout>
@ -121,16 +130,6 @@
<EventHandler event="keyTyped" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="keyTyped"/> <EventHandler event="keyTyped" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="keyTyped"/>
</Events> </Events>
</Component> </Component>
<Component class="javax.swing.JTextField" name="txtPassword">
</Component>
<Component class="javax.swing.JLabel" name="lblUserName">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtPassword"/>
</Property>
<Property name="text" type="java.lang.String" value="Password:"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="btnConnect"> <Component class="javax.swing.JButton" name="btnConnect">
<Properties> <Properties>
<Property name="text" type="java.lang.String" value="Connect"/> <Property name="text" type="java.lang.String" value="Connect"/>
@ -155,77 +154,6 @@
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="chkAutoConnectActionPerformed"/> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="chkAutoConnectActionPerformed"/>
</Events> </Events>
</Component> </Component>
<Component class="javax.swing.JCheckBox" name="chkUseProxy">
<Properties>
<Property name="text" type="java.lang.String" value="Use Proxy"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="chkUseProxyActionPerformed"/>
</Events>
</Component>
<Container class="javax.swing.JPanel" name="pnlProxy">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0">
<Component id="lblProxyPort" alignment="1" min="-2" max="-2" attributes="0"/>
<Component id="lblProxyServer" alignment="1" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="txtProxyPort" min="-2" pref="71" max="-2" attributes="0"/>
<Component id="txtProxyServer" alignment="0" pref="260" max="32767" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="30" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<Group type="103" groupAlignment="3" attributes="0">
<Component id="lblProxyServer" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtProxyServer" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="lblProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="lblProxyServer">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtServer"/>
</Property>
<Property name="text" type="java.lang.String" value="Server:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtProxyServer">
</Component>
<Component class="javax.swing.JLabel" name="lblProxyPort">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtPort"/>
</Property>
<Property name="text" type="java.lang.String" value="Port:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtProxyPort">
<Events>
<EventHandler event="keyTyped" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="txtProxyPortkeyTyped"/>
</Events>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JButton" name="jButton1"> <Component class="javax.swing.JButton" name="jButton1">
<Properties> <Properties>
<Property name="text" type="java.lang.String" value="Find..."/> <Property name="text" type="java.lang.String" value="Find..."/>
@ -233,8 +161,191 @@
<Property name="name" type="java.lang.String" value="findServerBtn" noResource="true"/> <Property name="name" type="java.lang.String" value="findServerBtn" noResource="true"/>
</Properties> </Properties>
<Events> <Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="findPublicServerActionPerformed"/>
</Events> </Events>
</Component> </Component>
<Component class="javax.swing.JComboBox" name="cbProxyType">
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="cbProxyTypeActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JLabel" name="lblProxyType">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="cbProxyType"/>
</Property>
<Property name="text" type="java.lang.String" value="Proxy:"/>
</Properties>
</Component>
<Container class="javax.swing.JPanel" name="pnlProxySettings">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.EtchedBorderInfo">
<EtchetBorder/>
</Border>
</Property>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[0, 0]"/>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="pnlProxyAuth" alignment="0" max="32767" attributes="0"/>
<Component id="pnlProxy" alignment="0" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="pnlProxy" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Component id="pnlProxyAuth" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="pnlProxy">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0">
<Component id="lblProxyServer" min="-2" pref="57" max="-2" attributes="0"/>
<Component id="lblProxyPort" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0">
<Component id="txtProxyPort" alignment="0" min="-2" pref="71" max="-2" attributes="0"/>
<Component id="txtProxyServer" pref="334" max="32767" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="lblProxyServer" min="-2" max="-2" attributes="0"/>
<Component id="txtProxyServer" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="txtProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="lblProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="lblProxyServer">
<Properties>
<Property name="horizontalAlignment" type="int" value="4"/>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtProxyServer"/>
</Property>
<Property name="text" type="java.lang.String" value="Server:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtProxyServer">
</Component>
<Component class="javax.swing.JLabel" name="lblProxyPort">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtProxyPort"/>
</Property>
<Property name="text" type="java.lang.String" value="Port:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtProxyPort">
<Events>
<EventHandler event="keyTyped" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="txtProxyPortkeyTyped"/>
</Events>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="pnlProxyAuth">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="lblProxyPassword" min="-2" max="-2" attributes="0"/>
<Component id="lblProxyUserName" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="txtPasswordField" pref="335" max="32767" attributes="1"/>
<Component id="txtProxyUserName" alignment="0" pref="335" max="32767" attributes="1"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Group type="103" groupAlignment="3" attributes="0">
<Component id="txtProxyUserName" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="lblProxyUserName" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace pref="8" max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="txtPasswordField" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="lblProxyPassword" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="lblProxyUserName">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtProxyUserName"/>
</Property>
<Property name="text" type="java.lang.String" value="User Name:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtProxyUserName">
</Component>
<Component class="javax.swing.JLabel" name="lblProxyPassword">
<Properties>
<Property name="text" type="java.lang.String" value="Password:"/>
</Properties>
</Component>
<Component class="javax.swing.JPasswordField" name="txtPasswordField">
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="txtPasswordFieldActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Container>
<Component class="javax.swing.JLabel" name="lblPassword">
<Properties>
<Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
<ComponentRef name="txtPassword"/>
</Property>
<Property name="text" type="java.lang.String" value="Password:"/>
</Properties>
</Component>
<Component class="javax.swing.JPasswordField" name="txtPassword">
</Component>
<Component class="javax.swing.JLabel" name="lblStatus">
</Component>
</SubComponents> </SubComponents>
</Form> </Form>

View file

@ -39,10 +39,18 @@ import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog; import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import mage.remote.Connection;
import mage.remote.Connection.ProxyType;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -53,22 +61,26 @@ import org.apache.log4j.Logger;
public class ConnectDialog extends JDialog { public class ConnectDialog extends JDialog {
private final static Logger logger = Logger.getLogger(ConnectDialog.class); private final static Logger logger = Logger.getLogger(ConnectDialog.class);
private ConsoleFrame console; private ConsoleFrame console;
private Connection connection;
private ConnectTask task;
/** Creates new form ConnectDialog */ /** Creates new form ConnectDialog */
public ConnectDialog() { public ConnectDialog() {
initComponents(); initComponents();
cbProxyType.setModel(new DefaultComboBoxModel(Connection.ProxyType.values()));
} }
public void showDialog(ConsoleFrame console) { public void showDialog(ConsoleFrame console) {
this.console = console; this.console = console;
this.txtServer.setText(ConsoleFrame.getPreferences().get("serverAddress", "")); this.txtServer.setText(ConsoleFrame.getPreferences().get("serverAddress", "localhost"));
this.txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", "")); this.txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", Integer.toString(17171)));
this.chkAutoConnect.setSelected(Boolean.parseBoolean(ConsoleFrame.getPreferences().get("autoConnect", "false"))); this.chkAutoConnect.setSelected(Boolean.parseBoolean(ConsoleFrame.getPreferences().get("autoConnect", "false")));
this.txtProxyServer.setText(ConsoleFrame.getPreferences().get("proxyAddress", "")); this.txtProxyServer.setText(ConsoleFrame.getPreferences().get("proxyAddress", "localhost"));
this.txtProxyPort.setText(ConsoleFrame.getPreferences().get("proxyPort", "")); this.txtProxyPort.setText(ConsoleFrame.getPreferences().get("proxyPort", Integer.toString(17171)));
this.chkUseProxy.setSelected(Boolean.parseBoolean(ConsoleFrame.getPreferences().get("useProxy", "false"))); this.cbProxyType.setSelectedItem(Connection.ProxyType.valueOf(ConsoleFrame.getPreferences().get("proxyType", "NONE").toUpperCase()));
this.txtProxyUserName.setText(ConsoleFrame.getPreferences().get("proxyUsername", ""));
this.txtPasswordField.setText(ConsoleFrame.getPreferences().get("proxyPassword", ""));
this.showProxySettings(); this.showProxySettings();
this.setModal(true); this.setModal(true);
this.setLocation(50, 50); this.setLocation(50, 50);
@ -76,14 +88,22 @@ public class ConnectDialog extends JDialog {
} }
private void showProxySettings() { private void showProxySettings() {
if (chkUseProxy.isSelected()) { if (cbProxyType.getSelectedItem() == Connection.ProxyType.SOCKS) {
this.pnlProxy.setVisible(true); this.pnlProxy.setVisible(true);
this.pnlProxyAuth.setVisible(false);
this.pnlProxySettings.setVisible(true);
} }
else { else if (cbProxyType.getSelectedItem() == Connection.ProxyType.HTTP) {
this.pnlProxy.setVisible(true);
this.pnlProxyAuth.setVisible(true);
this.pnlProxySettings.setVisible(true);
}
else if (cbProxyType.getSelectedItem() == Connection.ProxyType.NONE) {
this.pnlProxy.setVisible(false); this.pnlProxy.setVisible(false);
this.pnlProxyAuth.setVisible(false);
this.pnlProxySettings.setVisible(false);
} }
this.pack(); this.pack();
// this.revalidate();
this.repaint(); this.repaint();
} }
@ -93,7 +113,11 @@ public class ConnectDialog extends JDialog {
ConsoleFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected())); ConsoleFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected()));
ConsoleFrame.getPreferences().put("proxyAddress", txtProxyServer.getText()); ConsoleFrame.getPreferences().put("proxyAddress", txtProxyServer.getText());
ConsoleFrame.getPreferences().put("proxyPort", txtProxyPort.getText()); ConsoleFrame.getPreferences().put("proxyPort", txtProxyPort.getText());
ConsoleFrame.getPreferences().put("useProxy", Boolean.toString(chkUseProxy.isSelected())); ConsoleFrame.getPreferences().put("proxyType", cbProxyType.getSelectedItem().toString());
ConsoleFrame.getPreferences().put("proxyUsername", txtProxyUserName.getText());
char[] input = txtPasswordField.getPassword();
ConsoleFrame.getPreferences().put("proxyPassword", new String(input));
Arrays.fill(input, '0');
} }
/** This method is called from within the constructor to /** This method is called from within the constructor to
@ -109,18 +133,26 @@ public class ConnectDialog extends JDialog {
lblServer = new javax.swing.JLabel(); lblServer = new javax.swing.JLabel();
lblPort = new javax.swing.JLabel(); lblPort = new javax.swing.JLabel();
txtPort = new javax.swing.JTextField(); txtPort = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
lblUserName = new javax.swing.JLabel();
btnConnect = new javax.swing.JButton(); btnConnect = new javax.swing.JButton();
btnCancel = new javax.swing.JButton(); btnCancel = new javax.swing.JButton();
chkAutoConnect = new javax.swing.JCheckBox(); chkAutoConnect = new javax.swing.JCheckBox();
chkUseProxy = new javax.swing.JCheckBox(); jButton1 = new javax.swing.JButton();
cbProxyType = new javax.swing.JComboBox();
lblProxyType = new javax.swing.JLabel();
pnlProxySettings = new javax.swing.JPanel();
pnlProxy = new javax.swing.JPanel(); pnlProxy = new javax.swing.JPanel();
lblProxyServer = new javax.swing.JLabel(); lblProxyServer = new javax.swing.JLabel();
txtProxyServer = new javax.swing.JTextField(); txtProxyServer = new javax.swing.JTextField();
lblProxyPort = new javax.swing.JLabel(); lblProxyPort = new javax.swing.JLabel();
txtProxyPort = new javax.swing.JTextField(); txtProxyPort = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton(); pnlProxyAuth = new javax.swing.JPanel();
lblProxyUserName = new javax.swing.JLabel();
txtProxyUserName = new javax.swing.JTextField();
lblProxyPassword = new javax.swing.JLabel();
txtPasswordField = new javax.swing.JPasswordField();
lblPassword = new javax.swing.JLabel();
txtPassword = new javax.swing.JPasswordField();
lblStatus = new javax.swing.JLabel();
setTitle("Connect"); setTitle("Connect");
@ -136,9 +168,6 @@ public class ConnectDialog extends JDialog {
} }
}); });
lblUserName.setLabelFor(txtPassword);
lblUserName.setText("Password:");
btnConnect.setText("Connect"); btnConnect.setText("Connect");
btnConnect.addActionListener(new java.awt.event.ActionListener() { btnConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
@ -160,17 +189,32 @@ public class ConnectDialog extends JDialog {
} }
}); });
chkUseProxy.setText("Use Proxy"); jButton1.setText("Find...");
chkUseProxy.addActionListener(new java.awt.event.ActionListener() { jButton1.setToolTipText("Find public server");
jButton1.setName("findServerBtn"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
chkUseProxyActionPerformed(evt); findPublicServerActionPerformed(evt);
} }
}); });
lblProxyServer.setLabelFor(txtServer); cbProxyType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbProxyTypeActionPerformed(evt);
}
});
lblProxyType.setLabelFor(cbProxyType);
lblProxyType.setText("Proxy:");
pnlProxySettings.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlProxySettings.setMinimumSize(new java.awt.Dimension(0, 0));
lblProxyServer.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
lblProxyServer.setLabelFor(txtProxyServer);
lblProxyServer.setText("Server:"); lblProxyServer.setText("Server:");
lblProxyPort.setLabelFor(txtPort); lblProxyPort.setLabelFor(txtProxyPort);
lblProxyPort.setText("Port:"); lblProxyPort.setText("Port:");
txtProxyPort.addKeyListener(new java.awt.event.KeyAdapter() { txtProxyPort.addKeyListener(new java.awt.event.KeyAdapter() {
@ -186,36 +230,86 @@ public class ConnectDialog extends JDialog {
.addGroup(pnlProxyLayout.createSequentialGroup() .addGroup(pnlProxyLayout.createSequentialGroup()
.addContainerGap() .addContainerGap()
.addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblProxyPort) .addComponent(lblProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblProxyServer)) .addComponent(lblProxyPort))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtProxyPort, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)) .addComponent(txtProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE))
.addGap(30, 30, 30)) .addContainerGap())
); );
pnlProxyLayout.setVerticalGroup( pnlProxyLayout.setVerticalGroup(
pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlProxyLayout.createSequentialGroup() .addGroup(pnlProxyLayout.createSequentialGroup()
.addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addContainerGap()
.addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblProxyServer) .addComponent(lblProxyServer)
.addComponent(txtProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblProxyPort) .addComponent(txtProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lblProxyPort))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
); );
jButton1.setText("Find..."); lblProxyUserName.setLabelFor(txtProxyUserName);
jButton1.setToolTipText("Find public server"); lblProxyUserName.setText("User Name:");
jButton1.setName("findServerBtn"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() { lblProxyPassword.setText("Password:");
txtPasswordField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) { public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt); txtPasswordFieldActionPerformed(evt);
} }
}); });
javax.swing.GroupLayout pnlProxyAuthLayout = new javax.swing.GroupLayout(pnlProxyAuth);
pnlProxyAuth.setLayout(pnlProxyAuthLayout);
pnlProxyAuthLayout.setHorizontalGroup(
pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlProxyAuthLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblProxyPassword)
.addComponent(lblProxyUserName))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
.addComponent(txtProxyUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE))
.addContainerGap())
);
pnlProxyAuthLayout.setVerticalGroup(
pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlProxyAuthLayout.createSequentialGroup()
.addGroup(pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtProxyUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblProxyUserName))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addGroup(pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblProxyPassword))
.addContainerGap())
);
javax.swing.GroupLayout pnlProxySettingsLayout = new javax.swing.GroupLayout(pnlProxySettings);
pnlProxySettings.setLayout(pnlProxySettingsLayout);
pnlProxySettingsLayout.setHorizontalGroup(
pnlProxySettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlProxyAuth, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlProxy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pnlProxySettingsLayout.setVerticalGroup(
pnlProxySettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlProxySettingsLayout.createSequentialGroup()
.addComponent(pnlProxy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlProxyAuth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
lblPassword.setLabelFor(txtPassword);
lblPassword.setText("Password:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout); getContentPane().setLayout(layout);
layout.setHorizontalGroup( layout.setHorizontalGroup(
@ -223,31 +317,36 @@ public class ConnectDialog extends JDialog {
.addGroup(layout.createSequentialGroup() .addGroup(layout.createSequentialGroup()
.addContainerGap() .addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnConnect)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancel))
.addComponent(pnlProxySettings, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup() .addGroup(layout.createSequentialGroup()
.addComponent(lblProxyType)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chkAutoConnect, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
.addComponent(cbProxyType, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup() .addComponent(lblPassword)
.addComponent(btnConnect) .addComponent(lblServer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblPort))
.addComponent(btnCancel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblPort) .addGap(131, 131, 131))
.addComponent(lblServer) .addGroup(layout.createSequentialGroup()
.addComponent(lblUserName)) .addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1)))))
.addGroup(layout.createSequentialGroup() .addContainerGap())
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(131, 131, 131))
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addComponent(chkAutoConnect, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addComponent(chkUseProxy, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)))))
.addContainerGap())
.addComponent(pnlProxy, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
); );
layout.setVerticalGroup( layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
@ -262,19 +361,22 @@ public class ConnectDialog extends JDialog {
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblPort)) .addComponent(lblPort))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblUserName)) .addComponent(lblPassword))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chkAutoConnect) .addComponent(chkAutoConnect)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chkUseProxy) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbProxyType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblProxyType))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlProxy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(pnlProxySettings, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCancel) .addComponent(btnCancel)
.addComponent(btnConnect)) .addComponent(btnConnect)
.addComponent(lblStatus))
.addContainerGap()) .addContainerGap())
); );
@ -283,12 +385,15 @@ public class ConnectDialog extends JDialog {
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
ConsoleFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected())); ConsoleFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected()));
this.setVisible(false); if (task != null && !task.isDone())
task.cancel(true);
else
this.setVisible(false);
}//GEN-LAST:event_btnCancelActionPerformed }//GEN-LAST:event_btnCancelActionPerformed
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
if (txtPassword.getText().isEmpty()) { if (txtPassword.getPassword().length == 0) {
JOptionPane.showMessageDialog(rootPane, "Please provide a password"); JOptionPane.showMessageDialog(rootPane, "Please provide a password");
return; return;
} }
@ -302,31 +407,65 @@ public class ConnectDialog extends JDialog {
} }
if (Integer.valueOf(txtPort.getText()) < 1 || Integer.valueOf(txtPort.getText()) > 65535 ) { if (Integer.valueOf(txtPort.getText()) < 1 || Integer.valueOf(txtPort.getText()) > 65535 ) {
JOptionPane.showMessageDialog(rootPane, "Invalid port number"); JOptionPane.showMessageDialog(rootPane, "Invalid port number");
txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", "")); txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", Integer.toString(17171)));
return; return;
} }
try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
setCursor(new Cursor(Cursor.WAIT_CURSOR)); connection = new Connection();
if (chkUseProxy.isSelected()) { connection.setHost(this.txtServer.getText());
if (console.connect(txtPassword.getText(), txtServer.getText().trim(), Integer.valueOf(txtPort.getText()), txtProxyServer.getText().trim(), Integer.valueOf(txtProxyPort.getText()))) { connection.setPort(Integer.valueOf(this.txtPort.getText()));
this.saveSettings(); connection.setPassword(new String(txtPassword.getPassword()));
this.setVisible(false); connection.setProxyType((ProxyType) this.cbProxyType.getSelectedItem());
} connection.setProxyHost(this.txtProxyServer.getText());
} connection.setProxyPort(Integer.valueOf(this.txtProxyPort.getText()));
else { connection.setProxyUsername(this.txtProxyUserName.getText());
if (console.connect(txtPassword.getText(), txtServer.getText().trim(), Integer.valueOf(txtPort.getText()))) { connection.setProxyPassword(new String(this.txtPasswordField.getPassword()));
this.saveSettings(); logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort());
this.setVisible(false); task = new ConnectTask();
} task.execute();
}
}
finally {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}//GEN-LAST:event_btnConnectActionPerformed }//GEN-LAST:event_btnConnectActionPerformed
private class ConnectTask extends SwingWorker<Boolean, Void> {
private boolean result = false;
@Override
protected Boolean doInBackground() throws Exception {
lblStatus.setText("Connecting...");
btnConnect.setEnabled(false);
result = console.connect(connection);
return result;
}
@Override
protected void done() {
try {
get();
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
btnConnect.setEnabled(true);
if (result) {
lblStatus.setText("");
connected();
}
else {
lblStatus.setText("Could not connect");
}
} catch (InterruptedException ex) {
logger.fatal("Update Players Task error", ex);
} catch (ExecutionException ex) {
logger.fatal("Update Players Task error", ex);
} catch (CancellationException ex) {}
}
}
private void connected() {
this.saveSettings();
this.setVisible(false);
}
private void keyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyTyped private void keyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyTyped
char c = evt.getKeyChar(); char c = evt.getKeyChar();
if (!Character.isDigit(c)) if (!Character.isDigit(c))
@ -342,11 +481,7 @@ public class ConnectDialog extends JDialog {
// TODO add your handling code here: // TODO add your handling code here:
}//GEN-LAST:event_txtProxyPortkeyTyped }//GEN-LAST:event_txtProxyPortkeyTyped
private void chkUseProxyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUseProxyActionPerformed private void findPublicServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.showProxySettings();
}//GEN-LAST:event_chkUseProxyActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
BufferedReader in = null; BufferedReader in = null;
try { try {
URL serverListURL = new URL("http://mage.googlecode.com/files/server-list.txt"); URL serverListURL = new URL("http://mage.googlecode.com/files/server-list.txt");
@ -384,26 +519,41 @@ public class ConnectDialog extends JDialog {
} finally { } finally {
if (in != null) try { in.close(); } catch (Exception e) {} if (in != null) try { in.close(); } catch (Exception e) {}
} }
}//GEN-LAST:event_jButton1ActionPerformed
}//GEN-LAST:event_jButton1ActionPerformed private void cbProxyTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbProxyTypeActionPerformed
this.showProxySettings();
}//GEN-LAST:event_cbProxyTypeActionPerformed
private void txtPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPasswordFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables // Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel; private javax.swing.JButton btnCancel;
private javax.swing.JButton btnConnect; private javax.swing.JButton btnConnect;
private javax.swing.JComboBox cbProxyType;
private javax.swing.JCheckBox chkAutoConnect; private javax.swing.JCheckBox chkAutoConnect;
private javax.swing.JCheckBox chkUseProxy;
private javax.swing.JButton jButton1; private javax.swing.JButton jButton1;
private javax.swing.JLabel lblPassword;
private javax.swing.JLabel lblPort; private javax.swing.JLabel lblPort;
private javax.swing.JLabel lblProxyPassword;
private javax.swing.JLabel lblProxyPort; private javax.swing.JLabel lblProxyPort;
private javax.swing.JLabel lblProxyServer; private javax.swing.JLabel lblProxyServer;
private javax.swing.JLabel lblProxyType;
private javax.swing.JLabel lblProxyUserName;
private javax.swing.JLabel lblServer; private javax.swing.JLabel lblServer;
private javax.swing.JLabel lblUserName; private javax.swing.JLabel lblStatus;
private javax.swing.JPanel pnlProxy; private javax.swing.JPanel pnlProxy;
private javax.swing.JTextField txtPassword; private javax.swing.JPanel pnlProxyAuth;
private javax.swing.JPanel pnlProxySettings;
private javax.swing.JPasswordField txtPassword;
private javax.swing.JPasswordField txtPasswordField;
private javax.swing.JTextField txtPort; private javax.swing.JTextField txtPort;
private javax.swing.JTextField txtProxyPort; private javax.swing.JTextField txtProxyPort;
private javax.swing.JTextField txtProxyServer; private javax.swing.JTextField txtProxyServer;
private javax.swing.JTextField txtProxyUserName;
private javax.swing.JTextField txtServer; private javax.swing.JTextField txtServer;
// End of variables declaration//GEN-END:variables // End of variables declaration//GEN-END:variables

View file

@ -34,11 +34,16 @@
package mage.server.console; package mage.server.console;
import java.util.UUID;
import java.util.prefs.Preferences; import java.util.prefs.Preferences;
import javax.swing.Box; import javax.swing.Box;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager; import javax.swing.UIManager;
import mage.server.console.remote.Session; import mage.interfaces.MageClient;
import mage.interfaces.callback.ClientCallback;
import mage.remote.Connection;
import mage.remote.Session;
import mage.utils.MageVersion; import mage.utils.MageVersion;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -46,14 +51,14 @@ import org.apache.log4j.Logger;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ConsoleFrame extends javax.swing.JFrame { public class ConsoleFrame extends javax.swing.JFrame implements MageClient {
private final static Logger logger = Logger.getLogger(ConsoleFrame.class); private final static Logger logger = Logger.getLogger(ConsoleFrame.class);
private static Session session; private static Session session;
private ConnectDialog connectDialog; private ConnectDialog connectDialog;
private static Preferences prefs = Preferences.userNodeForPackage(ConsoleFrame.class); private static Preferences prefs = Preferences.userNodeForPackage(ConsoleFrame.class);
private final static MageVersion version = new MageVersion(0, 7, 4, ""); private final static MageVersion version = new MageVersion(0, 8, 0, "");
/** /**
* @return the session * @return the session
@ -66,7 +71,8 @@ public class ConsoleFrame extends javax.swing.JFrame {
return prefs; return prefs;
} }
public static MageVersion getVersion() { @Override
public MageVersion getVersion() {
return version; return version;
} }
@ -82,16 +88,8 @@ public class ConsoleFrame extends javax.swing.JFrame {
} }
} }
public boolean connect(String password, String serverName, int port) { public boolean connect(Connection connection) {
if (session.connect(password, serverName, port)) { if (session.connect(connection)) {
this.consolePanel1.start();
return true;
}
return false;
}
public boolean connect(String password, String serverName, int port, String proxyServer, int proxyPort) {
if (session.connect(password, serverName, port, proxyServer, proxyPort)) {
this.consolePanel1.start(); this.consolePanel1.start();
return true; return true;
} }
@ -168,7 +166,7 @@ public class ConsoleFrame extends javax.swing.JFrame {
if (session.isConnected()) { if (session.isConnected()) {
if (JOptionPane.showConfirmDialog(this, "Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (JOptionPane.showConfirmDialog(this, "Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
this.consolePanel1.stop(); this.consolePanel1.stop();
session.disconnect(); session.disconnect(false);
} }
} else { } else {
connectDialog.showDialog(this); connectDialog.showDialog(this);
@ -186,6 +184,10 @@ public class ConsoleFrame extends javax.swing.JFrame {
}); });
} }
private ConsoleFrame getFrame() {
return this;
}
// Variables declaration - do not modify//GEN-BEGIN:variables // Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnConnect; private javax.swing.JButton btnConnect;
private mage.server.console.ConsolePanel consolePanel1; private mage.server.console.ConsolePanel consolePanel1;
@ -193,4 +195,79 @@ public class ConsoleFrame extends javax.swing.JFrame {
private javax.swing.JLabel lblStatus; private javax.swing.JLabel lblStatus;
// End of variables declaration//GEN-END:variables // End of variables declaration//GEN-END:variables
@Override
public UUID getId() {
return null;
}
@Override
public void connected(final String message) {
if (SwingUtilities.isEventDispatchThread()) {
setStatusText(message);
enableButtons();
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setStatusText(message);
enableButtons();
}
});
}
}
@Override
public void disconnected() {
if (SwingUtilities.isEventDispatchThread()) {
consolePanel1.stop();
setStatusText("Not connected");
disableButtons();
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
consolePanel1.stop();
setStatusText("Not connected");
disableButtons();
}
});
}
}
@Override
public void showMessage(final String message) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(this, message);
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(getFrame(), message);
}
});
}
}
@Override
public void showError(final String message) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(getFrame(), message, "Error", JOptionPane.ERROR_MESSAGE);
}
});
}
}
@Override
public void processCallback(ClientCallback callback) {
}
} }

View file

@ -36,11 +36,14 @@ package mage.server.console;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker; import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel; import javax.swing.table.AbstractTableModel;
import mage.server.console.remote.Session; import mage.remote.Session;
import mage.view.TableView; import mage.view.TableView;
import mage.view.UserView; import mage.view.UserView;
import org.apache.log4j.Logger;
/** /**
* *
@ -48,6 +51,8 @@ import mage.view.UserView;
*/ */
public class ConsolePanel extends javax.swing.JPanel { public class ConsolePanel extends javax.swing.JPanel {
private final static Logger logger = Logger.getLogger(ConsolePanel.class);
private TableUserModel tableUserModel; private TableUserModel tableUserModel;
private TableTableModel tableTableModel; private TableTableModel tableTableModel;
private UpdateUsersTask updateUsersTask; private UpdateUsersTask updateUsersTask;
@ -239,7 +244,7 @@ public class ConsolePanel extends javax.swing.JPanel {
private void btnDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDisconnectActionPerformed private void btnDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDisconnectActionPerformed
int row = this.tblUsers.getSelectedRow(); int row = this.tblUsers.getSelectedRow();
ConsoleFrame.getSession().disconnectUser((UUID)tableUserModel.getValueAt(row, 3)); ConsoleFrame.getSession().disconnectUser((String)tableUserModel.getValueAt(row, 3));
}//GEN-LAST:event_btnDisconnectActionPerformed }//GEN-LAST:event_btnDisconnectActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
@ -394,6 +399,8 @@ class UpdateUsersTask extends SwingWorker<Void, List<UserView>> {
private Session session; private Session session;
private ConsolePanel panel; private ConsolePanel panel;
private final static Logger logger = Logger.getLogger(UpdateUsersTask.class);
UpdateUsersTask(Session session, ConsolePanel panel) { UpdateUsersTask(Session session, ConsolePanel panel) {
this.session = session; this.session = session;
this.panel = panel; this.panel = panel;
@ -413,6 +420,16 @@ class UpdateUsersTask extends SwingWorker<Void, List<UserView>> {
panel.update(view.get(0)); panel.update(view.get(0));
} }
@Override
protected void done() {
try {
get();
} catch (InterruptedException ex) {
logger.fatal("Update Users Task error", ex);
} catch (ExecutionException ex) {
logger.fatal("Update Users Task error", ex);
} catch (CancellationException ex) {}
}
} }
class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> { class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> {
@ -421,6 +438,8 @@ class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> {
private UUID roomId; private UUID roomId;
private ConsolePanel panel; private ConsolePanel panel;
private final static Logger logger = Logger.getLogger(UpdateTablesTask.class);
UpdateTablesTask(Session session, UUID roomId, ConsolePanel panel) { UpdateTablesTask(Session session, UUID roomId, ConsolePanel panel) {
this.session = session; this.session = session;
this.roomId = roomId; this.roomId = roomId;
@ -441,4 +460,14 @@ class UpdateTablesTask extends SwingWorker<Void, Collection<TableView>> {
panel.update(view.get(0)); panel.update(view.get(0));
} }
@Override
protected void done() {
try {
get();
} catch (InterruptedException ex) {
logger.fatal("Update Tables Task error", ex);
} catch (ExecutionException ex) {
logger.fatal("Update Tables Task error", ex);
} catch (CancellationException ex) {}
}
} }

View file

@ -1,732 +0,0 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.server.console.remote;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
import mage.cards.decks.DeckCardLists;
import mage.game.GameException;
import mage.MageException;
import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions;
import mage.interfaces.Server;
import mage.interfaces.ServerState;
import mage.server.console.ConsoleFrame;
import mage.view.DraftPickView;
import mage.view.GameTypeView;
import mage.view.TableView;
import mage.view.TournamentTypeView;
import mage.view.TournamentView;
import mage.view.UserView;
import org.apache.log4j.Logger;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class Session {
private final static Logger logger = Logger.getLogger(Session.class);
private static ScheduledExecutorService sessionExecutor = Executors.newScheduledThreadPool(1);
private UUID sessionId;
private Server server;
private ConsoleFrame frame;
private ServerState serverState;
private ScheduledFuture<?> future;
public Session(ConsoleFrame frame) {
this.frame = frame;
}
public synchronized boolean connect(String password, String serverName, int port) {
return connect(password, serverName, port, "", 0);
}
public synchronized boolean connect(String password, String serverName, int port, String proxyServer, int proxyPort) {
if (isConnected()) {
disconnect();
}
try {
System.setSecurityManager(null);
if (proxyServer.length() > 0) {
System.setProperty("socksProxyHost", proxyServer);
System.setProperty("socksProxyPort", Integer.toString(proxyPort));
}
else {
System.clearProperty("socksProxyHost");
System.clearProperty("socksProxyPort");
}
Registry reg = LocateRegistry.getRegistry(serverName, port);
this.server = (Server) reg.lookup("mage-server");
sessionId = server.registerAdmin(password, frame.getVersion());
serverState = server.getServerState();
future = sessionExecutor.scheduleWithFixedDelay(new ServerPinger(), 5, 5, TimeUnit.SECONDS);
logger.info("Connected to RMI server at " + serverName + ":" + port);
frame.setStatusText("Connected to " + serverName + ":" + port + " ");
frame.enableButtons();
return true;
} catch (RemoteException ex) {
logger.fatal("Unable to connect to server - ", ex);
disconnect();
JOptionPane.showMessageDialog(frame, "Unable to connect to server. " + ex.getMessage());
} catch (NotBoundException ex) {
logger.fatal("Unable to connect to server - ", ex);
} catch (Exception ex) {
logger.fatal("Unable to connect to server - ", ex);
}
return false;
}
public synchronized void disconnect() {
if (isConnected()) {
try {
server.deregisterClient(sessionId);
} catch (RemoteException ex) {
logger.fatal("Error disconnecting ...", ex);
} catch (MageException ex) {
logger.fatal("Error disconnecting ...", ex);
}
removeServer();
}
}
public void removeServer() {
if (future != null && !future.isDone())
future.cancel(true);
server = null;
frame.setStatusText("Not connected");
frame.disableButtons();
logger.info("Disconnected ... ");
JOptionPane.showMessageDialog(frame, "Disconnected.", "Disconnected", JOptionPane.INFORMATION_MESSAGE);
}
// public void ack(int messageId) {
// try {
// server.ack(messageId, sessionId);
// } catch (RemoteException ex) {
// handleRemoteException(ex);
// } catch (MageException ex) {
// handleMageException(ex);
// }
// }
public boolean ping() {
try {
return server.ping(sessionId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean isConnected() {
return server != null;
}
public String[] getPlayerTypes() {
return serverState.getPlayerTypes();
}
public List<GameTypeView> getGameTypes() {
return serverState.getGameTypes();
}
public String[] getDeckTypes() {
return serverState.getDeckTypes();
}
public List<TournamentTypeView> getTournamentTypes() {
return serverState.getTournamentTypes();
}
public boolean isTestMode() {
if (serverState != null)
return serverState.isTestMode();
return false;
}
public UUID getMainRoomId() {
try {
return server.getMainRoomId();
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public UUID getRoomChatId(UUID roomId) {
try {
return server.getRoomChatId(roomId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public UUID getTableChatId(UUID tableId) {
try {
return server.getTableChatId(tableId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public UUID getGameChatId(UUID gameId) {
try {
return server.getGameChatId(gameId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public TableView getTable(UUID roomId, UUID tableId) {
try {
return server.getTable(roomId, tableId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public boolean watchTable(UUID roomId, UUID tableId) {
try {
server.watchTable(sessionId, roomId, tableId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList) {
try {
return server.joinTable(sessionId, roomId, tableId, playerName, playerType, skill, deckList);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (GameException ex) {
handleGameException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill) {
try {
return server.joinTournamentTable(sessionId, roomId, tableId, playerName, playerType, skill);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (GameException ex) {
handleGameException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public Collection<TableView> getTables(UUID roomId) throws Exception {
try {
return server.getTables(roomId);
} catch (RemoteException ex) {
handleRemoteException(ex);
throw new Exception();
} catch (MageException ex) {
handleMageException(ex);
throw new Exception();
}
}
public TournamentView getTournament(UUID tournamentId) throws Exception {
try {
return server.getTournament(tournamentId);
} catch (RemoteException ex) {
handleRemoteException(ex);
throw new Exception();
} catch (MageException ex) {
handleMageException(ex);
throw new Exception();
}
}
public UUID getTournamentChatId(UUID tournamentId) {
try {
return server.getTournamentChatId(tournamentId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public boolean sendPlayerUUID(UUID gameId, UUID data) {
try {
server.sendPlayerUUID(gameId, sessionId, data);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean sendPlayerBoolean(UUID gameId, boolean data) {
try {
server.sendPlayerBoolean(gameId, sessionId, data);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean sendPlayerInteger(UUID gameId, int data) {
try {
server.sendPlayerInteger(gameId, sessionId, data);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean sendPlayerString(UUID gameId, String data) {
try {
server.sendPlayerString(gameId, sessionId, data);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public DraftPickView sendCardPick(UUID draftId, UUID cardId) {
try {
return server.sendCardPick(draftId, sessionId, cardId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public boolean leaveChat(UUID chatId) {
try {
server.leaveChat(chatId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean sendChatMessage(UUID chatId, String message) {
try {
server.sendChatMessage(chatId, "", message);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean joinGame(UUID gameId) {
try {
server.joinGame(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean joinDraft(UUID draftId) {
try {
server.joinDraft(draftId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean joinTournament(UUID tournamentId) {
try {
server.joinTournament(tournamentId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean watchGame(UUID gameId) {
try {
server.watchGame(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean replayGame(UUID gameId) {
try {
server.replayGame(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public TableView createTable(UUID roomId, MatchOptions matchOptions) {
try {
return server.createTable(sessionId, roomId, matchOptions);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public TableView createTournamentTable(UUID roomId, TournamentOptions tournamentOptions) {
try {
return server.createTournamentTable(sessionId, roomId, tournamentOptions);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public boolean isTableOwner(UUID roomId, UUID tableId) {
try {
return server.isTableOwner(sessionId, roomId, tableId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean removeTable(UUID tableId) {
try {
server.removeTable(sessionId, tableId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean swapSeats(UUID roomId, UUID tableId, int seatNum1, int seatNum2) {
try {
server.swapSeats(sessionId, roomId, tableId, seatNum1, seatNum2);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean leaveTable(UUID roomId, UUID tableId) {
try {
server.leaveTable(sessionId, roomId, tableId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean startGame(UUID roomId, UUID tableId) {
try {
server.startMatch(sessionId, roomId, tableId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean startTournament(UUID roomId, UUID tableId) {
try {
server.startTournament(sessionId, roomId, tableId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean startChallenge(UUID roomId, UUID tableId, UUID challengeId) {
try {
server.startChallenge(sessionId, roomId, tableId, challengeId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean submitDeck(UUID tableId, DeckCardLists deck) {
try {
return server.submitDeck(sessionId, tableId, deck);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (GameException ex) {
handleGameException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean concedeGame(UUID gameId) {
try {
server.concedeGame(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean stopWatching(UUID gameId) {
try {
server.stopWatching(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean startReplay(UUID gameId) {
try {
server.startReplay(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean stopReplay(UUID gameId) {
try {
server.stopReplay(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean nextPlay(UUID gameId) {
try {
server.nextPlay(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean previousPlay(UUID gameId) {
try {
server.previousPlay(gameId, sessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public boolean cheat(UUID gameId, UUID playerId, DeckCardLists deckList) {
try {
server.cheat(gameId, sessionId, playerId, deckList);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
public List<UserView> getUsers() {
try {
return server.getUsers(sessionId);
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return null;
}
public boolean disconnectUser(UUID userSessionId) {
try {
server.disconnectUser(sessionId, userSessionId);
return true;
} catch (RemoteException ex) {
handleRemoteException(ex);
} catch (MageException ex) {
handleMageException(ex);
}
return false;
}
private void handleRemoteException(RemoteException ex) {
logger.fatal("Communication error", ex);
if (ex instanceof java.rmi.ConnectException) {
server = null;
frame.setStatusText("Not connected");
frame.disableButtons();
JOptionPane.showMessageDialog(frame, "Communication error - disconnecting.", "Error", JOptionPane.ERROR_MESSAGE);
}
else
JOptionPane.showMessageDialog(frame, "Communication error.", "Error", JOptionPane.ERROR_MESSAGE);
}
private void handleMageException(MageException ex) {
logger.fatal("Server error", ex);
JOptionPane.showMessageDialog(frame, "Critical server error. Disconnecting", "Error", JOptionPane.ERROR_MESSAGE);
disconnect();
frame.disableButtons();
}
private void handleGameException(GameException ex) {
logger.fatal("Game error", ex);
JOptionPane.showMessageDialog(frame, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
public Server getServerRef() {
return server;
}
class ServerPinger implements Runnable {
private int missed = 0;
@Override
public void run() {
if (!ping()) {
missed++;
if (missed > 10) {
logger.info("Connection to server timed out");
removeServer();
}
}
else {
missed = 0;
}
}
}
}

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Deck-Constructed</artifactId> <artifactId>Mage-Deck-Constructed</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Deck-Limited</artifactId> <artifactId>Mage-Deck-Limited</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Game-FreeForAll</artifactId> <artifactId>Mage-Game-FreeForAll</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Game-TwoPlayerDuel</artifactId> <artifactId>Mage-Game-TwoPlayerDuel</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Player-AI-MA</artifactId> <artifactId>Mage-Player-AI-MA</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Player-AI</artifactId> <artifactId>Mage-Player-AI</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Player-AIMinimax</artifactId> <artifactId>Mage-Player-AIMinimax</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Player-Human</artifactId> <artifactId>Mage-Player-Human</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Tournament-BoosterDraft</artifactId> <artifactId>Mage-Tournament-BoosterDraft</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Tournament-Sealed</artifactId> <artifactId>Mage-Tournament-Sealed</artifactId>

View file

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Server-Plugins</artifactId> <artifactId>Mage-Server-Plugins</artifactId>

View file

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Server</artifactId> <artifactId>Mage-Server</artifactId>
@ -39,8 +39,7 @@
<artifactId>jaxb-impl</artifactId> <artifactId>jaxb-impl</artifactId>
<version>2.1.12</version> <version>2.1.12</version>
</dependency> </dependency>
<dependency>
<dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>1.2.14</version> <version>1.2.14</version>

View file

@ -54,12 +54,12 @@ public class ChatManager {
return chatSession.getChatId(); return chatSession.getChatId();
} }
public void joinChat(UUID chatId, UUID sessionId, String userName) { public void joinChat(UUID chatId, UUID userId) {
chatSessions.get(chatId).join(userName, sessionId); chatSessions.get(chatId).join(userId);
} }
public void leaveChat(UUID chatId, UUID sessionId) { public void leaveChat(UUID chatId, UUID userId) {
chatSessions.get(chatId).kill(sessionId); chatSessions.get(chatId).kill(userId);
} }
public void destroyChatSession(UUID chatId) { public void destroyChatSession(UUID chatId) {
@ -70,9 +70,27 @@ public class ChatManager {
chatSessions.get(chatId).broadcast(userName, message, color); chatSessions.get(chatId).broadcast(userName, message, color);
} }
void removeSession(UUID sessionId) { /**
*
* use mainly for announcing that a user connection was lost or that a user has reconnected
*
* @param userId
* @param message
* @param color
*/
public void broadcast(UUID userId, String message, MessageColor color) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
for (ChatSession chat: chatSessions.values()) {
if (chat.hasUser(userId))
chat.broadcast(user.getName(), message, color);
}
}
}
void removeUser(UUID userId) {
for (ChatSession chat: chatSessions.values()) { for (ChatSession chat: chatSessions.values()) {
chat.kill(sessionId); chat.kill(userId);
} }
} }
} }

View file

@ -34,8 +34,6 @@ import java.util.Calendar;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import mage.MageException;
import mage.interfaces.callback.CallbackException;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.view.ChatMessage; import mage.view.ChatMessage;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
@ -52,22 +50,24 @@ public class ChatSession {
private UUID chatId; private UUID chatId;
private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT); private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT);
//TODO: use sessionId for chatting - prevents sending without being part of the chat
public ChatSession() { public ChatSession() {
chatId = UUID.randomUUID(); chatId = UUID.randomUUID();
} }
public void join(String userName, UUID sessionId) { public void join(UUID userId) {
clients.put(sessionId, userName); User user = UserManager.getInstance().getUser(userId);
broadcast(userName, " has joined", MessageColor.BLACK); if (user != null) {
logger.info(userName + " joined chat " + chatId); String userName = user.getName();
clients.put(userId, userName);
broadcast(userName, " has joined", MessageColor.BLACK);
logger.info(userName + " joined chat " + chatId);
}
} }
public void kill(UUID sessionId) { public void kill(UUID userId) {
if (clients.containsKey(sessionId)) { if (clients.containsKey(userId)) {
String userName = clients.get(sessionId); String userName = clients.get(userId);
clients.remove(sessionId); clients.remove(userId);
broadcast(userName, " has left", MessageColor.BLACK); broadcast(userName, " has left", MessageColor.BLACK);
logger.info(userName + " has left chat " + chatId); logger.info(userName + " has left chat " + chatId);
} }
@ -79,12 +79,12 @@ public class ChatSession {
final String time = timeFormatter.format(cal.getTime()); final String time = timeFormatter.format(cal.getTime());
final String username = userName; final String username = userName;
logger.debug("Broadcasting '" + msg + "' for " + chatId); logger.debug("Broadcasting '" + msg + "' for " + chatId);
for (UUID sessionId: clients.keySet()) { for (UUID userId: clients.keySet()) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) if (user != null)
session.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color))); user.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color)));
else else
kill(sessionId); kill(userId);
} }
} }
@ -95,4 +95,8 @@ public class ChatSession {
return chatId; return chatId;
} }
public boolean hasUser(UUID userId) {
return clients.containsKey(userId);
}
} }

View file

@ -28,12 +28,6 @@
package mage.server; package mage.server;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.ExportException;
import java.rmi.server.RemoteServer;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -43,9 +37,9 @@ import mage.cards.decks.DeckCardLists;
import mage.game.GameException; import mage.game.GameException;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.interfaces.Server; import mage.interfaces.MageServer;
//import mage.interfaces.Server;
import mage.interfaces.ServerState; import mage.interfaces.ServerState;
import mage.interfaces.callback.ClientCallback;
import mage.server.game.DeckValidatorFactory; import mage.server.game.DeckValidatorFactory;
import mage.server.draft.DraftManager; import mage.server.draft.DraftManager;
import mage.server.game.GameFactory; import mage.server.game.GameFactory;
@ -69,97 +63,52 @@ import org.apache.log4j.Logger;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ServerImpl extends RemoteServer implements Server { public class MageServerImpl implements MageServer {
private final static Logger logger = Logger.getLogger("Mage Server"); private final static Logger logger = Logger.getLogger("Mage Server");
private static ExecutorService rmiExecutor = ThreadExecutor.getInstance().getRMIExecutor(); private static ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor();
private boolean testMode;
private String password; private String password;
private boolean testMode;
public MageServerImpl(String password, boolean testMode) {
this.password = password;
this.testMode = testMode;
}
@Override
public boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException {
public ServerImpl(int port, String name, boolean testMode, String password) {
try { try {
System.setSecurityManager(null); if (version.compareTo(Main.getVersion()) != 0)
Registry reg = LocateRegistry.createRegistry(port); throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion());
Server stub = (Server) UnicastRemoteObject.exportObject(this, port); return SessionManager.getInstance().registerUser(sessionId, userName);
reg.rebind(name, stub); } catch (Exception ex) {
this.testMode = testMode; handleException(ex);
this.password = password;
logger.info("Started MAGE server - listening on port " + port);
if (testMode)
logger.info("MAGE server running in test mode");
} catch (ExportException ex) {
logger.fatal("ERROR: Unable to start Mage Server - another server is likely running");
} catch (RemoteException ex) {
logger.fatal("Failed to start RMI server at port " + port, ex);
}
}
public boolean isTestMode() {
return testMode;
}
@Override
public ClientCallback callback(UUID sessionId) {
Session session = SessionManager.getInstance().getSession(sessionId);
if (session == null) {
return null;
}
return session.callback();
}
@Override
public void ack(String message, UUID sessionId) throws RemoteException, MageException {
SessionManager.getInstance().getSession(sessionId).ack(message);
}
@Override
public boolean ping(UUID sessionId) {
Session session = SessionManager.getInstance().getSession(sessionId);
if (session != null) {
session.ping();
return true;
} }
return false; return false;
} }
@Override @Override
public UUID registerClient(String userName, UUID clientId, MageVersion version) throws MageException, RemoteException { public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException {
UUID sessionId = null;
try {
if (version.compareTo(Main.getVersion()) != 0)
throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion());
sessionId = SessionManager.getInstance().createSession(userName, getClientHost(), clientId);
logger.info("User " + userName + " connected from " + getClientHost());
} catch (Exception ex) {
handleException(ex);
}
return sessionId;
}
@Override
public UUID registerAdmin(String password, MageVersion version) throws RemoteException, MageException {
UUID sessionId = null;
try { try {
if (version.compareTo(Main.getVersion()) != 0) if (version.compareTo(Main.getVersion()) != 0)
throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion());
if (!password.equals(this.password)) if (!password.equals(this.password))
throw new MageException("Wrong password"); throw new MageException("Wrong password");
sessionId = SessionManager.getInstance().createSession(getClientHost()); return SessionManager.getInstance().registerAdmin(sessionId);
logger.info("Admin connected from " + getClientHost());
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
return sessionId; return false;
} }
@Override @Override
public TableView createTable(UUID sessionId, UUID roomId, MatchOptions options) throws MageException { public TableView createTable(String sessionId, UUID roomId, MatchOptions options) throws MageException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(sessionId, options); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options);
logger.info("Table " + table.getTableId() + " created"); logger.info("Table " + table.getTableId() + " created");
return table; return table;
} }
@ -171,10 +120,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public TableView createTournamentTable(UUID sessionId, UUID roomId, TournamentOptions options) throws MageException { public TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions options) throws MageException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(sessionId, options); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(userId, options);
logger.info("Tournament table " + table.getTableId() + " created"); logger.info("Tournament table " + table.getTableId() + " created");
return table; return table;
} }
@ -186,14 +136,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void removeTable(final UUID sessionId, final UUID roomId, final UUID tableId) throws MageException { public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TableManager.getInstance().removeTable(sessionId, tableId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().removeTable(userId, tableId);
} }
} }
); );
@ -205,10 +156,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public boolean joinTable(UUID sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException, GameException { public boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException, GameException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(sessionId, tableId, name, playerType, skill, deckList); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList);
logger.info("Session " + sessionId + " joined table " + tableId); logger.info("Session " + sessionId + " joined table " + tableId);
return ret; return ret;
} }
@ -222,10 +174,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public boolean joinTournamentTable(UUID sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill) throws MageException, GameException { public boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill) throws MageException, GameException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(sessionId, tableId, name, playerType, skill); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill);
logger.info("Session " + sessionId + " joined table " + tableId); logger.info("Session " + sessionId + " joined table " + tableId);
return ret; return ret;
} }
@ -239,10 +192,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public boolean submitDeck(UUID sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException { public boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
boolean ret = TableManager.getInstance().submitDeck(sessionId, tableId, deckList); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList);
logger.info("Session " + sessionId + " submitted deck"); logger.info("Session " + sessionId + " submitted deck");
return ret; return ret;
} }
@ -270,8 +224,8 @@ public class ServerImpl extends RemoteServer implements Server {
public List<String> getConnectedPlayers(UUID roomId) throws MageException { public List<String> getConnectedPlayers(UUID roomId) throws MageException {
try { try {
List<String> players = new ArrayList<String>(); List<String> players = new ArrayList<String>();
for (Session session : SessionManager.getInstance().getSessions().values()) { for (User user : UserManager.getInstance().getUsers()) {
players.add(session.getUsername()); players.add(user.getName());
} }
return players; return players;
} }
@ -293,17 +247,14 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void deregisterClient(final UUID sessionId) throws MageException { public void deregisterClient(final String sessionId) throws MageException {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
Session session = SessionManager.getInstance().getSession(sessionId); SessionManager.getInstance().disconnect(sessionId, true);
if (session != null) { logger.info("Client deregistered ...");
session.kill();
logger.info("Client deregistered ...");
}
} }
} }
); );
@ -314,14 +265,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void startMatch(final UUID sessionId, final UUID roomId, final UUID tableId) throws MageException { public void startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TableManager.getInstance().startMatch(sessionId, roomId, tableId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().startMatch(userId, roomId, tableId);
} }
} }
); );
@ -333,14 +285,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void startChallenge(final UUID sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws RemoteException, MageException { public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TableManager.getInstance().startChallenge(sessionId, roomId, tableId, challengeId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId);
} }
} }
); );
@ -352,14 +305,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void startTournament(final UUID sessionId, final UUID roomId, final UUID tableId) throws MageException { public void startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TableManager.getInstance().startTournament(sessionId, roomId, tableId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().startTournament(userId, roomId, tableId);
} }
} }
); );
@ -371,7 +325,7 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public TournamentView getTournament(UUID tournamentId) throws RemoteException, MageException { public TournamentView getTournament(UUID tournamentId) throws MageException {
try { try {
return TournamentManager.getInstance().getTournamentView(tournamentId); return TournamentManager.getInstance().getTournamentView(tournamentId);
} }
@ -384,7 +338,7 @@ public class ServerImpl extends RemoteServer implements Server {
@Override @Override
public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
@ -399,13 +353,14 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void joinChat(final UUID chatId, final UUID sessionId, final String userName) throws MageException { public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ChatManager.getInstance().joinChat(chatId, sessionId, userName); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ChatManager.getInstance().joinChat(chatId, userId);
} }
} }
); );
@ -416,13 +371,14 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void leaveChat(final UUID chatId, final UUID sessionId) throws MageException { public void leaveChat(final UUID chatId, final String sessionId) throws MageException {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ChatManager.getInstance().leaveChat(chatId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ChatManager.getInstance().leaveChat(chatId, userId);
} }
} }
); );
@ -455,9 +411,10 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public boolean isTableOwner(UUID sessionId, UUID roomId, UUID tableId) throws MageException { public boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException {
try { try {
return TableManager.getInstance().isTableOwner(tableId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
return TableManager.getInstance().isTableOwner(tableId, userId);
} }
catch (Exception ex) { catch (Exception ex) {
handleException(ex); handleException(ex);
@ -466,14 +423,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void swapSeats(final UUID sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws RemoteException, MageException { public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TableManager.getInstance().swapSeats(tableId, sessionId, seatNum1, seatNum2); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2);
} }
} }
); );
@ -485,14 +443,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void leaveTable(final UUID sessionId, final UUID roomId, final UUID tableId) throws MageException { public void leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GamesRoomManager.getInstance().getRoom(roomId).leaveTable(sessionId, tableId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId);
} }
} }
); );
@ -515,14 +474,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void joinGame(final UUID gameId, final UUID sessionId) throws MageException { public void joinGame(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().joinGame(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().joinGame(gameId, userId);
} }
} }
); );
@ -534,14 +494,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void joinDraft(final UUID draftId, final UUID sessionId) throws MageException { public void joinDraft(final UUID draftId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
DraftManager.getInstance().joinDraft(draftId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
DraftManager.getInstance().joinDraft(draftId, userId);
} }
} }
); );
@ -553,14 +514,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void joinTournament(final UUID tournamentId, final UUID sessionId) throws MageException { public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TournamentManager.getInstance().joinTournament(tournamentId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TournamentManager.getInstance().joinTournament(tournamentId, userId);
} }
} }
); );
@ -594,14 +556,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void sendPlayerUUID(final UUID gameId, final UUID sessionId, final UUID data) throws MageException { public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().sendPlayerUUID(gameId, sessionId, data); User user = SessionManager.getInstance().getUser(sessionId);
user.sendPlayerUUID(gameId, data);
} }
} }
); );
@ -613,14 +576,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void sendPlayerString(final UUID gameId, final UUID sessionId, final String data) throws MageException { public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().sendPlayerString(gameId, sessionId, data); User user = SessionManager.getInstance().getUser(sessionId);
user.sendPlayerString(gameId, data);
} }
} }
); );
@ -632,14 +596,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void sendPlayerBoolean(final UUID gameId, final UUID sessionId, final Boolean data) throws MageException { public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().sendPlayerBoolean(gameId, sessionId, data); User user = SessionManager.getInstance().getUser(sessionId);
user.sendPlayerBoolean(gameId, data);
} }
} }
); );
@ -651,14 +616,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void sendPlayerInteger(final UUID gameId, final UUID sessionId, final Integer data) throws RemoteException, MageException { public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().sendPlayerInteger(gameId, sessionId, data); User user = SessionManager.getInstance().getUser(sessionId);
user.sendPlayerInteger(gameId, data);
} }
} }
); );
@ -670,10 +636,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public DraftPickView sendCardPick(final UUID draftId, final UUID sessionId, final UUID cardPick) throws MageException { public DraftPickView sendCardPick(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
return DraftManager.getInstance().sendCardPick(draftId, sessionId, cardPick); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
return DraftManager.getInstance().sendCardPick(draftId, userId, cardPick);
} }
} }
catch (Exception ex) { catch (Exception ex) {
@ -683,14 +650,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void concedeGame(final UUID gameId, final UUID sessionId) throws MageException { public void concedeGame(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().concedeGame(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().concedeGame(gameId, userId);
} }
} }
); );
@ -702,10 +670,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public boolean watchTable(UUID sessionId, UUID roomId, UUID tableId) throws MageException { public boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException {
try { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
return GamesRoomManager.getInstance().getRoom(roomId).watchTable(sessionId, tableId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
return GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId);
} }
} }
catch (Exception ex) { catch (Exception ex) {
@ -715,14 +684,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void watchGame(final UUID gameId, final UUID sessionId) throws MageException { public void watchGame(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().watchGame(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().watchGame(gameId, userId);
} }
} }
); );
@ -734,14 +704,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void stopWatching(final UUID gameId, final UUID sessionId) throws MageException { public void stopWatching(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().stopWatching(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().stopWatching(gameId, userId);
} }
} }
); );
@ -753,14 +724,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void replayGame(final UUID gameId, final UUID sessionId) throws MageException { public void replayGame(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ReplayManager.getInstance().replayGame(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().replayGame(gameId, userId);
} }
} }
); );
@ -772,14 +744,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void startReplay(final UUID gameId, final UUID sessionId) throws MageException { public void startReplay(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ReplayManager.getInstance().startReplay(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().startReplay(gameId, userId);
} }
} }
); );
@ -791,14 +764,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void stopReplay(final UUID gameId, final UUID sessionId) throws MageException { public void stopReplay(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ReplayManager.getInstance().stopReplay(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().stopReplay(gameId, userId);
} }
} }
); );
@ -810,14 +784,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void nextPlay(final UUID gameId, final UUID sessionId) throws MageException { public void nextPlay(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ReplayManager.getInstance().nextPlay(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().nextPlay(gameId, userId);
} }
} }
); );
@ -829,14 +804,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void previousPlay(final UUID gameId, final UUID sessionId) throws MageException { public void previousPlay(final UUID gameId, final String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
ReplayManager.getInstance().previousPlay(gameId, sessionId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().previousPlay(gameId, userId);
} }
} }
); );
@ -848,7 +824,7 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public ServerState getServerState() throws RemoteException, MageException { public ServerState getServerState() throws MageException {
try { try {
return new ServerState( return new ServerState(
GameFactory.getInstance().getGameTypes(), GameFactory.getInstance().getGameTypes(),
@ -865,15 +841,17 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void cheat(final UUID gameId, final UUID sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (testMode) if (testMode) {
GameManager.getInstance().cheat(gameId, sessionId, playerId, deckList); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().cheat(gameId, userId, playerId, deckList);
}
} }
} }
); );
@ -885,10 +863,11 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public boolean cheat(final UUID gameId, final UUID sessionId, final UUID playerId, final String cardName) throws MageException { public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException {
if (testMode) { if (testMode) {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
return GameManager.getInstance().cheat(gameId, sessionId, playerId, cardName); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
return GameManager.getInstance().cheat(gameId, userId, playerId, cardName);
} }
} }
return false; return false;
@ -900,26 +879,31 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public GameView getGameView(final UUID gameId, final UUID sessionId, final UUID playerId) { public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
return GameManager.getInstance().getGameView(gameId, sessionId, playerId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
return GameManager.getInstance().getGameView(gameId, userId, playerId);
} }
return null; return null;
} }
@Override @Override
public List<UserView> getUsers(UUID sessionId) throws RemoteException, MageException { public List<UserView> getUsers(String sessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId) && SessionManager.getInstance().isAdmin(sessionId)) {
return SessionManager.getInstance().getUsers(sessionId); List<UserView> users = new ArrayList<UserView>();
for (User user: UserManager.getInstance().getUsers()) {
users.add(new UserView(user.getName(), "", user.getSessionId(), user.getConnectionTime()));
}
return users;
} }
return null; return null;
} }
@Override @Override
public void disconnectUser(final UUID sessionId, final UUID userSessionId) throws RemoteException, MageException { public void disconnectUser(final String sessionId, final String userSessionId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
@ -935,14 +919,15 @@ public class ServerImpl extends RemoteServer implements Server {
} }
@Override @Override
public void removeTable(final UUID sessionId, final UUID tableId) throws RemoteException, MageException { public void removeTable(final String sessionId, final UUID tableId) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
rmiExecutor.execute( callExecutor.execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TableManager.getInstance().removeTable(sessionId, tableId); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().removeTable(userId, tableId);
} }
} }
); );

View file

@ -31,14 +31,14 @@ package mage.server;
import mage.server.util.PluginClassLoader; import mage.server.util.PluginClassLoader;
import java.io.File; import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.net.Inet4Address; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InterfaceAddress; import java.util.Map;
import java.net.NetworkInterface; import javax.management.MBeanServer;
import java.net.SocketException;
import java.util.Enumeration;
import mage.game.match.MatchType; import mage.game.match.MatchType;
import mage.game.tournament.TournamentType; import mage.game.tournament.TournamentType;
import mage.interfaces.MageServer;
import mage.remote.Connection;
import mage.server.game.DeckValidatorFactory; import mage.server.game.DeckValidatorFactory;
import mage.server.game.GameFactory; import mage.server.game.GameFactory;
import mage.server.game.PlayerFactory; import mage.server.game.PlayerFactory;
@ -46,9 +46,21 @@ import mage.server.tournament.TournamentFactory;
import mage.server.util.ConfigSettings; import mage.server.util.ConfigSettings;
import mage.server.util.config.Plugin; import mage.server.util.config.Plugin;
import mage.server.util.config.GamePlugin; import mage.server.util.config.GamePlugin;
import mage.util.Copier;
import mage.utils.MageVersion; import mage.utils.MageVersion;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jboss.remoting.Client;
import org.jboss.remoting.ClientDisconnectedException;
import org.jboss.remoting.ConnectionListener;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.Remoting;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.callback.InvokerCallbackHandler;
import org.jboss.remoting.callback.ServerInvokerCallbackHandler;
import org.jboss.remoting.transport.Connector;
import org.jboss.remoting.transporter.TransporterServer;
import org.w3c.dom.Element;
/** /**
* *
@ -61,11 +73,11 @@ public class Main {
private final static String testModeArg = "-testMode="; private final static String testModeArg = "-testMode=";
private final static String adminPasswordArg = "-adminPassword="; private final static String adminPasswordArg = "-adminPassword=";
private final static String pluginFolder = "plugins"; private final static String pluginFolder = "plugins";
private static MageVersion version = new MageVersion(0, 7, 4, ""); private static MageVersion version = new MageVersion(0, 8, 0, "");
public static PluginClassLoader classLoader = new PluginClassLoader(); public static PluginClassLoader classLoader = new PluginClassLoader();
public static ServerImpl server; public static TransporterServer server;
protected static boolean testMode;
/** /**
* @param args the command line arguments * @param args the command line arguments
*/ */
@ -87,7 +99,6 @@ public class Main {
for (Plugin plugin: config.getDeckTypes()) { for (Plugin plugin: config.getDeckTypes()) {
DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin)); DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin));
} }
boolean testMode = false;
String adminPassword = ""; String adminPassword = "";
for (String arg: args) { for (String arg: args) {
if (arg.startsWith(testModeArg)) { if (arg.startsWith(testModeArg)) {
@ -97,44 +108,105 @@ public class Main {
adminPassword = arg.replace(adminPasswordArg, ""); adminPassword = arg.replace(adminPasswordArg, "");
} }
} }
Copier.setLoader(classLoader); Connection connection = new Connection();
setServerAddress(config.getServerAddress()); connection.setHost(config.getServerAddress());
server = new ServerImpl(config.getPort(), config.getServerName(), testMode, adminPassword); connection.setPort(config.getPort());
try {
InvokerLocator serverLocator = new InvokerLocator(connection.getURI());
server = new MageTransporterServer(serverLocator, new MageServerImpl(adminPassword, testMode), MageServer.class.getName(), new MageServerInvocationHandler());
server.start();
logger.info("Started MAGE server - listening on " + connection.toString());
if (testMode)
logger.info("MAGE server running in test mode");
} catch (IOException ex) {
logger.fatal("Failed to start server - " + connection.toString(), ex);
} catch (Exception ex) {
logger.fatal("Failed to start server - " + connection.toString(), ex);
}
} }
private static void setServerAddress(String ip) { static class ClientConnectionListener implements ConnectionListener {
String ipParam = System.getProperty("server"); @Override
if (ipParam != null) { public void handleConnectionException(Throwable throwable, Client client) {
ip = ipParam; Session session = SessionManager.getInstance().getSession(client.getSessionId());
} if (session != null) {
if (ip.equals("localhost")) { String sessionName;
try { User user = UserManager.getInstance().getUser(session.getUserId());
String foundIP = ""; if (user != null)
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { sessionName = user.getName() + " at " + session.getHost();
NetworkInterface iface = interfaces.nextElement( ); else
if (iface.isLoopback()) sessionName = session.getHost();
continue; if (throwable instanceof ClientDisconnectedException) {
for (InterfaceAddress addr: iface.getInterfaceAddresses()) SessionManager.getInstance().disconnect(client.getSessionId(), true);
{ logger.info("client disconnected - " + sessionName);
InetAddress iaddr = addr.getAddress(); }
if (iaddr instanceof Inet4Address) { else {
foundIP = iaddr.getHostAddress(); SessionManager.getInstance().disconnect(client.getSessionId(), false);
break; logger.info("connection to client lost - " + sessionName);
}
}
if (foundIP.length() > 0)
break;
} }
if (foundIP.length() > 0)
ip = foundIP;
} catch (SocketException ex) {
logger.warn("Could not get server address: ", ex);
} }
} }
System.setProperty("java.rmi.server.hostname", ip); }
System.setProperty("sun.rmi.transport.tcp.readTimeout", "30000");
logger.info("MAGE server - using address " + ip); static class MageTransporterServer extends TransporterServer {
protected Connector connector;
public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler callback) throws Exception {
super(locator, target, subsystem);
connector.addInvocationHandler("callback", callback);
connector.setLeasePeriod(5000);
connector.addConnectionListener(new ClientConnectionListener());
}
public Connector getConnector() throws Exception {
return connector;
}
@Override
protected Connector getConnector(InvokerLocator locator, Map config, Element xmlConfig) throws Exception {
Connector c = super.getConnector(locator, config, xmlConfig);
this.connector = c;
return c;
}
}
static class MageServerInvocationHandler implements ServerInvocationHandler {
@Override
public void setMBeanServer(MBeanServer server) {}
@Override
public void setInvoker(ServerInvoker invoker) {}
@Override
public Object invoke(final InvocationRequest invocation) throws Throwable {
String sessionId = invocation.getSessionId();
InetAddress clientAddress = (InetAddress) invocation.getRequestPayload().get(Remoting.CLIENT_ADDRESS);
SessionManager.getInstance().getSession(sessionId).setHost(clientAddress.getHostAddress());
return null;
}
@Override
public void addListener(InvokerCallbackHandler callbackHandler) {
ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
try {
String sessionId = handler.getClientSessionId();
SessionManager.getInstance().createSession(sessionId, callbackHandler);
} catch (Throwable ex) {
logger.fatal("", ex);
}
}
@Override
public void removeListener(InvokerCallbackHandler callbackHandler) {
logger.fatal("removeListener called");
// ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
// String sessionId = handler.getCallbackClient().getSessionId();
// SessionManager.getInstance().disconnect(sessionId);
}
} }
private static Class<?> loadPlugin(Plugin plugin) { private static Class<?> loadPlugin(Plugin plugin) {
@ -198,4 +270,7 @@ public class Main {
return version; return version;
} }
public static boolean isTestMode() {
return testMode;
}
} }

View file

@ -30,12 +30,13 @@ package mage.server;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
import mage.cards.decks.Deck; import mage.MageException;
import mage.interfaces.callback.CallbackServerSession;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.game.GameManager;
import mage.view.TableClientMessage;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jboss.remoting.callback.AsynchInvokerCallbackHandler;
import org.jboss.remoting.callback.Callback;
import org.jboss.remoting.callback.HandleCallbackException;
import org.jboss.remoting.callback.InvokerCallbackHandler;
/** /**
* *
@ -45,124 +46,73 @@ public class Session {
private final static Logger logger = Logger.getLogger(Session.class); private final static Logger logger = Logger.getLogger(Session.class);
private UUID sessionId; private String sessionId;
private UUID clientId; private UUID userId;
private String username;
private String host; private String host;
private int messageId = 0; private int messageId = 0;
private String ackMessage;
private Date timeConnected; private Date timeConnected;
private long lastPing;
private boolean isAdmin = false; private boolean isAdmin = false;
private final CallbackServerSession callback = new CallbackServerSession(); private AsynchInvokerCallbackHandler callbackHandler;
public Session(String userName, String host, UUID clientId) { public Session(String sessionId, InvokerCallbackHandler callbackHandler) {
sessionId = UUID.randomUUID(); this.sessionId = sessionId;
this.username = userName; this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler;
this.host = host;
this.clientId = clientId;
this.isAdmin = false; this.isAdmin = false;
this.timeConnected = new Date(); this.timeConnected = new Date();
ping();
} }
public Session(String host) { public void registerUser(String userName) throws MageException {
sessionId = UUID.randomUUID(); this.isAdmin = false;
this.username = "Admin"; if (userName.equals("Admin"))
this.host = host; throw new MageException("User name already in use");
User user = UserManager.getInstance().createUser(userName, host);
if (user == null) { // user already exists
user = UserManager.getInstance().findUser(userName);
if (user.getHost().equals(host)) {
if (user.getSessionId().isEmpty())
logger.info("Reconnecting session for " + userName);
else
throw new MageException("This machine is already connected");
}
else {
throw new MageException("User name already in use");
}
}
if (!UserManager.getInstance().connectToSession(sessionId, user.getId()))
throw new MageException("Error connecting");
this.userId = user.getId();
}
public void registerAdmin() {
this.isAdmin = true; this.isAdmin = true;
this.timeConnected = new Date(); User user = UserManager.getInstance().createUser("Admin", host);
ping(); this.userId = user.getId();
} }
public UUID getId() { public String getId() {
return sessionId; return sessionId;
} }
public UUID getClientId() { public void disconnect() {
return clientId; UserManager.getInstance().disconnect(userId);
} }
public void kill() { public void kill() {
callback.destroy(); UserManager.getInstance().removeUser(userId);
SessionManager.getInstance().removeSession(sessionId);
TableManager.getInstance().removeSession(sessionId);
GameManager.getInstance().removeSession(sessionId);
ChatManager.getInstance().removeSession(sessionId);
} }
public ClientCallback callback() { synchronized void fireCallback(final ClientCallback call) {
try { try {
return callback.callback(); call.setMessageId(messageId++);
} catch (InterruptedException ex) { callbackHandler.handleCallbackOneway(new Callback(call));
logger.fatal("Session callback error", ex); } catch (HandleCallbackException ex) {
}
return null;
}
public synchronized void fireCallback(final ClientCallback call) {
call.setMessageId(messageId++);
if (logger.isDebugEnabled())
logger.debug(sessionId + " - " + call.getMessageId() + " - " + call.getMethod());
try {
callback.setCallback(call);
} catch (InterruptedException ex) {
logger.fatal("Session fireCallback error", ex); logger.fatal("Session fireCallback error", ex);
disconnect();
} }
} }
public void gameStarted(final UUID gameId, final UUID playerId) { public UUID getUserId() {
fireCallback(new ClientCallback("startGame", gameId, new TableClientMessage(gameId, playerId))); return userId;
}
public void draftStarted(final UUID draftId, final UUID playerId) {
fireCallback(new ClientCallback("startDraft", draftId, new TableClientMessage(draftId, playerId)));
}
public void tournamentStarted(final UUID tournamentId, final UUID playerId) {
fireCallback(new ClientCallback("startTournament", tournamentId, new TableClientMessage(tournamentId, playerId)));
}
public void sideboard(final Deck deck, final UUID tableId, final int time) {
fireCallback(new ClientCallback("sideboard", tableId, new TableClientMessage(deck, tableId, time)));
}
public void construct(final Deck deck, final UUID tableId, final int time) {
fireCallback(new ClientCallback("construct", tableId, new TableClientMessage(deck, tableId, time)));
}
public void watchGame(final UUID gameId) {
fireCallback(new ClientCallback("watchGame", gameId));
}
public void replayGame(final UUID gameId) {
fireCallback(new ClientCallback("replayGame", gameId));
}
public void ack(String message) {
this.ackMessage = message;
}
public String getAckMessage() {
return ackMessage;
}
public void clearAck() {
this.ackMessage = "";
}
public String getUsername() {
return username;
}
public void ping() {
this.lastPing = System.currentTimeMillis();
if (logger.isTraceEnabled())
logger.trace("Ping received from" + username + ":" + sessionId);
}
public boolean stillAlive() {
return (System.currentTimeMillis() - lastPing) < 60000;
} }
public boolean isAdmin() { public boolean isAdmin() {
@ -176,4 +126,8 @@ public class Session {
public Date getConnectionTime() { public Date getConnectionTime() {
return timeConnected; return timeConnected;
} }
void setHost(String hostAddress) {
this.host = hostAddress;
}
} }

View file

@ -28,18 +28,13 @@
package mage.server; package mage.server;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mage.MageException; import mage.MageException;
import mage.view.UserView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jboss.remoting.callback.InvokerCallbackHandler;
/** /**
* *
@ -49,92 +44,69 @@ public class SessionManager {
private final static Logger logger = Logger.getLogger(SessionManager.class); private final static Logger logger = Logger.getLogger(SessionManager.class);
private final static SessionManager INSTANCE = new SessionManager(); private final static SessionManager INSTANCE = new SessionManager();
private static ScheduledExecutorService sessionExecutor;
public static SessionManager getInstance() { public static SessionManager getInstance() {
return INSTANCE; return INSTANCE;
} }
protected SessionManager() { private ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<String, Session>();
sessionExecutor = Executors.newScheduledThreadPool(1);
sessionExecutor.scheduleWithFixedDelay(new SessionChecker(), 30, 10, TimeUnit.SECONDS);
}
private ConcurrentHashMap<UUID, Session> sessions = new ConcurrentHashMap<UUID, Session>(); public Session getSession(String sessionId) {
public Session getSession(UUID sessionId) {
if (sessions == null || sessionId == null) return null; if (sessions == null || sessionId == null) return null;
return sessions.get(sessionId); return sessions.get(sessionId);
} }
public UUID createSession(String userName, String host, UUID clientId) throws MageException { public void createSession(String sessionId, InvokerCallbackHandler callbackHandler) {
for (Session session: sessions.values()) { Session session = new Session(sessionId, callbackHandler);
if (session.getUsername().equals(userName)) { sessions.put(sessionId, session);
if (session.getClientId().equals(clientId)) { }
logger.info("Reconnecting session " + session.getId() + " for " + userName);
return session.getId(); public boolean registerUser(String sessionId, String userName) throws MageException {
} Session session = sessions.get(sessionId);
else { if (session != null) {
throw new MageException("User name already in use"); session.registerUser(userName);
} logger.info("User " + userName + " connected from " + session.getHost());
} return true;
} }
Session session = new Session(userName, host, clientId); return false;
sessions.put(session.getId(), session);
logger.info("Session " + session.getId() + " created for user " + userName);
return session.getId();
} }
public UUID createSession(String host) throws MageException { public boolean registerAdmin(String sessionId) {
Session session = new Session(host); Session session = sessions.get(sessionId);
sessions.put(session.getId(), session); if (session != null) {
logger.info("Admin session created"); session.registerAdmin();
return session.getId(); logger.info("Admin connected from " + session.getHost());
return true;
}
return false;
} }
public void removeSession(UUID sessionId) { public synchronized void disconnect(String sessionId, boolean voluntary) {
sessions.remove(sessionId); Session session = sessions.get(sessionId);
} if (session != null) {
if (voluntary)
public void checkSessions() {
logger.trace("Checking sessions");
for (Session session: sessions.values()) {
if (!session.stillAlive()) {
logger.info("Client for user " + session.getUsername() + ":" + session.getId() + " timed out - releasing resources");
session.kill(); session.kill();
} else
session.disconnect();
sessions.remove(sessionId);
} }
} }
public Map<UUID, Session> getSessions() { public Map<String, Session> getSessions() {
Map<UUID, Session> map = new HashMap<UUID, Session>(); Map<String, Session> map = new HashMap<String, Session>();
for (Map.Entry<UUID, Session> entry : sessions.entrySet()) { for (Map.Entry<String, Session> entry : sessions.entrySet()) {
map.put(entry.getKey(), entry.getValue()); map.put(entry.getKey(), entry.getValue());
} }
return map; return map;
} }
List<UserView> getUsers(UUID sessionId) { public void disconnectUser(String sessionId, String userSessionId) {
List<UserView> users = new ArrayList<UserView>();
Session admin = sessions.get(sessionId);
if (admin != null && admin.isAdmin()) {
for (Session session: sessions.values()) {
users.add(new UserView(session.getUsername(), session.getHost(), session.getId(), session.getConnectionTime()));
}
}
return users;
}
public void disconnectUser(UUID sessionId, UUID userSessionId) {
if (isAdmin(sessionId)) { if (isAdmin(sessionId)) {
Session session = sessions.get(userSessionId); disconnect(userSessionId, true);
if (session != null) {
session.kill();
}
} }
} }
public boolean isAdmin(UUID sessionId) { public boolean isAdmin(String sessionId) {
Session admin = sessions.get(sessionId); Session admin = sessions.get(sessionId);
if (admin != null) { if (admin != null) {
return admin.isAdmin(); return admin.isAdmin();
@ -142,19 +114,16 @@ public class SessionManager {
return false; return false;
} }
public boolean isValidSession(UUID sessionId) { public boolean isValidSession(String sessionId) {
if (sessions.containsKey(sessionId)) if (sessions.containsKey(sessionId))
return true; return true;
return false; return false;
} }
class SessionChecker implements Runnable { public User getUser(String sessionId) {
if (sessions.containsKey(sessionId)) {
@Override return UserManager.getInstance().getUser(sessions.get(sessionId).getUserId());
public void run() {
checkSessions();
} }
return null;
} }
} }

View file

@ -28,7 +28,6 @@
package mage.server; package mage.server;
import java.util.logging.Level;
import mage.Constants.RangeOfInfluence; import mage.Constants.RangeOfInfluence;
import mage.Constants.TableState; import mage.Constants.TableState;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
@ -67,36 +66,38 @@ public class TableController {
private final static Logger logger = Logger.getLogger(TableController.class); private final static Logger logger = Logger.getLogger(TableController.class);
private UUID sessionId; private UUID userId;
private UUID chatId; private UUID chatId;
private String controllerName; private String controllerName;
private Table table; private Table table;
private Match match; private Match match;
private MatchOptions options; private MatchOptions options;
private Tournament tournament; private Tournament tournament;
private ConcurrentHashMap<UUID, UUID> sessionPlayerMap = new ConcurrentHashMap<UUID, UUID>(); private ConcurrentHashMap<UUID, UUID> userPlayerMap = new ConcurrentHashMap<UUID, UUID>();
public TableController(UUID roomId, UUID sessionId, MatchOptions options) { public TableController(UUID roomId, UUID userId, MatchOptions options) {
this.sessionId = sessionId; this.userId = userId;
chatId = ChatManager.getInstance().createChatSession(); chatId = ChatManager.getInstance().createChatSession();
this.options = options; this.options = options;
match = GameFactory.getInstance().createMatch(options.getGameType(), options); match = GameFactory.getInstance().createMatch(options.getGameType(), options);
Session session = SessionManager.getInstance().getSession(sessionId); if (userId != null) {
if (session != null) User user = UserManager.getInstance().getUser(userId);
controllerName = session.getUsername(); controllerName = user.getName();
}
else else
controllerName = "System"; controllerName = "System";
table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match); table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match);
init(); init();
} }
public TableController(UUID roomId, UUID sessionId, TournamentOptions options) { public TableController(UUID roomId, UUID userId, TournamentOptions options) {
this.sessionId = sessionId; this.userId = userId;
chatId = ChatManager.getInstance().createChatSession(); chatId = ChatManager.getInstance().createChatSession();
tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options); tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options);
Session session = SessionManager.getInstance().getSession(sessionId); if (userId != null) {
if (session != null) User user = UserManager.getInstance().getUser(userId);
controllerName = session.getUsername(); controllerName = user.getName();
}
else else
controllerName = "System"; controllerName = "System";
table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), tournament); table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), tournament);
@ -124,7 +125,7 @@ public class TableController {
); );
} }
public synchronized boolean joinTournament(UUID sessionId, String name, String playerType, int skill) throws GameException { public synchronized boolean joinTournament(UUID userId, String name, String playerType, int skill) throws GameException {
if (table.getState() != TableState.WAITING) { if (table.getState() != TableState.WAITING) {
return false; return false;
} }
@ -138,13 +139,13 @@ public class TableController {
logger.info("player joined " + player.getId()); logger.info("player joined " + player.getId());
//only add human players to sessionPlayerMap //only add human players to sessionPlayerMap
if (seat.getPlayer().isHuman()) { if (seat.getPlayer().isHuman()) {
sessionPlayerMap.put(sessionId, player.getId()); userPlayerMap.put(userId, player.getId());
} }
return true; return true;
} }
public synchronized boolean joinTable(UUID sessionId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { public synchronized boolean joinTable(UUID userId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
if (table.getState() != TableState.WAITING) { if (table.getState() != TableState.WAITING) {
return false; return false;
} }
@ -153,7 +154,7 @@ public class TableController {
throw new GameException("No available seats."); throw new GameException("No available seats.");
} }
Deck deck = Deck.load(deckList); Deck deck = Deck.load(deckList);
if (!Main.server.isTestMode() && !table.getValidator().validate(deck)) { if (!Main.isTestMode() && !table.getValidator().validate(deck)) {
throw new InvalidDeckException(name + " has an invalid deck for this format", table.getValidator().getInvalid()); throw new InvalidDeckException(name + " has an invalid deck for this format", table.getValidator().getInvalid());
} }
@ -163,13 +164,13 @@ public class TableController {
logger.info("player joined " + player.getId()); logger.info("player joined " + player.getId());
//only add human players to sessionPlayerMap //only add human players to sessionPlayerMap
if (seat.getPlayer().isHuman()) { if (seat.getPlayer().isHuman()) {
sessionPlayerMap.put(sessionId, player.getId()); userPlayerMap.put(userId, player.getId());
} }
return true; return true;
} }
public void addPlayer(UUID sessionId, Player player, String playerType, Deck deck) throws GameException { public void addPlayer(UUID userId, Player player, String playerType, Deck deck) throws GameException {
if (table.getState() != TableState.WAITING) { if (table.getState() != TableState.WAITING) {
return; return;
} }
@ -180,44 +181,45 @@ public class TableController {
match.addPlayer(player, deck); match.addPlayer(player, deck);
table.joinTable(player, seat); table.joinTable(player, seat);
if (player.isHuman()) { if (player.isHuman()) {
sessionPlayerMap.put(sessionId, player.getId()); userPlayerMap.put(userId, player.getId());
} }
} }
public synchronized boolean submitDeck(UUID sessionId, DeckCardLists deckList) throws MageException { public synchronized boolean submitDeck(UUID userId, DeckCardLists deckList) throws MageException {
UUID playerId = userPlayerMap.get(userId);
if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) { if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) {
return false; return false;
} }
Deck deck = Deck.load(deckList); Deck deck = Deck.load(deckList);
if (!Main.server.isTestMode() && !table.getValidator().validate(deck)) { if (!Main.isTestMode() && !table.getValidator().validate(deck)) {
throw new InvalidDeckException("Invalid deck for this format", table.getValidator().getInvalid()); throw new InvalidDeckException("Invalid deck for this format", table.getValidator().getInvalid());
} }
submitDeck(sessionId, deck); submitDeck(playerId, deck);
return true; return true;
} }
private void submitDeck(UUID sessionId, Deck deck) { private void submitDeck(UUID playerId, Deck deck) {
if (table.getState() == TableState.SIDEBOARDING) { if (table.getState() == TableState.SIDEBOARDING) {
match.submitDeck(sessionPlayerMap.get(sessionId), deck); match.submitDeck(playerId, deck);
} }
else { else {
TournamentManager.getInstance().submitDeck(tournament.getId(), sessionId, deck); TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck);
} }
} }
public boolean watchTable(UUID sessionId) { public boolean watchTable(UUID userId) {
if (table.getState() != TableState.DUELING) { if (table.getState() != TableState.DUELING) {
return false; return false;
} }
SessionManager.getInstance().getSession(sessionId).watchGame(match.getGame().getId()); UserManager.getInstance().getUser(userId).watchGame(match.getGame().getId());
return true; return true;
} }
public boolean replayTable(UUID sessionId) { public boolean replayTable(UUID userId) {
if (table.getState() != TableState.FINISHED) { if (table.getState() != TableState.FINISHED) {
return false; return false;
} }
ReplayManager.getInstance().replayGame(sessionId, table.getId()); ReplayManager.getInstance().replayGame(table.getId(), userId);
return true; return true;
} }
@ -233,19 +235,24 @@ public class TableController {
return player; return player;
} }
public synchronized void leaveTable(UUID sessionId) { public void kill(UUID userId) {
if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING) leaveTable(userId);
table.leaveTable(sessionPlayerMap.get(sessionId)); userPlayerMap.remove(userId);
} }
public synchronized void startMatch(UUID sessionId) { public synchronized void leaveTable(UUID userId) {
if (sessionId.equals(this.sessionId)) { if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING)
table.leaveTable(userPlayerMap.get(userId));
}
public synchronized void startMatch(UUID userId) {
if (userId.equals(this.userId)) {
startMatch(); startMatch();
} }
} }
public synchronized void startChallenge(UUID sessionId, UUID challengeId) { public synchronized void startChallenge(UUID userId, UUID challengeId) {
if (sessionId.equals(this.sessionId)) { if (userId.equals(this.userId)) {
try { try {
match.startMatch(); match.startMatch();
match.startGame(); match.startGame();
@ -253,11 +260,10 @@ public class TableController {
GameOptions options = new GameOptions(); GameOptions options = new GameOptions();
options.testMode = true; options.testMode = true;
// match.getGame().setGameOptions(options); // match.getGame().setGameOptions(options);
GameManager.getInstance().createGameSession(match.getGame(), sessionPlayerMap, table.getId(), null); GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), null);
ChallengeManager.getInstance().prepareChallenge(getPlayerId(), match); ChallengeManager.getInstance().prepareChallenge(getPlayerId(), match);
SessionManager sessionManager = SessionManager.getInstance(); for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
for (Entry<UUID, UUID> entry: sessionPlayerMap.entrySet()) { UserManager.getInstance().getUser(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue());
sessionManager.getSession(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue());
} }
} catch (GameException ex) { } catch (GameException ex) {
logger.fatal(null, ex); logger.fatal(null, ex);
@ -267,7 +273,7 @@ public class TableController {
private UUID getPlayerId() throws GameException { private UUID getPlayerId() throws GameException {
UUID playerId = null; UUID playerId = null;
for (Entry<UUID, UUID> entry : sessionPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
playerId = entry.getValue(); playerId = entry.getValue();
break; break;
} }
@ -292,12 +298,11 @@ public class TableController {
try { try {
match.startGame(); match.startGame();
table.initGame(); table.initGame();
GameManager.getInstance().createGameSession(match.getGame(), sessionPlayerMap, table.getId(), choosingPlayerId); GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId);
SessionManager sessionManager = SessionManager.getInstance(); for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
for (Entry<UUID, UUID> entry: sessionPlayerMap.entrySet()) { User user = UserManager.getInstance().getUser(entry.getKey());
Session session = sessionManager.getSession(entry.getKey()); if (user != null) {
if (session != null) { user.gameStarted(match.getGame().getId(), entry.getValue());
session.gameStarted(match.getGame().getId(), entry.getValue());
} }
else { else {
TableManager.getInstance().removeTable(table.getId()); TableManager.getInstance().removeTable(table.getId());
@ -314,38 +319,37 @@ public class TableController {
} }
} }
public synchronized void startTournament(UUID sessionId) { public synchronized void startTournament(UUID userId) {
try { try {
if (sessionId.equals(this.sessionId) && table.getState() == TableState.STARTING) { if (userId.equals(this.userId) && table.getState() == TableState.STARTING) {
TournamentManager.getInstance().createTournamentSession(tournament, sessionPlayerMap, table.getId()); TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId());
SessionManager sessionManager = SessionManager.getInstance(); for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
for (Entry<UUID, UUID> entry: sessionPlayerMap.entrySet()) { User user = UserManager.getInstance().getUser(entry.getKey());
Session session = sessionManager.getSession(entry.getKey()); user.tournamentStarted(tournament.getId(), entry.getValue());
session.tournamentStarted(tournament.getId(), entry.getValue());
} }
} }
} }
catch (Exception ex) { catch (Exception ex) {
logger.fatal("Error starting tournament", ex); logger.fatal("Error starting tournament", ex);
TableManager.getInstance().removeTable(table.getId()); TableManager.getInstance().removeTable(table.getId());
TournamentManager.getInstance().kill(tournament.getId(), sessionId); TournamentManager.getInstance().kill(tournament.getId(), userId);
} }
} }
public void startDraft(Draft draft) { public void startDraft(Draft draft) {
table.initDraft(); table.initDraft();
DraftManager.getInstance().createDraftSession(draft, sessionPlayerMap, table.getId()); DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId());
SessionManager sessionManager = SessionManager.getInstance(); for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
for (Entry<UUID, UUID> entry: sessionPlayerMap.entrySet()) { UserManager.getInstance().getUser(entry.getKey()).draftStarted(draft.getId(), entry.getValue());
sessionManager.getSession(entry.getKey()).draftStarted(draft.getId(), entry.getValue());
} }
} }
private void sideboard(UUID playerId, Deck deck, int timeout) throws MageException { private void sideboard(UUID playerId, Deck deck, int timeout) throws MageException {
SessionManager sessionManager = SessionManager.getInstance(); for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
for (Entry<UUID, UUID> entry: sessionPlayerMap.entrySet()) {
if (entry.getValue().equals(playerId)) { if (entry.getValue().equals(playerId)) {
sessionManager.getSession(entry.getKey()).sideboard(deck, table.getId(), timeout); User user = UserManager.getInstance().getUser(entry.getKey());
if (user != null)
user.sideboard(deck, table.getId(), timeout);
break; break;
} }
} }
@ -382,6 +386,10 @@ public class TableController {
tournament.nextStep(); tournament.nextStep();
} }
public void endTournament(Tournament tournament) {
//TODO: implement this
}
public void swapSeats(int seatNum1, int seatNum2) { public void swapSeats(int seatNum1, int seatNum2) {
if (table.getState() == TableState.STARTING) { if (table.getState() == TableState.STARTING) {
if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) { if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) {
@ -395,8 +403,8 @@ public class TableController {
} }
} }
public boolean isOwner(UUID sessionId) { public boolean isOwner(UUID userId) {
return sessionId.equals(this.sessionId); return userId.equals(this.userId);
} }
public Table getTable() { public Table getTable() {

View file

@ -38,6 +38,7 @@ import mage.game.GameException;
import mage.game.draft.Draft; import mage.game.draft.Draft;
import mage.game.match.Match; import mage.game.match.Match;
import mage.game.match.MatchOptions; import mage.game.match.MatchOptions;
import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentOptions; import mage.game.tournament.TournamentOptions;
import mage.MageException; import mage.MageException;
import mage.players.Player; import mage.players.Player;
@ -60,22 +61,22 @@ public class TableManager {
return INSTANCE; return INSTANCE;
} }
public Table createTable(UUID roomId, UUID sessionId, MatchOptions options) { public Table createTable(UUID roomId, UUID userId, MatchOptions options) {
TableController tableController = new TableController(roomId, sessionId, options); TableController tableController = new TableController(roomId, userId, options);
controllers.put(tableController.getTable().getId(), tableController); controllers.put(tableController.getTable().getId(), tableController);
tables.put(tableController.getTable().getId(), tableController.getTable()); tables.put(tableController.getTable().getId(), tableController.getTable());
return tableController.getTable(); return tableController.getTable();
} }
public Table createTable(UUID roomId, MatchOptions options) { public Table createTable(UUID roomId, MatchOptions options) {
TableController tableController = new TableController(roomId, UUID.randomUUID(), options); TableController tableController = new TableController(roomId, null, options);
controllers.put(tableController.getTable().getId(), tableController); controllers.put(tableController.getTable().getId(), tableController);
tables.put(tableController.getTable().getId(), tableController.getTable()); tables.put(tableController.getTable().getId(), tableController.getTable());
return tableController.getTable(); return tableController.getTable();
} }
public Table createTournamentTable(UUID roomId, UUID sessionId, TournamentOptions options) { public Table createTournamentTable(UUID roomId, UUID userId, TournamentOptions options) {
TableController tableController = new TableController(roomId, sessionId, options); TableController tableController = new TableController(roomId, userId, options);
controllers.put(tableController.getTable().getId(), tableController); controllers.put(tableController.getTable().getId(), tableController);
tables.put(tableController.getTable().getId(), tableController.getTable()); tables.put(tableController.getTable().getId(), tableController.getTable());
return tableController.getTable(); return tableController.getTable();
@ -95,45 +96,47 @@ public class TableManager {
return tables.values(); return tables.values();
} }
public boolean joinTable(UUID sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
return controllers.get(tableId).joinTable(sessionId, name, playerType, skill, deckList); return controllers.get(tableId).joinTable(userId, name, playerType, skill, deckList);
return false; return false;
} }
public boolean joinTournament(UUID sessionId, UUID tableId, String name, String playerType, int skill) throws GameException { public boolean joinTournament(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
return controllers.get(tableId).joinTournament(sessionId, name, playerType, skill); return controllers.get(tableId).joinTournament(userId, name, playerType, skill);
return false; return false;
} }
public boolean submitDeck(UUID sessionId, UUID tableId, DeckCardLists deckList) throws MageException { public boolean submitDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
return controllers.get(tableId).submitDeck(sessionId, deckList); return controllers.get(tableId).submitDeck(userId, deckList);
return false; return false;
} }
public void removeSession(UUID sessionId) { public void removeSession(UUID userId) {
// TODO: search through tables and remove session for (TableController controller: controllers.values()) {
controller.kill(userId);
}
} }
public boolean isTableOwner(UUID tableId, UUID sessionId) { public boolean isTableOwner(UUID tableId, UUID userId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
return controllers.get(tableId).isOwner(sessionId); return controllers.get(tableId).isOwner(userId);
return false; return false;
} }
public boolean removeTable(UUID sessionId, UUID tableId) { public boolean removeTable(UUID userId, UUID tableId) {
if (isTableOwner(tableId, sessionId) || SessionManager.getInstance().isAdmin(sessionId)) { if (isTableOwner(tableId, userId) || UserManager.getInstance().isAdmin(userId)) {
removeTable(tableId); removeTable(tableId);
return true; return true;
} }
return false; return false;
} }
public void leaveTable(UUID sessionId, UUID tableId) { public void leaveTable(UUID userId, UUID tableId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
controllers.get(tableId).leaveTable(sessionId); controllers.get(tableId).leaveTable(userId);
} }
public UUID getChatId(UUID tableId) { public UUID getChatId(UUID tableId) {
@ -142,9 +145,9 @@ public class TableManager {
return null; return null;
} }
public void startMatch(UUID sessionId, UUID roomId, UUID tableId) { public void startMatch(UUID userId, UUID roomId, UUID tableId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
controllers.get(tableId).startMatch(sessionId); controllers.get(tableId).startMatch(userId);
} }
public void startMatch(UUID roomId, UUID tableId) { public void startMatch(UUID roomId, UUID tableId) {
@ -152,14 +155,14 @@ public class TableManager {
controllers.get(tableId).startMatch(); controllers.get(tableId).startMatch();
} }
public void startChallenge(UUID sessionId, UUID roomId, UUID tableId, UUID challengeId) { public void startChallenge(UUID userId, UUID roomId, UUID tableId, UUID challengeId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
controllers.get(tableId).startChallenge(sessionId, challengeId); controllers.get(tableId).startChallenge(userId, challengeId);
} }
public void startTournament(UUID sessionId, UUID roomId, UUID tableId) { public void startTournament(UUID userId, UUID roomId, UUID tableId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
controllers.get(tableId).startTournament(sessionId); controllers.get(tableId).startTournament(userId);
} }
public void startDraft(UUID tableId, Draft draft) { public void startDraft(UUID tableId, Draft draft) {
@ -167,15 +170,15 @@ public class TableManager {
controllers.get(tableId).startDraft(draft); controllers.get(tableId).startDraft(draft);
} }
public boolean watchTable(UUID sessionId, UUID tableId) { public boolean watchTable(UUID userId, UUID tableId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
return controllers.get(tableId).watchTable(sessionId); return controllers.get(tableId).watchTable(userId);
return false; return false;
} }
public boolean replayTable(UUID sessionId, UUID tableId) { public boolean replayTable(UUID userId, UUID tableId) {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
return controllers.get(tableId).replayTable(sessionId); return controllers.get(tableId).replayTable(userId);
return false; return false;
} }
@ -189,8 +192,13 @@ public class TableManager {
controllers.get(tableId).endDraft(draft); controllers.get(tableId).endDraft(draft);
} }
public void swapSeats(UUID tableId, UUID sessionId, int seatNum1, int seatNum2) { public void endTournament(UUID tableId, Tournament tournament) {
if (controllers.containsKey(tableId) && isTableOwner(tableId, sessionId)) { if (controllers.containsKey(tableId))
controllers.get(tableId).endTournament(tournament);
}
public void swapSeats(UUID tableId, UUID userId, int seatNum1, int seatNum2) {
if (controllers.containsKey(tableId) && isTableOwner(tableId, userId)) {
controllers.get(tableId).swapSeats(seatNum1, seatNum2); controllers.get(tableId).swapSeats(seatNum1, seatNum2);
} }
} }
@ -200,9 +208,9 @@ public class TableManager {
controllers.get(tableId).construct(); controllers.get(tableId).construct();
} }
public void addPlayer(UUID sessionId, UUID tableId, Player player, String playerType, Deck deck) throws GameException { public void addPlayer(UUID userId, UUID tableId, Player player, String playerType, Deck deck) throws GameException {
if (controllers.containsKey(tableId)) if (controllers.containsKey(tableId))
controllers.get(tableId).addPlayer(sessionId, player, playerType, deck); controllers.get(tableId).addPlayer(userId, player, playerType, deck);
} }
public void removeTable(UUID tableId) { public void removeTable(UUID tableId) {

View file

@ -0,0 +1,219 @@
/*
* Copyright 2011 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.server;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import mage.cards.decks.Deck;
import mage.interfaces.callback.ClientCallback;
import mage.server.draft.DraftSession;
import mage.server.game.GameManager;
import mage.server.game.GameSession;
import mage.server.tournament.TournamentSession;
import mage.view.TableClientMessage;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class User {
public enum UserState {
Created, Connected, Disconnected, Reconnected;
}
private UUID userId = UUID.randomUUID();
private String userName;
private String sessionId = "";
private String host;
private Date connectionTime = new Date();
private Date lastActivity = new Date();
private UserState userState;
private Map<UUID, GameSession> gameSessions = new HashMap<UUID, GameSession>();
private Map<UUID, DraftSession> draftSessions = new HashMap<UUID, DraftSession>();
private Map<UUID, TournamentSession> tournamentSessions = new HashMap<UUID, TournamentSession>();
public User(String userName, String host) {
this.userName = userName;
this.host = host;
this.userState = UserState.Created;
}
public String getName() {
return userName;
}
public UUID getId() {
return userId;
}
public String getHost() {
return host;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
if (sessionId.isEmpty())
userState = UserState.Disconnected;
else if (userState == UserState.Created)
userState = UserState.Connected;
else {
userState = UserState.Reconnected;
reconnect();
}
}
public boolean isConnected() {
return userState == UserState.Connected || userState == UserState.Reconnected;
}
public Date getConnectionTime() {
return connectionTime;
}
public synchronized void fireCallback(final ClientCallback call) {
if (isConnected()) {
Session session = SessionManager.getInstance().getSession(sessionId);
session.fireCallback(call);
}
}
public void gameStarted(final UUID gameId, final UUID playerId) {
fireCallback(new ClientCallback("startGame", gameId, new TableClientMessage(gameId, playerId)));
}
public void draftStarted(final UUID draftId, final UUID playerId) {
fireCallback(new ClientCallback("startDraft", draftId, new TableClientMessage(draftId, playerId)));
}
public void tournamentStarted(final UUID tournamentId, final UUID playerId) {
fireCallback(new ClientCallback("startTournament", tournamentId, new TableClientMessage(tournamentId, playerId)));
}
public void sideboard(final Deck deck, final UUID tableId, final int time) {
fireCallback(new ClientCallback("sideboard", tableId, new TableClientMessage(deck, tableId, time)));
}
public void construct(final Deck deck, final UUID tableId, final int time) {
fireCallback(new ClientCallback("construct", tableId, new TableClientMessage(deck, tableId, time)));
}
public void watchGame(final UUID gameId) {
fireCallback(new ClientCallback("watchGame", gameId));
}
public void replayGame(final UUID gameId) {
fireCallback(new ClientCallback("replayGame", gameId));
}
public void sendPlayerUUID(final UUID gameId, final UUID data) {
lastActivity = new Date();
GameManager.getInstance().sendPlayerUUID(gameId, userId, data);
}
public void sendPlayerString(final UUID gameId, final String data) {
lastActivity = new Date();
GameManager.getInstance().sendPlayerString(gameId, userId, data);
}
public void sendPlayerBoolean(final UUID gameId, final Boolean data) {
lastActivity = new Date();
GameManager.getInstance().sendPlayerBoolean(gameId, userId, data);
}
public void sendPlayerInteger(final UUID gameId, final Integer data) {
lastActivity = new Date();
GameManager.getInstance().sendPlayerInteger(gameId, userId, data);
}
public boolean isExpired(Date expired) {
return userState == UserState.Disconnected && lastActivity.before(expired);
}
private void reconnect() {
for (Entry<UUID, GameSession> entry: gameSessions.entrySet()) {
gameStarted(entry.getValue().getGameId(), entry.getKey());
entry.getValue().init();
GameManager.getInstance().sendPlayerString(entry.getValue().getGameId(), userId, "");
}
for (Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
draftStarted(entry.getValue().getDraftId(), entry.getKey());
entry.getValue().init();
entry.getValue().update();
}
for (Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
tournamentStarted(entry.getValue().getTournamentId(), entry.getKey());
entry.getValue().init();
entry.getValue().update();
}
}
public void addGame(UUID playerId, GameSession gameSession) {
gameSessions.put(playerId, gameSession);
}
public void removeGame(UUID playerId) {
gameSessions.remove(playerId);
}
public void addDraft(UUID playerId, DraftSession draftSession) {
draftSessions.put(playerId, draftSession);
}
public void removeDraft(UUID playerId) {
draftSessions.remove(playerId);
}
public void addTournament(UUID playerId, TournamentSession tournamentSession) {
tournamentSessions.put(playerId, tournamentSession);
}
public void removeTournament(UUID playerId) {
tournamentSessions.remove(playerId);
}
public void kill() {
for (Entry<UUID, GameSession> entry: gameSessions.entrySet()) {
entry.getValue().kill();
}
for (Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
entry.getValue().setKilled();
}
for (Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
entry.getValue().setKilled();
}
}
}

View file

@ -0,0 +1,134 @@
/*
* Copyright 2011 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.server;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mage.view.ChatMessage.MessageColor;
/**
*
* manages users - if a user is disconnected and 10 minutes have passed with no
* activity the user is removed
*
* @author BetaSteward_at_googlemail.com
*/
public class UserManager {
protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
private final static UserManager INSTANCE = new UserManager();
public static UserManager getInstance() {
return INSTANCE;
}
private UserManager() {
expireExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
checkExpired();
}
}, 60, 60, TimeUnit.SECONDS);
}
private ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<UUID, User>();
public User createUser(String userName, String host) {
if (findUser(userName) != null)
return null; //user already exists
User user = new User(userName, host);
users.put(user.getId(), user);
return user;
}
public User getUser(UUID userId) {
return users.get(userId);
}
public User findUser(String userName) {
for (User user: users.values()) {
if (user.getName().equals(userName))
return user;
}
return null;
}
public Collection<User> getUsers() {
return users.values();
}
public boolean connectToSession(String sessionId, UUID userId) {
if (users.containsKey(userId)) {
users.get(userId).setSessionId(sessionId);
return true;
}
return false;
}
public void disconnect(UUID userId) {
if (users.containsKey(userId)) {
users.get(userId).setSessionId("");
ChatManager.getInstance().broadcast(userId, "has lost connection", MessageColor.BLACK);
}
}
public boolean isAdmin(UUID userId) {
if (users.containsKey(userId)) {
return users.get(userId).getName().equals("Admin");
}
return false;
}
public void removeUser(UUID userId) {
if (users.containsKey(userId)) {
users.get(userId).setSessionId("");
ChatManager.getInstance().broadcast(userId, "has disconnected", MessageColor.BLACK);
users.get(userId).kill();
users.remove(userId);
}
}
private void checkExpired() {
Calendar expired = Calendar.getInstance();
expired.add(Calendar.MINUTE, -10) ;
for (User user: users.values()) {
if (user.isExpired(expired.getTime())) {
user.kill();
users.remove(user.getId());
}
}
}
}

View file

@ -28,6 +28,7 @@
package mage.server.draft; package mage.server.draft;
import java.io.File;
import java.util.UUID; import java.util.UUID;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -40,6 +41,7 @@ import mage.game.events.TableEvent;
import mage.MageException; import mage.MageException;
import mage.server.game.GameController; import mage.server.game.GameController;
import mage.server.TableManager; import mage.server.TableManager;
import mage.server.UserManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.DraftPickView; import mage.view.DraftPickView;
import mage.view.DraftView; import mage.view.DraftView;
@ -52,16 +54,17 @@ import org.apache.log4j.Logger;
public class DraftController { public class DraftController {
private final static Logger logger = Logger.getLogger(GameController.class); private final static Logger logger = Logger.getLogger(GameController.class);
public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt";
private ConcurrentHashMap<UUID, DraftSession> draftSessions = new ConcurrentHashMap<UUID, DraftSession>(); private ConcurrentHashMap<UUID, DraftSession> draftSessions = new ConcurrentHashMap<UUID, DraftSession>();
private ConcurrentHashMap<UUID, UUID> sessionPlayerMap; private ConcurrentHashMap<UUID, UUID> userPlayerMap;
private UUID draftSessionId; private UUID draftSessionId;
private Draft draft; private Draft draft;
private UUID tableId; private UUID tableId;
public DraftController(Draft draft, ConcurrentHashMap<UUID, UUID> sessionPlayerMap, UUID tableId) { public DraftController(Draft draft, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
draftSessionId = UUID.randomUUID(); draftSessionId = UUID.randomUUID();
this.sessionPlayerMap = sessionPlayerMap; this.userPlayerMap = userPlayerMap;
this.draft = draft; this.draft = draft;
this.tableId = tableId; this.tableId = tableId;
init(); init();
@ -114,22 +117,23 @@ public class DraftController {
checkStart(); checkStart();
} }
private UUID getPlayerId(UUID sessionId) { private UUID getPlayerId(UUID userId) {
return sessionPlayerMap.get(sessionId); return userPlayerMap.get(userId);
} }
public void join(UUID sessionId) { public void join(UUID userId) {
UUID playerId = sessionPlayerMap.get(sessionId); UUID playerId = userPlayerMap.get(userId);
DraftSession draftSession = new DraftSession(draft, sessionId, playerId); DraftSession draftSession = new DraftSession(draft, userId, playerId);
draftSessions.put(playerId, draftSession); draftSessions.put(playerId, draftSession);
logger.info("player " + playerId + " has joined draft " + draft.getId()); UserManager.getInstance().getUser(userId).addDraft(playerId, draftSession);
logger.info("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId());
draft.getPlayer(playerId).setJoined(); draft.getPlayer(playerId).setJoined();
checkStart(); checkStart();
} }
private synchronized void startDraft() { private synchronized void startDraft() {
for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) { for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
if (!entry.getValue().init(getDraftView())) { if (!entry.getValue().init()) {
logger.fatal("Unable to initialize client"); logger.fatal("Unable to initialize client");
//TODO: generate client error message //TODO: generate client error message
return; return;
@ -140,7 +144,7 @@ public class DraftController {
private void checkStart() { private void checkStart() {
if (allJoined()) { if (allJoined()) {
ThreadExecutor.getInstance().getRMIExecutor().execute( ThreadExecutor.getInstance().getCallExecutor().execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
@ -161,29 +165,31 @@ public class DraftController {
return true; return true;
} }
private void leave(UUID sessionId) { private void leave(UUID userId) {
draft.leave(getPlayerId(sessionId)); draft.leave(getPlayerId(userId));
} }
private void endDraft() throws MageException { private void endDraft() throws MageException {
for (final DraftSession draftSession: draftSessions.values()) { for (final DraftSession draftSession: draftSessions.values()) {
draftSession.draftOver(); draftSession.draftOver();
draftSession.removeDraft();
} }
TableManager.getInstance().endDraft(tableId, draft); TableManager.getInstance().endDraft(tableId, draft);
} }
public void kill(UUID sessionId) { public void kill(UUID userId) {
if (sessionPlayerMap.containsKey(sessionId)) { if (userPlayerMap.containsKey(userId)) {
draftSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); draftSessions.get(userPlayerMap.get(userId)).setKilled();
draftSessions.remove(sessionPlayerMap.get(sessionId)); draftSessions.remove(userPlayerMap.get(userId));
leave(sessionId); leave(userId);
sessionPlayerMap.remove(sessionId); userPlayerMap.remove(userId);
} }
} }
public void timeout(UUID sessionId) { public void timeout(UUID userId) {
if (sessionPlayerMap.containsKey(sessionId)) { if (userPlayerMap.containsKey(userId)) {
draft.autoPick(sessionPlayerMap.get(sessionId)); draft.autoPick(userPlayerMap.get(userId));
logger.info("Draft pick timeout - autopick for player: " + userPlayerMap.get(userId));
} }
} }
@ -191,30 +197,19 @@ public class DraftController {
return this.draftSessionId; return this.draftSessionId;
} }
public DraftPickView sendCardPick(UUID sessionId, UUID cardId) { public DraftPickView sendCardPick(UUID userId, UUID cardId) {
if (draftSessions.get(sessionPlayerMap.get(sessionId)).sendCardPick(cardId)) { return draftSessions.get(userPlayerMap.get(userId)).sendCardPick(cardId);
return getDraftPickView(sessionPlayerMap.get(sessionId), 0);
}
return null;
} }
private synchronized void updateDraft() throws MageException { private synchronized void updateDraft() throws MageException {
for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) { for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
entry.getValue().update(getDraftView()); entry.getValue().update();
} }
} }
private synchronized void pickCard(UUID playerId, int timeout) throws MageException { private synchronized void pickCard(UUID playerId, int timeout) throws MageException {
if (draftSessions.containsKey(playerId)) if (draftSessions.containsKey(playerId))
draftSessions.get(playerId).pickCard(getDraftPickView(playerId, timeout), timeout); draftSessions.get(playerId).pickCard(timeout);
}
private DraftView getDraftView() {
return new DraftView(draft);
}
private DraftPickView getDraftPickView(UUID playerId, int timeout) {
return new DraftPickView(draft.getPlayer(playerId), timeout);
} }
} }

View file

@ -48,36 +48,36 @@ public class DraftManager {
private ConcurrentHashMap<UUID, DraftController> draftControllers = new ConcurrentHashMap<UUID, DraftController>(); private ConcurrentHashMap<UUID, DraftController> draftControllers = new ConcurrentHashMap<UUID, DraftController>();
public UUID createDraftSession(Draft draft, ConcurrentHashMap<UUID, UUID> sessionPlayerMap, UUID tableId) { public UUID createDraftSession(Draft draft, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
DraftController draftController = new DraftController(draft, sessionPlayerMap, tableId); DraftController draftController = new DraftController(draft, userPlayerMap, tableId);
draftControllers.put(draft.getId(), draftController); draftControllers.put(draft.getId(), draftController);
return draftController.getSessionId(); return draftController.getSessionId();
} }
public void joinDraft(UUID draftId, UUID sessionId) { public void joinDraft(UUID draftId, UUID userId) {
draftControllers.get(draftId).join(sessionId); draftControllers.get(draftId).join(userId);
} }
public void destroyChatSession(UUID gameId) { public void destroyChatSession(UUID gameId) {
draftControllers.remove(gameId); draftControllers.remove(gameId);
} }
public DraftPickView sendCardPick(UUID draftId, UUID sessionId, UUID cardId) { public DraftPickView sendCardPick(UUID draftId, UUID userId, UUID cardId) {
return draftControllers.get(draftId).sendCardPick(sessionId, cardId); return draftControllers.get(draftId).sendCardPick(userId, cardId);
} }
public void removeSession(UUID sessionId) { public void removeSession(UUID userId) {
for (DraftController controller: draftControllers.values()) { for (DraftController controller: draftControllers.values()) {
controller.kill(sessionId); controller.kill(userId);
} }
} }
public void kill(UUID draftId, UUID sessionId) { public void kill(UUID draftId, UUID userId) {
draftControllers.get(draftId).kill(sessionId); draftControllers.get(draftId).kill(userId);
} }
public void timeout(UUID gameId, UUID sessionId) { public void timeout(UUID gameId, UUID userId) {
draftControllers.get(gameId).timeout(sessionId); draftControllers.get(gameId).timeout(userId);
} }
public void removeDraft(UUID draftId) { public void removeDraft(UUID draftId) {

View file

@ -32,15 +32,11 @@ import java.rmi.RemoteException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import mage.game.draft.Draft; import mage.game.draft.Draft;
import mage.MageException;
import mage.interfaces.callback.CallbackException;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.Session; import mage.server.User;
import mage.server.SessionManager; import mage.server.UserManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.DraftClientMessage; import mage.view.DraftClientMessage;
import mage.view.DraftPickView; import mage.view.DraftPickView;
@ -55,7 +51,7 @@ public class DraftSession {
protected final static Logger logger = Logger.getLogger(DraftSession.class); protected final static Logger logger = Logger.getLogger(DraftSession.class);
protected UUID sessionId; protected UUID userId;
protected UUID playerId; protected UUID playerId;
protected Draft draft; protected Draft draft;
protected boolean killed = false; protected boolean killed = false;
@ -63,64 +59,59 @@ public class DraftSession {
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
public DraftSession(Draft draft, UUID sessionId, UUID playerId) { public DraftSession(Draft draft, UUID userId, UUID playerId) {
this.sessionId = sessionId; this.userId = userId;
this.draft = draft; this.draft = draft;
this.playerId = playerId; this.playerId = playerId;
} }
public boolean init(final DraftView draftView) { public boolean init() {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("draftInit", draft.getId(), draftView)); if (futureTimeout != null && !futureTimeout.isDone()) {
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
user.fireCallback(new ClientCallback("draftInit", draft.getId(), new DraftClientMessage(getDraftPickView(remaining))));
}
return true; return true;
} }
} }
return false; return false;
} }
// public boolean waitForAck(String message) { public void update() {
// Session session = SessionManager.getInstance().getSession(sessionId);
// do {
// //TODO: add timeout
// } while (!session.getAckMessage().equals(message) && !killed);
// return true;
// }
public void update(final DraftView draftView) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("draftUpdate", draft.getId(), draftView)); user.fireCallback(new ClientCallback("draftUpdate", draft.getId(), getDraftView()));
} }
} }
} }
public void inform(final String message, final DraftView draftView) { public void inform(final String message) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(draftView, message))); user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message)));
} }
} }
} }
public void draftOver() { public void draftOver() {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("draftOver", draft.getId())); user.fireCallback(new ClientCallback("draftOver", draft.getId()));
} }
} }
} }
public void pickCard(final DraftPickView draftPickView, int timeout) { public void pickCard(int timeout) {
if (!killed) { if (!killed) {
setupTimeout(timeout); setupTimeout(timeout);
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(draftPickView))); user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(getDraftPickView(timeout))));
} }
} }
} }
@ -132,7 +123,7 @@ public class DraftSession {
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
DraftManager.getInstance().timeout(draft.getId(), sessionId); DraftManager.getInstance().timeout(draft.getId(), userId);
} }
}, },
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
@ -143,23 +134,41 @@ public class DraftSession {
private synchronized void cancelTimeout() { private synchronized void cancelTimeout() {
if (futureTimeout != null) { if (futureTimeout != null) {
futureTimeout.cancel(false); futureTimeout.cancel(false);
((ThreadPoolExecutor)timeoutExecutor).getQueue().remove(futureTimeout);
} }
} }
protected void handleRemoteException(RemoteException ex) { protected void handleRemoteException(RemoteException ex) {
logger.fatal("DraftSession error ", ex); logger.fatal("DraftSession error ", ex);
DraftManager.getInstance().kill(draft.getId(), sessionId); DraftManager.getInstance().kill(draft.getId(), userId);
} }
public void setKilled() { public void setKilled() {
killed = true; killed = true;
} }
public boolean sendCardPick(UUID cardId) { public DraftPickView sendCardPick(UUID cardId) {
cancelTimeout(); cancelTimeout();
return draft.addPick(playerId, cardId); if (draft.addPick(playerId, cardId))
return getDraftPickView(0);
return null;
}
public void removeDraft() {
User user = UserManager.getInstance().getUser(userId);
if (user != null)
user.removeDraft(playerId);
}
private DraftView getDraftView() {
return new DraftView(draft);
}
private DraftPickView getDraftPickView(int timeout) {
return new DraftPickView(draft.getPlayer(playerId), timeout);
}
public UUID getDraftId() {
return draft.getId();
} }
} }

View file

@ -29,9 +29,7 @@
package mage.server.game; package mage.server.game;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.util.logging.Level;
import mage.game.LookedAt;
import mage.MageException; import mage.MageException;
import mage.server.TableManager; import mage.server.TableManager;
import java.io.File; import java.io.File;
@ -64,6 +62,7 @@ import mage.game.events.TableEvent;
import mage.game.permanent.Permanent; import mage.game.permanent.Permanent;
import mage.players.Player; import mage.players.Player;
import mage.server.ChatManager; import mage.server.ChatManager;
import mage.server.UserManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.sets.Sets; import mage.sets.Sets;
import mage.view.*; import mage.view.*;
@ -82,7 +81,7 @@ public class GameController implements GameCallback {
private ConcurrentHashMap<UUID, GameSession> gameSessions = new ConcurrentHashMap<UUID, GameSession>(); private ConcurrentHashMap<UUID, GameSession> gameSessions = new ConcurrentHashMap<UUID, GameSession>();
private ConcurrentHashMap<UUID, GameWatcher> watchers = new ConcurrentHashMap<UUID, GameWatcher>(); private ConcurrentHashMap<UUID, GameWatcher> watchers = new ConcurrentHashMap<UUID, GameWatcher>();
private ConcurrentHashMap<UUID, UUID> sessionPlayerMap; private ConcurrentHashMap<UUID, UUID> userPlayerMap;
private UUID gameSessionId; private UUID gameSessionId;
private Game game; private Game game;
private UUID chatId; private UUID chatId;
@ -91,9 +90,9 @@ public class GameController implements GameCallback {
private Future<?> gameFuture; private Future<?> gameFuture;
public GameController(Game game, ConcurrentHashMap<UUID, UUID> sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { public GameController(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId) {
gameSessionId = UUID.randomUUID(); gameSessionId = UUID.randomUUID();
this.sessionPlayerMap = sessionPlayerMap; this.userPlayerMap = userPlayerMap;
chatId = ChatManager.getInstance().createChatSession(); chatId = ChatManager.getInstance().createChatSession();
this.game = game; this.game = game;
this.tableId = tableId; this.tableId = tableId;
@ -180,14 +179,15 @@ public class GameController implements GameCallback {
checkStart(); checkStart();
} }
private UUID getPlayerId(UUID sessionId) { private UUID getPlayerId(UUID userId) {
return sessionPlayerMap.get(sessionId); return userPlayerMap.get(userId);
} }
public void join(UUID sessionId) { public void join(UUID userId) {
UUID playerId = sessionPlayerMap.get(sessionId); UUID playerId = userPlayerMap.get(userId);
GameSession gameSession = new GameSession(game, sessionId, playerId); GameSession gameSession = new GameSession(game, userId, playerId);
gameSessions.put(playerId, gameSession); gameSessions.put(playerId, gameSession);
UserManager.getInstance().getUser(userId).addGame(playerId, gameSession);
logger.info("player " + playerId + " has joined game " + game.getId()); logger.info("player " + playerId + " has joined game " + game.getId());
ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getName() + " has joined the game", MessageColor.BLACK); ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getName() + " has joined the game", MessageColor.BLACK);
checkStart(); checkStart();
@ -196,7 +196,7 @@ public class GameController implements GameCallback {
private synchronized void startGame() { private synchronized void startGame() {
if (gameFuture == null) { if (gameFuture == null) {
for (final Entry<UUID, GameSession> entry: gameSessions.entrySet()) { for (final Entry<UUID, GameSession> entry: gameSessions.entrySet()) {
if (!entry.getValue().init(getGameView(entry.getKey()))) { if (!entry.getValue().init()) {
logger.fatal("Unable to initialize client"); logger.fatal("Unable to initialize client");
//TODO: generate client error message //TODO: generate client error message
return; return;
@ -209,7 +209,7 @@ public class GameController implements GameCallback {
private void checkStart() { private void checkStart() {
if (allJoined()) { if (allJoined()) {
ThreadExecutor.getInstance().getRMIExecutor().execute( ThreadExecutor.getInstance().getCallExecutor().execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
@ -228,27 +228,27 @@ public class GameController implements GameCallback {
return true; return true;
} }
public void watch(UUID sessionId) { public void watch(UUID userId) {
GameWatcher gameWatcher = new GameWatcher(sessionId, game.getId()); GameWatcher gameWatcher = new GameWatcher(userId, game);
watchers.put(sessionId, gameWatcher); watchers.put(userId, gameWatcher);
gameWatcher.init(getGameView()); gameWatcher.init();
ChatManager.getInstance().broadcast(chatId, "", " has started watching", MessageColor.BLACK); ChatManager.getInstance().broadcast(chatId, "", " has started watching", MessageColor.BLACK);
} }
public void stopWatching(UUID sessionId) { public void stopWatching(UUID userId) {
watchers.remove(sessionId); watchers.remove(userId);
ChatManager.getInstance().broadcast(chatId, "", " has stopped watching", MessageColor.BLACK); ChatManager.getInstance().broadcast(chatId, "", " has stopped watching", MessageColor.BLACK);
} }
public void concede(UUID sessionId) { public void concede(UUID userId) {
game.concede(getPlayerId(sessionId)); game.concede(getPlayerId(userId));
} }
private void leave(UUID sessionId) { private void leave(UUID userId) {
game.quit(getPlayerId(sessionId)); game.quit(getPlayerId(userId));
} }
public void cheat(UUID sessionId, UUID playerId, DeckCardLists deckList) { public void cheat(UUID userId, UUID playerId, DeckCardLists deckList) {
Deck deck; Deck deck;
try { try {
deck = Deck.load(deckList); deck = Deck.load(deckList);
@ -263,7 +263,7 @@ public class GameController implements GameCallback {
updateGame(); updateGame();
} }
public boolean cheat(UUID sessionId, UUID playerId, String cardName) { public boolean cheat(UUID userId, UUID playerId, String cardName) {
Card card = Sets.findCard(cardName, true); Card card = Sets.findCard(cardName, true);
if (card != null) { if (card != null) {
Set<Card> cards = new HashSet<Card>(); Set<Card> cards = new HashSet<Card>();
@ -276,30 +276,30 @@ public class GameController implements GameCallback {
} }
} }
public void kill(UUID sessionId) { public void kill(UUID userId) {
if (sessionPlayerMap.containsKey(sessionId)) { if (userPlayerMap.containsKey(userId)) {
GameSession session = gameSessions.get(sessionPlayerMap.get(sessionId)); gameSessions.get(userPlayerMap.get(userId)).setKilled();
if (session != null) session.destroy(); gameSessions.remove(userPlayerMap.get(userId));
gameSessions.remove(sessionPlayerMap.get(sessionId)); leave(userId);
leave(sessionId); userPlayerMap.remove(userId);
sessionPlayerMap.remove(sessionId);
} }
if (watchers.containsKey(sessionId)) { if (watchers.containsKey(userId)) {
watchers.get(sessionId).setKilled(); watchers.get(userId).setKilled();
watchers.remove(sessionId); watchers.remove(userId);
} }
} }
public void timeout(UUID sessionId) { public void timeout(UUID userId) {
if (sessionPlayerMap.containsKey(sessionId)) { if (userPlayerMap.containsKey(userId)) {
ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(sessionPlayerMap.get(sessionId)).getName() + " has timed out. Auto concede.", MessageColor.BLACK); ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(userPlayerMap.get(userId)).getName() + " has timed out. Auto concede.", MessageColor.BLACK);
concede(sessionId); concede(userId);
} }
} }
public void endGame(final String message) throws MageException { public void endGame(final String message) throws MageException {
for (final GameSession gameSession: gameSessions.values()) { for (final GameSession gameSession: gameSessions.values()) {
gameSession.gameOver(message); gameSession.gameOver(message);
gameSession.removeGame();
} }
for (final GameWatcher gameWatcher: watchers.values()) { for (final GameWatcher gameWatcher: watchers.values()) {
gameWatcher.gameOver(message); gameWatcher.gameOver(message);
@ -315,34 +315,34 @@ public class GameController implements GameCallback {
return chatId; return chatId;
} }
public void sendPlayerUUID(UUID sessionId, UUID data) { public void sendPlayerUUID(UUID userId, UUID data) {
gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerUUID(data); gameSessions.get(userPlayerMap.get(userId)).sendPlayerUUID(data);
} }
public void sendPlayerString(UUID sessionId, String data) { public void sendPlayerString(UUID userId, String data) {
gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerString(data); gameSessions.get(userPlayerMap.get(userId)).sendPlayerString(data);
} }
public void sendPlayerBoolean(UUID sessionId, Boolean data) { public void sendPlayerBoolean(UUID userId, Boolean data) {
gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerBoolean(data); gameSessions.get(userPlayerMap.get(userId)).sendPlayerBoolean(data);
} }
public void sendPlayerInteger(UUID sessionId, Integer data) { public void sendPlayerInteger(UUID userId, Integer data) {
gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerInteger(data); gameSessions.get(userPlayerMap.get(userId)).sendPlayerInteger(data);
} }
private synchronized void updateGame() { private synchronized void updateGame() {
for (final Entry<UUID, GameSession> entry: gameSessions.entrySet()) { for (final GameSession gameSession: gameSessions.values()) {
entry.getValue().update(getGameView(entry.getKey())); gameSession.update();
} }
for (final GameWatcher gameWatcher: watchers.values()) { for (final GameWatcher gameWatcher: watchers.values()) {
gameWatcher.update(getGameView()); gameWatcher.update();
} }
} }
private synchronized void ask(UUID playerId, String question) throws MageException { private synchronized void ask(UUID playerId, String question) throws MageException {
if (gameSessions.containsKey(playerId)) if (gameSessions.containsKey(playerId))
gameSessions.get(playerId).ask(question, getGameView(playerId)); gameSessions.get(playerId).ask(question);
informOthers(playerId); informOthers(playerId);
} }
@ -361,41 +361,41 @@ public class GameController implements GameCallback {
private synchronized void target(UUID playerId, String question, Cards cards, List<Permanent> perms, Set<UUID> targets, boolean required, Map<String, Serializable> options) throws MageException { private synchronized void target(UUID playerId, String question, Cards cards, List<Permanent> perms, Set<UUID> targets, boolean required, Map<String, Serializable> options) throws MageException {
if (gameSessions.containsKey(playerId)) { if (gameSessions.containsKey(playerId)) {
if (cards != null) if (cards != null)
gameSessions.get(playerId).target(question, new CardsView(cards.getCards(game)), targets, required, getGameView(playerId), options); gameSessions.get(playerId).target(question, new CardsView(cards.getCards(game)), targets, required, options);
else if (perms != null) { else if (perms != null) {
CardsView permsView = new CardsView(); CardsView permsView = new CardsView();
for (Permanent perm: perms) { for (Permanent perm: perms) {
permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()))); permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId())));
} }
gameSessions.get(playerId).target(question, permsView, targets, required, getGameView(playerId), options); gameSessions.get(playerId).target(question, permsView, targets, required, options);
} }
else else
gameSessions.get(playerId).target(question, new CardsView(), targets, required, getGameView(playerId), options); gameSessions.get(playerId).target(question, new CardsView(), targets, required, options);
} }
informOthers(playerId); informOthers(playerId);
} }
private synchronized void target(UUID playerId, String question, Collection<? extends Ability> abilities, boolean required, Map<String, Serializable> options) throws MageException { private synchronized void target(UUID playerId, String question, Collection<? extends Ability> abilities, boolean required, Map<String, Serializable> options) throws MageException {
if (gameSessions.containsKey(playerId)) if (gameSessions.containsKey(playerId))
gameSessions.get(playerId).target(question, new CardsView(abilities, game), null, required, getGameView(playerId), options); gameSessions.get(playerId).target(question, new CardsView(abilities, game), null, required, options);
informOthers(playerId); informOthers(playerId);
} }
private synchronized void select(UUID playerId, String message) throws MageException { private synchronized void select(UUID playerId, String message) throws MageException {
if (gameSessions.containsKey(playerId)) if (gameSessions.containsKey(playerId))
gameSessions.get(playerId).select(message, getGameView(playerId)); gameSessions.get(playerId).select(message);
informOthers(playerId); informOthers(playerId);
} }
private synchronized void playMana(UUID playerId, String message) throws MageException { private synchronized void playMana(UUID playerId, String message) throws MageException {
if (gameSessions.containsKey(playerId)) if (gameSessions.containsKey(playerId))
gameSessions.get(playerId).playMana(message, getGameView(playerId)); gameSessions.get(playerId).playMana(message);
informOthers(playerId); informOthers(playerId);
} }
private synchronized void playXMana(UUID playerId, String message) throws MageException { private synchronized void playXMana(UUID playerId, String message) throws MageException {
if (gameSessions.containsKey(playerId)) if (gameSessions.containsKey(playerId))
gameSessions.get(playerId).playXMana(message, getGameView(playerId)); gameSessions.get(playerId).playXMana(message);
informOthers(playerId); informOthers(playerId);
} }
@ -420,11 +420,11 @@ public class GameController implements GameCallback {
final String message = "Waiting for " + game.getPlayer(playerId).getName(); final String message = "Waiting for " + game.getPlayer(playerId).getName();
for (final Entry<UUID, GameSession> entry: gameSessions.entrySet()) { for (final Entry<UUID, GameSession> entry: gameSessions.entrySet()) {
if (!entry.getKey().equals(playerId)) { if (!entry.getKey().equals(playerId)) {
entry.getValue().inform(message, getGameView(entry.getKey())); entry.getValue().inform(message);
} }
} }
for (final GameWatcher watcher: watchers.values()) { for (final GameWatcher watcher: watchers.values()) {
watcher.inform(message, getGameView()); watcher.inform(message);
} }
} }
@ -434,21 +434,8 @@ public class GameController implements GameCallback {
} }
} }
private GameView getGameView() {
return new GameView(game.getState(), game);
}
public GameView getGameView(UUID playerId) { public GameView getGameView(UUID playerId) {
GameView gameView = new GameView(game.getState(), game); return gameSessions.get(playerId).getGameView();
gameView.setHand(new CardsView(game.getPlayer(playerId).getHand().getCards(game)));
List<LookedAtView> list = new ArrayList<LookedAtView>();
for (Entry<String, Cards> entry : game.getState().getLookedAt(playerId).entrySet()) {
list.add(new LookedAtView(entry.getKey(), entry.getValue(), game));
}
gameView.setLookedAt(list);
return gameView;
} }
@Override @Override

View file

@ -32,7 +32,6 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.game.Game; import mage.game.Game;
import mage.MageException;
import mage.view.GameView; import mage.view.GameView;
/** /**
@ -50,15 +49,15 @@ public class GameManager {
private ConcurrentHashMap<UUID, GameController> gameControllers = new ConcurrentHashMap<UUID, GameController>(); private ConcurrentHashMap<UUID, GameController> gameControllers = new ConcurrentHashMap<UUID, GameController>();
public UUID createGameSession(Game game, ConcurrentHashMap<UUID, UUID> sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { public UUID createGameSession(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId) {
GameController gameController = new GameController(game, sessionPlayerMap, tableId, choosingPlayerId); GameController gameController = new GameController(game, userPlayerMap, tableId, choosingPlayerId);
gameControllers.put(game.getId(), gameController); gameControllers.put(game.getId(), gameController);
return gameController.getSessionId(); return gameController.getSessionId();
} }
public void joinGame(UUID gameId, UUID sessionId) { public void joinGame(UUID gameId, UUID userId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).join(sessionId); gameControllers.get(gameId).join(userId);
} }
public void destroyChatSession(UUID gameId) { public void destroyChatSession(UUID gameId) {
@ -71,66 +70,66 @@ public class GameManager {
return null; return null;
} }
public void sendPlayerUUID(UUID gameId, UUID sessionId, UUID data) { public void sendPlayerUUID(UUID gameId, UUID userId, UUID data) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).sendPlayerUUID(sessionId, data); gameControllers.get(gameId).sendPlayerUUID(userId, data);
} }
public void sendPlayerString(UUID gameId, UUID sessionId, String data) { public void sendPlayerString(UUID gameId, UUID userId, String data) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).sendPlayerString(sessionId, data); gameControllers.get(gameId).sendPlayerString(userId, data);
} }
public void sendPlayerBoolean(UUID gameId, UUID sessionId, Boolean data) { public void sendPlayerBoolean(UUID gameId, UUID userId, Boolean data) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).sendPlayerBoolean(sessionId, data); gameControllers.get(gameId).sendPlayerBoolean(userId, data);
} }
public void sendPlayerInteger(UUID gameId, UUID sessionId, Integer data) { public void sendPlayerInteger(UUID gameId, UUID userId, Integer data) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).sendPlayerInteger(sessionId, data); gameControllers.get(gameId).sendPlayerInteger(userId, data);
} }
public void concedeGame(UUID gameId, UUID sessionId) { public void concedeGame(UUID gameId, UUID userId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).concede(sessionId); gameControllers.get(gameId).concede(userId);
} }
public void watchGame(UUID gameId, UUID sessionId) { public void watchGame(UUID gameId, UUID userId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).watch(sessionId); gameControllers.get(gameId).watch(userId);
} }
public void stopWatching(UUID gameId, UUID sessionId) { public void stopWatching(UUID gameId, UUID userId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).stopWatching(sessionId); gameControllers.get(gameId).stopWatching(userId);
} }
public void removeSession(UUID sessionId) { public void removeSession(UUID userId) {
for (GameController controller: gameControllers.values()) { for (GameController controller: gameControllers.values()) {
controller.kill(sessionId); controller.kill(userId);
} }
} }
public void kill(UUID gameId, UUID sessionId) { public void kill(UUID gameId, UUID userId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).kill(sessionId); gameControllers.get(gameId).kill(userId);
} }
public void cheat(UUID gameId, UUID sessionId, UUID playerId, DeckCardLists deckList) { public void cheat(UUID gameId, UUID userId, UUID playerId, DeckCardLists deckList) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).cheat(sessionId, playerId, deckList); gameControllers.get(gameId).cheat(userId, playerId, deckList);
} }
public boolean cheat(UUID gameId, UUID sessionId, UUID playerId, String cardName) { public boolean cheat(UUID gameId, UUID userId, UUID playerId, String cardName) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
return gameControllers.get(gameId).cheat(sessionId, playerId, cardName); return gameControllers.get(gameId).cheat(userId, playerId, cardName);
return false; return false;
} }
public void timeout(UUID gameId, UUID sessionId) { public void timeout(UUID gameId, UUID userId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
gameControllers.get(gameId).timeout(sessionId); gameControllers.get(gameId).timeout(userId);
} }
public void removeGame(UUID gameId) { public void removeGame(UUID gameId) {
@ -142,7 +141,7 @@ public class GameManager {
gameControllers.get(gameId).saveGame(); gameControllers.get(gameId).saveGame();
} }
public GameView getGameView(UUID gameId, UUID sessionId, UUID playerId) { public GameView getGameView(UUID gameId, UUID userId, UUID playerId) {
if (gameControllers.containsKey(gameId)) if (gameControllers.containsKey(gameId))
return gameControllers.get(gameId).getGameView(playerId); return gameControllers.get(gameId).getGameView(playerId);
return null; return null;

View file

@ -29,25 +29,27 @@
package mage.server.game; package mage.server.game;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import mage.cards.Cards;
import mage.game.Game; import mage.game.Game;
import mage.MageException;
import mage.interfaces.callback.CallbackException;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.Session; import mage.server.User;
import mage.server.SessionManager; import mage.server.UserManager;
import mage.server.util.ConfigSettings; import mage.server.util.ConfigSettings;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.AbilityPickerView; import mage.view.AbilityPickerView;
import mage.view.CardsView; import mage.view.CardsView;
import mage.view.GameClientMessage; import mage.view.GameClientMessage;
import mage.view.GameView; import mage.view.GameView;
import mage.view.LookedAtView;
/** /**
* *
@ -55,44 +57,42 @@ import mage.view.GameView;
*/ */
public class GameSession extends GameWatcher { public class GameSession extends GameWatcher {
private Game game;
private UUID playerId; private UUID playerId;
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
public GameSession(Game game, UUID sessionId, UUID playerId) { public GameSession(Game game, UUID userId, UUID playerId) {
super(sessionId, game.getId()); super(userId, game);
this.game = game;
this.playerId = playerId; this.playerId = playerId;
} }
public void ask(final String question, final GameView gameView) { public void ask(final String question) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(gameView, question))); user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question)));
} }
} }
} }
public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final GameView gameView, final Map<String, Serializable> options) { public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(gameView, question, cardView, targets, required, options))); user.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(getGameView(), question, cardView, targets, required, options)));
} }
} }
} }
public void select(final String message, final GameView gameView) { public void select(final String message) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(gameView, message))); user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message)));
} }
} }
} }
@ -100,9 +100,9 @@ public class GameSession extends GameWatcher {
public void chooseAbility(final AbilityPickerView abilities) { public void chooseAbility(final AbilityPickerView abilities) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities)); user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities));
} }
} }
} }
@ -110,29 +110,29 @@ public class GameSession extends GameWatcher {
public void choose(final String message, final Set<String> choices) { public void choose(final String message, final Set<String> choices) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameChoose", game.getId(), new GameClientMessage(choices.toArray(new String[0]), message))); user.fireCallback(new ClientCallback("gameChoose", game.getId(), new GameClientMessage(choices.toArray(new String[0]), message)));
} }
} }
} }
public void playMana(final String message, final GameView gameView) { public void playMana(final String message) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(gameView, message))); user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message)));
} }
} }
} }
public void playXMana(final String message, final GameView gameView) { public void playXMana(final String message) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(gameView, message))); user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message)));
} }
} }
} }
@ -140,30 +140,29 @@ public class GameSession extends GameWatcher {
public void getAmount(final String message, final int min, final int max) { public void getAmount(final String message, final int min, final int max) {
if (!killed) { if (!killed) {
setupTimeout(); setupTimeout();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max))); user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max)));
} }
} }
} }
public void revealCards(final String name, final CardsView cardView) { public void revealCards(final String name, final CardsView cardView) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameReveal", game.getId(), new GameClientMessage(cardView, name))); user.fireCallback(new ClientCallback("gameReveal", game.getId(), new GameClientMessage(cardView, name)));
} }
} }
} }
private synchronized void setupTimeout() { private synchronized void setupTimeout() {
cancelTimeout(); cancelTimeout();
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
GameManager.getInstance().timeout(gameId, sessionId); GameManager.getInstance().timeout(game.getId(), userId);
} }
}, },
ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS
@ -173,8 +172,6 @@ public class GameSession extends GameWatcher {
private synchronized void cancelTimeout() { private synchronized void cancelTimeout() {
if (futureTimeout != null) { if (futureTimeout != null) {
futureTimeout.cancel(false); futureTimeout.cancel(false);
((ThreadPoolExecutor)timeoutExecutor).getQueue().remove(futureTimeout);
//System.out.println("tasks:"+ ((ThreadPoolExecutor)timeoutExecutor).getTaskCount());
} }
} }
@ -198,8 +195,32 @@ public class GameSession extends GameWatcher {
game.getPlayer(playerId).setResponseInteger(data); game.getPlayer(playerId).setResponseInteger(data);
} }
public void destroy() { @Override
cancelTimeout(); public GameView getGameView() {
setKilled(); GameView gameView = new GameView(game.getState(), game);
gameView.setHand(new CardsView(game.getPlayer(playerId).getHand().getCards(game)));
List<LookedAtView> list = new ArrayList<LookedAtView>();
for (Entry<String, Cards> entry : game.getState().getLookedAt(playerId).entrySet()) {
list.add(new LookedAtView(entry.getKey(), entry.getValue(), game));
}
gameView.setLookedAt(list);
return gameView;
} }
public void removeGame() {
User user = UserManager.getInstance().getUser(userId);
if (user != null)
user.removeGame(playerId);
}
public UUID getGameId() {
return game.getId();
}
public void kill() {
game.quit(playerId);
}
} }

View file

@ -30,12 +30,10 @@ package mage.server.game;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import mage.game.Game;
import mage.MageException;
import mage.interfaces.callback.CallbackException;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.Session; import mage.server.User;
import mage.server.SessionManager; import mage.server.UserManager;
import mage.view.GameClientMessage; import mage.view.GameClientMessage;
import mage.view.GameView; import mage.view.GameView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -48,69 +46,73 @@ public class GameWatcher {
protected final static Logger logger = Logger.getLogger(GameWatcher.class); protected final static Logger logger = Logger.getLogger(GameWatcher.class);
protected UUID sessionId; protected UUID userId;
protected UUID gameId; protected Game game;
protected boolean killed = false; protected boolean killed = false;
public GameWatcher(UUID sessionId, UUID gameId) { public GameWatcher(UUID userId, Game game) {
this.sessionId = sessionId; this.userId = userId;
this.gameId = gameId; this.game = game;
} }
public boolean init(final GameView gameView) { public boolean init() {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameInit", gameId, gameView)); user.fireCallback(new ClientCallback("gameInit", game.getId(), getGameView()));
return true; return true;
} }
} }
return false; return false;
} }
public void update(final GameView gameView) { public void update() {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameUpdate", gameId, gameView)); user.fireCallback(new ClientCallback("gameUpdate", game.getId(), getGameView()));
} }
} }
} }
public void inform(final String message, final GameView gameView) { public void inform(final String message) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameInform", gameId, new GameClientMessage(gameView, message))); user.fireCallback(new ClientCallback("gameInform", game.getId(), new GameClientMessage(getGameView(), message)));
} }
} }
} }
public void gameOver(final String message) { public void gameOver(final String message) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameOver", gameId, message)); user.fireCallback(new ClientCallback("gameOver", game.getId(), message));
} }
} }
} }
public void gameError(final String message) { public void gameError(final String message) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("gameError", gameId, message)); user.fireCallback(new ClientCallback("gameError", game.getId(), message));
} }
} }
} }
protected void handleRemoteException(RemoteException ex) { protected void handleRemoteException(RemoteException ex) {
logger.fatal("GameWatcher error", ex); logger.fatal("GameWatcher error", ex);
GameManager.getInstance().kill(gameId, sessionId); GameManager.getInstance().kill(game.getId(), userId);
} }
public void setKilled() { public void setKilled() {
killed = true; killed = true;
} }
public GameView getGameView() {
return new GameView(game.getState(), game);
}
} }

View file

@ -45,14 +45,14 @@ import mage.view.TableView;
public interface GamesRoom extends Room { public interface GamesRoom extends Room {
public List<TableView> getTables(); public List<TableView> getTables();
public boolean joinTable(UUID sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException; public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException;
public boolean joinTournamentTable(UUID sessionId, UUID tableId, String name, String playerType, int skill) throws GameException; public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException;
public TableView createTable(UUID sessionId, MatchOptions options); public TableView createTable(UUID userId, MatchOptions options);
public TableView createTournamentTable(UUID sessionId, TournamentOptions options); public TableView createTournamentTable(UUID userId, TournamentOptions options);
public void removeTable(UUID sessionId, UUID tableId); public void removeTable(UUID userId, UUID tableId);
public void removeTable(UUID tableId); public void removeTable(UUID tableId);
public TableView getTable(UUID tableId); public TableView getTable(UUID tableId);
public void leaveTable(UUID sessionId, UUID tableId); public void leaveTable(UUID userId, UUID tableId);
public boolean watchTable(UUID sessionId, UUID tableId) throws MageException; public boolean watchTable(UUID userId, UUID tableId) throws MageException;
} }

View file

@ -64,33 +64,33 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} }
@Override @Override
public boolean joinTable(UUID sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
if (tables.containsKey(tableId)) { if (tables.containsKey(tableId)) {
return TableManager.getInstance().joinTable(sessionId, tableId, name, playerType, skill, deckList); return TableManager.getInstance().joinTable(userId, tableId, name, playerType, skill, deckList);
} else { } else {
return false; return false;
} }
} }
@Override @Override
public TableView createTable(UUID sessionId, MatchOptions options) { public TableView createTable(UUID userId, MatchOptions options) {
Table table = TableManager.getInstance().createTable(this.getRoomId(), sessionId, options); Table table = TableManager.getInstance().createTable(this.getRoomId(), userId, options);
tables.put(table.getId(), table); tables.put(table.getId(), table);
return new TableView(table); return new TableView(table);
} }
@Override @Override
public boolean joinTournamentTable(UUID sessionId, UUID tableId, String name, String playerType, int skill) throws GameException { public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
if (tables.containsKey(tableId)) { if (tables.containsKey(tableId)) {
return TableManager.getInstance().joinTournament(sessionId, tableId, name, playerType, skill); return TableManager.getInstance().joinTournament(userId, tableId, name, playerType, skill);
} else { } else {
return false; return false;
} }
} }
@Override @Override
public TableView createTournamentTable(UUID sessionId, TournamentOptions options) { public TableView createTournamentTable(UUID userId, TournamentOptions options) {
Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), sessionId, options); Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), userId, options);
tables.put(table.getId(), table); tables.put(table.getId(), table);
return new TableView(table); return new TableView(table);
} }
@ -103,7 +103,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} }
@Override @Override
public void removeTable(UUID sessionId, UUID tableId) { public void removeTable(UUID userId, UUID tableId) {
tables.remove(tableId); tables.remove(tableId);
} }
@ -115,13 +115,13 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} }
@Override @Override
public void leaveTable(UUID sessionId, UUID tableId) { public void leaveTable(UUID userId, UUID tableId) {
TableManager.getInstance().leaveTable(sessionId, tableId); TableManager.getInstance().leaveTable(userId, tableId);
} }
@Override @Override
public boolean watchTable(UUID sessionId, UUID tableId) throws MageException { public boolean watchTable(UUID userId, UUID tableId) throws MageException {
return TableManager.getInstance().watchTable(sessionId, tableId); return TableManager.getInstance().watchTable(userId, tableId);
} }
} }

View file

@ -30,8 +30,7 @@ package mage.server.game;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import mage.MageException; import mage.server.UserManager;
import mage.server.SessionManager;
/** /**
* *
@ -48,26 +47,26 @@ public class ReplayManager {
private ConcurrentHashMap<String, ReplaySession> replaySessions = new ConcurrentHashMap<String, ReplaySession>(); private ConcurrentHashMap<String, ReplaySession> replaySessions = new ConcurrentHashMap<String, ReplaySession>();
public void replayGame(UUID gameId, UUID sessionId) { public void replayGame(UUID gameId, UUID userId) {
ReplaySession replaySession = new ReplaySession(gameId, sessionId); ReplaySession replaySession = new ReplaySession(gameId, userId);
replaySessions.put(gameId.toString() + sessionId.toString(), replaySession); replaySessions.put(gameId.toString() + userId.toString(), replaySession);
SessionManager.getInstance().getSession(sessionId).replayGame(gameId); UserManager.getInstance().getUser(userId).replayGame(gameId);
} }
public void startReplay(UUID gameId, UUID sessionId) { public void startReplay(UUID gameId, UUID userId) {
replaySessions.get(gameId.toString() + sessionId.toString()).replay(); replaySessions.get(gameId.toString() + userId.toString()).replay();
} }
public void stopReplay(UUID gameId, UUID sessionId) { public void stopReplay(UUID gameId, UUID userId) {
replaySessions.get(gameId.toString() + sessionId.toString()).stop(); replaySessions.get(gameId.toString() + userId.toString()).stop();
} }
public void nextPlay(UUID gameId, UUID sessionId) { public void nextPlay(UUID gameId, UUID userId) {
replaySessions.get(gameId.toString() + sessionId.toString()).next(); replaySessions.get(gameId.toString() + userId.toString()).next();
} }
public void previousPlay(UUID gameId, UUID sessionId) { public void previousPlay(UUID gameId, UUID userId) {
replaySessions.get(gameId.toString() + sessionId.toString()).previous(); replaySessions.get(gameId.toString() + userId.toString()).previous();
} }
} }

View file

@ -31,11 +31,9 @@ package mage.server.game;
import java.util.UUID; import java.util.UUID;
import mage.game.Game; import mage.game.Game;
import mage.game.GameState; import mage.game.GameState;
import mage.MageException;
import mage.interfaces.callback.CallbackException;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.Session; import mage.server.User;
import mage.server.SessionManager; import mage.server.UserManager;
import mage.view.GameView; import mage.view.GameView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -47,18 +45,18 @@ public class ReplaySession implements GameCallback {
private final static Logger logger = Logger.getLogger(ReplaySession.class); private final static Logger logger = Logger.getLogger(ReplaySession.class);
private GameReplay replay; private GameReplay replay;
protected UUID sessionId; protected UUID userId;
ReplaySession(UUID gameId, UUID sessionId) { ReplaySession(UUID gameId, UUID userId) {
this.replay = new GameReplay(gameId); this.replay = new GameReplay(gameId);
this.sessionId = sessionId; this.userId = userId;
} }
public void replay() { public void replay() {
replay.start(); replay.start();
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("replayInit", replay.getGame().getId(), new GameView(replay.next(), replay.getGame()))); user.fireCallback(new ClientCallback("replayInit", replay.getGame().getId(), new GameView(replay.next(), replay.getGame())));
} }
} }
@ -76,9 +74,9 @@ public class ReplaySession implements GameCallback {
@Override @Override
public void gameResult(final String result) { public void gameResult(final String result) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("replayDone", replay.getGame().getId(), result)); user.fireCallback(new ClientCallback("replayDone", replay.getGame().getId(), result));
} }
} }
@ -87,9 +85,9 @@ public class ReplaySession implements GameCallback {
gameResult("game ended"); gameResult("game ended");
} }
else { else {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game))); user.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game)));
} }
} }
} }

View file

@ -31,7 +31,6 @@ package mage.server.tournament;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.game.GameException; import mage.game.GameException;
import mage.game.Table; import mage.game.Table;
@ -46,6 +45,7 @@ import mage.game.tournament.TournamentPlayer;
import mage.MageException; import mage.MageException;
import mage.server.ChatManager; import mage.server.ChatManager;
import mage.server.TableManager; import mage.server.TableManager;
import mage.server.UserManager;
import mage.server.game.GamesRoomManager; import mage.server.game.GamesRoomManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
@ -60,16 +60,15 @@ public class TournamentController {
private final static Logger logger = Logger.getLogger(TournamentController.class); private final static Logger logger = Logger.getLogger(TournamentController.class);
private UUID sessionId;
private UUID chatId; private UUID chatId;
private UUID tableId; private UUID tableId;
private boolean started = false;
private Tournament tournament; private Tournament tournament;
private ConcurrentHashMap<UUID, UUID> sessionPlayerMap = new ConcurrentHashMap<UUID, UUID>(); private ConcurrentHashMap<UUID, UUID> userPlayerMap = new ConcurrentHashMap<UUID, UUID>();
private ConcurrentHashMap<UUID, TournamentSession> tournamentSessions = new ConcurrentHashMap<UUID, TournamentSession>(); private ConcurrentHashMap<UUID, TournamentSession> tournamentSessions = new ConcurrentHashMap<UUID, TournamentSession>();
public TournamentController(Tournament tournament, ConcurrentHashMap<UUID, UUID> sessionPlayerMap, UUID tableId) { public TournamentController(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
sessionId = UUID.randomUUID(); this.userPlayerMap = userPlayerMap;
this.sessionPlayerMap = sessionPlayerMap;
chatId = ChatManager.getInstance().createChatSession(); chatId = ChatManager.getInstance().createChatSession();
this.tournament = tournament; this.tournament = tournament;
this.tableId = tableId; this.tableId = tableId;
@ -98,6 +97,9 @@ public class TournamentController {
case CONSTRUCT: case CONSTRUCT:
construct(); construct();
break; break;
case END:
endTournament();
break;
} }
} }
} }
@ -128,10 +130,11 @@ public class TournamentController {
checkStart(); checkStart();
} }
public synchronized void join(UUID sessionId) { public synchronized void join(UUID userId) {
UUID playerId = sessionPlayerMap.get(sessionId); UUID playerId = userPlayerMap.get(userId);
TournamentSession tournamentSession = new TournamentSession(tournament, sessionId, tableId, playerId); TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId);
tournamentSessions.put(playerId, tournamentSession); tournamentSessions.put(playerId, tournamentSession);
UserManager.getInstance().getUser(userId).addTournament(playerId, tournamentSession);
TournamentPlayer player = tournament.getPlayer(playerId); TournamentPlayer player = tournament.getPlayer(playerId);
player.setJoined(); player.setJoined();
logger.info("player " + playerId + " has joined tournament " + tournament.getId()); logger.info("player " + playerId + " has joined tournament " + tournament.getId());
@ -140,8 +143,8 @@ public class TournamentController {
} }
private void checkStart() { private void checkStart() {
if (allJoined()) { if (!started && allJoined()) {
ThreadExecutor.getInstance().getRMIExecutor().execute( ThreadExecutor.getInstance().getCallExecutor().execute(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
@ -164,15 +167,24 @@ public class TournamentController {
private synchronized void startTournament() { private synchronized void startTournament() {
for (final Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) { for (final Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
if (!entry.getValue().init(getTournamentView())) { if (!entry.getValue().init()) {
logger.fatal("Unable to initialize client"); logger.fatal("Unable to initialize client");
//TODO: generate client error message //TODO: generate client error message
return; return;
} }
} }
started = true;
tournament.nextStep(); tournament.nextStep();
} }
private void endTournament() {
for (final TournamentSession tournamentSession: tournamentSessions.values()) {
tournamentSession.tournamentOver();
tournamentSession.removeTournament();
}
TableManager.getInstance().endTournament(tableId, tournament);
}
private void startMatch(TournamentPairing pair, MatchOptions matchOptions) { private void startMatch(TournamentPairing pair, MatchOptions matchOptions) {
try { try {
TableManager tableManager = TableManager.getInstance(); TableManager tableManager = TableManager.getInstance();
@ -196,49 +208,49 @@ public class TournamentController {
TableManager.getInstance().construct(tableId); TableManager.getInstance().construct(tableId);
} }
private void construct(UUID sessionId, Deck deck, int timeout) throws MageException { private void construct(UUID playerId, Deck deck, int timeout) throws MageException {
if (tournamentSessions.containsKey(sessionId)) if (tournamentSessions.containsKey(playerId))
tournamentSessions.get(sessionId).construct(deck, timeout); tournamentSessions.get(playerId).construct(deck, timeout);
} }
public void submitDeck(UUID sessionId, Deck deck) { public void submitDeck(UUID playerId, Deck deck) {
tournamentSessions.get(sessionPlayerMap.get(sessionId)).submitDeck(deck); tournamentSessions.get(playerId).submitDeck(deck);
} }
public void timeout(UUID sessionId) { public void timeout(UUID userId) {
if (sessionPlayerMap.containsKey(sessionId)) { if (userPlayerMap.containsKey(userId)) {
TournamentPlayer player = tournament.getPlayer(sessionPlayerMap.get(sessionId)); TournamentPlayer player = tournament.getPlayer(userPlayerMap.get(userId));
tournament.autoSubmit(sessionPlayerMap.get(sessionId), player.getDeck()); tournament.autoSubmit(userPlayerMap.get(userId), player.getDeck());
} }
} }
public UUID getSessionId() { // public UUID getSessionId() {
return this.sessionId; // return this.sessionId;
} // }
public UUID getChatId() { public UUID getChatId() {
return chatId; return chatId;
} }
public void kill(UUID sessionId) { public void kill(UUID userId) {
if (sessionPlayerMap.containsKey(sessionId)) { if (userPlayerMap.containsKey(userId)) {
tournamentSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); tournamentSessions.get(userPlayerMap.get(userId)).setKilled();
tournamentSessions.remove(sessionPlayerMap.get(sessionId)); tournamentSessions.remove(userPlayerMap.get(userId));
leave(sessionId); leave(userId);
sessionPlayerMap.remove(sessionId); userPlayerMap.remove(userId);
} }
} }
private void leave(UUID sessionId) { private void leave(UUID userId) {
tournament.leave(getPlayerId(sessionId)); tournament.leave(getPlayerId(userId));
} }
private UUID getPlayerId(UUID sessionId) { private UUID getPlayerId(UUID userId) {
return sessionPlayerMap.get(sessionId); return userPlayerMap.get(userId);
} }
private UUID getPlayerSessionId(UUID playerId) { private UUID getPlayerSessionId(UUID playerId) {
for (Entry<UUID, UUID> entry: sessionPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
if (entry.getValue().equals(playerId)) if (entry.getValue().equals(playerId))
return entry.getKey(); return entry.getKey();
} }

View file

@ -48,26 +48,25 @@ public class TournamentManager {
return INSTANCE; return INSTANCE;
} }
public UUID createTournamentSession(Tournament tournament, ConcurrentHashMap<UUID, UUID> sessionPlayerMap, UUID tableId) { public void createTournamentSession(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
TournamentController tournamentController = new TournamentController(tournament, sessionPlayerMap, tableId); TournamentController tournamentController = new TournamentController(tournament, userPlayerMap, tableId);
controllers.put(tournament.getId(), tournamentController); controllers.put(tournament.getId(), tournamentController);
return tournamentController.getSessionId();
} }
public void joinTournament(UUID tournamentId, UUID sessionId) { public void joinTournament(UUID tournamentId, UUID userId) {
controllers.get(tournamentId).join(sessionId); controllers.get(tournamentId).join(userId);
} }
public void kill(UUID tournamentId, UUID sessionId) { public void kill(UUID tournamentId, UUID userId) {
controllers.get(tournamentId).kill(sessionId); controllers.get(tournamentId).kill(userId);
} }
public void timeout(UUID tournamentId, UUID sessionId) { public void timeout(UUID tournamentId, UUID userId) {
controllers.get(tournamentId).timeout(sessionId); controllers.get(tournamentId).timeout(userId);
} }
public void submitDeck(UUID tournamentId, UUID sessionId, Deck deck) { public void submitDeck(UUID tournamentId, UUID playerId, Deck deck) {
controllers.get(tournamentId).submitDeck(sessionId, deck); controllers.get(tournamentId).submitDeck(playerId, deck);
} }
public TournamentView getTournamentView(UUID tournamentId) { public TournamentView getTournamentView(UUID tournamentId) {

View file

@ -32,16 +32,13 @@ import java.rmi.RemoteException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
import mage.MageException; import mage.MageException;
import mage.interfaces.callback.CallbackException;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.Session; import mage.server.User;
import mage.server.SessionManager; import mage.server.UserManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.TournamentView; import mage.view.TournamentView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -53,7 +50,7 @@ import org.apache.log4j.Logger;
public class TournamentSession { public class TournamentSession {
protected final static Logger logger = Logger.getLogger(TournamentSession.class); protected final static Logger logger = Logger.getLogger(TournamentSession.class);
protected UUID sessionId; protected UUID userId;
protected UUID playerId; protected UUID playerId;
protected UUID tableId; protected UUID tableId;
protected Tournament tournament; protected Tournament tournament;
@ -62,46 +59,38 @@ public class TournamentSession {
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
public TournamentSession(Tournament tournament, UUID sessionId, UUID tableId, UUID playerId) { public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) {
this.sessionId = sessionId; this.userId = userId;
this.tournament = tournament; this.tournament = tournament;
this.playerId = playerId; this.playerId = playerId;
this.tableId = tableId; this.tableId = tableId;
} }
public boolean init(final TournamentView tournamentView) { public boolean init() {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), tournamentView)); user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView()));
return true; return true;
} }
} }
return false; return false;
} }
// public boolean waitForAck(String message) { public void update() {
// Session session = SessionManager.getInstance().getSession(sessionId);
// do {
// //TODO: add timeout
// } while (!session.getAckMessage().equals(message) && !killed);
// return true;
// }
public void update(final TournamentView tournamentView) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), tournamentView)); user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView()));
} }
} }
} }
public void gameOver(final String message) { public void gameOver(final String message) {
if (!killed) { if (!killed) {
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) { if (user != null) {
session.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message)); user.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message));
} }
} }
} }
@ -109,9 +98,10 @@ public class TournamentSession {
public void construct(Deck deck, int timeout) throws MageException { public void construct(Deck deck, int timeout) throws MageException {
if (!killed) { if (!killed) {
setupTimeout(timeout); setupTimeout(timeout);
Session session = SessionManager.getInstance().getSession(sessionId); User user = UserManager.getInstance().getUser(userId);
if (session != null) if (user != null) {
session.construct(deck, tableId, timeout); user.construct(deck, tableId, timeout);
}
} }
} }
@ -122,7 +112,7 @@ public class TournamentSession {
protected void handleRemoteException(RemoteException ex) { protected void handleRemoteException(RemoteException ex) {
logger.fatal("TournamentSession error ", ex); logger.fatal("TournamentSession error ", ex);
TournamentManager.getInstance().kill(tournament.getId(), sessionId); TournamentManager.getInstance().kill(tournament.getId(), userId);
} }
public void setKilled() { public void setKilled() {
@ -136,7 +126,7 @@ public class TournamentSession {
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
TournamentManager.getInstance().timeout(tournament.getId(), sessionId); TournamentManager.getInstance().timeout(tournament.getId(), userId);
} }
}, },
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
@ -147,8 +137,25 @@ public class TournamentSession {
private synchronized void cancelTimeout() { private synchronized void cancelTimeout() {
if (futureTimeout != null) { if (futureTimeout != null) {
futureTimeout.cancel(false); futureTimeout.cancel(false);
((ThreadPoolExecutor)timeoutExecutor).getQueue().remove(futureTimeout);
} }
} }
public void removeTournament() {
User user = UserManager.getInstance().getUser(userId);
if (user != null)
user.removeTournament(playerId);
}
private TournamentView getTournamentView() {
return new TournamentView(tournament);
}
public UUID getTournamentId() {
return tournament.getId();
}
void tournamentOver() {
//TODO: implement this
}
} }

View file

@ -36,13 +36,13 @@ import java.util.concurrent.*;
*/ */
public class ThreadExecutor { public class ThreadExecutor {
private static ExecutorService rmiExecutor = Executors.newCachedThreadPool(); private static final ExecutorService callExecutor = Executors.newCachedThreadPool();
private static ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads()); private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads());
private static ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(5); private static final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(5);
static { static {
((ThreadPoolExecutor)rmiExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); ((ThreadPoolExecutor)callExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
((ThreadPoolExecutor)rmiExecutor).allowCoreThreadTimeOut(true); ((ThreadPoolExecutor)callExecutor).allowCoreThreadTimeOut(true);
((ThreadPoolExecutor)gameExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); ((ThreadPoolExecutor)gameExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
((ThreadPoolExecutor)gameExecutor).allowCoreThreadTimeOut(true); ((ThreadPoolExecutor)gameExecutor).allowCoreThreadTimeOut(true);
((ThreadPoolExecutor)timeoutExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); ((ThreadPoolExecutor)timeoutExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
@ -57,8 +57,8 @@ public class ThreadExecutor {
private ThreadExecutor() {} private ThreadExecutor() {}
public ExecutorService getRMIExecutor() { public ExecutorService getCallExecutor() {
return rmiExecutor; return callExecutor;
} }
public ExecutorService getGameExecutor() { public ExecutorService getGameExecutor() {

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>

View file

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage-Tests</artifactId> <artifactId>Mage-Tests</artifactId>

View file

@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
</parent> </parent>
<artifactId>Mage</artifactId> <artifactId>Mage</artifactId>

37
pom.xml
View file

@ -5,7 +5,7 @@
<groupId>org.mage</groupId> <groupId>org.mage</groupId>
<artifactId>mage-root</artifactId> <artifactId>mage-root</artifactId>
<version>0.7.4</version> <version>0.8.0</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Mage Root</name> <name>Mage Root</name>
<description>Mage Root POM</description> <description>Mage Root POM</description>
@ -31,10 +31,39 @@
<module>Mage.Plugins</module> <module>Mage.Plugins</module>
<module>Mage.Server.Plugins</module> <module>Mage.Server.Plugins</module>
<module>Mage.Server.Console</module> <module>Mage.Server.Console</module>
<module>Mage.Tests</module>
</modules> </modules>
<repositories> <repositories>
<repository>
<id>jboss-public-repository</id>
<name>JBoss Repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
<!-- These optional flags are designed to speed up your builds by reducing remote server calls -->
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
<repository>
<id>jboss-deprecated-repository-group</id>
<name>JBoss Deprecated Maven Repository Group</name>
<url>https://repository.jboss.org/nexus/content/repositories/deprecated/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
<repository>
<id>sonatype-org</id>
<url>https://maven.nuxeo.org/nexus/content/repositories/public/org/</url>
</repository>
<repository> <repository>
<id>mage.googlecode.com</id> <id>mage.googlecode.com</id>
<url>https://mage.googlecode.com/hg/repository/</url> <url>https://mage.googlecode.com/hg/repository/</url>
@ -48,7 +77,7 @@
<id>akathist-repository</id> <id>akathist-repository</id>
<name>Akathist Repository</name> <name>Akathist Repository</name>
<url>http://www.9stmaryrd.com/maven</url> <url>http://www.9stmaryrd.com/maven</url>
</repository> </repository>
</repositories> </repositories>
<pluginRepositories> <pluginRepositories>
@ -60,6 +89,6 @@
</pluginRepositories> </pluginRepositories>
<properties> <properties>
<mage-version>0.7.4</mage-version> <mage-version>0.8.0</mage-version>
</properties> </properties>
</project> </project>