From 716adf342378a9767911196a60d38507f0d5a513 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 22 Jun 2011 21:50:02 -0400 Subject: [PATCH 01/17] add jboss maven repositories --- pom.xml | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5447f5fc6d..44692a45bf 100644 --- a/pom.xml +++ b/pom.xml @@ -35,6 +35,36 @@ + + sonatype-org + https://maven.nuxeo.org/nexus/content/repositories/public/org/ + + + jboss-public-repository + JBoss Repository + https://repository.jboss.org/nexus/content/groups/public + + + never + + + daily + + + + + jboss-deprecated-repository-group + JBoss Deprecated Maven Repository Group + https://repository.jboss.org/nexus/content/repositories/deprecated/ + + true + never + + + true + never + + mage.googlecode.com https://mage.googlecode.com/hg/repository/ @@ -48,7 +78,7 @@ akathist-repository Akathist Repository http://www.9stmaryrd.com/maven - + From a8b8d36637338ddc5e453e0b54e43675e56b5462 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 22 Jun 2011 22:12:14 -0400 Subject: [PATCH 02/17] updated pom files --- Mage.Client/pom.xml | 2 +- Mage.Common/pom.xml | 22 +++++++++++++- Mage.Plugins/Mage.Card.Plugin/pom.xml | 2 +- Mage.Plugins/Mage.Counter.Plugin/pom.xml | 2 +- Mage.Plugins/Mage.Rating.Plugin/pom.xml | 2 +- Mage.Plugins/Mage.Theme.Plugin/pom.xml | 2 +- Mage.Plugins/pom.xml | 2 +- Mage.Server.Console/pom.xml | 2 +- .../Mage.Deck.Constructed/pom.xml | 2 +- Mage.Server.Plugins/Mage.Deck.Limited/pom.xml | 2 +- .../Mage.Game.FreeForAll/pom.xml | 2 +- .../Mage.Game.TwoPlayerDuel/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.AI/pom.xml | 2 +- .../Mage.Player.AIMinimax/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.Human/pom.xml | 2 +- .../Mage.Tournament.BoosterDraft/pom.xml | 2 +- .../Mage.Tournament.Sealed/pom.xml | 2 +- Mage.Server.Plugins/pom.xml | 2 +- Mage.Server/pom.xml | 30 +++++++++++++++++-- Mage.Sets/pom.xml | 2 +- Mage.Tests/pom.xml | 2 +- Mage/pom.xml | 2 +- pom.xml | 4 +-- 24 files changed, 71 insertions(+), 27 deletions(-) diff --git a/Mage.Client/pom.xml b/Mage.Client/pom.xml index fdcb8d1736..7493dafa22 100644 --- a/Mage.Client/pom.xml +++ b/Mage.Client/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.7.4 + 0.8 org.mage diff --git a/Mage.Common/pom.xml b/Mage.Common/pom.xml index 5cec33ff56..11b83c7b4f 100644 --- a/Mage.Common/pom.xml +++ b/Mage.Common/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.7.4 + 0.8 Mage-Common @@ -24,6 +24,26 @@ com.googlecode.jspf jspf-core ${jspf-version} + + + org.jboss.remoting + jboss-remoting + 2.5.2.SP2 + + + jboss + jboss-common-core + 2.2.16.GA + + + jboss + jboss-serialization + 4.2.2.GA + + + concurrent + concurrent + 1.3.4 diff --git a/Mage.Plugins/Mage.Card.Plugin/pom.xml b/Mage.Plugins/Mage.Card.Plugin/pom.xml index 97c5e369a3..5c577b01db 100644 --- a/Mage.Plugins/Mage.Card.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Card.Plugin/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Plugins - 0.7.4 + 0.8 Mage-Card-Plugin diff --git a/Mage.Plugins/Mage.Counter.Plugin/pom.xml b/Mage.Plugins/Mage.Counter.Plugin/pom.xml index 3fa40af077..b2381d3179 100644 --- a/Mage.Plugins/Mage.Counter.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Counter.Plugin/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Plugins - 0.7.4 + 0.8 Mage-Counter-Plugin diff --git a/Mage.Plugins/Mage.Rating.Plugin/pom.xml b/Mage.Plugins/Mage.Rating.Plugin/pom.xml index 588006ec6a..161a5d20c1 100644 --- a/Mage.Plugins/Mage.Rating.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Rating.Plugin/pom.xml @@ -6,7 +6,7 @@ org.mage Mage-Plugins - 0.7.4 + 0.8 org.mage diff --git a/Mage.Plugins/Mage.Theme.Plugin/pom.xml b/Mage.Plugins/Mage.Theme.Plugin/pom.xml index 09cd9bba35..e78e424587 100644 --- a/Mage.Plugins/Mage.Theme.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Theme.Plugin/pom.xml @@ -6,7 +6,7 @@ org.mage Mage-Plugins - 0.7.4 + 0.8 Mage-Theme-Plugin diff --git a/Mage.Plugins/pom.xml b/Mage.Plugins/pom.xml index 0bcccc68b8..506cef6aac 100644 --- a/Mage.Plugins/pom.xml +++ b/Mage.Plugins/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.7.4 + 0.8 Mage-Plugins diff --git a/Mage.Server.Console/pom.xml b/Mage.Server.Console/pom.xml index ceb2243562..b314b70874 100644 --- a/Mage.Server.Console/pom.xml +++ b/Mage.Server.Console/pom.xml @@ -5,7 +5,7 @@ mage-root org.mage - 0.7.4 + 0.8 org.mage Mage.Server.Console diff --git a/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml b/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml index b1b007f6c0..c599cd5930 100644 --- a/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml +++ b/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Deck-Constructed diff --git a/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml b/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml index c1d6e91b9b..6a45bebe3b 100644 --- a/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml +++ b/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Deck-Limited diff --git a/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml b/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml index ec3b8b88ed..59183b9339 100644 --- a/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Game-FreeForAll diff --git a/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml b/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml index 385da30a42..f5ff5ae827 100644 --- a/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Game-TwoPlayerDuel diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml index 17824f0583..1cb1635dbf 100644 --- a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Player-AI-MA diff --git a/Mage.Server.Plugins/Mage.Player.AI/pom.xml b/Mage.Server.Plugins/Mage.Player.AI/pom.xml index 29c266cd52..f256ed8ed8 100644 --- a/Mage.Server.Plugins/Mage.Player.AI/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Player-AI diff --git a/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml b/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml index 4470441f13..d5ce414ecd 100644 --- a/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Player-AIMinimax diff --git a/Mage.Server.Plugins/Mage.Player.Human/pom.xml b/Mage.Server.Plugins/Mage.Player.Human/pom.xml index 00d326f151..1c47d0b791 100644 --- a/Mage.Server.Plugins/Mage.Player.Human/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.Human/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Player-Human diff --git a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml index 7fd764e0b6..8658e5ffdf 100644 --- a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Tournament-BoosterDraft diff --git a/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml b/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml index 774bef03c8..a9a3158f84 100644 --- a/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.7.4 + 0.8 Mage-Tournament-Sealed diff --git a/Mage.Server.Plugins/pom.xml b/Mage.Server.Plugins/pom.xml index cbe329847a..a74f0f7813 100644 --- a/Mage.Server.Plugins/pom.xml +++ b/Mage.Server.Plugins/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.7.4 + 0.8 Mage-Server-Plugins diff --git a/Mage.Server/pom.xml b/Mage.Server/pom.xml index f4e9a77e33..c92bacd2c7 100644 --- a/Mage.Server/pom.xml +++ b/Mage.Server/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.7.4 + 0.8 Mage-Server @@ -39,8 +39,12 @@ jaxb-impl 2.1.12 - - + + org.jboss.remoting + jboss-remoting + 2.5.2.SP2 + + log4j log4j 1.2.14 @@ -106,6 +110,26 @@ ${project.version} runtime + + jboss + jboss-common-core + 2.2.16.GA + + + jboss + jboss-serialization + 4.2.2.GA + + + concurrent + concurrent + 1.3.4 + + + jboss + jboss-jmx + 4.2.2.GA + diff --git a/Mage.Sets/pom.xml b/Mage.Sets/pom.xml index 533e8508cc..76cc3cae9a 100644 --- a/Mage.Sets/pom.xml +++ b/Mage.Sets/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.7.4 + 0.8 org.mage diff --git a/Mage.Tests/pom.xml b/Mage.Tests/pom.xml index d8b8db9b5a..69e9310eab 100644 --- a/Mage.Tests/pom.xml +++ b/Mage.Tests/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.7.4 + 0.8 Mage-Tests diff --git a/Mage/pom.xml b/Mage/pom.xml index 1a93cb1b0e..6014a292a2 100644 --- a/Mage/pom.xml +++ b/Mage/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.7.4 + 0.8 Mage diff --git a/pom.xml b/pom.xml index 44692a45bf..a42f349646 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.mage mage-root - 0.7.4 + 0.8 pom Mage Root Mage Root POM @@ -90,6 +90,6 @@ - 0.7.4 + 0.8 \ No newline at end of file From 34cd3bbcdc91599606115516291e1837ea546f69 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 22 Jun 2011 22:32:33 -0400 Subject: [PATCH 03/17] fixed version --- Mage.Client/pom.xml | 2 +- Mage.Common/pom.xml | 2 +- Mage.Plugins/Mage.Card.Plugin/pom.xml | 2 +- Mage.Plugins/Mage.Counter.Plugin/pom.xml | 2 +- Mage.Plugins/Mage.Rating.Plugin/pom.xml | 2 +- Mage.Plugins/Mage.Theme.Plugin/pom.xml | 2 +- Mage.Plugins/pom.xml | 2 +- Mage.Server.Console/pom.xml | 4 ++-- Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml | 2 +- Mage.Server.Plugins/Mage.Deck.Limited/pom.xml | 2 +- Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml | 2 +- Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.AI/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml | 2 +- Mage.Server.Plugins/Mage.Player.Human/pom.xml | 2 +- Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml | 2 +- Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml | 2 +- Mage.Server.Plugins/pom.xml | 2 +- Mage.Server/pom.xml | 2 +- Mage.Sets/pom.xml | 2 +- Mage.Tests/pom.xml | 2 +- Mage/pom.xml | 2 +- pom.xml | 4 ++-- 24 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Mage.Client/pom.xml b/Mage.Client/pom.xml index 7493dafa22..b67dc5058d 100644 --- a/Mage.Client/pom.xml +++ b/Mage.Client/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.8 + 0.8.0 org.mage diff --git a/Mage.Common/pom.xml b/Mage.Common/pom.xml index 11b83c7b4f..7dde54dfa2 100644 --- a/Mage.Common/pom.xml +++ b/Mage.Common/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.8 + 0.8.0 Mage-Common diff --git a/Mage.Plugins/Mage.Card.Plugin/pom.xml b/Mage.Plugins/Mage.Card.Plugin/pom.xml index 5c577b01db..c1fdc2bc3a 100644 --- a/Mage.Plugins/Mage.Card.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Card.Plugin/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Plugins - 0.8 + 0.8.0 Mage-Card-Plugin diff --git a/Mage.Plugins/Mage.Counter.Plugin/pom.xml b/Mage.Plugins/Mage.Counter.Plugin/pom.xml index b2381d3179..32c8ba7d45 100644 --- a/Mage.Plugins/Mage.Counter.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Counter.Plugin/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Plugins - 0.8 + 0.8.0 Mage-Counter-Plugin diff --git a/Mage.Plugins/Mage.Rating.Plugin/pom.xml b/Mage.Plugins/Mage.Rating.Plugin/pom.xml index 161a5d20c1..6edc54fd58 100644 --- a/Mage.Plugins/Mage.Rating.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Rating.Plugin/pom.xml @@ -6,7 +6,7 @@ org.mage Mage-Plugins - 0.8 + 0.8.0 org.mage diff --git a/Mage.Plugins/Mage.Theme.Plugin/pom.xml b/Mage.Plugins/Mage.Theme.Plugin/pom.xml index e78e424587..5e3cf64cb4 100644 --- a/Mage.Plugins/Mage.Theme.Plugin/pom.xml +++ b/Mage.Plugins/Mage.Theme.Plugin/pom.xml @@ -6,7 +6,7 @@ org.mage Mage-Plugins - 0.8 + 0.8.0 Mage-Theme-Plugin diff --git a/Mage.Plugins/pom.xml b/Mage.Plugins/pom.xml index 506cef6aac..a12b93a5c4 100644 --- a/Mage.Plugins/pom.xml +++ b/Mage.Plugins/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.8 + 0.8.0 Mage-Plugins diff --git a/Mage.Server.Console/pom.xml b/Mage.Server.Console/pom.xml index b314b70874..b14622c924 100644 --- a/Mage.Server.Console/pom.xml +++ b/Mage.Server.Console/pom.xml @@ -5,11 +5,11 @@ mage-root org.mage - 0.8 + 0.8.0 org.mage Mage.Server.Console - 0.8 + 0.8.0 Mage Server Console http://maven.apache.org diff --git a/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml b/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml index c599cd5930..d391b0a4a2 100644 --- a/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml +++ b/Mage.Server.Plugins/Mage.Deck.Constructed/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Deck-Constructed diff --git a/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml b/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml index 6a45bebe3b..50b83fd64c 100644 --- a/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml +++ b/Mage.Server.Plugins/Mage.Deck.Limited/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Deck-Limited diff --git a/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml b/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml index 59183b9339..00a0e4b14f 100644 --- a/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.FreeForAll/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Game-FreeForAll diff --git a/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml b/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml index f5ff5ae827..9b7da3a49b 100644 --- a/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml +++ b/Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Game-TwoPlayerDuel diff --git a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml index 1cb1635dbf..c21dc75666 100644 --- a/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI.MA/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Player-AI-MA diff --git a/Mage.Server.Plugins/Mage.Player.AI/pom.xml b/Mage.Server.Plugins/Mage.Player.AI/pom.xml index f256ed8ed8..a952fb32a4 100644 --- a/Mage.Server.Plugins/Mage.Player.AI/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AI/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Player-AI diff --git a/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml b/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml index d5ce414ecd..cdf59e9645 100644 --- a/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.AIMinimax/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Player-AIMinimax diff --git a/Mage.Server.Plugins/Mage.Player.Human/pom.xml b/Mage.Server.Plugins/Mage.Player.Human/pom.xml index 1c47d0b791..a353f013c4 100644 --- a/Mage.Server.Plugins/Mage.Player.Human/pom.xml +++ b/Mage.Server.Plugins/Mage.Player.Human/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Player-Human diff --git a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml index 8658e5ffdf..615b2fa5ed 100644 --- a/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.BoosterDraft/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Tournament-BoosterDraft diff --git a/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml b/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml index a9a3158f84..aef71a4376 100644 --- a/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml +++ b/Mage.Server.Plugins/Mage.Tournament.Sealed/pom.xml @@ -7,7 +7,7 @@ org.mage Mage-Server-Plugins - 0.8 + 0.8.0 Mage-Tournament-Sealed diff --git a/Mage.Server.Plugins/pom.xml b/Mage.Server.Plugins/pom.xml index a74f0f7813..54ad7d73b7 100644 --- a/Mage.Server.Plugins/pom.xml +++ b/Mage.Server.Plugins/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.8 + 0.8.0 Mage-Server-Plugins diff --git a/Mage.Server/pom.xml b/Mage.Server/pom.xml index c92bacd2c7..54c90225b7 100644 --- a/Mage.Server/pom.xml +++ b/Mage.Server/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.8 + 0.8.0 Mage-Server diff --git a/Mage.Sets/pom.xml b/Mage.Sets/pom.xml index 76cc3cae9a..bbddd5f70d 100644 --- a/Mage.Sets/pom.xml +++ b/Mage.Sets/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.8 + 0.8.0 org.mage diff --git a/Mage.Tests/pom.xml b/Mage.Tests/pom.xml index 69e9310eab..064db269b6 100644 --- a/Mage.Tests/pom.xml +++ b/Mage.Tests/pom.xml @@ -6,7 +6,7 @@ org.mage mage-root - 0.8 + 0.8.0 Mage-Tests diff --git a/Mage/pom.xml b/Mage/pom.xml index 6014a292a2..733e7cd249 100644 --- a/Mage/pom.xml +++ b/Mage/pom.xml @@ -7,7 +7,7 @@ org.mage mage-root - 0.8 + 0.8.0 Mage diff --git a/pom.xml b/pom.xml index a42f349646..8f7b680a7c 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.mage mage-root - 0.8 + 0.8.0 pom Mage Root Mage Root POM @@ -90,6 +90,6 @@ - 0.8 + 0.8.0 \ No newline at end of file From 05be0a14ed923a8d229bcc0b4548d85710956596 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 22 Jun 2011 22:37:50 -0400 Subject: [PATCH 04/17] integrated jboss remoting --- .../src/mage/interfaces/MageServer.java | 124 +++ Mage.Common/src/mage/interfaces/Server.java | 129 --- .../callback/CallbackClientDaemon.java | 82 -- .../callback/CallbackException.java | 46 -- .../interfaces/callback/CallbackServer.java | 42 - .../callback/CallbackServerSession.java | 110 --- Mage.Common/src/mage/remote/Connection.java | 14 - Mage.Common/src/mage/remote/Session.java | 509 ++++++------ Mage.Common/src/mage/view/UserView.java | 6 +- .../mage/server/console/ConnectDialog.form | 347 ++++++--- .../mage/server/console/ConnectDialog.java | 340 ++++++-- .../mage/server/console/ConsoleFrame.java | 104 ++- .../mage/server/console/ConsolePanel.java | 4 +- .../mage/server/console/remote/Session.java | 732 ------------------ .../main/java/mage/server/ChatManager.java | 6 +- .../main/java/mage/server/ChatSession.java | 10 +- .../{ServerImpl.java => MageServerImpl.java} | 172 ++-- .../src/main/java/mage/server/Main.java | 143 +++- .../src/main/java/mage/server/Session.java | 83 +- .../main/java/mage/server/SessionManager.java | 105 +-- .../java/mage/server/TableController.java | 60 +- .../main/java/mage/server/TableManager.java | 34 +- .../mage/server/draft/DraftController.java | 16 +- .../java/mage/server/draft/DraftManager.java | 12 +- .../java/mage/server/draft/DraftSession.java | 9 +- .../java/mage/server/game/GameController.java | 37 +- .../java/mage/server/game/GameManager.java | 30 +- .../java/mage/server/game/GameSession.java | 12 +- .../java/mage/server/game/GameWatcher.java | 7 +- .../main/java/mage/server/game/GamesRoom.java | 14 +- .../java/mage/server/game/GamesRoomImpl.java | 14 +- .../java/mage/server/game/ReplayManager.java | 10 +- .../java/mage/server/game/ReplaySession.java | 6 +- .../tournament/TournamentController.java | 28 +- .../server/tournament/TournamentManager.java | 12 +- .../server/tournament/TournamentSession.java | 8 +- 36 files changed, 1356 insertions(+), 2061 deletions(-) create mode 100644 Mage.Common/src/mage/interfaces/MageServer.java delete mode 100644 Mage.Common/src/mage/interfaces/Server.java delete mode 100644 Mage.Common/src/mage/interfaces/callback/CallbackClientDaemon.java delete mode 100644 Mage.Common/src/mage/interfaces/callback/CallbackException.java delete mode 100644 Mage.Common/src/mage/interfaces/callback/CallbackServer.java delete mode 100644 Mage.Common/src/mage/interfaces/callback/CallbackServerSession.java delete mode 100644 Mage.Server.Console/src/main/java/mage/server/console/remote/Session.java rename Mage.Server/src/main/java/mage/server/{ServerImpl.java => MageServerImpl.java} (72%) diff --git a/Mage.Common/src/mage/interfaces/MageServer.java b/Mage.Common/src/mage/interfaces/MageServer.java new file mode 100644 index 0000000000..2982bf681b --- /dev/null +++ b/Mage.Common/src/mage/interfaces/MageServer.java @@ -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 getTables(UUID roomId) throws MageException; + public List 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 getUsers(String sessionId) throws MageException; + public void disconnectUser(String sessionId, String userSessionId) throws MageException; + public void removeTable(String sessionId, UUID tableId) throws MageException; + +} diff --git a/Mage.Common/src/mage/interfaces/Server.java b/Mage.Common/src/mage/interfaces/Server.java deleted file mode 100644 index c8889a03a9..0000000000 --- a/Mage.Common/src/mage/interfaces/Server.java +++ /dev/null @@ -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 getTables(UUID roomId) throws RemoteException, MageException; - public List 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 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; - -} diff --git a/Mage.Common/src/mage/interfaces/callback/CallbackClientDaemon.java b/Mage.Common/src/mage/interfaces/callback/CallbackClientDaemon.java deleted file mode 100644 index b643f570f9..0000000000 --- a/Mage.Common/src/mage/interfaces/callback/CallbackClientDaemon.java +++ /dev/null @@ -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); - } - } -} diff --git a/Mage.Common/src/mage/interfaces/callback/CallbackException.java b/Mage.Common/src/mage/interfaces/callback/CallbackException.java deleted file mode 100644 index c388f3cfe6..0000000000 --- a/Mage.Common/src/mage/interfaces/callback/CallbackException.java +++ /dev/null @@ -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); - } - -} diff --git a/Mage.Common/src/mage/interfaces/callback/CallbackServer.java b/Mage.Common/src/mage/interfaces/callback/CallbackServer.java deleted file mode 100644 index f3e1b8ce35..0000000000 --- a/Mage.Common/src/mage/interfaces/callback/CallbackServer.java +++ /dev/null @@ -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; - -} diff --git a/Mage.Common/src/mage/interfaces/callback/CallbackServerSession.java b/Mage.Common/src/mage/interfaces/callback/CallbackServerSession.java deleted file mode 100644 index 31e130a543..0000000000 --- a/Mage.Common/src/mage/interfaces/callback/CallbackServerSession.java +++ /dev/null @@ -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(); - } - } - -} diff --git a/Mage.Common/src/mage/remote/Connection.java b/Mage.Common/src/mage/remote/Connection.java index 691b5923a2..43b253a47b 100644 --- a/Mage.Common/src/mage/remote/Connection.java +++ b/Mage.Common/src/mage/remote/Connection.java @@ -28,10 +28,6 @@ package mage.remote; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import mage.interfaces.Server; - /** * * @author BetaSteward_at_googlemail.com @@ -48,16 +44,6 @@ public class Connection { private String proxyUsername; private String proxyPassword; -// protected Server getServer() { -// Server server = null; -// try { -// Registry reg = LocateRegistry.getRegistry(host, port); -// server = (Server) reg.lookup("mage-server"); -// } -// catch (Exception ignored) {} -// return server; -// } - @Override public int hashCode() { return (host + Integer.toString(port) + proxyType.toString()).hashCode(); diff --git a/Mage.Common/src/mage/remote/Session.java b/Mage.Common/src/mage/remote/Session.java index ca623e0302..288f745c78 100644 --- a/Mage.Common/src/mage/remote/Session.java +++ b/Mage.Common/src/mage/remote/Session.java @@ -29,19 +29,13 @@ package mage.remote; import java.net.Authenticator; +import java.net.MalformedURLException; import java.net.PasswordAuthentication; -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.HashMap; import java.util.List; +import java.util.Map; 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 java.util.concurrent.locks.ReentrantReadWriteLock; import mage.cards.decks.DeckCardLists; import mage.game.GameException; import mage.MageException; @@ -49,15 +43,23 @@ import mage.constants.Constants.SessionState; import mage.game.match.MatchOptions; import mage.game.tournament.TournamentOptions; import mage.interfaces.MageClient; -import mage.interfaces.Server; +import mage.interfaces.MageServer; import mage.interfaces.ServerState; -import mage.interfaces.callback.CallbackClientDaemon; +import mage.interfaces.callback.ClientCallback; 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; +import org.jboss.remoting.Client; +import org.jboss.remoting.InvokerLocator; +import org.jboss.remoting.callback.Callback; +import org.jboss.remoting.callback.HandleCallbackException; +import org.jboss.remoting.callback.InvokerCallbackHandler; +import org.jboss.remoting.transport.bisocket.Bisocket; +import org.jboss.remoting.transporter.TransporterClient; /** * @@ -66,16 +68,13 @@ import org.apache.log4j.Logger; 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 String sessionId; + private MageServer server; private MageClient client; - private String userName; + private Client callbackClient; private ServerState serverState; private SessionState sessionState = SessionState.DISCONNECTED; - private CallbackClientDaemon callbackDaemon; - private ScheduledFuture future; private Connection connection; /** @@ -85,7 +84,7 @@ public class Session { * * @author nantuko */ - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); +// private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public Session(MageClient client) { this.client = client; @@ -102,68 +101,76 @@ public class Session { public boolean connect() { sessionState = SessionState.CONNECTING; try { - System.setSecurityManager(null); - System.setProperty("http.nonProxyHosts", "code.google.com"); - System.setProperty("socksNonProxyHosts", "code.google.com"); - - // clear previous values - System.clearProperty("socksProxyHost"); - System.clearProperty("socksProxyPort"); - System.clearProperty("http.proxyHost"); - System.clearProperty("http.proxyPort"); - - switch (connection.getProxyType()) { - case SOCKS: - System.setProperty("socksProxyHost", connection.getProxyHost()); - System.setProperty("socksProxyPort", Integer.toString(connection.getProxyPort())); - break; - case HTTP: - System.setProperty("http.proxyHost", connection.getProxyHost()); - System.setProperty("http.proxyPort", Integer.toString(connection.getProxyPort())); - Authenticator.setDefault(new MageAuthenticator(connection.getProxyUsername(), connection.getProxyPassword())); - break; +// System.setSecurityManager(null); +// System.setProperty("http.nonProxyHosts", "code.google.com"); +// System.setProperty("socksNonProxyHosts", "code.google.com"); +// +// // clear previous values +// System.clearProperty("socksProxyHost"); +// System.clearProperty("socksProxyPort"); +// System.clearProperty("http.proxyHost"); +// System.clearProperty("http.proxyPort"); +// +// switch (connection.getProxyType()) { +// case SOCKS: +// System.setProperty("socksProxyHost", connection.getProxyHost()); +// System.setProperty("socksProxyPort", Integer.toString(connection.getProxyPort())); +// break; +// case HTTP: +// System.setProperty("http.proxyHost", connection.getProxyHost()); +// System.setProperty("http.proxyPort", Integer.toString(connection.getProxyPort())); +// Authenticator.setDefault(new MageAuthenticator(connection.getProxyUsername(), connection.getProxyPassword())); +// break; +// } + InvokerLocator clientLocator = new InvokerLocator(connection.getURI()); + server = (MageServer) TransporterClient.createTransporterClient(clientLocator, MageServer.class); + + callbackClient = new Client(clientLocator, "callback"); + callbackClient.connect(); + + Map metadata = new HashMap(); + metadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); + CallbackHandler callbackHandler = new CallbackHandler(); + callbackClient.addListener(callbackHandler, metadata); + + this.sessionId = callbackClient.getSessionId(); + boolean registerResult = false; + if (connection.getPassword().isEmpty()) + registerResult = server.registerClient(connection.getUsername(), sessionId, client.getVersion()); + else + registerResult = server.registerAdmin(connection.getPassword(), sessionId, client.getVersion()); + if (registerResult) { + sessionState = SessionState.CONNECTED; + serverState = server.getServerState(); + logger.info("Connected to MAGE server at " + connection.getHost() + ":" + connection.getPort()); + client.connected("Connected to " + connection.getHost() + ":" + connection.getPort() + " "); + return true; } - Registry reg = LocateRegistry.getRegistry(connection.getHost(), connection.getPort()); - this.server = (Server) reg.lookup("mage-server"); - this.userName = connection.getUsername(); - sessionId = server.registerClient(userName, client.getId(), client.getVersion()); - callbackDaemon = new CallbackClientDaemon(sessionId, client, server); - sessionState = SessionState.CONNECTED; - serverState = server.getServerState(); - future = sessionExecutor.scheduleWithFixedDelay(new ServerPinger(), 5, 5, TimeUnit.SECONDS); - logger.info("Connected to RMI server at " + connection.getHost() + ":" + connection.getPort()); - client.connected("Connected to " + connection.getHost() + ":" + connection.getPort() + " "); - return true; - } catch (MageException ex) { + disconnect(false); + client.showMessage("Unable to connect to server."); + } catch (MalformedURLException ex) { logger.fatal("", ex); - disconnect(false); client.showMessage("Unable to connect to server. " + ex.getMessage()); - } catch (RemoteException ex) { - logger.fatal("Unable to connect to server - ", ex); + } catch (Throwable t) { + logger.fatal("Unable to connect to server - ", t); disconnect(false); - client.showMessage("Unable to connect to server. " + ex.getMessage()); - } catch (NotBoundException ex) { - logger.fatal("Unable to connect to server - ", ex); + client.showMessage("Unable to connect to server. " + t.getMessage()); } return false; } public synchronized void disconnect(boolean showMessage) { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) sessionState = SessionState.DISCONNECTING; - if (future != null && !future.isDone()) - future.cancel(true); - if (connection == null || server == null) + if (connection == null) return; - if (sessionState == SessionState.DISCONNECTING) { - try { - server.deregisterClient(sessionId); - } catch (Exception ex) { - logger.fatal("Error disconnecting ...", ex); - } + try { + callbackClient.disconnect(); + TransporterClient.destroyTransporterClient(server); + } catch (Throwable ex) { + logger.fatal("Error disconnecting ...", ex); } - server = null; - if (sessionState == SessionState.DISCONNECTING) { + if (sessionState == SessionState.DISCONNECTING || sessionState == SessionState.CONNECTING) { sessionState = SessionState.DISCONNECTED; logger.info("Disconnected ... "); } @@ -172,19 +179,17 @@ public class Session { client.showError("Server error. You have been disconnected"); } - public boolean ping() { - try { - return server.ping(sessionId); - } catch (RemoteException ex) { - handleRemoteException(ex); - } catch (MageException ex) { - handleMageException(ex); + class CallbackHandler implements InvokerCallbackHandler { + @Override + public void handleCallback(Callback callback) throws HandleCallbackException { + client.processCallback((ClientCallback)callback.getCallbackObject()); } - return false; } - + public boolean isConnected() { - return sessionState == SessionState.CONNECTED; + if (callbackClient == null) + return false; + return callbackClient.isConnected(); } public String[] getPlayerTypes() { @@ -211,586 +216,623 @@ public class Session { public UUID getMainRoomId() { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getMainRoomId(); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public UUID getRoomChatId(UUID roomId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getRoomChatId(roomId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public UUID getTableChatId(UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getTableChatId(tableId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public UUID getGameChatId(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getGameChatId(gameId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public TableView getTable(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getTable(roomId, tableId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public boolean watchTable(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.watchTable(sessionId, roomId, tableId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deckList) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) 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); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean joinTournamentTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.joinTournamentTable(sessionId, roomId, tableId, playerName, playerType, skill); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (GameException ex) { handleGameException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public Collection getTables(UUID roomId) throws MageRemoteException { - lock.readLock().lock(); +// lock.readLock().lock(); try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getTables(roomId); - } catch (RemoteException ex) { - handleRemoteException(ex); - throw new MageRemoteException(); } catch (MageException ex) { handleMageException(ex); throw new MageRemoteException(); - } finally { - lock.readLock().unlock(); + } catch (Throwable t) { + handleThrowable(t); +// } finally { +// lock.readLock().unlock(); } return null; } public Collection getConnectedPlayers(UUID roomId) throws MageRemoteException { - lock.readLock().lock(); +// lock.readLock().lock(); try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getConnectedPlayers(roomId); - } catch (RemoteException ex) { - handleRemoteException(ex); - throw new MageRemoteException(); } catch (MageException ex) { handleMageException(ex); throw new MageRemoteException(); - } finally { - lock.readLock().unlock(); + } catch (Throwable t) { + handleThrowable(t); +// } finally { +// lock.readLock().unlock(); } return null; } public TournamentView getTournament(UUID tournamentId) throws MageRemoteException { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getTournament(tournamentId); - } catch (RemoteException ex) { - handleRemoteException(ex); - throw new MageRemoteException(); } catch (MageException ex) { handleMageException(ex); throw new MageRemoteException(); + } catch (Throwable t) { + handleThrowable(t); } return null; } public UUID getTournamentChatId(UUID tournamentId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.getTournamentChatId(tournamentId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public boolean sendPlayerUUID(UUID gameId, UUID data) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.sendPlayerUUID(gameId, sessionId, data); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean sendPlayerBoolean(UUID gameId, boolean data) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.sendPlayerBoolean(gameId, sessionId, data); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean sendPlayerInteger(UUID gameId, int data) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.sendPlayerInteger(gameId, sessionId, data); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean sendPlayerString(UUID gameId, String data) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.sendPlayerString(gameId, sessionId, data); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public DraftPickView sendCardPick(UUID draftId, UUID cardId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.sendCardPick(draftId, sessionId, cardId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public boolean joinChat(UUID chatId) { try { - if (sessionState == SessionState.CONNECTED) { - server.joinChat(chatId, sessionId, userName); + if (isConnected()) { + server.joinChat(chatId, sessionId, connection.getUsername()); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean leaveChat(UUID chatId) { - lock.readLock().lock(); +// lock.readLock().lock(); try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.leaveChat(chatId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); - } finally { - lock.readLock().unlock(); + } catch (Throwable t) { + handleThrowable(t); +// } finally { +// lock.readLock().unlock(); } return false; } public boolean sendChatMessage(UUID chatId, String message) { - lock.readLock().lock(); +// lock.readLock().lock(); try { - if (sessionState == SessionState.CONNECTED) { - server.sendChatMessage(chatId, userName, message); + if (isConnected()) { + server.sendChatMessage(chatId, connection.getUsername(), message); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); - } finally { - lock.readLock().unlock(); + } catch (Throwable t) { + handleThrowable(t); +// } finally { +// lock.readLock().unlock(); } return false; } public boolean joinGame(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.joinGame(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean joinDraft(UUID draftId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.joinDraft(draftId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean joinTournament(UUID tournamentId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.joinTournament(tournamentId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean watchGame(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.watchGame(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean replayGame(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.replayGame(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public TableView createTable(UUID roomId, MatchOptions matchOptions) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.createTable(sessionId, roomId, matchOptions); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public TableView createTournamentTable(UUID roomId, TournamentOptions tournamentOptions) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.createTournamentTable(sessionId, roomId, tournamentOptions); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return null; } public boolean isTableOwner(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.isTableOwner(sessionId, roomId, tableId); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean removeTable(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.removeTable(sessionId, roomId, tableId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); + } + return false; + } + + public boolean removeTable(UUID tableId) { + try { + if (isConnected()) { + server.removeTable(sessionId, tableId); + return true; + } + } catch (MageException ex) { + handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean swapSeats(UUID roomId, UUID tableId, int seatNum1, int seatNum2) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.swapSeats(sessionId, roomId, tableId, seatNum1, seatNum2); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean leaveTable(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.leaveTable(sessionId, roomId, tableId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean startGame(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.startMatch(sessionId, roomId, tableId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean startTournament(UUID roomId, UUID tableId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.startTournament(sessionId, roomId, tableId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean startChallenge(UUID roomId, UUID tableId, UUID challengeId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.startChallenge(sessionId, roomId, tableId, challengeId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean submitDeck(UUID tableId, DeckCardLists deck) { try { - if (sessionState == SessionState.CONNECTED) + if (isConnected()) return server.submitDeck(sessionId, tableId, deck); - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (GameException ex) { handleGameException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean concedeGame(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.concedeGame(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean stopWatching(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.stopWatching(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean startReplay(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.startReplay(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean stopReplay(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.stopReplay(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean nextPlay(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.nextPlay(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean previousPlay(UUID gameId) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.previousPlay(gameId, sessionId); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } public boolean cheat(UUID gameId, UUID playerId, DeckCardLists deckList) { try { - if (sessionState == SessionState.CONNECTED) { + if (isConnected()) { server.cheat(gameId, sessionId, playerId, deckList); return true; } - } catch (RemoteException ex) { - handleRemoteException(ex); } catch (MageException ex) { handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); } return false; } - private void handleRemoteException(RemoteException ex) { - logger.fatal("Communication error", ex); + public List getUsers() { + try { + if (isConnected()) + return server.getUsers(sessionId); + } catch (MageException ex) { + handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); + } + return null; + } + + public boolean disconnectUser(String userSessionId) { + try { + if (isConnected()) { + server.disconnectUser(sessionId, userSessionId); + return true; + } + } catch (MageException ex) { + handleMageException(ex); + } catch (Throwable t) { + handleThrowable(t); + } + return false; + } + + private void handleThrowable(Throwable t) { + logger.fatal("Communication error", t); sessionState = SessionState.SERVER_UNAVAILABLE; disconnect(true); } @@ -806,28 +848,9 @@ public class Session { public String getUserName() { - return userName; + return connection.getUsername(); } - 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"); - disconnect(true); - } - } - else { - missed = 0; - } - } - - } } class MageAuthenticator extends Authenticator { diff --git a/Mage.Common/src/mage/view/UserView.java b/Mage.Common/src/mage/view/UserView.java index 73847d0127..cca7a1def0 100644 --- a/Mage.Common/src/mage/view/UserView.java +++ b/Mage.Common/src/mage/view/UserView.java @@ -39,10 +39,10 @@ public class UserView implements Serializable { private String userName; private String host; - private UUID sessionId; + private String sessionId; 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.host = host; this.sessionId = sessionId; @@ -57,7 +57,7 @@ public class UserView implements Serializable { return host; } - public UUID getSessionId() { + public String getSessionId() { return sessionId; } diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form index 1ee8b0374f..8cb9ff303f 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form @@ -1,6 +1,6 @@ -
+ @@ -27,38 +27,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -78,21 +88,30 @@ - + - + + + + + + - + + + + - + + - + @@ -121,14 +140,14 @@ - + - + - + @@ -155,77 +174,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -233,8 +181,189 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java index 58a83b84fd..3074f63a9b 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java @@ -39,10 +39,18 @@ import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; +import java.util.Arrays; 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.JFrame; + import javax.swing.JOptionPane; +import javax.swing.SwingWorker; + +import mage.remote.Connection; +import mage.remote.Connection.ProxyType; import org.apache.log4j.Logger; @@ -53,22 +61,27 @@ import org.apache.log4j.Logger; public class ConnectDialog extends JDialog { private final static Logger logger = Logger.getLogger(ConnectDialog.class); - private ConsoleFrame console; + private Connection connection; + private ConnectTask task; /** Creates new form ConnectDialog */ public ConnectDialog() { initComponents(); + cbProxyType.setModel(new DefaultComboBoxModel(Connection.ProxyType.values())); } public void showDialog(ConsoleFrame console) { this.console = console; - this.txtServer.setText(ConsoleFrame.getPreferences().get("serverAddress", "")); - this.txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", "")); + this.txtServer.setText(ConsoleFrame.getPreferences().get("serverAddress", "localhost")); + this.txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", Integer.toString(17171))); + this.txtUserName.setText(ConsoleFrame.getPreferences().get("userName", "")); this.chkAutoConnect.setSelected(Boolean.parseBoolean(ConsoleFrame.getPreferences().get("autoConnect", "false"))); - this.txtProxyServer.setText(ConsoleFrame.getPreferences().get("proxyAddress", "")); - this.txtProxyPort.setText(ConsoleFrame.getPreferences().get("proxyPort", "")); - this.chkUseProxy.setSelected(Boolean.parseBoolean(ConsoleFrame.getPreferences().get("useProxy", "false"))); + this.txtProxyServer.setText(ConsoleFrame.getPreferences().get("proxyAddress", "localhost")); + this.txtProxyPort.setText(ConsoleFrame.getPreferences().get("proxyPort", Integer.toString(17171))); + 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.setModal(true); this.setLocation(50, 50); @@ -76,24 +89,37 @@ public class ConnectDialog extends JDialog { } private void showProxySettings() { - if (chkUseProxy.isSelected()) { + if (cbProxyType.getSelectedItem() == Connection.ProxyType.SOCKS) { 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.pnlProxyAuth.setVisible(false); + this.pnlProxySettings.setVisible(false); } this.pack(); -// this.revalidate(); this.repaint(); } private void saveSettings() { ConsoleFrame.getPreferences().put("serverAddress", txtServer.getText()); ConsoleFrame.getPreferences().put("serverPort", txtPort.getText()); + ConsoleFrame.getPreferences().put("userName", txtUserName.getText()); ConsoleFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected())); ConsoleFrame.getPreferences().put("proxyAddress", txtProxyServer.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 @@ -109,18 +135,28 @@ public class ConnectDialog extends JDialog { lblServer = new javax.swing.JLabel(); lblPort = new javax.swing.JLabel(); txtPort = new javax.swing.JTextField(); - txtPassword = new javax.swing.JTextField(); + txtUserName = new javax.swing.JTextField(); lblUserName = new javax.swing.JLabel(); btnConnect = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); 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(); lblProxyServer = new javax.swing.JLabel(); txtProxyServer = new javax.swing.JTextField(); lblProxyPort = new javax.swing.JLabel(); 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"); @@ -136,8 +172,8 @@ public class ConnectDialog extends JDialog { } }); - lblUserName.setLabelFor(txtPassword); - lblUserName.setText("Password:"); + lblUserName.setLabelFor(txtUserName); + lblUserName.setText("User Name:"); btnConnect.setText("Connect"); btnConnect.addActionListener(new java.awt.event.ActionListener() { @@ -160,17 +196,31 @@ public class ConnectDialog extends JDialog { } }); - chkUseProxy.setText("Use Proxy"); - chkUseProxy.addActionListener(new java.awt.event.ActionListener() { + jButton1.setText("Find..."); + jButton1.setToolTipText("Find public server"); + jButton1.setName("findServerBtn"); // NOI18N + jButton1.addActionListener(new java.awt.event.ActionListener() { 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.setLabelFor(txtProxyServer); lblProxyServer.setText("Server:"); - lblProxyPort.setLabelFor(txtPort); + lblProxyPort.setLabelFor(txtProxyPort); lblProxyPort.setText("Port:"); txtProxyPort.addKeyListener(new java.awt.event.KeyAdapter() { @@ -184,22 +234,22 @@ public class ConnectDialog extends JDialog { pnlProxyLayout.setHorizontalGroup( pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlProxyLayout.createSequentialGroup() - .addContainerGap() + .addContainerGap(28, Short.MAX_VALUE) .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblProxyPort) .addComponent(lblProxyServer)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(txtProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)) - .addGap(30, 30, 30)) + .addComponent(txtProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)) + .addContainerGap()) ); pnlProxyLayout.setVerticalGroup( pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlProxyLayout.createSequentialGroup() .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .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) + .addComponent(lblProxyServer)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblProxyPort) @@ -207,15 +257,64 @@ public class ConnectDialog extends JDialog { .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); - jButton1.setText("Find..."); - jButton1.setToolTipText("Find public server"); - jButton1.setName("findServerBtn"); // NOI18N - jButton1.addActionListener(new java.awt.event.ActionListener() { + lblProxyUserName.setLabelFor(txtProxyUserName); + lblProxyUserName.setText("User Name:"); + + lblProxyPassword.setText("Password:"); + + txtPasswordField.addActionListener(new java.awt.event.ActionListener() { 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.TRAILING, false) + .addComponent(txtPasswordField) + .addComponent(txtProxyUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 358, 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(pnlProxy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(pnlProxyAuth, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + pnlProxySettingsLayout.setVerticalGroup( + pnlProxySettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(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()); getContentPane().setLayout(layout); layout.setHorizontalGroup( @@ -225,29 +324,38 @@ public class ConnectDialog extends JDialog { .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(lblPort) + .addComponent(lblServer) + .addComponent(lblUserName)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() - .addComponent(btnConnect) + .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(131, 131, 131)) + .addComponent(txtUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnCancel)) - .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(lblPort) - .addComponent(lblServer) - .addComponent(lblUserName)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .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))) + .addComponent(jButton1)))) + .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, 406, Short.MAX_VALUE) + .addComponent(cbProxyType, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 294, 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() + .addGap(6, 6, 6) + .addComponent(lblPassword) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE))) + .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) @@ -263,18 +371,25 @@ public class ConnectDialog extends JDialog { .addComponent(lblPort)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblUserName)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .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(lblPassword)) + .addGap(18, 18, 18) .addComponent(chkAutoConnect) .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) - .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) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel) - .addComponent(btnConnect)) + .addComponent(btnConnect) + .addComponent(lblStatus)) .addContainerGap()) ); @@ -283,13 +398,16 @@ public class ConnectDialog extends JDialog { private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed 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 private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed - if (txtPassword.getText().isEmpty()) { - JOptionPane.showMessageDialog(rootPane, "Please provide a password"); + if (txtUserName.getText().isEmpty()) { + JOptionPane.showMessageDialog(rootPane, "Please provide a user name"); return; } if (txtServer.getText().trim().isEmpty()) { @@ -302,31 +420,72 @@ public class ConnectDialog extends JDialog { } if (Integer.valueOf(txtPort.getText()) < 1 || Integer.valueOf(txtPort.getText()) > 65535 ) { JOptionPane.showMessageDialog(rootPane, "Invalid port number"); - txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", "")); + txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", Integer.toString(17171))); return; } + char[] input = new char[0]; try { - setCursor(new Cursor(Cursor.WAIT_CURSOR)); - if (chkUseProxy.isSelected()) { - if (console.connect(txtPassword.getText(), txtServer.getText().trim(), Integer.valueOf(txtPort.getText()), txtProxyServer.getText().trim(), Integer.valueOf(txtProxyPort.getText()))) { - this.saveSettings(); - this.setVisible(false); - } - } - else { - if (console.connect(txtPassword.getText(), txtServer.getText().trim(), Integer.valueOf(txtPort.getText()))) { - this.saveSettings(); - this.setVisible(false); - } - } + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + connection = new Connection(); + connection.setHost(this.txtServer.getText()); + connection.setPort(Integer.valueOf(this.txtPort.getText())); + connection.setUsername(this.txtUserName.getText()); + connection.setProxyType((ProxyType) this.cbProxyType.getSelectedItem()); + connection.setProxyHost(this.txtProxyServer.getText()); + connection.setProxyPort(Integer.valueOf(this.txtProxyPort.getText())); + connection.setProxyUsername(this.txtProxyUserName.getText()); + input = txtPasswordField.getPassword(); + connection.setProxyPassword(new String(input)); + logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort()); + task = new ConnectTask(); + task.execute(); } finally { - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + Arrays.fill(input, '0'); } }//GEN-LAST:event_btnConnectActionPerformed + private class ConnectTask extends SwingWorker { + + 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 char c = evt.getKeyChar(); if (!Character.isDigit(c)) @@ -342,23 +501,19 @@ public class ConnectDialog extends JDialog { // TODO add your handling code here: }//GEN-LAST:event_txtProxyPortkeyTyped - private void chkUseProxyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUseProxyActionPerformed - this.showProxySettings(); - }//GEN-LAST:event_chkUseProxyActionPerformed - - private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + private void findPublicServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed BufferedReader in = null; try { URL serverListURL = new URL("http://mage.googlecode.com/files/server-list.txt"); in = new BufferedReader(new InputStreamReader(serverListURL.openStream())); - + List servers = new ArrayList(); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Found server: "+inputLine); servers.add(inputLine); } - + if (servers.size() == 0) { JOptionPane.showMessageDialog(null, "Couldn't find any server."); return; @@ -384,27 +539,44 @@ public class ConnectDialog extends JDialog { } finally { 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 private javax.swing.JButton btnCancel; private javax.swing.JButton btnConnect; + private javax.swing.JComboBox cbProxyType; private javax.swing.JCheckBox chkAutoConnect; - private javax.swing.JCheckBox chkUseProxy; private javax.swing.JButton jButton1; + private javax.swing.JLabel lblPassword; private javax.swing.JLabel lblPort; + private javax.swing.JLabel lblProxyPassword; private javax.swing.JLabel lblProxyPort; private javax.swing.JLabel lblProxyServer; + private javax.swing.JLabel lblProxyType; + private javax.swing.JLabel lblProxyUserName; private javax.swing.JLabel lblServer; + private javax.swing.JLabel lblStatus; private javax.swing.JLabel lblUserName; 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 txtProxyPort; private javax.swing.JTextField txtProxyServer; + private javax.swing.JTextField txtProxyUserName; private javax.swing.JTextField txtServer; + private javax.swing.JTextField txtUserName; // End of variables declaration//GEN-END:variables } diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java index 11a28b9c85..0ee1b69284 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java @@ -34,11 +34,16 @@ package mage.server.console; +import java.util.UUID; import java.util.prefs.Preferences; import javax.swing.Box; import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; 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 org.apache.log4j.Logger; @@ -46,7 +51,7 @@ import org.apache.log4j.Logger; * * @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); @@ -66,7 +71,8 @@ public class ConsoleFrame extends javax.swing.JFrame { return prefs; } - public static MageVersion getVersion() { + @Override + public MageVersion getVersion() { return version; } @@ -82,16 +88,9 @@ public class ConsoleFrame extends javax.swing.JFrame { } } - public boolean connect(String password, String serverName, int port) { - if (session.connect(password, serverName, port)) { - 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)) { + public boolean connect(Connection connection) { + if (session.connect(connection)) { + this.consolePanel1.start(); return true; } @@ -168,7 +167,7 @@ public class ConsoleFrame extends javax.swing.JFrame { if (session.isConnected()) { if (JOptionPane.showConfirmDialog(this, "Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { this.consolePanel1.stop(); - session.disconnect(); + session.disconnect(false); } } else { connectDialog.showDialog(this); @@ -185,6 +184,10 @@ public class ConsoleFrame extends javax.swing.JFrame { } }); } + + private ConsoleFrame getFrame() { + return this; + } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnConnect; @@ -193,4 +196,77 @@ public class ConsoleFrame extends javax.swing.JFrame { private javax.swing.JLabel lblStatus; // 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()) { + setStatusText("Not connected"); + disableButtons(); + } + else { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + 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) { + } + } diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java index 1019fe330b..186471f3bb 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java @@ -38,7 +38,7 @@ import java.util.List; import java.util.UUID; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; -import mage.server.console.remote.Session; +import mage.remote.Session; import mage.view.TableView; import mage.view.UserView; @@ -239,7 +239,7 @@ public class ConsolePanel extends javax.swing.JPanel { private void btnDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDisconnectActionPerformed 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 private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed diff --git a/Mage.Server.Console/src/main/java/mage/server/console/remote/Session.java b/Mage.Server.Console/src/main/java/mage/server/console/remote/Session.java deleted file mode 100644 index 68409c4cf5..0000000000 --- a/Mage.Server.Console/src/main/java/mage/server/console/remote/Session.java +++ /dev/null @@ -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 getGameTypes() { - return serverState.getGameTypes(); - } - - public String[] getDeckTypes() { - return serverState.getDeckTypes(); - } - - public List 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 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 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; - } - } - - } - -} \ No newline at end of file diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index 55e2cc8fa5..7aa563f476 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -54,11 +54,11 @@ public class ChatManager { return chatSession.getChatId(); } - public void joinChat(UUID chatId, UUID sessionId, String userName) { + public void joinChat(UUID chatId, String sessionId, String userName) { chatSessions.get(chatId).join(userName, sessionId); } - public void leaveChat(UUID chatId, UUID sessionId) { + public void leaveChat(UUID chatId, String sessionId) { chatSessions.get(chatId).kill(sessionId); } @@ -70,7 +70,7 @@ public class ChatManager { chatSessions.get(chatId).broadcast(userName, message, color); } - void removeSession(UUID sessionId) { + void removeSession(String sessionId) { for (ChatSession chat: chatSessions.values()) { chat.kill(sessionId); } diff --git a/Mage.Server/src/main/java/mage/server/ChatSession.java b/Mage.Server/src/main/java/mage/server/ChatSession.java index 8ecc32714f..e60003044d 100644 --- a/Mage.Server/src/main/java/mage/server/ChatSession.java +++ b/Mage.Server/src/main/java/mage/server/ChatSession.java @@ -34,8 +34,6 @@ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import mage.MageException; -import mage.interfaces.callback.CallbackException; import mage.interfaces.callback.ClientCallback; import mage.view.ChatMessage; import mage.view.ChatMessage.MessageColor; @@ -48,7 +46,7 @@ import org.apache.log4j.Logger; public class ChatSession { private final static Logger logger = Logger.getLogger(ChatSession.class); - private ConcurrentHashMap clients = new ConcurrentHashMap(); + private ConcurrentHashMap clients = new ConcurrentHashMap(); private UUID chatId; private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT); @@ -58,13 +56,13 @@ public class ChatSession { chatId = UUID.randomUUID(); } - public void join(String userName, UUID sessionId) { + public void join(String userName, String sessionId) { clients.put(sessionId, userName); broadcast(userName, " has joined", MessageColor.BLACK); logger.info(userName + " joined chat " + chatId); } - public void kill(UUID sessionId) { + public void kill(String sessionId) { if (clients.containsKey(sessionId)) { String userName = clients.get(sessionId); clients.remove(sessionId); @@ -79,7 +77,7 @@ public class ChatSession { final String time = timeFormatter.format(cal.getTime()); final String username = userName; logger.debug("Broadcasting '" + msg + "' for " + chatId); - for (UUID sessionId: clients.keySet()) { + for (String sessionId: clients.keySet()) { Session session = SessionManager.getInstance().getSession(sessionId); if (session != null) session.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color))); diff --git a/Mage.Server/src/main/java/mage/server/ServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java similarity index 72% rename from Mage.Server/src/main/java/mage/server/ServerImpl.java rename to Mage.Server/src/main/java/mage/server/MageServerImpl.java index be7798e799..7afe35741e 100644 --- a/Mage.Server/src/main/java/mage/server/ServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -28,12 +28,6 @@ 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.List; import java.util.UUID; @@ -43,9 +37,9 @@ import mage.cards.decks.DeckCardLists; import mage.game.GameException; import mage.game.match.MatchOptions; import mage.game.tournament.TournamentOptions; -import mage.interfaces.Server; +import mage.interfaces.MageServer; +//import mage.interfaces.Server; import mage.interfaces.ServerState; -import mage.interfaces.callback.ClientCallback; import mage.server.game.DeckValidatorFactory; import mage.server.draft.DraftManager; import mage.server.game.GameFactory; @@ -69,94 +63,48 @@ import org.apache.log4j.Logger; * * @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 static ExecutorService rmiExecutor = ThreadExecutor.getInstance().getRMIExecutor(); - private boolean testMode; 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 { - System.setSecurityManager(null); - Registry reg = LocateRegistry.createRegistry(port); - Server stub = (Server) UnicastRemoteObject.exportObject(this, port); - reg.rebind(name, stub); - this.testMode = testMode; - 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; + if (version.compareTo(Main.getVersion()) != 0) + throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); + return SessionManager.getInstance().registerUser(sessionId, userName); + } catch (Exception ex) { + handleException(ex); } return false; } @Override - public UUID registerClient(String userName, UUID clientId, MageVersion version) throws MageException, RemoteException { - - 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; + public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException { try { if (version.compareTo(Main.getVersion()) != 0) throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); if (!password.equals(this.password)) throw new MageException("Wrong password"); - sessionId = SessionManager.getInstance().createSession(getClientHost()); - logger.info("Admin connected from " + getClientHost()); + return SessionManager.getInstance().registerAdmin(sessionId); } catch (Exception ex) { handleException(ex); } - return sessionId; + return false; } @Override - public TableView createTable(UUID sessionId, UUID roomId, MatchOptions options) throws MageException { + public TableView createTable(String sessionId, UUID roomId, MatchOptions options) throws MageException { try { if (SessionManager.getInstance().isValidSession(sessionId)) { TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(sessionId, options); @@ -171,7 +119,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public TableView createTournamentTable(UUID sessionId, UUID roomId, TournamentOptions options) throws MageException { + public TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions options) throws MageException { try { if (SessionManager.getInstance().isValidSession(sessionId)) { TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(sessionId, options); @@ -186,7 +134,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -205,7 +153,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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 { if (SessionManager.getInstance().isValidSession(sessionId)) { boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(sessionId, tableId, name, playerType, skill, deckList); @@ -222,7 +170,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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 { if (SessionManager.getInstance().isValidSession(sessionId)) { boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(sessionId, tableId, name, playerType, skill); @@ -239,7 +187,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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 { if (SessionManager.getInstance().isValidSession(sessionId)) { boolean ret = TableManager.getInstance().submitDeck(sessionId, tableId, deckList); @@ -293,7 +241,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public void deregisterClient(final UUID sessionId) throws MageException { + public void deregisterClient(final String sessionId) throws MageException { try { rmiExecutor.execute( new Runnable() { @@ -314,7 +262,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -333,7 +281,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -352,7 +300,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -371,7 +319,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public TournamentView getTournament(UUID tournamentId) throws RemoteException, MageException { + public TournamentView getTournament(UUID tournamentId) throws MageException { try { return TournamentManager.getInstance().getTournamentView(tournamentId); } @@ -399,7 +347,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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 { rmiExecutor.execute( new Runnable() { @@ -416,7 +364,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public void leaveChat(final UUID chatId, final UUID sessionId) throws MageException { + public void leaveChat(final UUID chatId, final String sessionId) throws MageException { try { rmiExecutor.execute( new Runnable() { @@ -455,7 +403,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public boolean isTableOwner(UUID sessionId, UUID roomId, UUID tableId) throws MageException { + public boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException { try { return TableManager.getInstance().isTableOwner(tableId, sessionId); } @@ -466,7 +414,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -485,7 +433,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -515,7 +463,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -534,7 +482,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -553,7 +501,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -594,7 +542,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -613,7 +561,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -632,7 +580,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -651,7 +599,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -670,7 +618,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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 { if (SessionManager.getInstance().isValidSession(sessionId)) { return DraftManager.getInstance().sendCardPick(draftId, sessionId, cardPick); @@ -683,7 +631,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -702,7 +650,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public boolean watchTable(UUID sessionId, UUID roomId, UUID tableId) throws MageException { + public boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException { try { if (SessionManager.getInstance().isValidSession(sessionId)) { return GamesRoomManager.getInstance().getRoom(roomId).watchTable(sessionId, tableId); @@ -715,7 +663,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -734,7 +682,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -753,7 +701,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -772,7 +720,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -791,7 +739,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -810,7 +758,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -829,7 +777,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -848,7 +796,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public ServerState getServerState() throws RemoteException, MageException { + public ServerState getServerState() throws MageException { try { return new ServerState( GameFactory.getInstance().getGameTypes(), @@ -865,7 +813,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -885,7 +833,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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 (SessionManager.getInstance().isValidSession(sessionId)) { return GameManager.getInstance().cheat(gameId, sessionId, playerId, cardName); @@ -900,7 +848,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { return GameManager.getInstance().getGameView(gameId, sessionId, playerId); } @@ -908,7 +856,7 @@ public class ServerImpl extends RemoteServer implements Server { } @Override - public List getUsers(UUID sessionId) throws RemoteException, MageException { + public List getUsers(String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { return SessionManager.getInstance().getUsers(sessionId); } @@ -916,7 +864,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( @@ -935,7 +883,7 @@ public class ServerImpl extends RemoteServer implements Server { } @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)) { try { rmiExecutor.execute( diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index a8816d1736..6a2f98563f 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -37,8 +37,11 @@ import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; +import java.util.Map; +import javax.management.MBeanServer; import mage.game.match.MatchType; import mage.game.tournament.TournamentType; +import mage.interfaces.MageServer; import mage.server.game.DeckValidatorFactory; import mage.server.game.GameFactory; import mage.server.game.PlayerFactory; @@ -46,9 +49,17 @@ import mage.server.tournament.TournamentFactory; import mage.server.util.ConfigSettings; import mage.server.util.config.Plugin; import mage.server.util.config.GamePlugin; -import mage.util.Copier; import mage.utils.MageVersion; import org.apache.log4j.Logger; +import org.jboss.remoting.InvocationRequest; +import org.jboss.remoting.InvokerLocator; +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 +72,11 @@ public class Main { private final static String testModeArg = "-testMode="; private final static String adminPasswordArg = "-adminPassword="; private final static String pluginFolder = "plugins"; - private static MageVersion version = new MageVersion(0, 7, 4, "beta-2"); + private static MageVersion version = new MageVersion(0, 8, 0, ""); public static PluginClassLoader classLoader = new PluginClassLoader(); - public static ServerImpl server; - + public static TransporterServer server; + protected static boolean testMode; /** * @param args the command line arguments */ @@ -87,7 +98,6 @@ public class Main { for (Plugin plugin: config.getDeckTypes()) { DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin)); } - boolean testMode = false; String adminPassword = ""; for (String arg: args) { if (arg.startsWith(testModeArg)) { @@ -97,44 +107,102 @@ public class Main { adminPassword = arg.replace(adminPasswordArg, ""); } } - Copier.setLoader(classLoader); - setServerAddress(config.getServerAddress()); - server = new ServerImpl(config.getPort(), config.getServerName(), testMode, adminPassword); + String host = getServerAddress(); + int port = config.getPort(); + String locatorURI = "bisocket://" + host + ":" + port; + try { + InvokerLocator serverLocator = new InvokerLocator(locatorURI); + server = new MageTransporterServer(serverLocator, new MageServerImpl(adminPassword, testMode), MageServer.class.getName(), new MageServerInvocationHandler()); + server.start(); + logger.info("Started MAGE server - listening on " + host + ":" + port); + if (testMode) + logger.info("MAGE server running in test mode"); + + } catch (Exception ex) { + logger.fatal("Failed to start server - " + host + ":" + port, ex); + } } - private static void setServerAddress(String ip) { - String ipParam = System.getProperty("server"); - if (ipParam != null) { - ip = ipParam; + static class MageTransporterServer extends TransporterServer { + + Connector connector; + + public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler callback) throws Exception { + super(locator, target, subsystem); + connector.addInvocationHandler("callback", callback); } - if (ip.equals("localhost")) { + + 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 { + return null; + } + + @Override + public void addListener(InvokerCallbackHandler callbackHandler) { + ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; try { - String foundIP = ""; - for (Enumeration 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) { - foundIP = iaddr.getHostAddress(); - break; - } - } - if (foundIP.length() > 0) - break; - } - if (foundIP.length() > 0) - ip = foundIP; - } catch (SocketException ex) { - logger.warn("Could not get server address: ", ex); + String sessionId = handler.getClientSessionId(); + InetAddress clientAddress = handler.getCallbackClient().getAddressSeenByServer(); + SessionManager.getInstance().createSession(sessionId, callbackHandler, clientAddress.getHostAddress()); + } catch (Throwable ex) { + logger.fatal("", ex); } } - System.setProperty("java.rmi.server.hostname", ip); - System.setProperty("sun.rmi.transport.tcp.readTimeout", "30000"); - logger.info("MAGE server - using address " + ip); + + @Override + public void removeListener(InvokerCallbackHandler callbackHandler) { + ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; + String sessionId = handler.getCallbackClient().getSessionId(); + SessionManager.getInstance().removeSession(sessionId); + } + + } + + private static String getServerAddress() { + try { + String foundIP = ""; + for (Enumeration 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) { + foundIP = iaddr.getHostAddress(); + break; + } + } + if (foundIP.length() > 0) + break; + } + if (foundIP.length() > 0) + return foundIP; + } catch (SocketException ex) { + logger.warn("Could not get server address: ", ex); + } + return null; } private static Class loadPlugin(Plugin plugin) { @@ -198,4 +266,7 @@ public class Main { return version; } + public static boolean isTestMode() { + return testMode; + } } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 58d745549a..345d1a75e5 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -31,11 +31,14 @@ package mage.server; import java.util.Date; import java.util.UUID; import mage.cards.decks.Deck; -import mage.interfaces.callback.CallbackServerSession; import mage.interfaces.callback.ClientCallback; import mage.server.game.GameManager; import mage.view.TableClientMessage; 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,68 +48,46 @@ public class Session { private final static Logger logger = Logger.getLogger(Session.class); - private UUID sessionId; - private UUID clientId; + private String sessionId; private String username; private String host; - private int messageId = 0; - private String ackMessage; private Date timeConnected; - private long lastPing; private boolean isAdmin = false; - private final CallbackServerSession callback = new CallbackServerSession(); + private AsynchInvokerCallbackHandler callbackHandler; - public Session(String userName, String host, UUID clientId) { - sessionId = UUID.randomUUID(); - this.username = userName; + public Session(String sessionId, InvokerCallbackHandler callbackHandler, String host) { + this.sessionId = sessionId; + this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler; this.host = host; - this.clientId = clientId; this.isAdmin = false; this.timeConnected = new Date(); - ping(); } - - public Session(String host) { - sessionId = UUID.randomUUID(); - this.username = "Admin"; - this.host = host; + + public void registerUser(String userName) { + this.isAdmin = false; + this.username = userName; + } + + public void registerAdmin() { this.isAdmin = true; - this.timeConnected = new Date(); - ping(); + this.username = "Admin"; } - - public UUID getId() { + + public String getId() { return sessionId; } - public UUID getClientId() { - return clientId; - } - public void kill() { - callback.destroy(); SessionManager.getInstance().removeSession(sessionId); TableManager.getInstance().removeSession(sessionId); GameManager.getInstance().removeSession(sessionId); ChatManager.getInstance().removeSession(sessionId); } - public ClientCallback callback() { - try { - return callback.callback(); - } catch (InterruptedException ex) { - logger.fatal("Session callback error", 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) { + callbackHandler.handleCallbackOneway(new Callback(call)); + } catch (HandleCallbackException ex) { logger.fatal("Session fireCallback error", ex); } } @@ -139,32 +120,10 @@ public class Session { 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() { return isAdmin; } diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 76b661910a..fe623d6b72 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -32,14 +32,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -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.MageException; import mage.view.UserView; import org.apache.log4j.Logger; +import org.jboss.remoting.callback.InvokerCallbackHandler; /** * @@ -49,83 +45,67 @@ public class SessionManager { private final static Logger logger = Logger.getLogger(SessionManager.class); private final static SessionManager INSTANCE = new SessionManager(); - private static ScheduledExecutorService sessionExecutor; public static SessionManager getInstance() { return INSTANCE; } - protected SessionManager() { - sessionExecutor = Executors.newScheduledThreadPool(1); - sessionExecutor.scheduleWithFixedDelay(new SessionChecker(), 30, 10, TimeUnit.SECONDS); - } + private ConcurrentHashMap sessions = new ConcurrentHashMap(); - private ConcurrentHashMap sessions = new ConcurrentHashMap(); - - public Session getSession(UUID sessionId) { + public Session getSession(String sessionId) { if (sessions == null || sessionId == null) return null; return sessions.get(sessionId); } - public UUID createSession(String userName, String host, UUID clientId) throws MageException { - for (Session session: sessions.values()) { - if (session.getUsername().equals(userName)) { - if (session.getClientId().equals(clientId)) { - logger.info("Reconnecting session " + session.getId() + " for " + userName); - return session.getId(); - } - else { - throw new MageException("User name already in use"); - } - } - } - Session session = new Session(userName, host, clientId); - sessions.put(session.getId(), session); - logger.info("Session " + session.getId() + " created for user " + userName); - return session.getId(); - } - - public UUID createSession(String host) throws MageException { - Session session = new Session(host); - sessions.put(session.getId(), session); - logger.info("Admin session created"); - return session.getId(); - } - - public void removeSession(UUID sessionId) { - sessions.remove(sessionId); - } - - 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(); - } - } + public void createSession(String sessionId, InvokerCallbackHandler callbackHandler, String host) { + Session session = new Session(sessionId, callbackHandler, host); + sessions.put(sessionId, session); } - public Map getSessions() { - Map map = new HashMap(); - for (Map.Entry entry : sessions.entrySet()) { + public boolean registerUser(String sessionId, String userName) { + Session session = sessions.get(sessionId); + if (session != null) { + session.registerUser(userName); + logger.info("User " + userName + " connected from " + session.getHost()); + return true; + } + return false; + } + + public boolean registerAdmin(String sessionId) { + Session session = sessions.get(sessionId); + if (session != null) { + session.registerAdmin(); + logger.info("Admin connected from " + session.getHost()); + return true; + } + return false; + } + + public void removeSession(String sessionId) { + sessions.remove(sessionId); + } + + public Map getSessions() { + Map map = new HashMap(); + for (Map.Entry entry : sessions.entrySet()) { map.put(entry.getKey(), entry.getValue()); } return map; } - List getUsers(UUID sessionId) { + List getUsers(String sessionId) { List users = new ArrayList(); 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())); + users.add(new UserView(session.getUsername(), "", session.getId(), session.getConnectionTime())); } } return users; } - public void disconnectUser(UUID sessionId, UUID userSessionId) { + public void disconnectUser(String sessionId, String userSessionId) { if (isAdmin(sessionId)) { Session session = sessions.get(userSessionId); if (session != null) { @@ -134,7 +114,7 @@ public class SessionManager { } } - public boolean isAdmin(UUID sessionId) { + public boolean isAdmin(String sessionId) { Session admin = sessions.get(sessionId); if (admin != null) { return admin.isAdmin(); @@ -142,19 +122,10 @@ public class SessionManager { return false; } - public boolean isValidSession(UUID sessionId) { + public boolean isValidSession(String sessionId) { if (sessions.containsKey(sessionId)) return true; return false; } - class SessionChecker implements Runnable { - - @Override - public void run() { - checkSessions(); - } - - } - } diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 59855cd257..b3a824ae3e 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -67,16 +67,16 @@ public class TableController { private final static Logger logger = Logger.getLogger(TableController.class); - private UUID sessionId; + private String sessionId; private UUID chatId; private String controllerName; private Table table; private Match match; private MatchOptions options; private Tournament tournament; - private ConcurrentHashMap sessionPlayerMap = new ConcurrentHashMap(); + private ConcurrentHashMap sessionPlayerMap = new ConcurrentHashMap(); - public TableController(UUID roomId, UUID sessionId, MatchOptions options) { + public TableController(UUID roomId, String sessionId, MatchOptions options) { this.sessionId = sessionId; chatId = ChatManager.getInstance().createChatSession(); this.options = options; @@ -90,7 +90,7 @@ public class TableController { init(); } - public TableController(UUID roomId, UUID sessionId, TournamentOptions options) { + public TableController(UUID roomId, String sessionId, TournamentOptions options) { this.sessionId = sessionId; chatId = ChatManager.getInstance().createChatSession(); tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options); @@ -124,7 +124,7 @@ public class TableController { ); } - public synchronized boolean joinTournament(UUID sessionId, String name, String playerType, int skill) throws GameException { + public synchronized boolean joinTournament(String sessionId, String name, String playerType, int skill) throws GameException { if (table.getState() != TableState.WAITING) { return false; } @@ -144,7 +144,7 @@ public class TableController { return true; } - public synchronized boolean joinTable(UUID sessionId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { + public synchronized boolean joinTable(String sessionId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { if (table.getState() != TableState.WAITING) { return false; } @@ -153,7 +153,7 @@ public class TableController { throw new GameException("No available seats."); } 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()); } @@ -169,7 +169,7 @@ public class TableController { return true; } - public void addPlayer(UUID sessionId, Player player, String playerType, Deck deck) throws GameException { + public void addPlayer(String sessionId, Player player, String playerType, Deck deck) throws GameException { if (table.getState() != TableState.WAITING) { return; } @@ -183,29 +183,33 @@ public class TableController { sessionPlayerMap.put(sessionId, player.getId()); } } + + public boolean submitDeck(String sessionId, DeckCardLists deckList) throws MageException { + return submitDeck(sessionPlayerMap.get(sessionId), deckList); + } - public synchronized boolean submitDeck(UUID sessionId, DeckCardLists deckList) throws MageException { + public synchronized boolean submitDeck(UUID playerId, DeckCardLists deckList) throws MageException { if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) { return false; } 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()); } - submitDeck(sessionId, deck); + submitDeck(playerId, deck); return true; } - private void submitDeck(UUID sessionId, Deck deck) { + private void submitDeck(UUID playerId, Deck deck) { if (table.getState() == TableState.SIDEBOARDING) { - match.submitDeck(sessionPlayerMap.get(sessionId), deck); + match.submitDeck(playerId, deck); } else { - TournamentManager.getInstance().submitDeck(tournament.getId(), sessionId, deck); + TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck); } } - public boolean watchTable(UUID sessionId) { + public boolean watchTable(String sessionId) { if (table.getState() != TableState.DUELING) { return false; } @@ -213,11 +217,11 @@ public class TableController { return true; } - public boolean replayTable(UUID sessionId) { + public boolean replayTable(String sessionId) { if (table.getState() != TableState.FINISHED) { return false; } - ReplayManager.getInstance().replayGame(sessionId, table.getId()); + ReplayManager.getInstance().replayGame(table.getId(), sessionId); return true; } @@ -233,18 +237,18 @@ public class TableController { return player; } - public synchronized void leaveTable(UUID sessionId) { + public synchronized void leaveTable(String sessionId) { if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING) table.leaveTable(sessionPlayerMap.get(sessionId)); } - public synchronized void startMatch(UUID sessionId) { + public synchronized void startMatch(String sessionId) { if (sessionId.equals(this.sessionId)) { startMatch(); } } - public synchronized void startChallenge(UUID sessionId, UUID challengeId) { + public synchronized void startChallenge(String sessionId, UUID challengeId) { if (sessionId.equals(this.sessionId)) { try { match.startMatch(); @@ -256,7 +260,7 @@ public class TableController { GameManager.getInstance().createGameSession(match.getGame(), sessionPlayerMap, table.getId(), null); ChallengeManager.getInstance().prepareChallenge(getPlayerId(), match); SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { + for (Entry entry: sessionPlayerMap.entrySet()) { sessionManager.getSession(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue()); } } catch (GameException ex) { @@ -267,7 +271,7 @@ public class TableController { private UUID getPlayerId() throws GameException { UUID playerId = null; - for (Entry entry : sessionPlayerMap.entrySet()) { + for (Entry entry : sessionPlayerMap.entrySet()) { playerId = entry.getValue(); break; } @@ -294,7 +298,7 @@ public class TableController { table.initGame(); GameManager.getInstance().createGameSession(match.getGame(), sessionPlayerMap, table.getId(), choosingPlayerId); SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { + for (Entry entry: sessionPlayerMap.entrySet()) { Session session = sessionManager.getSession(entry.getKey()); if (session != null) { session.gameStarted(match.getGame().getId(), entry.getValue()); @@ -314,12 +318,12 @@ public class TableController { } } - public synchronized void startTournament(UUID sessionId) { + public synchronized void startTournament(String sessionId) { try { if (sessionId.equals(this.sessionId) && table.getState() == TableState.STARTING) { TournamentManager.getInstance().createTournamentSession(tournament, sessionPlayerMap, table.getId()); SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { + for (Entry entry: sessionPlayerMap.entrySet()) { Session session = sessionManager.getSession(entry.getKey()); session.tournamentStarted(tournament.getId(), entry.getValue()); } @@ -336,14 +340,14 @@ public class TableController { table.initDraft(); DraftManager.getInstance().createDraftSession(draft, sessionPlayerMap, table.getId()); SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { + for (Entry entry: sessionPlayerMap.entrySet()) { sessionManager.getSession(entry.getKey()).draftStarted(draft.getId(), entry.getValue()); } } private void sideboard(UUID playerId, Deck deck, int timeout) throws MageException { SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { + for (Entry entry: sessionPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) { sessionManager.getSession(entry.getKey()).sideboard(deck, table.getId(), timeout); break; @@ -395,7 +399,7 @@ public class TableController { } } - public boolean isOwner(UUID sessionId) { + public boolean isOwner(String sessionId) { return sessionId.equals(this.sessionId); } diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index 2f7421d6c3..ff476b7e06 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -60,7 +60,7 @@ public class TableManager { return INSTANCE; } - public Table createTable(UUID roomId, UUID sessionId, MatchOptions options) { + public Table createTable(UUID roomId, String sessionId, MatchOptions options) { TableController tableController = new TableController(roomId, sessionId, options); controllers.put(tableController.getTable().getId(), tableController); tables.put(tableController.getTable().getId(), tableController.getTable()); @@ -68,13 +68,13 @@ public class TableManager { } public Table createTable(UUID roomId, MatchOptions options) { - TableController tableController = new TableController(roomId, UUID.randomUUID(), options); + TableController tableController = new TableController(roomId, UUID.randomUUID().toString(), options); controllers.put(tableController.getTable().getId(), tableController); tables.put(tableController.getTable().getId(), tableController.getTable()); return tableController.getTable(); } - public Table createTournamentTable(UUID roomId, UUID sessionId, TournamentOptions options) { + public Table createTournamentTable(UUID roomId, String sessionId, TournamentOptions options) { TableController tableController = new TableController(roomId, sessionId, options); controllers.put(tableController.getTable().getId(), tableController); tables.put(tableController.getTable().getId(), tableController.getTable()); @@ -95,35 +95,35 @@ public class TableManager { return tables.values(); } - public boolean joinTable(UUID sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { + public boolean joinTable(String sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { if (controllers.containsKey(tableId)) return controllers.get(tableId).joinTable(sessionId, name, playerType, skill, deckList); return false; } - public boolean joinTournament(UUID sessionId, UUID tableId, String name, String playerType, int skill) throws GameException { + public boolean joinTournament(String sessionId, UUID tableId, String name, String playerType, int skill) throws GameException { if (controllers.containsKey(tableId)) return controllers.get(tableId).joinTournament(sessionId, name, playerType, skill); return false; } - public boolean submitDeck(UUID sessionId, UUID tableId, DeckCardLists deckList) throws MageException { + public boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException { if (controllers.containsKey(tableId)) return controllers.get(tableId).submitDeck(sessionId, deckList); return false; } - public void removeSession(UUID sessionId) { + public void removeSession(String sessionId) { // TODO: search through tables and remove session } - public boolean isTableOwner(UUID tableId, UUID sessionId) { + public boolean isTableOwner(UUID tableId, String sessionId) { if (controllers.containsKey(tableId)) return controllers.get(tableId).isOwner(sessionId); return false; } - public boolean removeTable(UUID sessionId, UUID tableId) { + public boolean removeTable(String sessionId, UUID tableId) { if (isTableOwner(tableId, sessionId) || SessionManager.getInstance().isAdmin(sessionId)) { removeTable(tableId); return true; @@ -131,7 +131,7 @@ public class TableManager { return false; } - public void leaveTable(UUID sessionId, UUID tableId) { + public void leaveTable(String sessionId, UUID tableId) { if (controllers.containsKey(tableId)) controllers.get(tableId).leaveTable(sessionId); } @@ -142,7 +142,7 @@ public class TableManager { return null; } - public void startMatch(UUID sessionId, UUID roomId, UUID tableId) { + public void startMatch(String sessionId, UUID roomId, UUID tableId) { if (controllers.containsKey(tableId)) controllers.get(tableId).startMatch(sessionId); } @@ -152,12 +152,12 @@ public class TableManager { controllers.get(tableId).startMatch(); } - public void startChallenge(UUID sessionId, UUID roomId, UUID tableId, UUID challengeId) { + public void startChallenge(String sessionId, UUID roomId, UUID tableId, UUID challengeId) { if (controllers.containsKey(tableId)) controllers.get(tableId).startChallenge(sessionId, challengeId); } - public void startTournament(UUID sessionId, UUID roomId, UUID tableId) { + public void startTournament(String sessionId, UUID roomId, UUID tableId) { if (controllers.containsKey(tableId)) controllers.get(tableId).startTournament(sessionId); } @@ -167,13 +167,13 @@ public class TableManager { controllers.get(tableId).startDraft(draft); } - public boolean watchTable(UUID sessionId, UUID tableId) { + public boolean watchTable(String sessionId, UUID tableId) { if (controllers.containsKey(tableId)) return controllers.get(tableId).watchTable(sessionId); return false; } - public boolean replayTable(UUID sessionId, UUID tableId) { + public boolean replayTable(String sessionId, UUID tableId) { if (controllers.containsKey(tableId)) return controllers.get(tableId).replayTable(sessionId); return false; @@ -189,7 +189,7 @@ public class TableManager { controllers.get(tableId).endDraft(draft); } - public void swapSeats(UUID tableId, UUID sessionId, int seatNum1, int seatNum2) { + public void swapSeats(UUID tableId, String sessionId, int seatNum1, int seatNum2) { if (controllers.containsKey(tableId) && isTableOwner(tableId, sessionId)) { controllers.get(tableId).swapSeats(seatNum1, seatNum2); } @@ -200,7 +200,7 @@ public class TableManager { controllers.get(tableId).construct(); } - public void addPlayer(UUID sessionId, UUID tableId, Player player, String playerType, Deck deck) throws GameException { + public void addPlayer(String sessionId, UUID tableId, Player player, String playerType, Deck deck) throws GameException { if (controllers.containsKey(tableId)) controllers.get(tableId).addPlayer(sessionId, player, playerType, deck); } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index ac72195124..9b333fd888 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -56,12 +56,12 @@ public class DraftController { public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt"; private ConcurrentHashMap draftSessions = new ConcurrentHashMap(); - private ConcurrentHashMap sessionPlayerMap; + private ConcurrentHashMap sessionPlayerMap; private UUID draftSessionId; private Draft draft; private UUID tableId; - public DraftController(Draft draft, ConcurrentHashMap sessionPlayerMap, UUID tableId) { + public DraftController(Draft draft, ConcurrentHashMap sessionPlayerMap, UUID tableId) { draftSessionId = UUID.randomUUID(); this.sessionPlayerMap = sessionPlayerMap; this.draft = draft; @@ -116,11 +116,11 @@ public class DraftController { checkStart(); } - private UUID getPlayerId(UUID sessionId) { + private UUID getPlayerId(String sessionId) { return sessionPlayerMap.get(sessionId); } - public void join(UUID sessionId) { + public void join(String sessionId) { UUID playerId = sessionPlayerMap.get(sessionId); DraftSession draftSession = new DraftSession(draft, sessionId, playerId); draftSessions.put(playerId, draftSession); @@ -163,7 +163,7 @@ public class DraftController { return true; } - private void leave(UUID sessionId) { + private void leave(String sessionId) { draft.leave(getPlayerId(sessionId)); } @@ -174,7 +174,7 @@ public class DraftController { TableManager.getInstance().endDraft(tableId, draft); } - public void kill(UUID sessionId) { + public void kill(String sessionId) { if (sessionPlayerMap.containsKey(sessionId)) { draftSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); draftSessions.remove(sessionPlayerMap.get(sessionId)); @@ -183,7 +183,7 @@ public class DraftController { } } - public void timeout(UUID sessionId) { + public void timeout(String sessionId) { if (sessionPlayerMap.containsKey(sessionId)) { draft.autoPick(sessionPlayerMap.get(sessionId)); } @@ -193,7 +193,7 @@ public class DraftController { return this.draftSessionId; } - public DraftPickView sendCardPick(UUID sessionId, UUID cardId) { + public DraftPickView sendCardPick(String sessionId, UUID cardId) { if (draftSessions.get(sessionPlayerMap.get(sessionId)).sendCardPick(cardId)) { return getDraftPickView(sessionPlayerMap.get(sessionId), 0); } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftManager.java b/Mage.Server/src/main/java/mage/server/draft/DraftManager.java index e4fbdff9e8..3027943dbf 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftManager.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftManager.java @@ -48,13 +48,13 @@ public class DraftManager { private ConcurrentHashMap draftControllers = new ConcurrentHashMap(); - public UUID createDraftSession(Draft draft, ConcurrentHashMap sessionPlayerMap, UUID tableId) { + public UUID createDraftSession(Draft draft, ConcurrentHashMap sessionPlayerMap, UUID tableId) { DraftController draftController = new DraftController(draft, sessionPlayerMap, tableId); draftControllers.put(draft.getId(), draftController); return draftController.getSessionId(); } - public void joinDraft(UUID draftId, UUID sessionId) { + public void joinDraft(UUID draftId, String sessionId) { draftControllers.get(draftId).join(sessionId); } @@ -62,21 +62,21 @@ public class DraftManager { draftControllers.remove(gameId); } - public DraftPickView sendCardPick(UUID draftId, UUID sessionId, UUID cardId) { + public DraftPickView sendCardPick(UUID draftId, String sessionId, UUID cardId) { return draftControllers.get(draftId).sendCardPick(sessionId, cardId); } - public void removeSession(UUID sessionId) { + public void removeSession(String sessionId) { for (DraftController controller: draftControllers.values()) { controller.kill(sessionId); } } - public void kill(UUID draftId, UUID sessionId) { + public void kill(UUID draftId, String sessionId) { draftControllers.get(draftId).kill(sessionId); } - public void timeout(UUID gameId, UUID sessionId) { + public void timeout(UUID gameId, String sessionId) { draftControllers.get(gameId).timeout(sessionId); } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java index f30e2a3040..d6c8e97a04 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java @@ -32,12 +32,8 @@ import java.rmi.RemoteException; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; import mage.game.draft.Draft; -import mage.MageException; -import mage.interfaces.callback.CallbackException; import mage.interfaces.callback.ClientCallback; import mage.server.Session; import mage.server.SessionManager; @@ -55,7 +51,7 @@ public class DraftSession { protected final static Logger logger = Logger.getLogger(DraftSession.class); - protected UUID sessionId; + protected String sessionId; protected UUID playerId; protected Draft draft; protected boolean killed = false; @@ -63,7 +59,7 @@ public class DraftSession { private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); - public DraftSession(Draft draft, UUID sessionId, UUID playerId) { + public DraftSession(Draft draft, String sessionId, UUID playerId) { this.sessionId = sessionId; this.draft = draft; this.playerId = playerId; @@ -143,7 +139,6 @@ public class DraftSession { private synchronized void cancelTimeout() { if (futureTimeout != null) { futureTimeout.cancel(false); - ((ThreadPoolExecutor)timeoutExecutor).getQueue().remove(futureTimeout); } } diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index 1d610e11d5..af282f6f22 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -81,8 +81,8 @@ public class GameController implements GameCallback { public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt"; private ConcurrentHashMap gameSessions = new ConcurrentHashMap(); - private ConcurrentHashMap watchers = new ConcurrentHashMap(); - private ConcurrentHashMap sessionPlayerMap; + private ConcurrentHashMap watchers = new ConcurrentHashMap(); + private ConcurrentHashMap sessionPlayerMap; private UUID gameSessionId; private Game game; private UUID chatId; @@ -91,7 +91,7 @@ public class GameController implements GameCallback { private Future gameFuture; - public GameController(Game game, ConcurrentHashMap sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { + public GameController(Game game, ConcurrentHashMap sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { gameSessionId = UUID.randomUUID(); this.sessionPlayerMap = sessionPlayerMap; chatId = ChatManager.getInstance().createChatSession(); @@ -180,11 +180,11 @@ public class GameController implements GameCallback { checkStart(); } - private UUID getPlayerId(UUID sessionId) { + private UUID getPlayerId(String sessionId) { return sessionPlayerMap.get(sessionId); } - public void join(UUID sessionId) { + public void join(String sessionId) { UUID playerId = sessionPlayerMap.get(sessionId); GameSession gameSession = new GameSession(game, sessionId, playerId); gameSessions.put(playerId, gameSession); @@ -228,27 +228,27 @@ public class GameController implements GameCallback { return true; } - public void watch(UUID sessionId) { + public void watch(String sessionId) { GameWatcher gameWatcher = new GameWatcher(sessionId, game.getId()); watchers.put(sessionId, gameWatcher); gameWatcher.init(getGameView()); ChatManager.getInstance().broadcast(chatId, "", " has started watching", MessageColor.BLACK); } - public void stopWatching(UUID sessionId) { + public void stopWatching(String sessionId) { watchers.remove(sessionId); ChatManager.getInstance().broadcast(chatId, "", " has stopped watching", MessageColor.BLACK); } - public void concede(UUID sessionId) { + public void concede(String sessionId) { game.concede(getPlayerId(sessionId)); } - private void leave(UUID sessionId) { + private void leave(String sessionId) { game.quit(getPlayerId(sessionId)); } - public void cheat(UUID sessionId, UUID playerId, DeckCardLists deckList) { + public void cheat(String sessionId, UUID playerId, DeckCardLists deckList) { Deck deck; try { deck = Deck.load(deckList); @@ -263,7 +263,7 @@ public class GameController implements GameCallback { updateGame(); } - public boolean cheat(UUID sessionId, UUID playerId, String cardName) { + public boolean cheat(String sessionId, UUID playerId, String cardName) { Card card = Sets.findCard(cardName, true); if (card != null) { Set cards = new HashSet(); @@ -276,10 +276,9 @@ public class GameController implements GameCallback { } } - public void kill(UUID sessionId) { + public void kill(String sessionId) { if (sessionPlayerMap.containsKey(sessionId)) { - GameSession session = gameSessions.get(sessionPlayerMap.get(sessionId)); - session.destroy(); + gameSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); gameSessions.remove(sessionPlayerMap.get(sessionId)); leave(sessionId); sessionPlayerMap.remove(sessionId); @@ -290,7 +289,7 @@ public class GameController implements GameCallback { } } - public void timeout(UUID sessionId) { + public void timeout(String sessionId) { if (sessionPlayerMap.containsKey(sessionId)) { ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(sessionPlayerMap.get(sessionId)).getName() + " has timed out. Auto concede.", MessageColor.BLACK); concede(sessionId); @@ -315,19 +314,19 @@ public class GameController implements GameCallback { return chatId; } - public void sendPlayerUUID(UUID sessionId, UUID data) { + public void sendPlayerUUID(String sessionId, UUID data) { gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerUUID(data); } - public void sendPlayerString(UUID sessionId, String data) { + public void sendPlayerString(String sessionId, String data) { gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerString(data); } - public void sendPlayerBoolean(UUID sessionId, Boolean data) { + public void sendPlayerBoolean(String sessionId, Boolean data) { gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerBoolean(data); } - public void sendPlayerInteger(UUID sessionId, Integer data) { + public void sendPlayerInteger(String sessionId, Integer data) { gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerInteger(data); } diff --git a/Mage.Server/src/main/java/mage/server/game/GameManager.java b/Mage.Server/src/main/java/mage/server/game/GameManager.java index 661031c7bb..b453f456fa 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameManager.java +++ b/Mage.Server/src/main/java/mage/server/game/GameManager.java @@ -50,13 +50,13 @@ public class GameManager { private ConcurrentHashMap gameControllers = new ConcurrentHashMap(); - public UUID createGameSession(Game game, ConcurrentHashMap sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { + public UUID createGameSession(Game game, ConcurrentHashMap sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { GameController gameController = new GameController(game, sessionPlayerMap, tableId, choosingPlayerId); gameControllers.put(game.getId(), gameController); return gameController.getSessionId(); } - public void joinGame(UUID gameId, UUID sessionId) { + public void joinGame(UUID gameId, String sessionId) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).join(sessionId); } @@ -71,64 +71,64 @@ public class GameManager { return null; } - public void sendPlayerUUID(UUID gameId, UUID sessionId, UUID data) { + public void sendPlayerUUID(UUID gameId, String sessionId, UUID data) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).sendPlayerUUID(sessionId, data); } - public void sendPlayerString(UUID gameId, UUID sessionId, String data) { + public void sendPlayerString(UUID gameId, String sessionId, String data) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).sendPlayerString(sessionId, data); } - public void sendPlayerBoolean(UUID gameId, UUID sessionId, Boolean data) { + public void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).sendPlayerBoolean(sessionId, data); } - public void sendPlayerInteger(UUID gameId, UUID sessionId, Integer data) { + public void sendPlayerInteger(UUID gameId, String sessionId, Integer data) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).sendPlayerInteger(sessionId, data); } - public void concedeGame(UUID gameId, UUID sessionId) { + public void concedeGame(UUID gameId, String sessionId) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).concede(sessionId); } - public void watchGame(UUID gameId, UUID sessionId) { + public void watchGame(UUID gameId, String sessionId) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).watch(sessionId); } - public void stopWatching(UUID gameId, UUID sessionId) { + public void stopWatching(UUID gameId, String sessionId) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).stopWatching(sessionId); } - public void removeSession(UUID sessionId) { + public void removeSession(String sessionId) { for (GameController controller: gameControllers.values()) { controller.kill(sessionId); } } - public void kill(UUID gameId, UUID sessionId) { + public void kill(UUID gameId, String sessionId) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).kill(sessionId); } - public void cheat(UUID gameId, UUID sessionId, UUID playerId, DeckCardLists deckList) { + public void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).cheat(sessionId, playerId, deckList); } - public boolean cheat(UUID gameId, UUID sessionId, UUID playerId, String cardName) { + public boolean cheat(UUID gameId, String sessionId, UUID playerId, String cardName) { if (gameControllers.containsKey(gameId)) return gameControllers.get(gameId).cheat(sessionId, playerId, cardName); return false; } - public void timeout(UUID gameId, UUID sessionId) { + public void timeout(UUID gameId, String sessionId) { if (gameControllers.containsKey(gameId)) gameControllers.get(gameId).timeout(sessionId); } @@ -142,7 +142,7 @@ public class GameManager { gameControllers.get(gameId).saveGame(); } - public GameView getGameView(UUID gameId, UUID sessionId, UUID playerId) { + public GameView getGameView(UUID gameId, String sessionId, UUID playerId) { if (gameControllers.containsKey(gameId)) return gameControllers.get(gameId).getGameView(playerId); return null; diff --git a/Mage.Server/src/main/java/mage/server/game/GameSession.java b/Mage.Server/src/main/java/mage/server/game/GameSession.java index 59e9658d83..ef42dd27dc 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSession.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSession.java @@ -34,11 +34,8 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import mage.game.Game; -import mage.MageException; -import mage.interfaces.callback.CallbackException; import mage.interfaces.callback.ClientCallback; import mage.server.Session; import mage.server.SessionManager; @@ -61,7 +58,7 @@ public class GameSession extends GameWatcher { private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); - public GameSession(Game game, UUID sessionId, UUID playerId) { + public GameSession(Game game, String sessionId, UUID playerId) { super(sessionId, game.getId()); this.game = game; this.playerId = playerId; @@ -173,8 +170,6 @@ public class GameSession extends GameWatcher { private synchronized void cancelTimeout() { if (futureTimeout != null) { futureTimeout.cancel(false); - ((ThreadPoolExecutor)timeoutExecutor).getQueue().remove(futureTimeout); - //System.out.println("tasks:"+ ((ThreadPoolExecutor)timeoutExecutor).getTaskCount()); } } @@ -197,9 +192,4 @@ public class GameSession extends GameWatcher { cancelTimeout(); game.getPlayer(playerId).setResponseInteger(data); } - - public void destroy() { - cancelTimeout(); - setKilled(); - } } diff --git a/Mage.Server/src/main/java/mage/server/game/GameWatcher.java b/Mage.Server/src/main/java/mage/server/game/GameWatcher.java index 6f8ceb38d6..85c6115aca 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameWatcher.java +++ b/Mage.Server/src/main/java/mage/server/game/GameWatcher.java @@ -30,9 +30,6 @@ package mage.server.game; import java.rmi.RemoteException; import java.util.UUID; -import java.util.logging.Level; -import mage.MageException; -import mage.interfaces.callback.CallbackException; import mage.interfaces.callback.ClientCallback; import mage.server.Session; import mage.server.SessionManager; @@ -48,11 +45,11 @@ public class GameWatcher { protected final static Logger logger = Logger.getLogger(GameWatcher.class); - protected UUID sessionId; + protected String sessionId; protected UUID gameId; protected boolean killed = false; - public GameWatcher(UUID sessionId, UUID gameId) { + public GameWatcher(String sessionId, UUID gameId) { this.sessionId = sessionId; this.gameId = gameId; } diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoom.java b/Mage.Server/src/main/java/mage/server/game/GamesRoom.java index 4c11cafaf7..4b263f84c3 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoom.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoom.java @@ -45,14 +45,14 @@ import mage.view.TableView; public interface GamesRoom extends Room { public List getTables(); - public boolean joinTable(UUID sessionId, 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 TableView createTable(UUID sessionId, MatchOptions options); - public TableView createTournamentTable(UUID sessionId, TournamentOptions options); - public void removeTable(UUID sessionId, UUID tableId); + public boolean joinTable(String sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException; + public boolean joinTournamentTable(String sessionId, UUID tableId, String name, String playerType, int skill) throws GameException; + public TableView createTable(String sessionId, MatchOptions options); + public TableView createTournamentTable(String sessionId, TournamentOptions options); + public void removeTable(String sessionId, UUID tableId); public void removeTable(UUID tableId); public TableView getTable(UUID tableId); - public void leaveTable(UUID sessionId, UUID tableId); - public boolean watchTable(UUID sessionId, UUID tableId) throws MageException; + public void leaveTable(String sessionId, UUID tableId); + public boolean watchTable(String sessionId, UUID tableId) throws MageException; } diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java index 26e6a8dede..5150ddf4f2 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java @@ -64,7 +64,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public boolean joinTable(UUID sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { + public boolean joinTable(String sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException { if (tables.containsKey(tableId)) { return TableManager.getInstance().joinTable(sessionId, tableId, name, playerType, skill, deckList); } else { @@ -73,14 +73,14 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public TableView createTable(UUID sessionId, MatchOptions options) { + public TableView createTable(String sessionId, MatchOptions options) { Table table = TableManager.getInstance().createTable(this.getRoomId(), sessionId, options); tables.put(table.getId(), table); return new TableView(table); } @Override - public boolean joinTournamentTable(UUID sessionId, UUID tableId, String name, String playerType, int skill) throws GameException { + public boolean joinTournamentTable(String sessionId, UUID tableId, String name, String playerType, int skill) throws GameException { if (tables.containsKey(tableId)) { return TableManager.getInstance().joinTournament(sessionId, tableId, name, playerType, skill); } else { @@ -89,7 +89,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public TableView createTournamentTable(UUID sessionId, TournamentOptions options) { + public TableView createTournamentTable(String sessionId, TournamentOptions options) { Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), sessionId, options); tables.put(table.getId(), table); return new TableView(table); @@ -103,7 +103,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public void removeTable(UUID sessionId, UUID tableId) { + public void removeTable(String sessionId, UUID tableId) { tables.remove(tableId); } @@ -115,12 +115,12 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public void leaveTable(UUID sessionId, UUID tableId) { + public void leaveTable(String sessionId, UUID tableId) { TableManager.getInstance().leaveTable(sessionId, tableId); } @Override - public boolean watchTable(UUID sessionId, UUID tableId) throws MageException { + public boolean watchTable(String sessionId, UUID tableId) throws MageException { return TableManager.getInstance().watchTable(sessionId, tableId); } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplayManager.java b/Mage.Server/src/main/java/mage/server/game/ReplayManager.java index a945babe0e..67ce4c1897 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplayManager.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplayManager.java @@ -48,25 +48,25 @@ public class ReplayManager { private ConcurrentHashMap replaySessions = new ConcurrentHashMap(); - public void replayGame(UUID gameId, UUID sessionId) { + public void replayGame(UUID gameId, String sessionId) { ReplaySession replaySession = new ReplaySession(gameId, sessionId); replaySessions.put(gameId.toString() + sessionId.toString(), replaySession); SessionManager.getInstance().getSession(sessionId).replayGame(gameId); } - public void startReplay(UUID gameId, UUID sessionId) { + public void startReplay(UUID gameId, String sessionId) { replaySessions.get(gameId.toString() + sessionId.toString()).replay(); } - public void stopReplay(UUID gameId, UUID sessionId) { + public void stopReplay(UUID gameId, String sessionId) { replaySessions.get(gameId.toString() + sessionId.toString()).stop(); } - public void nextPlay(UUID gameId, UUID sessionId) { + public void nextPlay(UUID gameId, String sessionId) { replaySessions.get(gameId.toString() + sessionId.toString()).next(); } - public void previousPlay(UUID gameId, UUID sessionId) { + public void previousPlay(UUID gameId, String sessionId) { replaySessions.get(gameId.toString() + sessionId.toString()).previous(); } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java index 7b24aaf092..0004fdef6f 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java @@ -31,8 +31,6 @@ package mage.server.game; import java.util.UUID; import mage.game.Game; import mage.game.GameState; -import mage.MageException; -import mage.interfaces.callback.CallbackException; import mage.interfaces.callback.ClientCallback; import mage.server.Session; import mage.server.SessionManager; @@ -47,9 +45,9 @@ public class ReplaySession implements GameCallback { private final static Logger logger = Logger.getLogger(ReplaySession.class); private GameReplay replay; - protected UUID sessionId; + protected String sessionId; - ReplaySession(UUID gameId, UUID sessionId) { + ReplaySession(UUID gameId, String sessionId) { this.replay = new GameReplay(gameId); this.sessionId = sessionId; } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index 5e8cfecec6..a93d7b7090 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -64,10 +64,10 @@ public class TournamentController { private UUID chatId; private UUID tableId; private Tournament tournament; - private ConcurrentHashMap sessionPlayerMap = new ConcurrentHashMap(); + private ConcurrentHashMap sessionPlayerMap = new ConcurrentHashMap(); private ConcurrentHashMap tournamentSessions = new ConcurrentHashMap(); - public TournamentController(Tournament tournament, ConcurrentHashMap sessionPlayerMap, UUID tableId) { + public TournamentController(Tournament tournament, ConcurrentHashMap sessionPlayerMap, UUID tableId) { sessionId = UUID.randomUUID(); this.sessionPlayerMap = sessionPlayerMap; chatId = ChatManager.getInstance().createChatSession(); @@ -128,7 +128,7 @@ public class TournamentController { checkStart(); } - public synchronized void join(UUID sessionId) { + public synchronized void join(String sessionId) { UUID playerId = sessionPlayerMap.get(sessionId); TournamentSession tournamentSession = new TournamentSession(tournament, sessionId, tableId, playerId); tournamentSessions.put(playerId, tournamentSession); @@ -196,16 +196,16 @@ public class TournamentController { TableManager.getInstance().construct(tableId); } - private void construct(UUID sessionId, Deck deck, int timeout) throws MageException { - if (tournamentSessions.containsKey(sessionId)) - tournamentSessions.get(sessionId).construct(deck, timeout); + private void construct(UUID playerId, Deck deck, int timeout) throws MageException { + if (tournamentSessions.containsKey(playerId)) + tournamentSessions.get(playerId).construct(deck, timeout); } - public void submitDeck(UUID sessionId, Deck deck) { - tournamentSessions.get(sessionPlayerMap.get(sessionId)).submitDeck(deck); + public void submitDeck(UUID playerId, Deck deck) { + tournamentSessions.get(playerId).submitDeck(deck); } - public void timeout(UUID sessionId) { + public void timeout(String sessionId) { if (sessionPlayerMap.containsKey(sessionId)) { TournamentPlayer player = tournament.getPlayer(sessionPlayerMap.get(sessionId)); tournament.autoSubmit(sessionPlayerMap.get(sessionId), player.getDeck()); @@ -220,7 +220,7 @@ public class TournamentController { return chatId; } - public void kill(UUID sessionId) { + public void kill(String sessionId) { if (sessionPlayerMap.containsKey(sessionId)) { tournamentSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); tournamentSessions.remove(sessionPlayerMap.get(sessionId)); @@ -229,16 +229,16 @@ public class TournamentController { } } - private void leave(UUID sessionId) { + private void leave(String sessionId) { tournament.leave(getPlayerId(sessionId)); } - private UUID getPlayerId(UUID sessionId) { + private UUID getPlayerId(String sessionId) { return sessionPlayerMap.get(sessionId); } - private UUID getPlayerSessionId(UUID playerId) { - for (Entry entry: sessionPlayerMap.entrySet()) { + private String getPlayerSessionId(UUID playerId) { + for (Entry entry: sessionPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) return entry.getKey(); } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java index 87b673be42..ffcc732bbf 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java @@ -48,26 +48,26 @@ public class TournamentManager { return INSTANCE; } - public UUID createTournamentSession(Tournament tournament, ConcurrentHashMap sessionPlayerMap, UUID tableId) { + public UUID createTournamentSession(Tournament tournament, ConcurrentHashMap sessionPlayerMap, UUID tableId) { TournamentController tournamentController = new TournamentController(tournament, sessionPlayerMap, tableId); controllers.put(tournament.getId(), tournamentController); return tournamentController.getSessionId(); } - public void joinTournament(UUID tournamentId, UUID sessionId) { + public void joinTournament(UUID tournamentId, String sessionId) { controllers.get(tournamentId).join(sessionId); } - public void kill(UUID tournamentId, UUID sessionId) { + public void kill(UUID tournamentId, String sessionId) { controllers.get(tournamentId).kill(sessionId); } - public void timeout(UUID tournamentId, UUID sessionId) { + public void timeout(UUID tournamentId, String sessionId) { controllers.get(tournamentId).timeout(sessionId); } - public void submitDeck(UUID tournamentId, UUID sessionId, Deck deck) { - controllers.get(tournamentId).submitDeck(sessionId, deck); + public void submitDeck(UUID tournamentId, UUID playerId, Deck deck) { + controllers.get(tournamentId).submitDeck(playerId, deck); } public TournamentView getTournamentView(UUID tournamentId) { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java index e91ea8a63b..88d30791b0 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java @@ -32,13 +32,10 @@ import java.rmi.RemoteException; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; import mage.cards.decks.Deck; import mage.game.tournament.Tournament; import mage.MageException; -import mage.interfaces.callback.CallbackException; import mage.interfaces.callback.ClientCallback; import mage.server.Session; import mage.server.SessionManager; @@ -53,7 +50,7 @@ import org.apache.log4j.Logger; public class TournamentSession { protected final static Logger logger = Logger.getLogger(TournamentSession.class); - protected UUID sessionId; + protected String sessionId; protected UUID playerId; protected UUID tableId; protected Tournament tournament; @@ -62,7 +59,7 @@ public class TournamentSession { private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); - public TournamentSession(Tournament tournament, UUID sessionId, UUID tableId, UUID playerId) { + public TournamentSession(Tournament tournament, String sessionId, UUID tableId, UUID playerId) { this.sessionId = sessionId; this.tournament = tournament; this.playerId = playerId; @@ -147,7 +144,6 @@ public class TournamentSession { private synchronized void cancelTimeout() { if (futureTimeout != null) { futureTimeout.cancel(false); - ((ThreadPoolExecutor)timeoutExecutor).getQueue().remove(futureTimeout); } } From 73939bd72c013279df66f41ba876705a29bf9eb7 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 22 Jun 2011 23:18:43 -0400 Subject: [PATCH 05/17] fixes for localhost ip --- Mage.Common/src/mage/remote/Connection.java | 32 ++++++++++++++++ Mage.Common/src/mage/remote/Session.java | 3 +- .../src/main/java/mage/server/Main.java | 38 +++---------------- 3 files changed, 38 insertions(+), 35 deletions(-) diff --git a/Mage.Common/src/mage/remote/Connection.java b/Mage.Common/src/mage/remote/Connection.java index 43b253a47b..564df9e248 100644 --- a/Mage.Common/src/mage/remote/Connection.java +++ b/Mage.Common/src/mage/remote/Connection.java @@ -28,6 +28,15 @@ package mage.remote; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.Enumeration; +import java.util.logging.Level; +import java.util.logging.Logger; + /** * * @author BetaSteward_at_googlemail.com @@ -64,6 +73,13 @@ public class Connection { } public String getURI() { + if (host.equals("localhost")) { + try { + return "bisocket://" + getLocalAddress().getHostAddress() + ":" + port; + } catch (SocketException ex) { + // just use localhost if can't find local ip + } + } return "bisocket://" + host + ":" + port; } @@ -160,5 +176,21 @@ public class Connection { public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } + + public static InetAddress getLocalAddress() throws SocketException { + for (Enumeration 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; + } } diff --git a/Mage.Common/src/mage/remote/Session.java b/Mage.Common/src/mage/remote/Session.java index 288f745c78..c93eb9ba5e 100644 --- a/Mage.Common/src/mage/remote/Session.java +++ b/Mage.Common/src/mage/remote/Session.java @@ -101,7 +101,6 @@ public class Session { public boolean connect() { sessionState = SessionState.CONNECTING; try { -// System.setSecurityManager(null); // System.setProperty("http.nonProxyHosts", "code.google.com"); // System.setProperty("socksNonProxyHosts", "code.google.com"); // @@ -135,7 +134,7 @@ public class Session { this.sessionId = callbackClient.getSessionId(); boolean registerResult = false; - if (connection.getPassword().isEmpty()) + if (connection.getPassword() == null) registerResult = server.registerClient(connection.getUsername(), sessionId, client.getVersion()); else registerResult = server.registerAdmin(connection.getPassword(), sessionId, client.getVersion()); diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 6a2f98563f..5994a39f4f 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -31,17 +31,13 @@ package mage.server; import mage.server.util.PluginClassLoader; import java.io.File; import java.io.FilenameFilter; -import java.net.Inet4Address; import java.net.InetAddress; -import java.net.InterfaceAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; import java.util.Map; import javax.management.MBeanServer; import mage.game.match.MatchType; import mage.game.tournament.TournamentType; import mage.interfaces.MageServer; +import mage.remote.Connection; import mage.server.game.DeckValidatorFactory; import mage.server.game.GameFactory; import mage.server.game.PlayerFactory; @@ -107,10 +103,12 @@ public class Main { adminPassword = arg.replace(adminPasswordArg, ""); } } - String host = getServerAddress(); + String host = config.getServerAddress(); int port = config.getPort(); - String locatorURI = "bisocket://" + host + ":" + port; try { + if (host.equals("localhost")) + host = Connection.getLocalAddress().getHostAddress(); + String locatorURI = "bisocket://" + host + ":" + port; InvokerLocator serverLocator = new InvokerLocator(locatorURI); server = new MageTransporterServer(serverLocator, new MageServerImpl(adminPassword, testMode), MageServer.class.getName(), new MageServerInvocationHandler()); server.start(); @@ -178,32 +176,6 @@ public class Main { } } - - private static String getServerAddress() { - try { - String foundIP = ""; - for (Enumeration 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) { - foundIP = iaddr.getHostAddress(); - break; - } - } - if (foundIP.length() > 0) - break; - } - if (foundIP.length() > 0) - return foundIP; - } catch (SocketException ex) { - logger.warn("Could not get server address: ", ex); - } - return null; - } private static Class loadPlugin(Plugin plugin) { try { From bc5c97c560af6f3b2cd8123515030556b492fdd6 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 22 Jun 2011 23:19:06 -0400 Subject: [PATCH 06/17] update client version number --- Mage.Client/src/main/java/mage/client/MageFrame.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mage.Client/src/main/java/mage/client/MageFrame.java b/Mage.Client/src/main/java/mage/client/MageFrame.java index 2b5aa4e61f..82c7da2a6a 100644 --- a/Mage.Client/src/main/java/mage/client/MageFrame.java +++ b/Mage.Client/src/main/java/mage/client/MageFrame.java @@ -108,7 +108,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private static Preferences prefs = Preferences.userNodeForPackage(MageFrame.class); private JLabel title; private Rectangle titleRectangle; - private final static MageVersion version = new MageVersion(0, 7, 4, "beta-2"); + private final static MageVersion version = new MageVersion(0, 8, 0, ""); private UUID clientId; private static MagePane activeFrame; private static boolean liteMode = false; From b1408507cb0f3da1c6135bc10c1a491b7097e32e Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Thu, 23 Jun 2011 22:58:11 -0400 Subject: [PATCH 07/17] added ping + code cleanup --- .../src/main/resources/log4j.properties | 2 +- Mage.Common/pom.xml | 9 ++++-- Mage.Common/src/mage/remote/Connection.java | 13 ++++---- Mage.Common/src/mage/remote/Session.java | 31 ++++++++++++++++--- Mage.Server/pom.xml | 25 --------------- .../src/main/java/mage/server/Main.java | 14 ++++----- 6 files changed, 47 insertions(+), 47 deletions(-) diff --git a/Mage.Client/src/main/resources/log4j.properties b/Mage.Client/src/main/resources/log4j.properties index 08d7f0e74f..cdef4d6b9e 100644 --- a/Mage.Client/src/main/resources/log4j.properties +++ b/Mage.Client/src/main/resources/log4j.properties @@ -1,5 +1,5 @@ #default levels -log4j.rootLogger=debug, console +log4j.rootLogger=info, console #console log log4j.appender.console=org.apache.log4j.ConsoleAppender diff --git a/Mage.Common/pom.xml b/Mage.Common/pom.xml index 7dde54dfa2..506977ac02 100644 --- a/Mage.Common/pom.xml +++ b/Mage.Common/pom.xml @@ -28,7 +28,7 @@ org.jboss.remoting jboss-remoting - 2.5.2.SP2 + 2.5.4.SP2 jboss @@ -38,13 +38,18 @@ jboss jboss-serialization - 4.2.2.GA + 1.0.3.GA concurrent concurrent 1.3.4 + + trove + trove + 1.0.2 + diff --git a/Mage.Common/src/mage/remote/Connection.java b/Mage.Common/src/mage/remote/Connection.java index 564df9e248..e120a1ed60 100644 --- a/Mage.Common/src/mage/remote/Connection.java +++ b/Mage.Common/src/mage/remote/Connection.java @@ -34,8 +34,6 @@ import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; /** * @@ -52,10 +50,13 @@ public class Connection { private int proxyPort; private String proxyUsername; private String proxyPassword; + + private static final String serialization = "?serializationtype=jboss"; + private static final String transport = "bisocket"; @Override public int hashCode() { - return (host + Integer.toString(port) + proxyType.toString()).hashCode(); + return (transport + host + Integer.toString(port) + proxyType.toString()).hashCode(); } @Override @@ -69,18 +70,18 @@ public class Connection { @Override public String toString() { - return host + ":" + Integer.toString(port); + return host + ":" + Integer.toString(port) + "/" + serialization; } public String getURI() { if (host.equals("localhost")) { try { - return "bisocket://" + getLocalAddress().getHostAddress() + ":" + port; + return transport + "://" + getLocalAddress().getHostAddress() + ":" + port + "/" + serialization; } catch (SocketException ex) { // just use localhost if can't find local ip } } - return "bisocket://" + host + ":" + port; + return transport + "://" + host + ":" + port + "/" + serialization; } public ProxyType getProxyType() { diff --git a/Mage.Common/src/mage/remote/Session.java b/Mage.Common/src/mage/remote/Session.java index c93eb9ba5e..9c379c6e42 100644 --- a/Mage.Common/src/mage/remote/Session.java +++ b/Mage.Common/src/mage/remote/Session.java @@ -54,11 +54,14 @@ import mage.view.TournamentView; import mage.view.UserView; import org.apache.log4j.Logger; import org.jboss.remoting.Client; +import org.jboss.remoting.ConnectionListener; +import org.jboss.remoting.ConnectionValidator; import org.jboss.remoting.InvokerLocator; import org.jboss.remoting.callback.Callback; import org.jboss.remoting.callback.HandleCallbackException; import org.jboss.remoting.callback.InvokerCallbackHandler; import org.jboss.remoting.transport.bisocket.Bisocket; +import org.jboss.remoting.transport.socket.SocketWrapper; import org.jboss.remoting.transporter.TransporterClient; /** @@ -122,15 +125,25 @@ public class Session { // break; // } InvokerLocator clientLocator = new InvokerLocator(connection.getURI()); - server = (MageServer) TransporterClient.createTransporterClient(clientLocator, MageServer.class); + Map metadata = new HashMap(); + metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); + metadata.put("generalizeSocketException", "true"); + server = (MageServer) TransporterClient.createTransporterClient(clientLocator.getLocatorURI(), MageServer.class, metadata); callbackClient = new Client(clientLocator, "callback"); callbackClient.connect(); - Map metadata = new HashMap(); - metadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); + Map listenerMetadata = new HashMap(); + listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_PERIOD, "5000"); + listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_TIMEOUT, "2000"); + callbackClient.addConnectionListener(new ClientConnectionListener(), listenerMetadata); + + Map callbackMetadata = new HashMap(); + callbackMetadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); + callbackMetadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); + callbackMetadata.put("generalizeSocketException", "true"); CallbackHandler callbackHandler = new CallbackHandler(); - callbackClient.addListener(callbackHandler, metadata); + callbackClient.addListener(callbackHandler, callbackMetadata); this.sessionId = callbackClient.getSessionId(); boolean registerResult = false; @@ -184,7 +197,15 @@ public class Session { client.processCallback((ClientCallback)callback.getCallbackObject()); } } - + + class ClientConnectionListener implements ConnectionListener { + @Override + public void handleConnectionException(Throwable throwable, Client client) { + logger.info("connection to server lost"); + disconnect(true); + } + } + public boolean isConnected() { if (callbackClient == null) return false; diff --git a/Mage.Server/pom.xml b/Mage.Server/pom.xml index 54c90225b7..a86f559402 100644 --- a/Mage.Server/pom.xml +++ b/Mage.Server/pom.xml @@ -39,11 +39,6 @@ jaxb-impl 2.1.12 - - org.jboss.remoting - jboss-remoting - 2.5.2.SP2 - log4j log4j @@ -110,26 +105,6 @@ ${project.version} runtime - - jboss - jboss-common-core - 2.2.16.GA - - - jboss - jboss-serialization - 4.2.2.GA - - - concurrent - concurrent - 1.3.4 - - - jboss - jboss-jmx - 4.2.2.GA - diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 5994a39f4f..31bfcd6cf5 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -103,21 +103,19 @@ public class Main { adminPassword = arg.replace(adminPasswordArg, ""); } } - String host = config.getServerAddress(); - int port = config.getPort(); + Connection connection = new Connection(); + connection.setHost(config.getServerAddress()); + connection.setPort(config.getPort()); try { - if (host.equals("localhost")) - host = Connection.getLocalAddress().getHostAddress(); - String locatorURI = "bisocket://" + host + ":" + port; - InvokerLocator serverLocator = new InvokerLocator(locatorURI); + 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 " + host + ":" + port); + logger.info("Started MAGE server - listening on " + connection.toString()); if (testMode) logger.info("MAGE server running in test mode"); } catch (Exception ex) { - logger.fatal("Failed to start server - " + host + ":" + port, ex); + logger.fatal("Failed to start server - " + connection.toString(), ex); } } From ade836c08a83f3ac53410e790d6cecaf00aaf6fe Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Sat, 25 Jun 2011 14:34:39 -0400 Subject: [PATCH 08/17] added connection leasing + cleanup --- Mage.Common/src/mage/remote/Session.java | 53 +++++++-------- .../main/java/mage/server/MageServerImpl.java | 65 +++++++++---------- .../src/main/java/mage/server/Main.java | 30 ++++++++- .../src/main/java/mage/server/Session.java | 3 +- .../main/java/mage/server/SessionManager.java | 8 ++- .../java/mage/server/TableController.java | 5 ++ .../main/java/mage/server/TableManager.java | 4 +- .../mage/server/draft/DraftController.java | 2 +- .../java/mage/server/game/GameController.java | 2 +- .../tournament/TournamentController.java | 2 +- .../java/mage/server/util/ThreadExecutor.java | 14 ++-- pom.xml | 11 ++-- 12 files changed, 115 insertions(+), 84 deletions(-) diff --git a/Mage.Common/src/mage/remote/Session.java b/Mage.Common/src/mage/remote/Session.java index 9c379c6e42..dbafa22ede 100644 --- a/Mage.Common/src/mage/remote/Session.java +++ b/Mage.Common/src/mage/remote/Session.java @@ -104,44 +104,45 @@ public class Session { public boolean connect() { sessionState = SessionState.CONNECTING; try { -// System.setProperty("http.nonProxyHosts", "code.google.com"); -// System.setProperty("socksNonProxyHosts", "code.google.com"); -// -// // clear previous values -// System.clearProperty("socksProxyHost"); -// System.clearProperty("socksProxyPort"); -// System.clearProperty("http.proxyHost"); -// System.clearProperty("http.proxyPort"); -// -// switch (connection.getProxyType()) { -// case SOCKS: -// System.setProperty("socksProxyHost", connection.getProxyHost()); -// System.setProperty("socksProxyPort", Integer.toString(connection.getProxyPort())); -// break; -// case HTTP: -// System.setProperty("http.proxyHost", connection.getProxyHost()); -// System.setProperty("http.proxyPort", Integer.toString(connection.getProxyPort())); -// Authenticator.setDefault(new MageAuthenticator(connection.getProxyUsername(), connection.getProxyPassword())); -// break; -// } + System.setProperty("http.nonProxyHosts", "code.google.com"); + System.setProperty("socksNonProxyHosts", "code.google.com"); + + // clear previous values + System.clearProperty("socksProxyHost"); + System.clearProperty("socksProxyPort"); + System.clearProperty("http.proxyHost"); + System.clearProperty("http.proxyPort"); + + switch (connection.getProxyType()) { + case SOCKS: + System.setProperty("socksProxyHost", connection.getProxyHost()); + System.setProperty("socksProxyPort", Integer.toString(connection.getProxyPort())); + break; + case HTTP: + System.setProperty("http.proxyHost", connection.getProxyHost()); + System.setProperty("http.proxyPort", Integer.toString(connection.getProxyPort())); + Authenticator.setDefault(new MageAuthenticator(connection.getProxyUsername(), connection.getProxyPassword())); + break; + } InvokerLocator clientLocator = new InvokerLocator(connection.getURI()); Map metadata = new HashMap(); metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); metadata.put("generalizeSocketException", "true"); server = (MageServer) TransporterClient.createTransporterClient(clientLocator.getLocatorURI(), MageServer.class, metadata); - callbackClient = new Client(clientLocator, "callback"); - callbackClient.connect(); + Map clientMetadata = new HashMap(); + clientMetadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); + clientMetadata.put("generalizeSocketException", "true"); + clientMetadata.put(Client.ENABLE_LEASE, "true"); + callbackClient = new Client(clientLocator, "callback", clientMetadata); Map listenerMetadata = new HashMap(); listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_PERIOD, "5000"); listenerMetadata.put(ConnectionValidator.VALIDATOR_PING_TIMEOUT, "2000"); - callbackClient.addConnectionListener(new ClientConnectionListener(), listenerMetadata); + callbackClient.connect(new ClientConnectionListener(), listenerMetadata); Map callbackMetadata = new HashMap(); callbackMetadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); - callbackMetadata.put(SocketWrapper.WRITE_TIMEOUT, "2000"); - callbackMetadata.put("generalizeSocketException", "true"); CallbackHandler callbackHandler = new CallbackHandler(); callbackClient.addListener(callbackHandler, callbackMetadata); @@ -201,7 +202,7 @@ public class Session { class ClientConnectionListener implements ConnectionListener { @Override public void handleConnectionException(Throwable throwable, Client client) { - logger.info("connection to server lost"); + logger.info("connection to server lost - " + throwable.getMessage()); disconnect(true); } } diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 7afe35741e..00487ff501 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -66,7 +66,7 @@ import org.apache.log4j.Logger; public class MageServerImpl implements MageServer { private final static Logger logger = Logger.getLogger("Mage Server"); - private static ExecutorService rmiExecutor = ThreadExecutor.getInstance().getRMIExecutor(); + private static ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); private String password; private boolean testMode; @@ -137,7 +137,7 @@ public class MageServerImpl implements MageServer { public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -243,15 +243,12 @@ public class MageServerImpl implements MageServer { @Override public void deregisterClient(final String sessionId) throws MageException { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.kill(); - logger.info("Client deregistered ..."); - } + SessionManager.getInstance().disconnect(sessionId); + logger.info("Client deregistered ..."); } } ); @@ -265,7 +262,7 @@ public class MageServerImpl implements MageServer { public void startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -284,7 +281,7 @@ public class MageServerImpl implements MageServer { public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -303,7 +300,7 @@ public class MageServerImpl implements MageServer { public void startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -332,7 +329,7 @@ public class MageServerImpl implements MageServer { @Override public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -349,7 +346,7 @@ public class MageServerImpl implements MageServer { @Override public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -366,7 +363,7 @@ public class MageServerImpl implements MageServer { @Override public void leaveChat(final UUID chatId, final String sessionId) throws MageException { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -417,7 +414,7 @@ public class MageServerImpl implements MageServer { 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)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -436,7 +433,7 @@ public class MageServerImpl implements MageServer { public void leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -466,7 +463,7 @@ public class MageServerImpl implements MageServer { public void joinGame(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -485,7 +482,7 @@ public class MageServerImpl implements MageServer { public void joinDraft(final UUID draftId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -504,7 +501,7 @@ public class MageServerImpl implements MageServer { public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -545,7 +542,7 @@ public class MageServerImpl implements MageServer { public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -564,7 +561,7 @@ public class MageServerImpl implements MageServer { public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -583,7 +580,7 @@ public class MageServerImpl implements MageServer { public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -602,7 +599,7 @@ public class MageServerImpl implements MageServer { public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -634,7 +631,7 @@ public class MageServerImpl implements MageServer { public void concedeGame(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -666,7 +663,7 @@ public class MageServerImpl implements MageServer { public void watchGame(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -685,7 +682,7 @@ public class MageServerImpl implements MageServer { public void stopWatching(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -704,7 +701,7 @@ public class MageServerImpl implements MageServer { public void replayGame(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -723,7 +720,7 @@ public class MageServerImpl implements MageServer { public void startReplay(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -742,7 +739,7 @@ public class MageServerImpl implements MageServer { public void stopReplay(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -761,7 +758,7 @@ public class MageServerImpl implements MageServer { public void nextPlay(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -780,7 +777,7 @@ public class MageServerImpl implements MageServer { public void previousPlay(final UUID gameId, final String sessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -816,7 +813,7 @@ public class MageServerImpl implements MageServer { public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -867,7 +864,7 @@ public class MageServerImpl implements MageServer { public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { @@ -886,7 +883,7 @@ public class MageServerImpl implements MageServer { public void removeTable(final String sessionId, final UUID tableId) throws MageException { if (SessionManager.getInstance().isValidSession(sessionId)) { try { - rmiExecutor.execute( + callExecutor.execute( new Runnable() { @Override public void run() { diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 31bfcd6cf5..6d94fd4488 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -31,6 +31,7 @@ package mage.server; import mage.server.util.PluginClassLoader; import java.io.File; import java.io.FilenameFilter; +import java.io.IOException; import java.net.InetAddress; import java.util.Map; import javax.management.MBeanServer; @@ -47,6 +48,9 @@ import mage.server.util.config.Plugin; import mage.server.util.config.GamePlugin; import mage.utils.MageVersion; 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.ServerInvocationHandler; @@ -113,20 +117,40 @@ public class Main { 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); } } + static class ClientConnectionListener implements ConnectionListener { + @Override + public void handleConnectionException(Throwable throwable, Client client) { + Session session = SessionManager.getInstance().getSession(client.getSessionId()); + if (session != null) { + String sessionName = session.getUsername() + " at " + session.getHost(); + if (throwable instanceof ClientDisconnectedException) { + logger.info("client disconnected - " + sessionName); + } + else { + logger.info("connection to client lost - " + sessionName); + } + SessionManager.getInstance().disconnect(client.getSessionId()); + } + } + } + static class MageTransporterServer extends TransporterServer { - Connector connector; + 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 { @@ -170,7 +194,7 @@ public class Main { public void removeListener(InvokerCallbackHandler callbackHandler) { ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; String sessionId = handler.getCallbackClient().getSessionId(); - SessionManager.getInstance().removeSession(sessionId); + SessionManager.getInstance().disconnect(sessionId); } } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 345d1a75e5..b8376dcdc6 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -76,9 +76,8 @@ public class Session { public String getId() { return sessionId; } - + public void kill() { - SessionManager.getInstance().removeSession(sessionId); TableManager.getInstance().removeSession(sessionId); GameManager.getInstance().removeSession(sessionId); ChatManager.getInstance().removeSession(sessionId); diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index fe623d6b72..3219308fb8 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -82,8 +82,12 @@ public class SessionManager { return false; } - public void removeSession(String sessionId) { - sessions.remove(sessionId); + public synchronized void disconnect(String sessionId) { + Session session = sessions.get(sessionId); + if (session != null) { + session.kill(); + sessions.remove(sessionId); + } } public Map getSessions() { diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index b3a824ae3e..93a904b793 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -237,6 +237,11 @@ public class TableController { return player; } + public void kill(String sessionId) { + leaveTable(sessionId); + sessionPlayerMap.remove(sessionId); + } + public synchronized void leaveTable(String sessionId) { if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING) table.leaveTable(sessionPlayerMap.get(sessionId)); diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index ff476b7e06..5f1d6fab8c 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -114,7 +114,9 @@ public class TableManager { } public void removeSession(String sessionId) { - // TODO: search through tables and remove session + for (TableController controller: controllers.values()) { + controller.kill(sessionId); + } } public boolean isTableOwner(UUID tableId, String sessionId) { diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index 9b333fd888..b1061b7871 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -142,7 +142,7 @@ public class DraftController { private void checkStart() { if (allJoined()) { - ThreadExecutor.getInstance().getRMIExecutor().execute( + ThreadExecutor.getInstance().getCallExecutor().execute( new Runnable() { @Override public void run() { diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index af282f6f22..183df1e94a 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -209,7 +209,7 @@ public class GameController implements GameCallback { private void checkStart() { if (allJoined()) { - ThreadExecutor.getInstance().getRMIExecutor().execute( + ThreadExecutor.getInstance().getCallExecutor().execute( new Runnable() { @Override public void run() { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index a93d7b7090..ff2d934baa 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -141,7 +141,7 @@ public class TournamentController { private void checkStart() { if (allJoined()) { - ThreadExecutor.getInstance().getRMIExecutor().execute( + ThreadExecutor.getInstance().getCallExecutor().execute( new Runnable() { @Override public void run() { diff --git a/Mage.Server/src/main/java/mage/server/util/ThreadExecutor.java b/Mage.Server/src/main/java/mage/server/util/ThreadExecutor.java index 318aa379b2..f2844fd5bb 100644 --- a/Mage.Server/src/main/java/mage/server/util/ThreadExecutor.java +++ b/Mage.Server/src/main/java/mage/server/util/ThreadExecutor.java @@ -36,13 +36,13 @@ import java.util.concurrent.*; */ public class ThreadExecutor { - private static ExecutorService rmiExecutor = Executors.newCachedThreadPool(); - private static ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads()); - private static ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(5); + private static final ExecutorService callExecutor = Executors.newCachedThreadPool(); + private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads()); + private static final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(5); static { - ((ThreadPoolExecutor)rmiExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); - ((ThreadPoolExecutor)rmiExecutor).allowCoreThreadTimeOut(true); + ((ThreadPoolExecutor)callExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); + ((ThreadPoolExecutor)callExecutor).allowCoreThreadTimeOut(true); ((ThreadPoolExecutor)gameExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); ((ThreadPoolExecutor)gameExecutor).allowCoreThreadTimeOut(true); ((ThreadPoolExecutor)timeoutExecutor).setKeepAliveTime(60, TimeUnit.SECONDS); @@ -57,8 +57,8 @@ public class ThreadExecutor { private ThreadExecutor() {} - public ExecutorService getRMIExecutor() { - return rmiExecutor; + public ExecutorService getCallExecutor() { + return callExecutor; } public ExecutorService getGameExecutor() { diff --git a/pom.xml b/pom.xml index 8f7b680a7c..d734aabb87 100644 --- a/pom.xml +++ b/pom.xml @@ -31,14 +31,9 @@ Mage.Plugins Mage.Server.Plugins Mage.Server.Console - Mage.Tests - - sonatype-org - https://maven.nuxeo.org/nexus/content/repositories/public/org/ - jboss-public-repository JBoss Repository @@ -65,6 +60,10 @@ never + + sonatype-org + https://maven.nuxeo.org/nexus/content/repositories/public/org/ + mage.googlecode.com https://mage.googlecode.com/hg/repository/ @@ -92,4 +91,4 @@ 0.8.0 - \ No newline at end of file + From 526f0c09bc361492f6712a4dd8ae45c504e4cf0a Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Sun, 26 Jun 2011 00:45:25 -0400 Subject: [PATCH 09/17] fixed client ip address --- Mage.Common/src/mage/remote/Session.java | 1 + Mage.Server/src/main/java/mage/server/Main.java | 7 +++++-- Mage.Server/src/main/java/mage/server/Session.java | 7 +++++-- Mage.Server/src/main/java/mage/server/SessionManager.java | 4 ++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Mage.Common/src/mage/remote/Session.java b/Mage.Common/src/mage/remote/Session.java index dbafa22ede..55079d9de7 100644 --- a/Mage.Common/src/mage/remote/Session.java +++ b/Mage.Common/src/mage/remote/Session.java @@ -145,6 +145,7 @@ public class Session { callbackMetadata.put(Bisocket.IS_CALLBACK_SERVER, "true"); CallbackHandler callbackHandler = new CallbackHandler(); callbackClient.addListener(callbackHandler, callbackMetadata); + callbackClient.invoke(""); this.sessionId = callbackClient.getSessionId(); boolean registerResult = false; diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 6d94fd4488..fe9321b9a3 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -53,6 +53,7 @@ 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; @@ -175,6 +176,9 @@ public class Main { @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; } @@ -183,8 +187,7 @@ public class Main { ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; try { String sessionId = handler.getClientSessionId(); - InetAddress clientAddress = handler.getCallbackClient().getAddressSeenByServer(); - SessionManager.getInstance().createSession(sessionId, callbackHandler, clientAddress.getHostAddress()); + SessionManager.getInstance().createSession(sessionId, callbackHandler); } catch (Throwable ex) { logger.fatal("", ex); } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index b8376dcdc6..4134d6e625 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -55,10 +55,9 @@ public class Session { private boolean isAdmin = false; private AsynchInvokerCallbackHandler callbackHandler; - public Session(String sessionId, InvokerCallbackHandler callbackHandler, String host) { + public Session(String sessionId, InvokerCallbackHandler callbackHandler) { this.sessionId = sessionId; this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler; - this.host = host; this.isAdmin = false; this.timeConnected = new Date(); } @@ -134,4 +133,8 @@ public class Session { public Date getConnectionTime() { return timeConnected; } + + void setHost(String hostAddress) { + this.host = hostAddress; + } } diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 3219308fb8..79c9f23e69 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -57,8 +57,8 @@ public class SessionManager { return sessions.get(sessionId); } - public void createSession(String sessionId, InvokerCallbackHandler callbackHandler, String host) { - Session session = new Session(sessionId, callbackHandler, host); + public void createSession(String sessionId, InvokerCallbackHandler callbackHandler) { + Session session = new Session(sessionId, callbackHandler); sessions.put(sessionId, session); } From 4657ea035288597105feaf0697c3f5b164c04c07 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Sun, 26 Jun 2011 00:45:57 -0400 Subject: [PATCH 10/17] fixed server console --- Mage.Server.Console/pom.xml | 63 +++++---- .../mage/server/console/ConnectDialog.form | 112 +++++++-------- .../mage/server/console/ConnectDialog.java | 132 ++++++++---------- .../mage/server/console/ConsoleFrame.java | 2 +- 4 files changed, 135 insertions(+), 174 deletions(-) diff --git a/Mage.Server.Console/pom.xml b/Mage.Server.Console/pom.xml index b14622c924..1d8e39775b 100644 --- a/Mage.Server.Console/pom.xml +++ b/Mage.Server.Console/pom.xml @@ -1,33 +1,34 @@ - - - 4.0.0 - - mage-root + + + 4.0.0 + + + org.mage + mage-root + 0.8.0 + + org.mage - 0.8.0 - - org.mage - Mage.Server.Console - 0.8.0 - Mage Server Console - http://maven.apache.org - - - junit - junit - 3.8.1 - test - - - ${project.groupId} - Mage-Common - 0.7.4 - - - org.swinglabs - swingx - 1.6.1 - - + Mage.Server.Console + jar + Mage Server Console + + + + org.mage + Mage-Common + ${project.version} + + + org.swinglabs + swingx + 1.6.1 + + + junit + junit + 4.8.2 + + diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form index 8cb9ff303f..a711e7a143 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.form @@ -25,36 +25,8 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -62,10 +34,33 @@ - - + - + + + + + + + + + + + + + + + + + + + + + + + + + @@ -86,26 +81,21 @@ - - - - - - + - + - + @@ -140,16 +130,6 @@ - - - - - - - - - - @@ -212,13 +192,13 @@ - + - + @@ -234,15 +214,15 @@ - + + - - - - + + + @@ -250,15 +230,16 @@ - - - - + + + + + - + @@ -268,6 +249,7 @@ + @@ -303,9 +285,9 @@ - - - + + + diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java index 3074f63a9b..6b78bd83b6 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConnectDialog.java @@ -75,7 +75,6 @@ public class ConnectDialog extends JDialog { this.console = console; this.txtServer.setText(ConsoleFrame.getPreferences().get("serverAddress", "localhost")); this.txtPort.setText(ConsoleFrame.getPreferences().get("serverPort", Integer.toString(17171))); - this.txtUserName.setText(ConsoleFrame.getPreferences().get("userName", "")); this.chkAutoConnect.setSelected(Boolean.parseBoolean(ConsoleFrame.getPreferences().get("autoConnect", "false"))); this.txtProxyServer.setText(ConsoleFrame.getPreferences().get("proxyAddress", "localhost")); this.txtProxyPort.setText(ConsoleFrame.getPreferences().get("proxyPort", Integer.toString(17171))); @@ -111,7 +110,6 @@ public class ConnectDialog extends JDialog { private void saveSettings() { ConsoleFrame.getPreferences().put("serverAddress", txtServer.getText()); ConsoleFrame.getPreferences().put("serverPort", txtPort.getText()); - ConsoleFrame.getPreferences().put("userName", txtUserName.getText()); ConsoleFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected())); ConsoleFrame.getPreferences().put("proxyAddress", txtProxyServer.getText()); ConsoleFrame.getPreferences().put("proxyPort", txtProxyPort.getText()); @@ -135,8 +133,6 @@ public class ConnectDialog extends JDialog { lblServer = new javax.swing.JLabel(); lblPort = new javax.swing.JLabel(); txtPort = new javax.swing.JTextField(); - txtUserName = new javax.swing.JTextField(); - lblUserName = new javax.swing.JLabel(); btnConnect = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); chkAutoConnect = new javax.swing.JCheckBox(); @@ -172,9 +168,6 @@ public class ConnectDialog extends JDialog { } }); - lblUserName.setLabelFor(txtUserName); - lblUserName.setText("User Name:"); - btnConnect.setText("Connect"); btnConnect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { @@ -217,6 +210,7 @@ public class ConnectDialog extends JDialog { 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:"); @@ -234,26 +228,27 @@ public class ConnectDialog extends JDialog { pnlProxyLayout.setHorizontalGroup( pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlProxyLayout.createSequentialGroup() - .addContainerGap(28, Short.MAX_VALUE) + .addContainerGap() .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(lblProxyPort) - .addComponent(lblProxyServer)) + .addComponent(lblProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(lblProxyPort)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(txtProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(txtProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)) + .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .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, 334, Short.MAX_VALUE)) .addContainerGap()) ); pnlProxyLayout.setVerticalGroup( pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlProxyLayout.createSequentialGroup() - .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(txtProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(lblProxyServer)) + .addContainerGap() + .addGroup(pnlProxyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(lblProxyServer) + .addComponent(txtProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .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)) ); @@ -278,9 +273,9 @@ public class ConnectDialog extends JDialog { .addComponent(lblProxyPassword) .addComponent(lblProxyUserName)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(pnlProxyAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) - .addComponent(txtPasswordField) - .addComponent(txtProxyUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)) + .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( @@ -300,12 +295,12 @@ public class ConnectDialog extends JDialog { pnlProxySettings.setLayout(pnlProxySettingsLayout); pnlProxySettingsLayout.setHorizontalGroup( pnlProxySettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(pnlProxy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .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(pnlProxySettingsLayout.createSequentialGroup() + .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) @@ -322,39 +317,35 @@ public class ConnectDialog extends JDialog { .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(lblPort) - .addComponent(lblServer) - .addComponent(lblUserName)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) - .addGap(131, 131, 131)) - .addComponent(txtUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(jButton1)))) - .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, 406, Short.MAX_VALUE) - .addComponent(cbProxyType, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE) + .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() - .addGap(6, 6, 6) - .addComponent(lblPassword) + .addComponent(lblProxyType) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE))) + .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) + .addComponent(lblPassword) + .addComponent(lblServer) + .addComponent(lblPort)) + .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() + .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(131, 131, 131)) + .addGroup(layout.createSequentialGroup() + .addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton1))))) .addContainerGap()) ); layout.setVerticalGroup( @@ -370,14 +361,10 @@ public class ConnectDialog extends JDialog { .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblPort)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(lblUserName)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .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(lblPassword)) - .addGap(18, 18, 18) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkAutoConnect) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) @@ -406,8 +393,8 @@ public class ConnectDialog extends JDialog { private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed - if (txtUserName.getText().isEmpty()) { - JOptionPane.showMessageDialog(rootPane, "Please provide a user name"); + if (txtPassword.getPassword().length == 0) { + JOptionPane.showMessageDialog(rootPane, "Please provide a password"); return; } if (txtServer.getText().trim().isEmpty()) { @@ -424,26 +411,19 @@ public class ConnectDialog extends JDialog { return; } - char[] input = new char[0]; - try { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - connection = new Connection(); - connection.setHost(this.txtServer.getText()); - connection.setPort(Integer.valueOf(this.txtPort.getText())); - connection.setUsername(this.txtUserName.getText()); - connection.setProxyType((ProxyType) this.cbProxyType.getSelectedItem()); - connection.setProxyHost(this.txtProxyServer.getText()); - connection.setProxyPort(Integer.valueOf(this.txtProxyPort.getText())); - connection.setProxyUsername(this.txtProxyUserName.getText()); - input = txtPasswordField.getPassword(); - connection.setProxyPassword(new String(input)); - logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort()); - task = new ConnectTask(); - task.execute(); - } - finally { - Arrays.fill(input, '0'); - } + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + connection = new Connection(); + connection.setHost(this.txtServer.getText()); + connection.setPort(Integer.valueOf(this.txtPort.getText())); + connection.setPassword(new String(txtPassword.getPassword())); + connection.setProxyType((ProxyType) this.cbProxyType.getSelectedItem()); + connection.setProxyHost(this.txtProxyServer.getText()); + connection.setProxyPort(Integer.valueOf(this.txtProxyPort.getText())); + connection.setProxyUsername(this.txtProxyUserName.getText()); + connection.setProxyPassword(new String(this.txtPasswordField.getPassword())); + logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort()); + task = new ConnectTask(); + task.execute(); }//GEN-LAST:event_btnConnectActionPerformed @@ -565,7 +545,6 @@ public class ConnectDialog extends JDialog { private javax.swing.JLabel lblProxyUserName; private javax.swing.JLabel lblServer; private javax.swing.JLabel lblStatus; - private javax.swing.JLabel lblUserName; private javax.swing.JPanel pnlProxy; private javax.swing.JPanel pnlProxyAuth; private javax.swing.JPanel pnlProxySettings; @@ -576,7 +555,6 @@ public class ConnectDialog extends JDialog { private javax.swing.JTextField txtProxyServer; private javax.swing.JTextField txtProxyUserName; private javax.swing.JTextField txtServer; - private javax.swing.JTextField txtUserName; // End of variables declaration//GEN-END:variables } diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java index 0ee1b69284..7d1faec2e6 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java @@ -58,7 +58,7 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { private static Session session; private ConnectDialog connectDialog; private static Preferences prefs = Preferences.userNodeForPackage(ConsoleFrame.class); - private final static MageVersion version = new MageVersion(0, 7, 4, "beta-2"); + private final static MageVersion version = new MageVersion(0, 8, 0, ""); /** * @return the session From b55dd5d787f69b718108324ad29def545b3ca729 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Sun, 26 Jun 2011 22:41:45 -0400 Subject: [PATCH 11/17] another Server Console fix --- .../mage/server/console/ConsoleFrame.java | 3 +- .../mage/server/console/ConsolePanel.java | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java index 7d1faec2e6..207db3c52d 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsoleFrame.java @@ -90,7 +90,6 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { public boolean connect(Connection connection) { if (session.connect(connection)) { - this.consolePanel1.start(); return true; } @@ -221,6 +220,7 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { @Override public void disconnected() { if (SwingUtilities.isEventDispatchThread()) { + consolePanel1.stop(); setStatusText("Not connected"); disableButtons(); } @@ -228,6 +228,7 @@ public class ConsoleFrame extends javax.swing.JFrame implements MageClient { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { + consolePanel1.stop(); setStatusText("Not connected"); disableButtons(); } diff --git a/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java b/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java index 186471f3bb..cc4aa69c8d 100644 --- a/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java +++ b/Mage.Server.Console/src/main/java/mage/server/console/ConsolePanel.java @@ -36,11 +36,14 @@ package mage.server.console; import java.util.Collection; import java.util.List; import java.util.UUID; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import javax.swing.table.AbstractTableModel; import mage.remote.Session; import mage.view.TableView; import mage.view.UserView; +import org.apache.log4j.Logger; /** * @@ -48,6 +51,8 @@ import mage.view.UserView; */ public class ConsolePanel extends javax.swing.JPanel { + private final static Logger logger = Logger.getLogger(ConsolePanel.class); + private TableUserModel tableUserModel; private TableTableModel tableTableModel; private UpdateUsersTask updateUsersTask; @@ -394,6 +399,8 @@ class UpdateUsersTask extends SwingWorker> { private Session session; private ConsolePanel panel; + private final static Logger logger = Logger.getLogger(UpdateUsersTask.class); + UpdateUsersTask(Session session, ConsolePanel panel) { this.session = session; this.panel = panel; @@ -413,6 +420,16 @@ class UpdateUsersTask extends SwingWorker> { 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> { @@ -421,6 +438,8 @@ class UpdateTablesTask extends SwingWorker> { private UUID roomId; private ConsolePanel panel; + private final static Logger logger = Logger.getLogger(UpdateTablesTask.class); + UpdateTablesTask(Session session, UUID roomId, ConsolePanel panel) { this.session = session; this.roomId = roomId; @@ -441,4 +460,14 @@ class UpdateTablesTask extends SwingWorker> { 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) {} + } } \ No newline at end of file From bdd8a2a28e290e22960279e12f823b2b2fc8e371 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Mon, 27 Jun 2011 21:50:35 -0400 Subject: [PATCH 12/17] separated User from Session - will be need for reconnecting --- .../client/deckeditor/DeckEditorPanel.java | 35 ++++++++++--------- .../main/java/mage/server/MageServerImpl.java | 2 +- .../src/main/java/mage/server/Main.java | 2 +- .../src/main/java/mage/server/Session.java | 27 ++++++++++---- .../main/java/mage/server/SessionManager.java | 5 +-- .../java/mage/server/TableController.java | 4 +-- 6 files changed, 46 insertions(+), 29 deletions(-) diff --git a/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java b/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java index 3ae8a937e2..07d68ca436 100644 --- a/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java +++ b/Mage.Client/src/main/java/mage/client/deckeditor/DeckEditorPanel.java @@ -579,26 +579,27 @@ public class DeckEditorPanel extends javax.swing.JPanel { int ret = fcImportDeck.showOpenDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { File file = fcImportDeck.getSelectedFile(); - try { - setCursor(new Cursor(Cursor.WAIT_CURSOR)); - DeckImporter importer = getDeckImporter(file.getPath()); - if (importer != null) { - deck = Deck.load(importer.importDeck(file.getPath())); + if (file != null) { + try { + setCursor(new Cursor(Cursor.WAIT_CURSOR)); + DeckImporter importer = getDeckImporter(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 { - JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Unknown deck format", "Error importing deck", JOptionPane.ERROR_MESSAGE); + finally { + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } - } catch (Exception ex) { - Logger.getLogger(DeckEditorPanel.class.getName()).log(Level.SEVERE, null, ex); - } - finally { - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - refreshDeck(); - try { - if (file != null) + refreshDeck(); + try { MageFrame.getPreferences().put("lastImportFolder", file.getCanonicalPath()); - } catch (IOException ex) { } + } catch (IOException ex) { } + } } fcImportDeck.setSelectedFile(null); }//GEN-LAST:event_btnImportActionPerformed diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 00487ff501..c2166c65d6 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -219,7 +219,7 @@ public class MageServerImpl implements MageServer { try { List players = new ArrayList(); for (Session session : SessionManager.getInstance().getSessions().values()) { - players.add(session.getUsername()); + players.add(session.getUser().getName()); } return players; } diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index fe9321b9a3..1b6cbf763d 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -131,7 +131,7 @@ public class Main { public void handleConnectionException(Throwable throwable, Client client) { Session session = SessionManager.getInstance().getSession(client.getSessionId()); if (session != null) { - String sessionName = session.getUsername() + " at " + session.getHost(); + String sessionName = session.getUser().getName() + " at " + session.getHost(); if (throwable instanceof ClientDisconnectedException) { logger.info("client disconnected - " + sessionName); } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 4134d6e625..868dc6ca8d 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -30,6 +30,7 @@ package mage.server; import java.util.Date; import java.util.UUID; +import mage.MageException; import mage.cards.decks.Deck; import mage.interfaces.callback.ClientCallback; import mage.server.game.GameManager; @@ -49,7 +50,7 @@ public class Session { private final static Logger logger = Logger.getLogger(Session.class); private String sessionId; - private String username; + private User user; private String host; private Date timeConnected; private boolean isAdmin = false; @@ -62,14 +63,27 @@ public class Session { this.timeConnected = new Date(); } - public void registerUser(String userName) { + public void registerUser(String userName) throws MageException { this.isAdmin = false; - this.username = userName; + User user = UserManager.getInstance().findUser(userName); + if (user == null) { + user = UserManager.getInstance().createUser(userName, host); + } + else { + if (user.getHost().equals(host)) { + logger.info("Reconnecting session for " + userName); + } + else { + throw new MageException("User name already in use"); + } + } + UserManager.getInstance().connectToSession(sessionId, userName); + this.user = user; } public void registerAdmin() { this.isAdmin = true; - this.username = "Admin"; + this.user = UserManager.getInstance().createUser("Admin", host); } public String getId() { @@ -80,6 +94,7 @@ public class Session { TableManager.getInstance().removeSession(sessionId); GameManager.getInstance().removeSession(sessionId); ChatManager.getInstance().removeSession(sessionId); + UserManager.getInstance().disconnect(user.getName()); } public synchronized void fireCallback(final ClientCallback call) { @@ -118,8 +133,8 @@ public class Session { fireCallback(new ClientCallback("replayGame", gameId)); } - public String getUsername() { - return username; + public User getUser() { + return user; } public boolean isAdmin() { diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 79c9f23e69..9779b358d9 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -33,6 +33,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import mage.MageException; import mage.view.UserView; import org.apache.log4j.Logger; import org.jboss.remoting.callback.InvokerCallbackHandler; @@ -62,7 +63,7 @@ public class SessionManager { sessions.put(sessionId, session); } - public boolean registerUser(String sessionId, String userName) { + public boolean registerUser(String sessionId, String userName) throws MageException { Session session = sessions.get(sessionId); if (session != null) { session.registerUser(userName); @@ -103,7 +104,7 @@ public class SessionManager { Session admin = sessions.get(sessionId); if (admin != null && admin.isAdmin()) { for (Session session: sessions.values()) { - users.add(new UserView(session.getUsername(), "", session.getId(), session.getConnectionTime())); + users.add(new UserView(session.getUser().getName(), "", session.getId(), session.getConnectionTime())); } } return users; diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 93a904b793..d4c5f4415c 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -83,7 +83,7 @@ public class TableController { match = GameFactory.getInstance().createMatch(options.getGameType(), options); Session session = SessionManager.getInstance().getSession(sessionId); if (session != null) - controllerName = session.getUsername(); + controllerName = session.getUser().getName(); else controllerName = "System"; table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match); @@ -96,7 +96,7 @@ public class TableController { tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options); Session session = SessionManager.getInstance().getSession(sessionId); if (session != null) - controllerName = session.getUsername(); + controllerName = session.getUser().getName(); else controllerName = "System"; table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), tournament); From 3d540160a89d82c1a4a90789b6769bf82da324e8 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Mon, 27 Jun 2011 21:50:53 -0400 Subject: [PATCH 13/17] missed some files --- .../src/main/java/mage/server/User.java | 67 +++++++++++++++++ .../main/java/mage/server/UserManager.java | 73 +++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 Mage.Server/src/main/java/mage/server/User.java create mode 100644 Mage.Server/src/main/java/mage/server/UserManager.java diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java new file mode 100644 index 0000000000..a17b3791d8 --- /dev/null +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -0,0 +1,67 @@ +/* + * 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.UUID; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class User { + + private UUID userId = UUID.randomUUID(); + private String userName; + private String sessionId; + private String host; + + public User(String userName, String host) { + this.userName = userName; + this.host = host; + } + + 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; + } +} diff --git a/Mage.Server/src/main/java/mage/server/UserManager.java b/Mage.Server/src/main/java/mage/server/UserManager.java new file mode 100644 index 0000000000..64a79d1f08 --- /dev/null +++ b/Mage.Server/src/main/java/mage/server/UserManager.java @@ -0,0 +1,73 @@ +/* + * 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.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class UserManager { + + private final static UserManager INSTANCE = new UserManager(); + + public static UserManager getInstance() { + return INSTANCE; + } + + private UserManager() {} + + private ConcurrentHashMap users = new ConcurrentHashMap(); + + public User createUser(String userName, String host) { + if (users.containsKey(userName)) + return null; + User user = new User(userName, host); + users.put(userName, user); + return user; + } + + public User findUser(String userName) { + return users.get(userName); + } + + public void connectToSession(String sessionId, String userName) { + if (users.containsKey(userName)) { + users.get(userName).setSessionId(sessionId); + } + } + + public void disconnect(String userName) { + if (users.containsKey(userName)) { + users.get(userName).setSessionId(""); + } + } + +} From 1a43757ed077cc49d67bc4544d2a8c35b9fe8ca8 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Sun, 3 Jul 2011 22:55:14 -0400 Subject: [PATCH 14/17] Replaced Session with User - needed for reconnect --- .../main/java/mage/server/ChatManager.java | 12 +- .../main/java/mage/server/ChatSession.java | 33 +++-- .../main/java/mage/server/MageServerImpl.java | 120 +++++++++++------ .../src/main/java/mage/server/Main.java | 7 +- .../src/main/java/mage/server/Session.java | 72 ++++------ .../main/java/mage/server/SessionManager.java | 11 -- .../java/mage/server/TableController.java | 123 +++++++++--------- .../main/java/mage/server/TableManager.java | 66 +++++----- .../src/main/java/mage/server/User.java | 71 +++++++++- .../main/java/mage/server/UserManager.java | 44 +++++-- .../mage/server/draft/DraftController.java | 47 +++---- .../java/mage/server/draft/DraftManager.java | 24 ++-- .../java/mage/server/draft/DraftSession.java | 44 +++---- .../java/mage/server/game/GameController.java | 84 ++++++------ .../java/mage/server/game/GameManager.java | 59 +++++---- .../java/mage/server/game/GameSession.java | 64 ++++----- .../java/mage/server/game/GameWatcher.java | 42 +++--- .../main/java/mage/server/game/GamesRoom.java | 14 +- .../java/mage/server/game/GamesRoomImpl.java | 26 ++-- .../java/mage/server/game/ReplayManager.java | 27 ++-- .../java/mage/server/game/ReplaySession.java | 28 ++-- .../tournament/TournamentController.java | 53 ++++---- .../server/tournament/TournamentManager.java | 17 ++- .../server/tournament/TournamentSession.java | 47 +++---- 24 files changed, 610 insertions(+), 525 deletions(-) diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index 7aa563f476..de23636a9e 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -54,12 +54,12 @@ public class ChatManager { return chatSession.getChatId(); } - public void joinChat(UUID chatId, String sessionId, String userName) { - chatSessions.get(chatId).join(userName, sessionId); + public void joinChat(UUID chatId, UUID userId) { + chatSessions.get(chatId).join(userId); } - public void leaveChat(UUID chatId, String sessionId) { - chatSessions.get(chatId).kill(sessionId); + public void leaveChat(UUID chatId, UUID userId) { + chatSessions.get(chatId).kill(userId); } public void destroyChatSession(UUID chatId) { @@ -70,9 +70,9 @@ public class ChatManager { chatSessions.get(chatId).broadcast(userName, message, color); } - void removeSession(String sessionId) { + void removeUser(UUID userId) { for (ChatSession chat: chatSessions.values()) { - chat.kill(sessionId); + chat.kill(userId); } } } diff --git a/Mage.Server/src/main/java/mage/server/ChatSession.java b/Mage.Server/src/main/java/mage/server/ChatSession.java index e60003044d..e75c1dec36 100644 --- a/Mage.Server/src/main/java/mage/server/ChatSession.java +++ b/Mage.Server/src/main/java/mage/server/ChatSession.java @@ -32,6 +32,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; +import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mage.interfaces.callback.ClientCallback; @@ -46,7 +47,7 @@ import org.apache.log4j.Logger; public class ChatSession { private final static Logger logger = Logger.getLogger(ChatSession.class); - private ConcurrentHashMap clients = new ConcurrentHashMap(); + private ConcurrentHashMap clients = new ConcurrentHashMap(); private UUID chatId; private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT); @@ -56,16 +57,20 @@ public class ChatSession { chatId = UUID.randomUUID(); } - public void join(String userName, String sessionId) { - clients.put(sessionId, userName); - broadcast(userName, " has joined", MessageColor.BLACK); - logger.info(userName + " joined chat " + chatId); + public void join(UUID userId) { + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + String userName = user.getName(); + clients.put(userId, userName); + broadcast(userName, " has joined", MessageColor.BLACK); + logger.info(userName + " joined chat " + chatId); + } } - public void kill(String sessionId) { - if (clients.containsKey(sessionId)) { - String userName = clients.get(sessionId); - clients.remove(sessionId); + public void kill(UUID userId) { + if (clients.containsKey(userId)) { + String userName = clients.get(userId); + clients.remove(userId); broadcast(userName, " has left", MessageColor.BLACK); logger.info(userName + " has left chat " + chatId); } @@ -77,12 +82,12 @@ public class ChatSession { final String time = timeFormatter.format(cal.getTime()); final String username = userName; logger.debug("Broadcasting '" + msg + "' for " + chatId); - for (String sessionId: clients.keySet()) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) - session.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color))); + for (UUID userId: clients.keySet()) { + User user = UserManager.getInstance().getUser(userId); + if (user != null) + user.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color))); else - kill(sessionId); + kill(userId); } } diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index c2166c65d6..55fd4593ac 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -107,7 +107,8 @@ public class MageServerImpl implements MageServer { public TableView createTable(String sessionId, UUID roomId, MatchOptions options) throws MageException { try { 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"); return table; } @@ -122,7 +123,8 @@ public class MageServerImpl implements MageServer { public TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions options) throws MageException { try { 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"); return table; } @@ -141,7 +143,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TableManager.getInstance().removeTable(sessionId, tableId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); } } ); @@ -156,7 +159,8 @@ public class MageServerImpl implements MageServer { public boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException, GameException { try { 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); return ret; } @@ -173,7 +177,8 @@ public class MageServerImpl implements MageServer { public boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill) throws MageException, GameException { try { 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); return ret; } @@ -190,7 +195,8 @@ public class MageServerImpl implements MageServer { public boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException, GameException { try { 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"); return ret; } @@ -218,8 +224,8 @@ public class MageServerImpl implements MageServer { public List getConnectedPlayers(UUID roomId) throws MageException { try { List players = new ArrayList(); - for (Session session : SessionManager.getInstance().getSessions().values()) { - players.add(session.getUser().getName()); + for (User user : UserManager.getInstance().getUsers()) { + players.add(user.getName()); } return players; } @@ -266,7 +272,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TableManager.getInstance().startMatch(sessionId, roomId, tableId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startMatch(userId, roomId, tableId); } } ); @@ -285,7 +292,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TableManager.getInstance().startChallenge(sessionId, roomId, tableId, challengeId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId); } } ); @@ -304,7 +312,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TableManager.getInstance().startTournament(sessionId, roomId, tableId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startTournament(userId, roomId, tableId); } } ); @@ -350,7 +359,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ChatManager.getInstance().joinChat(chatId, sessionId, userName); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ChatManager.getInstance().joinChat(chatId, userId); } } ); @@ -367,7 +377,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ChatManager.getInstance().leaveChat(chatId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ChatManager.getInstance().leaveChat(chatId, userId); } } ); @@ -402,7 +413,8 @@ public class MageServerImpl implements MageServer { @Override public boolean isTableOwner(String sessionId, UUID roomId, UUID tableId) throws MageException { try { - return TableManager.getInstance().isTableOwner(tableId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + return TableManager.getInstance().isTableOwner(tableId, userId); } catch (Exception ex) { handleException(ex); @@ -418,7 +430,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TableManager.getInstance().swapSeats(tableId, sessionId, seatNum1, seatNum2); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); } } ); @@ -437,7 +450,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GamesRoomManager.getInstance().getRoom(roomId).leaveTable(sessionId, tableId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); } } ); @@ -467,7 +481,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().joinGame(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().joinGame(gameId, userId); } } ); @@ -486,7 +501,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - DraftManager.getInstance().joinDraft(draftId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + DraftManager.getInstance().joinDraft(draftId, userId); } } ); @@ -505,7 +521,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TournamentManager.getInstance().joinTournament(tournamentId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TournamentManager.getInstance().joinTournament(tournamentId, userId); } } ); @@ -546,7 +563,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().sendPlayerUUID(gameId, sessionId, data); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().sendPlayerUUID(gameId, userId, data); } } ); @@ -565,7 +583,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().sendPlayerString(gameId, sessionId, data); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().sendPlayerString(gameId, userId, data); } } ); @@ -584,7 +603,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().sendPlayerBoolean(gameId, sessionId, data); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().sendPlayerBoolean(gameId, userId, data); } } ); @@ -603,7 +623,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().sendPlayerInteger(gameId, sessionId, data); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().sendPlayerInteger(gameId, userId, data); } } ); @@ -618,7 +639,8 @@ public class MageServerImpl implements MageServer { public DraftPickView sendCardPick(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { try { 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) { @@ -635,7 +657,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().concedeGame(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().concedeGame(gameId, userId); } } ); @@ -650,7 +673,8 @@ public class MageServerImpl implements MageServer { public boolean watchTable(String sessionId, UUID roomId, UUID tableId) throws MageException { try { 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) { @@ -667,7 +691,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().watchGame(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().watchGame(gameId, userId); } } ); @@ -686,7 +711,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - GameManager.getInstance().stopWatching(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().stopWatching(gameId, userId); } } ); @@ -705,7 +731,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ReplayManager.getInstance().replayGame(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().replayGame(gameId, userId); } } ); @@ -724,7 +751,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ReplayManager.getInstance().startReplay(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().startReplay(gameId, userId); } } ); @@ -743,7 +771,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ReplayManager.getInstance().stopReplay(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().stopReplay(gameId, userId); } } ); @@ -762,7 +791,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ReplayManager.getInstance().nextPlay(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().nextPlay(gameId, userId); } } ); @@ -781,7 +811,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - ReplayManager.getInstance().previousPlay(gameId, sessionId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().previousPlay(gameId, userId); } } ); @@ -817,8 +848,10 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - if (testMode) - GameManager.getInstance().cheat(gameId, sessionId, playerId, deckList); + if (testMode) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().cheat(gameId, userId, playerId, deckList); + } } } ); @@ -833,7 +866,8 @@ public class MageServerImpl implements MageServer { public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException { if (testMode) { 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; @@ -847,15 +881,20 @@ public class MageServerImpl implements MageServer { @Override public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) { 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; } @Override public List getUsers(String sessionId) throws MageException { - if (SessionManager.getInstance().isValidSession(sessionId)) { - return SessionManager.getInstance().getUsers(sessionId); + if (SessionManager.getInstance().isValidSession(sessionId) && SessionManager.getInstance().isAdmin(sessionId)) { + List users = new ArrayList(); + for (User user: UserManager.getInstance().getUsers()) { + users.add(new UserView(user.getName(), "", user.getSessionId(), user.getConnectionTime())); + } + return users; } return null; } @@ -887,7 +926,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - TableManager.getInstance().removeTable(sessionId, tableId); + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); } } ); diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 1b6cbf763d..75e512f614 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -131,7 +131,12 @@ public class Main { public void handleConnectionException(Throwable throwable, Client client) { Session session = SessionManager.getInstance().getSession(client.getSessionId()); if (session != null) { - String sessionName = session.getUser().getName() + " at " + session.getHost(); + String sessionName; + User user = UserManager.getInstance().getUser(session.getUserId()); + if (user != null) + sessionName = user.getName() + " at " + session.getHost(); + else + sessionName = session.getHost(); if (throwable instanceof ClientDisconnectedException) { logger.info("client disconnected - " + sessionName); } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 868dc6ca8d..9499a06441 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -31,10 +31,7 @@ package mage.server; import java.util.Date; import java.util.UUID; import mage.MageException; -import mage.cards.decks.Deck; import mage.interfaces.callback.ClientCallback; -import mage.server.game.GameManager; -import mage.view.TableClientMessage; import org.apache.log4j.Logger; import org.jboss.remoting.callback.AsynchInvokerCallbackHandler; import org.jboss.remoting.callback.Callback; @@ -50,8 +47,9 @@ public class Session { private final static Logger logger = Logger.getLogger(Session.class); private String sessionId; - private User user; + private UUID userId; private String host; + private int messageId = 0; private Date timeConnected; private boolean isAdmin = false; private AsynchInvokerCallbackHandler callbackHandler; @@ -65,25 +63,30 @@ public class Session { public void registerUser(String userName) throws MageException { this.isAdmin = false; - User user = UserManager.getInstance().findUser(userName); - if (user == null) { - user = UserManager.getInstance().createUser(userName, host); - } - else { + if (userName.equals("Admin")) + 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)) { - logger.info("Reconnecting session for " + userName); + 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"); } } - UserManager.getInstance().connectToSession(sessionId, userName); - this.user = user; + if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) + throw new MageException("Error connecting"); + this.userId = user.getId(); } public void registerAdmin() { this.isAdmin = true; - this.user = UserManager.getInstance().createUser("Admin", host); + User user = UserManager.getInstance().createUser("Admin", host); + this.userId = user.getId(); } public String getId() { @@ -91,50 +94,23 @@ public class Session { } public void kill() { - TableManager.getInstance().removeSession(sessionId); - GameManager.getInstance().removeSession(sessionId); - ChatManager.getInstance().removeSession(sessionId); - UserManager.getInstance().disconnect(user.getName()); +// TableManager.getInstance().removeSession(sessionId); +// GameManager.getInstance().removeSession(sessionId); +// ChatManager.getInstance().removeSession(sessionId); + UserManager.getInstance().disconnect(userId); } - public synchronized void fireCallback(final ClientCallback call) { + synchronized void fireCallback(final ClientCallback call) { try { + call.setMessageId(messageId++); callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { logger.fatal("Session fireCallback error", ex); } } - 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 User getUser() { - return user; + public UUID getUserId() { + return userId; } public boolean isAdmin() { diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 9779b358d9..15f973e0a3 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -99,17 +99,6 @@ public class SessionManager { return map; } - List getUsers(String sessionId) { - List users = new ArrayList(); - Session admin = sessions.get(sessionId); - if (admin != null && admin.isAdmin()) { - for (Session session: sessions.values()) { - users.add(new UserView(session.getUser().getName(), "", session.getId(), session.getConnectionTime())); - } - } - return users; - } - public void disconnectUser(String sessionId, String userSessionId) { if (isAdmin(sessionId)) { Session session = sessions.get(userSessionId); diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index d4c5f4415c..c22d155553 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -28,7 +28,6 @@ package mage.server; -import java.util.logging.Level; import mage.Constants.RangeOfInfluence; import mage.Constants.TableState; import mage.cards.decks.Deck; @@ -67,36 +66,38 @@ public class TableController { private final static Logger logger = Logger.getLogger(TableController.class); - private String sessionId; + private UUID userId; private UUID chatId; private String controllerName; private Table table; private Match match; private MatchOptions options; private Tournament tournament; - private ConcurrentHashMap sessionPlayerMap = new ConcurrentHashMap(); + private ConcurrentHashMap userPlayerMap = new ConcurrentHashMap(); - public TableController(UUID roomId, String sessionId, MatchOptions options) { - this.sessionId = sessionId; + public TableController(UUID roomId, UUID userId, MatchOptions options) { + this.userId = userId; chatId = ChatManager.getInstance().createChatSession(); this.options = options; match = GameFactory.getInstance().createMatch(options.getGameType(), options); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) - controllerName = session.getUser().getName(); + if (userId != null) { + User user = UserManager.getInstance().getUser(userId); + controllerName = user.getName(); + } else controllerName = "System"; table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match); init(); } - public TableController(UUID roomId, String sessionId, TournamentOptions options) { - this.sessionId = sessionId; + public TableController(UUID roomId, UUID userId, TournamentOptions options) { + this.userId = userId; chatId = ChatManager.getInstance().createChatSession(); tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) - controllerName = session.getUser().getName(); + if (userId != null) { + User user = UserManager.getInstance().getUser(userId); + controllerName = user.getName(); + } else controllerName = "System"; 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(String 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) { return false; } @@ -138,13 +139,13 @@ public class TableController { logger.info("player joined " + player.getId()); //only add human players to sessionPlayerMap if (seat.getPlayer().isHuman()) { - sessionPlayerMap.put(sessionId, player.getId()); + userPlayerMap.put(userId, player.getId()); } return true; } - public synchronized boolean joinTable(String 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) { return false; } @@ -163,13 +164,13 @@ public class TableController { logger.info("player joined " + player.getId()); //only add human players to sessionPlayerMap if (seat.getPlayer().isHuman()) { - sessionPlayerMap.put(sessionId, player.getId()); + userPlayerMap.put(userId, player.getId()); } return true; } - public void addPlayer(String 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) { return; } @@ -180,15 +181,12 @@ public class TableController { match.addPlayer(player, deck); table.joinTable(player, seat); if (player.isHuman()) { - sessionPlayerMap.put(sessionId, player.getId()); + userPlayerMap.put(userId, player.getId()); } } - public boolean submitDeck(String sessionId, DeckCardLists deckList) throws MageException { - return submitDeck(sessionPlayerMap.get(sessionId), deckList); - } - - public synchronized boolean submitDeck(UUID playerId, 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) { return false; } @@ -209,19 +207,19 @@ public class TableController { } } - public boolean watchTable(String sessionId) { + public boolean watchTable(UUID userId) { if (table.getState() != TableState.DUELING) { return false; } - SessionManager.getInstance().getSession(sessionId).watchGame(match.getGame().getId()); + UserManager.getInstance().getUser(userId).watchGame(match.getGame().getId()); return true; } - public boolean replayTable(String sessionId) { + public boolean replayTable(UUID userId) { if (table.getState() != TableState.FINISHED) { return false; } - ReplayManager.getInstance().replayGame(table.getId(), sessionId); + ReplayManager.getInstance().replayGame(table.getId(), userId); return true; } @@ -237,24 +235,24 @@ public class TableController { return player; } - public void kill(String sessionId) { - leaveTable(sessionId); - sessionPlayerMap.remove(sessionId); + public void kill(UUID userId) { + leaveTable(userId); + userPlayerMap.remove(userId); } - public synchronized void leaveTable(String sessionId) { + public synchronized void leaveTable(UUID userId) { if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING) - table.leaveTable(sessionPlayerMap.get(sessionId)); + table.leaveTable(userPlayerMap.get(userId)); } - public synchronized void startMatch(String sessionId) { - if (sessionId.equals(this.sessionId)) { + public synchronized void startMatch(UUID userId) { + if (userId.equals(this.userId)) { startMatch(); } } - public synchronized void startChallenge(String sessionId, UUID challengeId) { - if (sessionId.equals(this.sessionId)) { + public synchronized void startChallenge(UUID userId, UUID challengeId) { + if (userId.equals(this.userId)) { try { match.startMatch(); match.startGame(); @@ -262,11 +260,10 @@ public class TableController { GameOptions options = new GameOptions(); options.testMode = true; // 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); - SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { - sessionManager.getSession(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue()); + for (Entry entry: userPlayerMap.entrySet()) { + UserManager.getInstance().getUser(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue()); } } catch (GameException ex) { logger.fatal(null, ex); @@ -276,7 +273,7 @@ public class TableController { private UUID getPlayerId() throws GameException { UUID playerId = null; - for (Entry entry : sessionPlayerMap.entrySet()) { + for (Entry entry : userPlayerMap.entrySet()) { playerId = entry.getValue(); break; } @@ -301,12 +298,11 @@ public class TableController { try { match.startGame(); table.initGame(); - GameManager.getInstance().createGameSession(match.getGame(), sessionPlayerMap, table.getId(), choosingPlayerId); - SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { - Session session = sessionManager.getSession(entry.getKey()); - if (session != null) { - session.gameStarted(match.getGame().getId(), entry.getValue()); + GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId); + for (Entry entry: userPlayerMap.entrySet()) { + User user = UserManager.getInstance().getUser(entry.getKey()); + if (user != null) { + user.gameStarted(match.getGame().getId(), entry.getValue()); } else { TableManager.getInstance().removeTable(table.getId()); @@ -323,38 +319,35 @@ public class TableController { } } - public synchronized void startTournament(String sessionId) { + public synchronized void startTournament(UUID userId) { try { - if (sessionId.equals(this.sessionId) && table.getState() == TableState.STARTING) { - TournamentManager.getInstance().createTournamentSession(tournament, sessionPlayerMap, table.getId()); - SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { - Session session = sessionManager.getSession(entry.getKey()); - session.tournamentStarted(tournament.getId(), entry.getValue()); + if (userId.equals(this.userId) && table.getState() == TableState.STARTING) { + TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId()); + for (Entry entry: userPlayerMap.entrySet()) { + User user = UserManager.getInstance().getUser(entry.getKey()); + user.tournamentStarted(tournament.getId(), entry.getValue()); } } } catch (Exception ex) { logger.fatal("Error starting tournament", ex); TableManager.getInstance().removeTable(table.getId()); - TournamentManager.getInstance().kill(tournament.getId(), sessionId); + TournamentManager.getInstance().kill(tournament.getId(), userId); } } public void startDraft(Draft draft) { table.initDraft(); - DraftManager.getInstance().createDraftSession(draft, sessionPlayerMap, table.getId()); - SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { - sessionManager.getSession(entry.getKey()).draftStarted(draft.getId(), entry.getValue()); + DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId()); + for (Entry entry: userPlayerMap.entrySet()) { + UserManager.getInstance().getUser(entry.getKey()).draftStarted(draft.getId(), entry.getValue()); } } private void sideboard(UUID playerId, Deck deck, int timeout) throws MageException { - SessionManager sessionManager = SessionManager.getInstance(); - for (Entry entry: sessionPlayerMap.entrySet()) { + for (Entry entry: userPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) { - sessionManager.getSession(entry.getKey()).sideboard(deck, table.getId(), timeout); + UserManager.getInstance().getUser(entry.getKey()).sideboard(deck, table.getId(), timeout); break; } } @@ -404,8 +397,8 @@ public class TableController { } } - public boolean isOwner(String sessionId) { - return sessionId.equals(this.sessionId); + public boolean isOwner(UUID userId) { + return userId.equals(this.userId); } public Table getTable() { diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index 5f1d6fab8c..b15c619dc4 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -60,22 +60,22 @@ public class TableManager { return INSTANCE; } - public Table createTable(UUID roomId, String sessionId, MatchOptions options) { - TableController tableController = new TableController(roomId, sessionId, options); + public Table createTable(UUID roomId, UUID userId, MatchOptions options) { + TableController tableController = new TableController(roomId, userId, options); controllers.put(tableController.getTable().getId(), tableController); tables.put(tableController.getTable().getId(), tableController.getTable()); return tableController.getTable(); } public Table createTable(UUID roomId, MatchOptions options) { - TableController tableController = new TableController(roomId, UUID.randomUUID().toString(), options); + TableController tableController = new TableController(roomId, null, options); controllers.put(tableController.getTable().getId(), tableController); tables.put(tableController.getTable().getId(), tableController.getTable()); return tableController.getTable(); } - public Table createTournamentTable(UUID roomId, String sessionId, TournamentOptions options) { - TableController tableController = new TableController(roomId, sessionId, options); + public Table createTournamentTable(UUID roomId, UUID userId, TournamentOptions options) { + TableController tableController = new TableController(roomId, userId, options); controllers.put(tableController.getTable().getId(), tableController); tables.put(tableController.getTable().getId(), tableController.getTable()); return tableController.getTable(); @@ -95,47 +95,47 @@ public class TableManager { return tables.values(); } - public boolean joinTable(String 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)) - return controllers.get(tableId).joinTable(sessionId, name, playerType, skill, deckList); + return controllers.get(tableId).joinTable(userId, name, playerType, skill, deckList); return false; } - public boolean joinTournament(String 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)) - return controllers.get(tableId).joinTournament(sessionId, name, playerType, skill); + return controllers.get(tableId).joinTournament(userId, name, playerType, skill); return false; } - public boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList) throws MageException { + public boolean submitDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException { if (controllers.containsKey(tableId)) - return controllers.get(tableId).submitDeck(sessionId, deckList); + return controllers.get(tableId).submitDeck(userId, deckList); return false; } - public void removeSession(String sessionId) { + public void removeSession(UUID userId) { for (TableController controller: controllers.values()) { - controller.kill(sessionId); + controller.kill(userId); } } - public boolean isTableOwner(UUID tableId, String sessionId) { + public boolean isTableOwner(UUID tableId, UUID userId) { if (controllers.containsKey(tableId)) - return controllers.get(tableId).isOwner(sessionId); + return controllers.get(tableId).isOwner(userId); return false; } - public boolean removeTable(String sessionId, UUID tableId) { - if (isTableOwner(tableId, sessionId) || SessionManager.getInstance().isAdmin(sessionId)) { + public boolean removeTable(UUID userId, UUID tableId) { + if (isTableOwner(tableId, userId) || UserManager.getInstance().isAdmin(userId)) { removeTable(tableId); return true; } return false; } - public void leaveTable(String sessionId, UUID tableId) { + public void leaveTable(UUID userId, UUID tableId) { if (controllers.containsKey(tableId)) - controllers.get(tableId).leaveTable(sessionId); + controllers.get(tableId).leaveTable(userId); } public UUID getChatId(UUID tableId) { @@ -144,9 +144,9 @@ public class TableManager { return null; } - public void startMatch(String sessionId, UUID roomId, UUID tableId) { + public void startMatch(UUID userId, UUID roomId, UUID tableId) { if (controllers.containsKey(tableId)) - controllers.get(tableId).startMatch(sessionId); + controllers.get(tableId).startMatch(userId); } public void startMatch(UUID roomId, UUID tableId) { @@ -154,14 +154,14 @@ public class TableManager { controllers.get(tableId).startMatch(); } - public void startChallenge(String sessionId, UUID roomId, UUID tableId, UUID challengeId) { + public void startChallenge(UUID userId, UUID roomId, UUID tableId, UUID challengeId) { if (controllers.containsKey(tableId)) - controllers.get(tableId).startChallenge(sessionId, challengeId); + controllers.get(tableId).startChallenge(userId, challengeId); } - public void startTournament(String sessionId, UUID roomId, UUID tableId) { + public void startTournament(UUID userId, UUID roomId, UUID tableId) { if (controllers.containsKey(tableId)) - controllers.get(tableId).startTournament(sessionId); + controllers.get(tableId).startTournament(userId); } public void startDraft(UUID tableId, Draft draft) { @@ -169,15 +169,15 @@ public class TableManager { controllers.get(tableId).startDraft(draft); } - public boolean watchTable(String sessionId, UUID tableId) { + public boolean watchTable(UUID userId, UUID tableId) { if (controllers.containsKey(tableId)) - return controllers.get(tableId).watchTable(sessionId); + return controllers.get(tableId).watchTable(userId); return false; } - public boolean replayTable(String sessionId, UUID tableId) { + public boolean replayTable(UUID userId, UUID tableId) { if (controllers.containsKey(tableId)) - return controllers.get(tableId).replayTable(sessionId); + return controllers.get(tableId).replayTable(userId); return false; } @@ -191,8 +191,8 @@ public class TableManager { controllers.get(tableId).endDraft(draft); } - public void swapSeats(UUID tableId, String sessionId, int seatNum1, int seatNum2) { - if (controllers.containsKey(tableId) && isTableOwner(tableId, sessionId)) { + public void swapSeats(UUID tableId, UUID userId, int seatNum1, int seatNum2) { + if (controllers.containsKey(tableId) && isTableOwner(tableId, userId)) { controllers.get(tableId).swapSeats(seatNum1, seatNum2); } } @@ -202,9 +202,9 @@ public class TableManager { controllers.get(tableId).construct(); } - public void addPlayer(String 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)) - controllers.get(tableId).addPlayer(sessionId, player, playerType, deck); + controllers.get(tableId).addPlayer(userId, player, playerType, deck); } public void removeTable(UUID tableId) { diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index a17b3791d8..d63a3c4f36 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -27,7 +27,12 @@ */ package mage.server; +import java.util.Date; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import mage.cards.decks.Deck; +import mage.interfaces.callback.ClientCallback; +import mage.view.TableClientMessage; /** * @@ -35,14 +40,23 @@ import java.util.UUID; */ public class User { + public enum UserState { + Created, Connected, Disconnected, Reconnected; + } + private UUID userId = UUID.randomUUID(); private String userName; - private String sessionId; + private String sessionId = ""; private String host; + private Date connectionTime = new Date(); + private Date lastActivity = new Date(); + private UserState userState; + private CountDownLatch connectionSignal = new CountDownLatch(1); public User(String userName, String host) { this.userName = userName; this.host = host; + this.userState = UserState.Created; } public String getName() { @@ -63,5 +77,60 @@ public class User { 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; + } + + 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)); + } + + private void reconnect() { + } } diff --git a/Mage.Server/src/main/java/mage/server/UserManager.java b/Mage.Server/src/main/java/mage/server/UserManager.java index 64a79d1f08..138b7d95ba 100644 --- a/Mage.Server/src/main/java/mage/server/UserManager.java +++ b/Mage.Server/src/main/java/mage/server/UserManager.java @@ -27,6 +27,7 @@ */ package mage.server; +import java.util.Collection; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -44,30 +45,51 @@ public class UserManager { private UserManager() {} - private ConcurrentHashMap users = new ConcurrentHashMap(); + private ConcurrentHashMap users = new ConcurrentHashMap(); public User createUser(String userName, String host) { - if (users.containsKey(userName)) - return null; + if (findUser(userName) != null) + return null; //user already exists User user = new User(userName, host); - users.put(userName, user); + users.put(user.getId(), user); return user; } + public User getUser(UUID userId) { + return users.get(userId); + } + public User findUser(String userName) { - return users.get(userName); + for (User user: users.values()) { + if (user.getName().equals(userName)) + return user; + } + return null; + } + + public Collection getUsers() { + return users.values(); } - public void connectToSession(String sessionId, String userName) { - if (users.containsKey(userName)) { - users.get(userName).setSessionId(sessionId); + 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(""); } } - public void disconnect(String userName) { - if (users.containsKey(userName)) { - users.get(userName).setSessionId(""); + public boolean isAdmin(UUID userId) { + if (users.containsKey(userId)) { + return users.get(userId).getName().equals("Admin"); } + return false; } } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index b1061b7871..0e94ad7174 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -41,6 +41,7 @@ import mage.game.events.TableEvent; import mage.MageException; import mage.server.game.GameController; import mage.server.TableManager; +import mage.server.UserManager; import mage.server.util.ThreadExecutor; import mage.view.DraftPickView; import mage.view.DraftView; @@ -56,14 +57,14 @@ public class DraftController { public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt"; private ConcurrentHashMap draftSessions = new ConcurrentHashMap(); - private ConcurrentHashMap sessionPlayerMap; + private ConcurrentHashMap userPlayerMap; private UUID draftSessionId; private Draft draft; private UUID tableId; - public DraftController(Draft draft, ConcurrentHashMap sessionPlayerMap, UUID tableId) { + public DraftController(Draft draft, ConcurrentHashMap userPlayerMap, UUID tableId) { draftSessionId = UUID.randomUUID(); - this.sessionPlayerMap = sessionPlayerMap; + this.userPlayerMap = userPlayerMap; this.draft = draft; this.tableId = tableId; init(); @@ -116,15 +117,15 @@ public class DraftController { checkStart(); } - private UUID getPlayerId(String sessionId) { - return sessionPlayerMap.get(sessionId); + private UUID getPlayerId(UUID userId) { + return userPlayerMap.get(userId); } - public void join(String sessionId) { - UUID playerId = sessionPlayerMap.get(sessionId); - DraftSession draftSession = new DraftSession(draft, sessionId, playerId); + public void join(UUID userId) { + UUID playerId = userPlayerMap.get(userId); + DraftSession draftSession = new DraftSession(draft, userId, playerId); draftSessions.put(playerId, draftSession); - logger.info("player " + playerId + " has joined draft " + draft.getId()); + logger.info("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId()); draft.getPlayer(playerId).setJoined(); checkStart(); } @@ -163,8 +164,8 @@ public class DraftController { return true; } - private void leave(String sessionId) { - draft.leave(getPlayerId(sessionId)); + private void leave(UUID userId) { + draft.leave(getPlayerId(userId)); } private void endDraft() throws MageException { @@ -174,18 +175,18 @@ public class DraftController { TableManager.getInstance().endDraft(tableId, draft); } - public void kill(String sessionId) { - if (sessionPlayerMap.containsKey(sessionId)) { - draftSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); - draftSessions.remove(sessionPlayerMap.get(sessionId)); - leave(sessionId); - sessionPlayerMap.remove(sessionId); + public void kill(UUID userId) { + if (userPlayerMap.containsKey(userId)) { + draftSessions.get(userPlayerMap.get(userId)).setKilled(); + draftSessions.remove(userPlayerMap.get(userId)); + leave(userId); + userPlayerMap.remove(userId); } } - public void timeout(String sessionId) { - if (sessionPlayerMap.containsKey(sessionId)) { - draft.autoPick(sessionPlayerMap.get(sessionId)); + public void timeout(UUID userId) { + if (userPlayerMap.containsKey(userId)) { + draft.autoPick(userPlayerMap.get(userId)); } } @@ -193,9 +194,9 @@ public class DraftController { return this.draftSessionId; } - public DraftPickView sendCardPick(String sessionId, UUID cardId) { - if (draftSessions.get(sessionPlayerMap.get(sessionId)).sendCardPick(cardId)) { - return getDraftPickView(sessionPlayerMap.get(sessionId), 0); + public DraftPickView sendCardPick(UUID userId, UUID cardId) { + if (draftSessions.get(userPlayerMap.get(userId)).sendCardPick(cardId)) { + return getDraftPickView(userPlayerMap.get(userId), 0); } return null; } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftManager.java b/Mage.Server/src/main/java/mage/server/draft/DraftManager.java index 3027943dbf..1e72d3d04b 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftManager.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftManager.java @@ -48,36 +48,36 @@ public class DraftManager { private ConcurrentHashMap draftControllers = new ConcurrentHashMap(); - public UUID createDraftSession(Draft draft, ConcurrentHashMap sessionPlayerMap, UUID tableId) { - DraftController draftController = new DraftController(draft, sessionPlayerMap, tableId); + public UUID createDraftSession(Draft draft, ConcurrentHashMap userPlayerMap, UUID tableId) { + DraftController draftController = new DraftController(draft, userPlayerMap, tableId); draftControllers.put(draft.getId(), draftController); return draftController.getSessionId(); } - public void joinDraft(UUID draftId, String sessionId) { - draftControllers.get(draftId).join(sessionId); + public void joinDraft(UUID draftId, UUID userId) { + draftControllers.get(draftId).join(userId); } public void destroyChatSession(UUID gameId) { draftControllers.remove(gameId); } - public DraftPickView sendCardPick(UUID draftId, String sessionId, UUID cardId) { - return draftControllers.get(draftId).sendCardPick(sessionId, cardId); + public DraftPickView sendCardPick(UUID draftId, UUID userId, UUID cardId) { + return draftControllers.get(draftId).sendCardPick(userId, cardId); } - public void removeSession(String sessionId) { + public void removeSession(UUID userId) { for (DraftController controller: draftControllers.values()) { - controller.kill(sessionId); + controller.kill(userId); } } - public void kill(UUID draftId, String sessionId) { - draftControllers.get(draftId).kill(sessionId); + public void kill(UUID draftId, UUID userId) { + draftControllers.get(draftId).kill(userId); } - public void timeout(UUID gameId, String sessionId) { - draftControllers.get(gameId).timeout(sessionId); + public void timeout(UUID gameId, UUID userId) { + draftControllers.get(gameId).timeout(userId); } public void removeDraft(UUID draftId) { diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java index d6c8e97a04..27c99f3a07 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java @@ -35,8 +35,8 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import mage.game.draft.Draft; import mage.interfaces.callback.ClientCallback; -import mage.server.Session; -import mage.server.SessionManager; +import mage.server.User; +import mage.server.UserManager; import mage.server.util.ThreadExecutor; import mage.view.DraftClientMessage; import mage.view.DraftPickView; @@ -51,7 +51,7 @@ public class DraftSession { protected final static Logger logger = Logger.getLogger(DraftSession.class); - protected String sessionId; + protected UUID userId; protected UUID playerId; protected Draft draft; protected boolean killed = false; @@ -59,17 +59,17 @@ public class DraftSession { private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); - public DraftSession(Draft draft, String sessionId, UUID playerId) { - this.sessionId = sessionId; + public DraftSession(Draft draft, UUID userId, UUID playerId) { + this.userId = userId; this.draft = draft; this.playerId = playerId; } public boolean init(final DraftView draftView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("draftInit", draft.getId(), draftView)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("draftInit", draft.getId(), draftView)); return true; } } @@ -86,27 +86,27 @@ public class DraftSession { public void update(final DraftView draftView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("draftUpdate", draft.getId(), draftView)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("draftUpdate", draft.getId(), draftView)); } } } public void inform(final String message, final DraftView draftView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(draftView, message))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(draftView, message))); } } } public void draftOver() { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("draftOver", draft.getId())); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("draftOver", draft.getId())); } } } @@ -114,9 +114,9 @@ public class DraftSession { public void pickCard(final DraftPickView draftPickView, int timeout) { if (!killed) { setupTimeout(timeout); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(draftPickView))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(draftPickView))); } } } @@ -128,7 +128,7 @@ public class DraftSession { new Runnable() { @Override public void run() { - DraftManager.getInstance().timeout(draft.getId(), sessionId); + DraftManager.getInstance().timeout(draft.getId(), userId); } }, seconds, TimeUnit.SECONDS @@ -144,7 +144,7 @@ public class DraftSession { protected void handleRemoteException(RemoteException ex) { logger.fatal("DraftSession error ", ex); - DraftManager.getInstance().kill(draft.getId(), sessionId); + DraftManager.getInstance().kill(draft.getId(), userId); } public void setKilled() { diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index 183df1e94a..b22fe71a7d 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -29,9 +29,7 @@ package mage.server.game; import java.io.BufferedOutputStream; -import java.util.logging.Level; -import mage.game.LookedAt; import mage.MageException; import mage.server.TableManager; import java.io.File; @@ -81,8 +79,8 @@ public class GameController implements GameCallback { public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt"; private ConcurrentHashMap gameSessions = new ConcurrentHashMap(); - private ConcurrentHashMap watchers = new ConcurrentHashMap(); - private ConcurrentHashMap sessionPlayerMap; + private ConcurrentHashMap watchers = new ConcurrentHashMap(); + private ConcurrentHashMap userPlayerMap; private UUID gameSessionId; private Game game; private UUID chatId; @@ -91,9 +89,9 @@ public class GameController implements GameCallback { private Future gameFuture; - public GameController(Game game, ConcurrentHashMap sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { + public GameController(Game game, ConcurrentHashMap userPlayerMap, UUID tableId, UUID choosingPlayerId) { gameSessionId = UUID.randomUUID(); - this.sessionPlayerMap = sessionPlayerMap; + this.userPlayerMap = userPlayerMap; chatId = ChatManager.getInstance().createChatSession(); this.game = game; this.tableId = tableId; @@ -180,13 +178,13 @@ public class GameController implements GameCallback { checkStart(); } - private UUID getPlayerId(String sessionId) { - return sessionPlayerMap.get(sessionId); + private UUID getPlayerId(UUID userId) { + return userPlayerMap.get(userId); } - public void join(String sessionId) { - UUID playerId = sessionPlayerMap.get(sessionId); - GameSession gameSession = new GameSession(game, sessionId, playerId); + public void join(UUID userId) { + UUID playerId = userPlayerMap.get(userId); + GameSession gameSession = new GameSession(game, userId, playerId); gameSessions.put(playerId, gameSession); logger.info("player " + playerId + " has joined game " + game.getId()); ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getName() + " has joined the game", MessageColor.BLACK); @@ -228,27 +226,27 @@ public class GameController implements GameCallback { return true; } - public void watch(String sessionId) { - GameWatcher gameWatcher = new GameWatcher(sessionId, game.getId()); - watchers.put(sessionId, gameWatcher); + public void watch(UUID userId) { + GameWatcher gameWatcher = new GameWatcher(userId, game.getId()); + watchers.put(userId, gameWatcher); gameWatcher.init(getGameView()); ChatManager.getInstance().broadcast(chatId, "", " has started watching", MessageColor.BLACK); } - public void stopWatching(String sessionId) { - watchers.remove(sessionId); + public void stopWatching(UUID userId) { + watchers.remove(userId); ChatManager.getInstance().broadcast(chatId, "", " has stopped watching", MessageColor.BLACK); } - public void concede(String sessionId) { - game.concede(getPlayerId(sessionId)); + public void concede(UUID userId) { + game.concede(getPlayerId(userId)); } - private void leave(String sessionId) { - game.quit(getPlayerId(sessionId)); + private void leave(UUID userId) { + game.quit(getPlayerId(userId)); } - public void cheat(String sessionId, UUID playerId, DeckCardLists deckList) { + public void cheat(UUID userId, UUID playerId, DeckCardLists deckList) { Deck deck; try { deck = Deck.load(deckList); @@ -263,7 +261,7 @@ public class GameController implements GameCallback { updateGame(); } - public boolean cheat(String sessionId, UUID playerId, String cardName) { + public boolean cheat(UUID userId, UUID playerId, String cardName) { Card card = Sets.findCard(cardName, true); if (card != null) { Set cards = new HashSet(); @@ -276,23 +274,23 @@ public class GameController implements GameCallback { } } - public void kill(String sessionId) { - if (sessionPlayerMap.containsKey(sessionId)) { - gameSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); - gameSessions.remove(sessionPlayerMap.get(sessionId)); - leave(sessionId); - sessionPlayerMap.remove(sessionId); + public void kill(UUID userId) { + if (userPlayerMap.containsKey(userId)) { + gameSessions.get(userPlayerMap.get(userId)).setKilled(); + gameSessions.remove(userPlayerMap.get(userId)); + leave(userId); + userPlayerMap.remove(userId); } - if (watchers.containsKey(sessionId)) { - watchers.get(sessionId).setKilled(); - watchers.remove(sessionId); + if (watchers.containsKey(userId)) { + watchers.get(userId).setKilled(); + watchers.remove(userId); } } - public void timeout(String sessionId) { - if (sessionPlayerMap.containsKey(sessionId)) { - ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(sessionPlayerMap.get(sessionId)).getName() + " has timed out. Auto concede.", MessageColor.BLACK); - concede(sessionId); + public void timeout(UUID userId) { + if (userPlayerMap.containsKey(userId)) { + ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(userPlayerMap.get(userId)).getName() + " has timed out. Auto concede.", MessageColor.BLACK); + concede(userId); } } @@ -314,20 +312,20 @@ public class GameController implements GameCallback { return chatId; } - public void sendPlayerUUID(String sessionId, UUID data) { - gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerUUID(data); + public void sendPlayerUUID(UUID userId, UUID data) { + gameSessions.get(userPlayerMap.get(userId)).sendPlayerUUID(data); } - public void sendPlayerString(String sessionId, String data) { - gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerString(data); + public void sendPlayerString(UUID userId, String data) { + gameSessions.get(userPlayerMap.get(userId)).sendPlayerString(data); } - public void sendPlayerBoolean(String sessionId, Boolean data) { - gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerBoolean(data); + public void sendPlayerBoolean(UUID userId, Boolean data) { + gameSessions.get(userPlayerMap.get(userId)).sendPlayerBoolean(data); } - public void sendPlayerInteger(String sessionId, Integer data) { - gameSessions.get(sessionPlayerMap.get(sessionId)).sendPlayerInteger(data); + public void sendPlayerInteger(UUID userId, Integer data) { + gameSessions.get(userPlayerMap.get(userId)).sendPlayerInteger(data); } private synchronized void updateGame() { diff --git a/Mage.Server/src/main/java/mage/server/game/GameManager.java b/Mage.Server/src/main/java/mage/server/game/GameManager.java index b453f456fa..d674e68ba9 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameManager.java +++ b/Mage.Server/src/main/java/mage/server/game/GameManager.java @@ -32,7 +32,6 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mage.cards.decks.DeckCardLists; import mage.game.Game; -import mage.MageException; import mage.view.GameView; /** @@ -50,15 +49,15 @@ public class GameManager { private ConcurrentHashMap gameControllers = new ConcurrentHashMap(); - public UUID createGameSession(Game game, ConcurrentHashMap sessionPlayerMap, UUID tableId, UUID choosingPlayerId) { - GameController gameController = new GameController(game, sessionPlayerMap, tableId, choosingPlayerId); + public UUID createGameSession(Game game, ConcurrentHashMap userPlayerMap, UUID tableId, UUID choosingPlayerId) { + GameController gameController = new GameController(game, userPlayerMap, tableId, choosingPlayerId); gameControllers.put(game.getId(), gameController); return gameController.getSessionId(); } - public void joinGame(UUID gameId, String sessionId) { + public void joinGame(UUID gameId, UUID userId) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).join(sessionId); + gameControllers.get(gameId).join(userId); } public void destroyChatSession(UUID gameId) { @@ -71,66 +70,66 @@ public class GameManager { return null; } - public void sendPlayerUUID(UUID gameId, String sessionId, UUID data) { + public void sendPlayerUUID(UUID gameId, UUID userId, UUID data) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).sendPlayerUUID(sessionId, data); + gameControllers.get(gameId).sendPlayerUUID(userId, data); } - public void sendPlayerString(UUID gameId, String sessionId, String data) { + public void sendPlayerString(UUID gameId, UUID userId, String data) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).sendPlayerString(sessionId, data); + gameControllers.get(gameId).sendPlayerString(userId, data); } - public void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data) { + public void sendPlayerBoolean(UUID gameId, UUID userId, Boolean data) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).sendPlayerBoolean(sessionId, data); + gameControllers.get(gameId).sendPlayerBoolean(userId, data); } - public void sendPlayerInteger(UUID gameId, String sessionId, Integer data) { + public void sendPlayerInteger(UUID gameId, UUID userId, Integer data) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).sendPlayerInteger(sessionId, data); + gameControllers.get(gameId).sendPlayerInteger(userId, data); } - public void concedeGame(UUID gameId, String sessionId) { + public void concedeGame(UUID gameId, UUID userId) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).concede(sessionId); + gameControllers.get(gameId).concede(userId); } - public void watchGame(UUID gameId, String sessionId) { + public void watchGame(UUID gameId, UUID userId) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).watch(sessionId); + gameControllers.get(gameId).watch(userId); } - public void stopWatching(UUID gameId, String sessionId) { + public void stopWatching(UUID gameId, UUID userId) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).stopWatching(sessionId); + gameControllers.get(gameId).stopWatching(userId); } - public void removeSession(String sessionId) { + public void removeSession(UUID userId) { for (GameController controller: gameControllers.values()) { - controller.kill(sessionId); + controller.kill(userId); } } - public void kill(UUID gameId, String sessionId) { + public void kill(UUID gameId, UUID userId) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).kill(sessionId); + gameControllers.get(gameId).kill(userId); } - public void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList) { + public void cheat(UUID gameId, UUID userId, UUID playerId, DeckCardLists deckList) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).cheat(sessionId, playerId, deckList); + gameControllers.get(gameId).cheat(userId, playerId, deckList); } - public boolean cheat(UUID gameId, String sessionId, UUID playerId, String cardName) { + public boolean cheat(UUID gameId, UUID userId, UUID playerId, String cardName) { if (gameControllers.containsKey(gameId)) - return gameControllers.get(gameId).cheat(sessionId, playerId, cardName); + return gameControllers.get(gameId).cheat(userId, playerId, cardName); return false; } - public void timeout(UUID gameId, String sessionId) { + public void timeout(UUID gameId, UUID userId) { if (gameControllers.containsKey(gameId)) - gameControllers.get(gameId).timeout(sessionId); + gameControllers.get(gameId).timeout(userId); } public void removeGame(UUID gameId) { @@ -142,7 +141,7 @@ public class GameManager { gameControllers.get(gameId).saveGame(); } - public GameView getGameView(UUID gameId, String sessionId, UUID playerId) { + public GameView getGameView(UUID gameId, UUID userId, UUID playerId) { if (gameControllers.containsKey(gameId)) return gameControllers.get(gameId).getGameView(playerId); return null; diff --git a/Mage.Server/src/main/java/mage/server/game/GameSession.java b/Mage.Server/src/main/java/mage/server/game/GameSession.java index ef42dd27dc..cefd849d7c 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSession.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSession.java @@ -37,8 +37,8 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import mage.game.Game; import mage.interfaces.callback.ClientCallback; -import mage.server.Session; -import mage.server.SessionManager; +import mage.server.User; +import mage.server.UserManager; import mage.server.util.ConfigSettings; import mage.server.util.ThreadExecutor; import mage.view.AbilityPickerView; @@ -58,8 +58,8 @@ public class GameSession extends GameWatcher { private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); - public GameSession(Game game, String sessionId, UUID playerId) { - super(sessionId, game.getId()); + public GameSession(Game game, UUID userId, UUID playerId) { + super(userId, game.getId()); this.game = game; this.playerId = playerId; } @@ -67,9 +67,9 @@ public class GameSession extends GameWatcher { public void ask(final String question, final GameView gameView) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(gameView, question))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(gameView, question))); } } } @@ -77,9 +77,9 @@ public class GameSession extends GameWatcher { public void target(final String question, final CardsView cardView, final Set targets, final boolean required, final GameView gameView, final Map options) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(gameView, question, cardView, targets, required, options))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(gameView, question, cardView, targets, required, options))); } } } @@ -87,9 +87,9 @@ public class GameSession extends GameWatcher { public void select(final String message, final GameView gameView) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(gameView, message))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(gameView, message))); } } } @@ -97,9 +97,9 @@ public class GameSession extends GameWatcher { public void chooseAbility(final AbilityPickerView abilities) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities)); } } } @@ -107,9 +107,9 @@ public class GameSession extends GameWatcher { public void choose(final String message, final Set choices) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameChoose", game.getId(), new GameClientMessage(choices.toArray(new String[0]), message))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameChoose", game.getId(), new GameClientMessage(choices.toArray(new String[0]), message))); } } } @@ -117,9 +117,9 @@ public class GameSession extends GameWatcher { public void playMana(final String message, final GameView gameView) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(gameView, message))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(gameView, message))); } } } @@ -127,9 +127,9 @@ public class GameSession extends GameWatcher { public void playXMana(final String message, final GameView gameView) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(gameView, message))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(gameView, message))); } } } @@ -137,18 +137,18 @@ public class GameSession extends GameWatcher { public void getAmount(final String message, final int min, final int max) { if (!killed) { setupTimeout(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max))); } } } public void revealCards(final String name, final CardsView cardView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameReveal", game.getId(), new GameClientMessage(cardView, name))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameReveal", game.getId(), new GameClientMessage(cardView, name))); } } } @@ -160,7 +160,7 @@ public class GameSession extends GameWatcher { new Runnable() { @Override public void run() { - GameManager.getInstance().timeout(gameId, sessionId); + GameManager.getInstance().timeout(gameId, userId); } }, ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS diff --git a/Mage.Server/src/main/java/mage/server/game/GameWatcher.java b/Mage.Server/src/main/java/mage/server/game/GameWatcher.java index 85c6115aca..5576e38a72 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameWatcher.java +++ b/Mage.Server/src/main/java/mage/server/game/GameWatcher.java @@ -31,8 +31,8 @@ package mage.server.game; import java.rmi.RemoteException; import java.util.UUID; import mage.interfaces.callback.ClientCallback; -import mage.server.Session; -import mage.server.SessionManager; +import mage.server.User; +import mage.server.UserManager; import mage.view.GameClientMessage; import mage.view.GameView; import org.apache.log4j.Logger; @@ -45,20 +45,20 @@ public class GameWatcher { protected final static Logger logger = Logger.getLogger(GameWatcher.class); - protected String sessionId; + protected UUID userId; protected UUID gameId; protected boolean killed = false; - public GameWatcher(String sessionId, UUID gameId) { - this.sessionId = sessionId; + public GameWatcher(UUID userId, UUID gameId) { + this.userId = userId; this.gameId = gameId; } public boolean init(final GameView gameView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameInit", gameId, gameView)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameInit", gameId, gameView)); return true; } } @@ -67,43 +67,43 @@ public class GameWatcher { public void update(final GameView gameView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameUpdate", gameId, gameView)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameUpdate", gameId, gameView)); } } } public void inform(final String message, final GameView gameView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameInform", gameId, new GameClientMessage(gameView, message))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameInform", gameId, new GameClientMessage(gameView, message))); } } } public void gameOver(final String message) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameOver", gameId, message)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameOver", gameId, message)); } } } public void gameError(final String message) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("gameError", gameId, message)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("gameError", gameId, message)); } } } protected void handleRemoteException(RemoteException ex) { logger.fatal("GameWatcher error", ex); - GameManager.getInstance().kill(gameId, sessionId); + GameManager.getInstance().kill(gameId, userId); } public void setKilled() { diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoom.java b/Mage.Server/src/main/java/mage/server/game/GamesRoom.java index 4b263f84c3..8c5a527e13 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoom.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoom.java @@ -45,14 +45,14 @@ import mage.view.TableView; public interface GamesRoom extends Room { public List getTables(); - public boolean joinTable(String sessionId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException; - public boolean joinTournamentTable(String sessionId, UUID tableId, String name, String playerType, int skill) throws GameException; - public TableView createTable(String sessionId, MatchOptions options); - public TableView createTournamentTable(String sessionId, TournamentOptions options); - public void removeTable(String sessionId, UUID tableId); + public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException; + public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException; + public TableView createTable(UUID userId, MatchOptions options); + public TableView createTournamentTable(UUID userId, TournamentOptions options); + public void removeTable(UUID userId, UUID tableId); public void removeTable(UUID tableId); public TableView getTable(UUID tableId); - public void leaveTable(String sessionId, UUID tableId); - public boolean watchTable(String sessionId, UUID tableId) throws MageException; + public void leaveTable(UUID userId, UUID tableId); + public boolean watchTable(UUID userId, UUID tableId) throws MageException; } diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java index 5150ddf4f2..b2346b67cc 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java @@ -64,33 +64,33 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public boolean joinTable(String 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)) { - return TableManager.getInstance().joinTable(sessionId, tableId, name, playerType, skill, deckList); + return TableManager.getInstance().joinTable(userId, tableId, name, playerType, skill, deckList); } else { return false; } } @Override - public TableView createTable(String sessionId, MatchOptions options) { - Table table = TableManager.getInstance().createTable(this.getRoomId(), sessionId, options); + public TableView createTable(UUID userId, MatchOptions options) { + Table table = TableManager.getInstance().createTable(this.getRoomId(), userId, options); tables.put(table.getId(), table); return new TableView(table); } @Override - public boolean joinTournamentTable(String 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)) { - return TableManager.getInstance().joinTournament(sessionId, tableId, name, playerType, skill); + return TableManager.getInstance().joinTournament(userId, tableId, name, playerType, skill); } else { return false; } } @Override - public TableView createTournamentTable(String sessionId, TournamentOptions options) { - Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), sessionId, options); + public TableView createTournamentTable(UUID userId, TournamentOptions options) { + Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), userId, options); tables.put(table.getId(), table); return new TableView(table); } @@ -103,7 +103,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public void removeTable(String sessionId, UUID tableId) { + public void removeTable(UUID userId, UUID tableId) { tables.remove(tableId); } @@ -115,13 +115,13 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } @Override - public void leaveTable(String sessionId, UUID tableId) { - TableManager.getInstance().leaveTable(sessionId, tableId); + public void leaveTable(UUID userId, UUID tableId) { + TableManager.getInstance().leaveTable(userId, tableId); } @Override - public boolean watchTable(String sessionId, UUID tableId) throws MageException { - return TableManager.getInstance().watchTable(sessionId, tableId); + public boolean watchTable(UUID userId, UUID tableId) throws MageException { + return TableManager.getInstance().watchTable(userId, tableId); } } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplayManager.java b/Mage.Server/src/main/java/mage/server/game/ReplayManager.java index 67ce4c1897..a181936ecf 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplayManager.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplayManager.java @@ -30,8 +30,7 @@ package mage.server.game; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import mage.MageException; -import mage.server.SessionManager; +import mage.server.UserManager; /** * @@ -48,26 +47,26 @@ public class ReplayManager { private ConcurrentHashMap replaySessions = new ConcurrentHashMap(); - public void replayGame(UUID gameId, String sessionId) { - ReplaySession replaySession = new ReplaySession(gameId, sessionId); - replaySessions.put(gameId.toString() + sessionId.toString(), replaySession); - SessionManager.getInstance().getSession(sessionId).replayGame(gameId); + public void replayGame(UUID gameId, UUID userId) { + ReplaySession replaySession = new ReplaySession(gameId, userId); + replaySessions.put(gameId.toString() + userId.toString(), replaySession); + UserManager.getInstance().getUser(userId).replayGame(gameId); } - public void startReplay(UUID gameId, String sessionId) { - replaySessions.get(gameId.toString() + sessionId.toString()).replay(); + public void startReplay(UUID gameId, UUID userId) { + replaySessions.get(gameId.toString() + userId.toString()).replay(); } - public void stopReplay(UUID gameId, String sessionId) { - replaySessions.get(gameId.toString() + sessionId.toString()).stop(); + public void stopReplay(UUID gameId, UUID userId) { + replaySessions.get(gameId.toString() + userId.toString()).stop(); } - public void nextPlay(UUID gameId, String sessionId) { - replaySessions.get(gameId.toString() + sessionId.toString()).next(); + public void nextPlay(UUID gameId, UUID userId) { + replaySessions.get(gameId.toString() + userId.toString()).next(); } - public void previousPlay(UUID gameId, String sessionId) { - replaySessions.get(gameId.toString() + sessionId.toString()).previous(); + public void previousPlay(UUID gameId, UUID userId) { + replaySessions.get(gameId.toString() + userId.toString()).previous(); } } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java index 0004fdef6f..ed26b7c1c0 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java @@ -32,8 +32,8 @@ import java.util.UUID; import mage.game.Game; import mage.game.GameState; import mage.interfaces.callback.ClientCallback; -import mage.server.Session; -import mage.server.SessionManager; +import mage.server.User; +import mage.server.UserManager; import mage.view.GameView; import org.apache.log4j.Logger; @@ -45,18 +45,18 @@ public class ReplaySession implements GameCallback { private final static Logger logger = Logger.getLogger(ReplaySession.class); private GameReplay replay; - protected String sessionId; + protected UUID userId; - ReplaySession(UUID gameId, String sessionId) { + ReplaySession(UUID gameId, UUID userId) { this.replay = new GameReplay(gameId); - this.sessionId = sessionId; + this.userId = userId; } public void replay() { replay.start(); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("replayInit", replay.getGame().getId(), new GameView(replay.next(), replay.getGame()))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("replayInit", replay.getGame().getId(), new GameView(replay.next(), replay.getGame()))); } } @@ -74,9 +74,9 @@ public class ReplaySession implements GameCallback { @Override public void gameResult(final String result) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("replayDone", replay.getGame().getId(), result)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("replayDone", replay.getGame().getId(), result)); } } @@ -85,9 +85,9 @@ public class ReplaySession implements GameCallback { gameResult("game ended"); } else { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game))); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game))); } } } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index ff2d934baa..f7d46f0115 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -31,7 +31,6 @@ package mage.server.tournament; import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; import mage.cards.decks.Deck; import mage.game.GameException; import mage.game.Table; @@ -60,16 +59,14 @@ public class TournamentController { private final static Logger logger = Logger.getLogger(TournamentController.class); - private UUID sessionId; private UUID chatId; private UUID tableId; private Tournament tournament; - private ConcurrentHashMap sessionPlayerMap = new ConcurrentHashMap(); + private ConcurrentHashMap userPlayerMap = new ConcurrentHashMap(); private ConcurrentHashMap tournamentSessions = new ConcurrentHashMap(); - public TournamentController(Tournament tournament, ConcurrentHashMap sessionPlayerMap, UUID tableId) { - sessionId = UUID.randomUUID(); - this.sessionPlayerMap = sessionPlayerMap; + public TournamentController(Tournament tournament, ConcurrentHashMap userPlayerMap, UUID tableId) { + this.userPlayerMap = userPlayerMap; chatId = ChatManager.getInstance().createChatSession(); this.tournament = tournament; this.tableId = tableId; @@ -128,9 +125,9 @@ public class TournamentController { checkStart(); } - public synchronized void join(String sessionId) { - UUID playerId = sessionPlayerMap.get(sessionId); - TournamentSession tournamentSession = new TournamentSession(tournament, sessionId, tableId, playerId); + public synchronized void join(UUID userId) { + UUID playerId = userPlayerMap.get(userId); + TournamentSession tournamentSession = new TournamentSession(tournament, null, tableId, playerId); tournamentSessions.put(playerId, tournamentSession); TournamentPlayer player = tournament.getPlayer(playerId); player.setJoined(); @@ -205,40 +202,40 @@ public class TournamentController { tournamentSessions.get(playerId).submitDeck(deck); } - public void timeout(String sessionId) { - if (sessionPlayerMap.containsKey(sessionId)) { - TournamentPlayer player = tournament.getPlayer(sessionPlayerMap.get(sessionId)); - tournament.autoSubmit(sessionPlayerMap.get(sessionId), player.getDeck()); + public void timeout(UUID userId) { + if (userPlayerMap.containsKey(userId)) { + TournamentPlayer player = tournament.getPlayer(userPlayerMap.get(userId)); + tournament.autoSubmit(userPlayerMap.get(userId), player.getDeck()); } } - public UUID getSessionId() { - return this.sessionId; - } +// public UUID getSessionId() { +// return this.sessionId; +// } public UUID getChatId() { return chatId; } - public void kill(String sessionId) { - if (sessionPlayerMap.containsKey(sessionId)) { - tournamentSessions.get(sessionPlayerMap.get(sessionId)).setKilled(); - tournamentSessions.remove(sessionPlayerMap.get(sessionId)); - leave(sessionId); - sessionPlayerMap.remove(sessionId); + public void kill(UUID userId) { + if (userPlayerMap.containsKey(userId)) { + tournamentSessions.get(userPlayerMap.get(userId)).setKilled(); + tournamentSessions.remove(userPlayerMap.get(userId)); + leave(userId); + userPlayerMap.remove(userId); } } - private void leave(String sessionId) { - tournament.leave(getPlayerId(sessionId)); + private void leave(UUID userId) { + tournament.leave(getPlayerId(userId)); } - private UUID getPlayerId(String sessionId) { - return sessionPlayerMap.get(sessionId); + private UUID getPlayerId(UUID userId) { + return userPlayerMap.get(userId); } - private String getPlayerSessionId(UUID playerId) { - for (Entry entry: sessionPlayerMap.entrySet()) { + private UUID getPlayerSessionId(UUID playerId) { + for (Entry entry: userPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) return entry.getKey(); } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java index ffcc732bbf..0238d68696 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentManager.java @@ -48,22 +48,21 @@ public class TournamentManager { return INSTANCE; } - public UUID createTournamentSession(Tournament tournament, ConcurrentHashMap sessionPlayerMap, UUID tableId) { - TournamentController tournamentController = new TournamentController(tournament, sessionPlayerMap, tableId); + public void createTournamentSession(Tournament tournament, ConcurrentHashMap userPlayerMap, UUID tableId) { + TournamentController tournamentController = new TournamentController(tournament, userPlayerMap, tableId); controllers.put(tournament.getId(), tournamentController); - return tournamentController.getSessionId(); } - public void joinTournament(UUID tournamentId, String sessionId) { - controllers.get(tournamentId).join(sessionId); + public void joinTournament(UUID tournamentId, UUID userId) { + controllers.get(tournamentId).join(userId); } - public void kill(UUID tournamentId, String sessionId) { - controllers.get(tournamentId).kill(sessionId); + public void kill(UUID tournamentId, UUID userId) { + controllers.get(tournamentId).kill(userId); } - public void timeout(UUID tournamentId, String sessionId) { - controllers.get(tournamentId).timeout(sessionId); + public void timeout(UUID tournamentId, UUID userId) { + controllers.get(tournamentId).timeout(userId); } public void submitDeck(UUID tournamentId, UUID playerId, Deck deck) { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java index 88d30791b0..50c6b102a2 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java @@ -37,8 +37,8 @@ import mage.cards.decks.Deck; import mage.game.tournament.Tournament; import mage.MageException; import mage.interfaces.callback.ClientCallback; -import mage.server.Session; -import mage.server.SessionManager; +import mage.server.User; +import mage.server.UserManager; import mage.server.util.ThreadExecutor; import mage.view.TournamentView; import org.apache.log4j.Logger; @@ -50,7 +50,7 @@ import org.apache.log4j.Logger; public class TournamentSession { protected final static Logger logger = Logger.getLogger(TournamentSession.class); - protected String sessionId; + protected UUID userId; protected UUID playerId; protected UUID tableId; protected Tournament tournament; @@ -59,8 +59,8 @@ public class TournamentSession { private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); - public TournamentSession(Tournament tournament, String sessionId, UUID tableId, UUID playerId) { - this.sessionId = sessionId; + public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) { + this.userId = userId; this.tournament = tournament; this.playerId = playerId; this.tableId = tableId; @@ -68,37 +68,29 @@ public class TournamentSession { public boolean init(final TournamentView tournamentView) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), tournamentView)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), tournamentView)); return true; } } return false; } -// public boolean waitForAck(String message) { -// 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) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), tournamentView)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), tournamentView)); } } } public void gameOver(final String message) { if (!killed) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - session.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message)); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message)); } } } @@ -106,9 +98,10 @@ public class TournamentSession { public void construct(Deck deck, int timeout) throws MageException { if (!killed) { setupTimeout(timeout); - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) - session.construct(deck, tableId, timeout); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.construct(deck, tableId, timeout); + } } } @@ -119,7 +112,7 @@ public class TournamentSession { protected void handleRemoteException(RemoteException ex) { logger.fatal("TournamentSession error ", ex); - TournamentManager.getInstance().kill(tournament.getId(), sessionId); + TournamentManager.getInstance().kill(tournament.getId(), userId); } public void setKilled() { @@ -133,7 +126,7 @@ public class TournamentSession { new Runnable() { @Override public void run() { - TournamentManager.getInstance().timeout(tournament.getId(), sessionId); + TournamentManager.getInstance().timeout(tournament.getId(), userId); } }, seconds, TimeUnit.SECONDS From b4b02d0f68cb4b6d85aed2ed227c3723158c8602 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Mon, 4 Jul 2011 15:15:05 -0400 Subject: [PATCH 15/17] reconnect to games when client reconnects --- .../src/main/java/mage/server/Session.java | 1 + .../src/main/java/mage/server/User.java | 28 ++++++++-- .../java/mage/server/game/GameController.java | 50 +++++++---------- .../java/mage/server/game/GameSession.java | 55 ++++++++++++++----- .../java/mage/server/game/GameWatcher.java | 29 ++++++---- 5 files changed, 100 insertions(+), 63 deletions(-) diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 9499a06441..1dc657efa0 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -106,6 +106,7 @@ public class Session { callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { logger.fatal("Session fireCallback error", ex); + kill(); } } diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index d63a3c4f36..3acabe1b22 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -28,10 +28,14 @@ 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 java.util.concurrent.CountDownLatch; import mage.cards.decks.Deck; import mage.interfaces.callback.ClientCallback; +import mage.server.game.GameManager; +import mage.server.game.GameSession; import mage.view.TableClientMessage; /** @@ -39,7 +43,7 @@ import mage.view.TableClientMessage; * @author BetaSteward_at_googlemail.com */ public class User { - + public enum UserState { Created, Connected, Disconnected, Reconnected; } @@ -49,9 +53,8 @@ public class User { private String sessionId = ""; private String host; private Date connectionTime = new Date(); - private Date lastActivity = new Date(); private UserState userState; - private CountDownLatch connectionSignal = new CountDownLatch(1); + private Map gameSessions = new HashMap(); public User(String userName, String host) { this.userName = userName; @@ -88,7 +91,7 @@ public class User { } public boolean isConnected() { - return userState == UserState.Connected; + return userState == UserState.Connected || userState == UserState.Reconnected; } public Date getConnectionTime() { @@ -131,6 +134,19 @@ public class User { } private void reconnect() { - + for (Entry entry: gameSessions.entrySet()) { + gameStarted(entry.getValue().getGameId(), entry.getKey()); + entry.getValue().init(); + GameManager.getInstance().sendPlayerString(entry.getValue().getGameId(), userId, ""); + } } + + public void addGame(UUID playerId, GameSession gameSession) { + gameSessions.put(playerId, gameSession); + } + + public void removeGame(UUID playerId) { + gameSessions.remove(playerId); + } + } diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index b22fe71a7d..614da0a650 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -62,6 +62,7 @@ import mage.game.events.TableEvent; import mage.game.permanent.Permanent; import mage.players.Player; import mage.server.ChatManager; +import mage.server.UserManager; import mage.server.util.ThreadExecutor; import mage.sets.Sets; import mage.view.*; @@ -186,6 +187,7 @@ public class GameController implements GameCallback { UUID playerId = userPlayerMap.get(userId); GameSession gameSession = new GameSession(game, userId, playerId); gameSessions.put(playerId, gameSession); + UserManager.getInstance().getUser(userId).addGame(playerId, gameSession); logger.info("player " + playerId + " has joined game " + game.getId()); ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getName() + " has joined the game", MessageColor.BLACK); checkStart(); @@ -194,7 +196,7 @@ public class GameController implements GameCallback { private synchronized void startGame() { if (gameFuture == null) { for (final Entry entry: gameSessions.entrySet()) { - if (!entry.getValue().init(getGameView(entry.getKey()))) { + if (!entry.getValue().init()) { logger.fatal("Unable to initialize client"); //TODO: generate client error message return; @@ -227,9 +229,9 @@ public class GameController implements GameCallback { } public void watch(UUID userId) { - GameWatcher gameWatcher = new GameWatcher(userId, game.getId()); + GameWatcher gameWatcher = new GameWatcher(userId, game); watchers.put(userId, gameWatcher); - gameWatcher.init(getGameView()); + gameWatcher.init(); ChatManager.getInstance().broadcast(chatId, "", " has started watching", MessageColor.BLACK); } @@ -297,6 +299,7 @@ public class GameController implements GameCallback { public void endGame(final String message) throws MageException { for (final GameSession gameSession: gameSessions.values()) { gameSession.gameOver(message); + gameSession.removeGame(); } for (final GameWatcher gameWatcher: watchers.values()) { gameWatcher.gameOver(message); @@ -329,17 +332,17 @@ public class GameController implements GameCallback { } private synchronized void updateGame() { - for (final Entry entry: gameSessions.entrySet()) { - entry.getValue().update(getGameView(entry.getKey())); + for (final GameSession gameSession: gameSessions.values()) { + gameSession.update(); } for (final GameWatcher gameWatcher: watchers.values()) { - gameWatcher.update(getGameView()); + gameWatcher.update(); } } private synchronized void ask(UUID playerId, String question) throws MageException { if (gameSessions.containsKey(playerId)) - gameSessions.get(playerId).ask(question, getGameView(playerId)); + gameSessions.get(playerId).ask(question); informOthers(playerId); } @@ -358,41 +361,41 @@ public class GameController implements GameCallback { private synchronized void target(UUID playerId, String question, Cards cards, List perms, Set targets, boolean required, Map options) throws MageException { if (gameSessions.containsKey(playerId)) { 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) { CardsView permsView = new CardsView(); for (Permanent perm: perms) { 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 - gameSessions.get(playerId).target(question, new CardsView(), targets, required, getGameView(playerId), options); + gameSessions.get(playerId).target(question, new CardsView(), targets, required, options); } informOthers(playerId); } private synchronized void target(UUID playerId, String question, Collection abilities, boolean required, Map options) throws MageException { 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); } private synchronized void select(UUID playerId, String message) throws MageException { if (gameSessions.containsKey(playerId)) - gameSessions.get(playerId).select(message, getGameView(playerId)); + gameSessions.get(playerId).select(message); informOthers(playerId); } private synchronized void playMana(UUID playerId, String message) throws MageException { if (gameSessions.containsKey(playerId)) - gameSessions.get(playerId).playMana(message, getGameView(playerId)); + gameSessions.get(playerId).playMana(message); informOthers(playerId); } private synchronized void playXMana(UUID playerId, String message) throws MageException { if (gameSessions.containsKey(playerId)) - gameSessions.get(playerId).playXMana(message, getGameView(playerId)); + gameSessions.get(playerId).playXMana(message); informOthers(playerId); } @@ -417,11 +420,11 @@ public class GameController implements GameCallback { final String message = "Waiting for " + game.getPlayer(playerId).getName(); for (final Entry entry: gameSessions.entrySet()) { if (!entry.getKey().equals(playerId)) { - entry.getValue().inform(message, getGameView(entry.getKey())); + entry.getValue().inform(message); } } for (final GameWatcher watcher: watchers.values()) { - watcher.inform(message, getGameView()); + watcher.inform(message); } } @@ -431,21 +434,8 @@ public class GameController implements GameCallback { } } - private GameView getGameView() { - return new GameView(game.getState(), game); - } - public GameView getGameView(UUID playerId) { - GameView gameView = new GameView(game.getState(), game); - gameView.setHand(new CardsView(game.getPlayer(playerId).getHand().getCards(game))); - - List list = new ArrayList(); - for (Entry entry : game.getState().getLookedAt(playerId).entrySet()) { - list.add(new LookedAtView(entry.getKey(), entry.getValue(), game)); - } - gameView.setLookedAt(list); - - return gameView; + return gameSessions.get(playerId).getGameView(); } @Override diff --git a/Mage.Server/src/main/java/mage/server/game/GameSession.java b/Mage.Server/src/main/java/mage/server/game/GameSession.java index cefd849d7c..41eec5c57e 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSession.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSession.java @@ -29,12 +29,16 @@ package mage.server.game; import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import mage.cards.Cards; import mage.game.Game; import mage.interfaces.callback.ClientCallback; import mage.server.User; @@ -45,6 +49,7 @@ import mage.view.AbilityPickerView; import mage.view.CardsView; import mage.view.GameClientMessage; import mage.view.GameView; +import mage.view.LookedAtView; /** * @@ -52,44 +57,42 @@ import mage.view.GameView; */ public class GameSession extends GameWatcher { - private Game game; private UUID playerId; private ScheduledFuture futureTimeout; protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public GameSession(Game game, UUID userId, UUID playerId) { - super(userId, game.getId()); - this.game = game; + super(userId, game); this.playerId = playerId; } - public void ask(final String question, final GameView gameView) { + public void ask(final String question) { if (!killed) { setupTimeout(); User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.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 targets, final boolean required, final GameView gameView, final Map options) { + public void target(final String question, final CardsView cardView, final Set targets, final boolean required, final Map options) { if (!killed) { setupTimeout(); User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.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) { setupTimeout(); User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(gameView, message))); + user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message))); } } } @@ -114,22 +117,22 @@ public class GameSession extends GameWatcher { } } - public void playMana(final String message, final GameView gameView) { + public void playMana(final String message) { if (!killed) { setupTimeout(); User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.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) { setupTimeout(); User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(gameView, message))); + user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message))); } } } @@ -153,14 +156,13 @@ public class GameSession extends GameWatcher { } } - private synchronized void setupTimeout() { cancelTimeout(); futureTimeout = timeoutExecutor.schedule( new Runnable() { @Override public void run() { - GameManager.getInstance().timeout(gameId, userId); + GameManager.getInstance().timeout(game.getId(), userId); } }, ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS @@ -192,4 +194,27 @@ public class GameSession extends GameWatcher { cancelTimeout(); game.getPlayer(playerId).setResponseInteger(data); } + + @Override + public GameView getGameView() { + GameView gameView = new GameView(game.getState(), game); + gameView.setHand(new CardsView(game.getPlayer(playerId).getHand().getCards(game))); + + List list = new ArrayList(); + for (Entry entry : game.getState().getLookedAt(playerId).entrySet()) { + list.add(new LookedAtView(entry.getKey(), entry.getValue(), game)); + } + gameView.setLookedAt(list); + + return gameView; + } + + public void removeGame() { + UserManager.getInstance().getUser(userId).removeGame(playerId); + } + + public UUID getGameId() { + return game.getId(); + } + } diff --git a/Mage.Server/src/main/java/mage/server/game/GameWatcher.java b/Mage.Server/src/main/java/mage/server/game/GameWatcher.java index 5576e38a72..dbdd48e19c 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameWatcher.java +++ b/Mage.Server/src/main/java/mage/server/game/GameWatcher.java @@ -30,6 +30,7 @@ package mage.server.game; import java.rmi.RemoteException; import java.util.UUID; +import mage.game.Game; import mage.interfaces.callback.ClientCallback; import mage.server.User; import mage.server.UserManager; @@ -46,39 +47,39 @@ public class GameWatcher { protected final static Logger logger = Logger.getLogger(GameWatcher.class); protected UUID userId; - protected UUID gameId; + protected Game game; protected boolean killed = false; - public GameWatcher(UUID userId, UUID gameId) { + public GameWatcher(UUID userId, Game game) { this.userId = userId; - this.gameId = gameId; + this.game = game; } - public boolean init(final GameView gameView) { + public boolean init() { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("gameInit", gameId, gameView)); + user.fireCallback(new ClientCallback("gameInit", game.getId(), getGameView())); return true; } } return false; } - public void update(final GameView gameView) { + public void update() { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.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) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("gameInform", gameId, new GameClientMessage(gameView, message))); + user.fireCallback(new ClientCallback("gameInform", game.getId(), new GameClientMessage(getGameView(), message))); } } } @@ -87,7 +88,7 @@ public class GameWatcher { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("gameOver", gameId, message)); + user.fireCallback(new ClientCallback("gameOver", game.getId(), message)); } } } @@ -96,18 +97,22 @@ public class GameWatcher { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("gameError", gameId, message)); + user.fireCallback(new ClientCallback("gameError", game.getId(), message)); } } } protected void handleRemoteException(RemoteException ex) { logger.fatal("GameWatcher error", ex); - GameManager.getInstance().kill(gameId, userId); + GameManager.getInstance().kill(game.getId(), userId); } public void setKilled() { killed = true; } + public GameView getGameView() { + return new GameView(game.getState(), game); + } + } From bf2f4e3078c1439cfdb96358bfba51b857e15efe Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Wed, 6 Jul 2011 22:50:01 -0400 Subject: [PATCH 16/17] remove stale users after 10 minutes --- .../main/java/mage/server/ChatManager.java | 18 ++++++++ .../main/java/mage/server/ChatSession.java | 7 ++-- .../main/java/mage/server/MageServerImpl.java | 18 ++++---- .../src/main/java/mage/server/Main.java | 10 +++-- .../src/main/java/mage/server/Session.java | 13 +++--- .../main/java/mage/server/SessionManager.java | 22 ++++++---- .../src/main/java/mage/server/User.java | 31 ++++++++++++++ .../main/java/mage/server/UserManager.java | 41 ++++++++++++++++++- .../java/mage/server/game/GameSession.java | 8 +++- 9 files changed, 135 insertions(+), 33 deletions(-) diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index de23636a9e..e48219bdf4 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -70,6 +70,24 @@ public class ChatManager { chatSessions.get(chatId).broadcast(userName, message, color); } + /** + * + * 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()) { chat.kill(userId); diff --git a/Mage.Server/src/main/java/mage/server/ChatSession.java b/Mage.Server/src/main/java/mage/server/ChatSession.java index e75c1dec36..46b3018290 100644 --- a/Mage.Server/src/main/java/mage/server/ChatSession.java +++ b/Mage.Server/src/main/java/mage/server/ChatSession.java @@ -32,7 +32,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; -import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mage.interfaces.callback.ClientCallback; @@ -51,8 +50,6 @@ public class ChatSession { private UUID chatId; private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT); - //TODO: use sessionId for chatting - prevents sending without being part of the chat - public ChatSession() { chatId = UUID.randomUUID(); } @@ -98,4 +95,8 @@ public class ChatSession { return chatId; } + public boolean hasUser(UUID userId) { + return clients.containsKey(userId); + } + } diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 55fd4593ac..bb7910a1f9 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -253,7 +253,7 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - SessionManager.getInstance().disconnect(sessionId); + SessionManager.getInstance().disconnect(sessionId, true); logger.info("Client deregistered ..."); } } @@ -563,8 +563,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().sendPlayerUUID(gameId, userId, data); + User user = SessionManager.getInstance().getUser(sessionId); + user.sendPlayerUUID(gameId, data); } } ); @@ -583,8 +583,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().sendPlayerString(gameId, userId, data); + User user = SessionManager.getInstance().getUser(sessionId); + user.sendPlayerString(gameId, data); } } ); @@ -603,8 +603,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().sendPlayerBoolean(gameId, userId, data); + User user = SessionManager.getInstance().getUser(sessionId); + user.sendPlayerBoolean(gameId, data); } } ); @@ -623,8 +623,8 @@ public class MageServerImpl implements MageServer { new Runnable() { @Override public void run() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().sendPlayerInteger(gameId, userId, data); + User user = SessionManager.getInstance().getUser(sessionId); + user.sendPlayerInteger(gameId, data); } } ); diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 75e512f614..7437c6fe27 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -138,12 +138,13 @@ public class Main { else sessionName = session.getHost(); if (throwable instanceof ClientDisconnectedException) { + SessionManager.getInstance().disconnect(client.getSessionId(), true); logger.info("client disconnected - " + sessionName); } else { + SessionManager.getInstance().disconnect(client.getSessionId(), false); logger.info("connection to client lost - " + sessionName); } - SessionManager.getInstance().disconnect(client.getSessionId()); } } } @@ -200,9 +201,10 @@ public class Main { @Override public void removeListener(InvokerCallbackHandler callbackHandler) { - ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; - String sessionId = handler.getCallbackClient().getSessionId(); - SessionManager.getInstance().disconnect(sessionId); + logger.fatal("removeListener called"); +// ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; +// String sessionId = handler.getCallbackClient().getSessionId(); +// SessionManager.getInstance().disconnect(sessionId); } } diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index 1dc657efa0..0f99984258 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -93,20 +93,21 @@ public class Session { return sessionId; } - public void kill() { -// TableManager.getInstance().removeSession(sessionId); -// GameManager.getInstance().removeSession(sessionId); -// ChatManager.getInstance().removeSession(sessionId); + public void disconnect() { UserManager.getInstance().disconnect(userId); } - + + public void kill() { + UserManager.getInstance().removeUser(userId); + } + synchronized void fireCallback(final ClientCallback call) { try { call.setMessageId(messageId++); callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { logger.fatal("Session fireCallback error", ex); - kill(); + disconnect(); } } diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 15f973e0a3..d6cf60c40b 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -28,13 +28,11 @@ package mage.server; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import mage.MageException; -import mage.view.UserView; import org.apache.log4j.Logger; import org.jboss.remoting.callback.InvokerCallbackHandler; @@ -83,10 +81,13 @@ public class SessionManager { return false; } - public synchronized void disconnect(String sessionId) { + public synchronized void disconnect(String sessionId, boolean voluntary) { Session session = sessions.get(sessionId); if (session != null) { - session.kill(); + if (voluntary) + session.kill(); + else + session.disconnect(); sessions.remove(sessionId); } } @@ -101,10 +102,7 @@ public class SessionManager { public void disconnectUser(String sessionId, String userSessionId) { if (isAdmin(sessionId)) { - Session session = sessions.get(userSessionId); - if (session != null) { - session.kill(); - } + disconnect(userSessionId, true); } } @@ -122,4 +120,10 @@ public class SessionManager { return false; } + public User getUser(String sessionId) { + if (sessions.containsKey(sessionId)) { + return UserManager.getInstance().getUser(sessions.get(sessionId).getUserId()); + } + return null; + } } diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index 3acabe1b22..d64102df23 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -53,6 +53,7 @@ public class User { private String sessionId = ""; private String host; private Date connectionTime = new Date(); + private Date lastActivity = new Date(); private UserState userState; private Map gameSessions = new HashMap(); @@ -133,6 +134,30 @@ public class User { 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 entry: gameSessions.entrySet()) { gameStarted(entry.getValue().getGameId(), entry.getKey()); @@ -148,5 +173,11 @@ public class User { public void removeGame(UUID playerId) { gameSessions.remove(playerId); } + + public void kill() { + for (Entry entry: gameSessions.entrySet()) { + entry.getValue().kill(); + } + } } diff --git a/Mage.Server/src/main/java/mage/server/UserManager.java b/Mage.Server/src/main/java/mage/server/UserManager.java index 138b7d95ba..29944af1e1 100644 --- a/Mage.Server/src/main/java/mage/server/UserManager.java +++ b/Mage.Server/src/main/java/mage/server/UserManager.java @@ -27,23 +27,41 @@ */ 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() {} + private UserManager() { + expireExecutor.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + checkExpired(); + } + }, 60, 60, TimeUnit.SECONDS); + } private ConcurrentHashMap users = new ConcurrentHashMap(); @@ -82,6 +100,7 @@ public class UserManager { public void disconnect(UUID userId) { if (users.containsKey(userId)) { users.get(userId).setSessionId(""); + ChatManager.getInstance().broadcast(userId, "has lost connection", MessageColor.BLACK); } } @@ -91,5 +110,25 @@ public class UserManager { } 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()); + } + } + } } diff --git a/Mage.Server/src/main/java/mage/server/game/GameSession.java b/Mage.Server/src/main/java/mage/server/game/GameSession.java index 41eec5c57e..a386c66ac7 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSession.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSession.java @@ -210,11 +210,17 @@ public class GameSession extends GameWatcher { } public void removeGame() { - UserManager.getInstance().getUser(userId).removeGame(playerId); + User user = UserManager.getInstance().getUser(userId); + if (user != null) + user.removeGame(playerId); } public UUID getGameId() { return game.getId(); } + + public void kill() { + game.quit(playerId); + } } From 7f312ed453ab8b25def32279d3ace0f724bfd304 Mon Sep 17 00:00:00 2001 From: BetaSteward Date: Tue, 12 Jul 2011 23:13:50 -0400 Subject: [PATCH 17/17] reconnect to drafts and tournaments --- .../client/remote/CallbackClientImpl.java | 5 +- .../java/mage/server/TableController.java | 8 ++- .../main/java/mage/server/TableManager.java | 6 +++ .../src/main/java/mage/server/User.java | 36 +++++++++++++ .../mage/server/draft/DraftController.java | 22 +++----- .../java/mage/server/draft/DraftSession.java | 50 ++++++++++++------- .../tournament/TournamentController.java | 21 ++++++-- .../server/tournament/TournamentSession.java | 26 ++++++++-- 8 files changed, 132 insertions(+), 42 deletions(-) diff --git a/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java b/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java index a10572b810..e1c2ee9ee5 100644 --- a/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java +++ b/Mage.Client/src/main/java/mage/client/remote/CallbackClientImpl.java @@ -244,7 +244,10 @@ public class CallbackClientImpl implements CallbackClient { } } 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")) { diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index c22d155553..a16c773853 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -347,7 +347,9 @@ public class TableController { private void sideboard(UUID playerId, Deck deck, int timeout) throws MageException { for (Entry entry: userPlayerMap.entrySet()) { if (entry.getValue().equals(playerId)) { - UserManager.getInstance().getUser(entry.getKey()).sideboard(deck, table.getId(), timeout); + User user = UserManager.getInstance().getUser(entry.getKey()); + if (user != null) + user.sideboard(deck, table.getId(), timeout); break; } } @@ -384,6 +386,10 @@ public class TableController { tournament.nextStep(); } + public void endTournament(Tournament tournament) { + //TODO: implement this + } + public void swapSeats(int seatNum1, int seatNum2) { if (table.getState() == TableState.STARTING) { if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) { diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index b15c619dc4..517060b087 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -38,6 +38,7 @@ import mage.game.GameException; import mage.game.draft.Draft; import mage.game.match.Match; import mage.game.match.MatchOptions; +import mage.game.tournament.Tournament; import mage.game.tournament.TournamentOptions; import mage.MageException; import mage.players.Player; @@ -191,6 +192,11 @@ public class TableManager { controllers.get(tableId).endDraft(draft); } + public void endTournament(UUID tableId, Tournament tournament) { + 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); diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index d64102df23..bc53955d85 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -34,8 +34,10 @@ 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; /** @@ -56,6 +58,8 @@ public class User { private Date lastActivity = new Date(); private UserState userState; private Map gameSessions = new HashMap(); + private Map draftSessions = new HashMap(); + private Map tournamentSessions = new HashMap(); public User(String userName, String host) { this.userName = userName; @@ -164,6 +168,16 @@ public class User { entry.getValue().init(); GameManager.getInstance().sendPlayerString(entry.getValue().getGameId(), userId, ""); } + for (Entry entry: draftSessions.entrySet()) { + draftStarted(entry.getValue().getDraftId(), entry.getKey()); + entry.getValue().init(); + entry.getValue().update(); + } + for (Entry entry: tournamentSessions.entrySet()) { + tournamentStarted(entry.getValue().getTournamentId(), entry.getKey()); + entry.getValue().init(); + entry.getValue().update(); + } } public void addGame(UUID playerId, GameSession gameSession) { @@ -174,10 +188,32 @@ public class User { 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 entry: gameSessions.entrySet()) { entry.getValue().kill(); } + for (Entry entry: draftSessions.entrySet()) { + entry.getValue().setKilled(); + } + for (Entry entry: tournamentSessions.entrySet()) { + entry.getValue().setKilled(); + } } } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index 0e94ad7174..2b386b018b 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -125,6 +125,7 @@ public class DraftController { UUID playerId = userPlayerMap.get(userId); DraftSession draftSession = new DraftSession(draft, userId, playerId); draftSessions.put(playerId, draftSession); + UserManager.getInstance().getUser(userId).addDraft(playerId, draftSession); logger.info("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId()); draft.getPlayer(playerId).setJoined(); checkStart(); @@ -132,7 +133,7 @@ public class DraftController { private synchronized void startDraft() { for (final Entry entry: draftSessions.entrySet()) { - if (!entry.getValue().init(getDraftView())) { + if (!entry.getValue().init()) { logger.fatal("Unable to initialize client"); //TODO: generate client error message return; @@ -171,6 +172,7 @@ public class DraftController { private void endDraft() throws MageException { for (final DraftSession draftSession: draftSessions.values()) { draftSession.draftOver(); + draftSession.removeDraft(); } TableManager.getInstance().endDraft(tableId, draft); } @@ -187,6 +189,7 @@ public class DraftController { public void timeout(UUID userId) { if (userPlayerMap.containsKey(userId)) { draft.autoPick(userPlayerMap.get(userId)); + logger.info("Draft pick timeout - autopick for player: " + userPlayerMap.get(userId)); } } @@ -195,29 +198,18 @@ public class DraftController { } public DraftPickView sendCardPick(UUID userId, UUID cardId) { - if (draftSessions.get(userPlayerMap.get(userId)).sendCardPick(cardId)) { - return getDraftPickView(userPlayerMap.get(userId), 0); - } - return null; + return draftSessions.get(userPlayerMap.get(userId)).sendCardPick(cardId); } private synchronized void updateDraft() throws MageException { for (final Entry entry: draftSessions.entrySet()) { - entry.getValue().update(getDraftView()); + entry.getValue().update(); } } private synchronized void pickCard(UUID playerId, int timeout) throws MageException { if (draftSessions.containsKey(playerId)) - draftSessions.get(playerId).pickCard(getDraftPickView(playerId, timeout), timeout); - } - - private DraftView getDraftView() { - return new DraftView(draft); - } - - private DraftPickView getDraftPickView(UUID playerId, int timeout) { - return new DraftPickView(draft.getPlayer(playerId), timeout); + draftSessions.get(playerId).pickCard(timeout); } } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java index 27c99f3a07..fc947f6435 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java @@ -65,39 +65,34 @@ public class DraftSession { this.playerId = playerId; } - public boolean init(final DraftView draftView) { + public boolean init() { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.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 false; } -// public boolean waitForAck(String message) { -// Session session = SessionManager.getInstance().getSession(sessionId); -// do { -// //TODO: add timeout -// } while (!session.getAckMessage().equals(message) && !killed); -// return true; -// } - - public void update(final DraftView draftView) { + public void update() { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.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) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(draftView, message))); + user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message))); } } } @@ -111,12 +106,12 @@ public class DraftSession { } } - public void pickCard(final DraftPickView draftPickView, int timeout) { + public void pickCard(int timeout) { if (!killed) { setupTimeout(timeout); User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(draftPickView))); + user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(getDraftPickView(timeout)))); } } } @@ -151,10 +146,29 @@ public class DraftSession { killed = true; } - public boolean sendCardPick(UUID cardId) { + public DraftPickView sendCardPick(UUID cardId) { 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(); } } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index f7d46f0115..495b6b675d 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -45,6 +45,7 @@ import mage.game.tournament.TournamentPlayer; import mage.MageException; import mage.server.ChatManager; import mage.server.TableManager; +import mage.server.UserManager; import mage.server.game.GamesRoomManager; import mage.server.util.ThreadExecutor; import mage.view.ChatMessage.MessageColor; @@ -61,6 +62,7 @@ public class TournamentController { private UUID chatId; private UUID tableId; + private boolean started = false; private Tournament tournament; private ConcurrentHashMap userPlayerMap = new ConcurrentHashMap(); private ConcurrentHashMap tournamentSessions = new ConcurrentHashMap(); @@ -95,6 +97,9 @@ public class TournamentController { case CONSTRUCT: construct(); break; + case END: + endTournament(); + break; } } } @@ -127,8 +132,9 @@ public class TournamentController { public synchronized void join(UUID userId) { UUID playerId = userPlayerMap.get(userId); - TournamentSession tournamentSession = new TournamentSession(tournament, null, tableId, playerId); + TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId); tournamentSessions.put(playerId, tournamentSession); + UserManager.getInstance().getUser(userId).addTournament(playerId, tournamentSession); TournamentPlayer player = tournament.getPlayer(playerId); player.setJoined(); logger.info("player " + playerId + " has joined tournament " + tournament.getId()); @@ -137,7 +143,7 @@ public class TournamentController { } private void checkStart() { - if (allJoined()) { + if (!started && allJoined()) { ThreadExecutor.getInstance().getCallExecutor().execute( new Runnable() { @Override @@ -161,15 +167,24 @@ public class TournamentController { private synchronized void startTournament() { for (final Entry entry: tournamentSessions.entrySet()) { - if (!entry.getValue().init(getTournamentView())) { + if (!entry.getValue().init()) { logger.fatal("Unable to initialize client"); //TODO: generate client error message return; } } + started = true; 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) { try { TableManager tableManager = TableManager.getInstance(); diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java index 50c6b102a2..3e5a771f64 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java @@ -66,22 +66,22 @@ public class TournamentSession { this.tableId = tableId; } - public boolean init(final TournamentView tournamentView) { + public boolean init() { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), tournamentView)); + user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView())); return true; } } return false; } - public void update(final TournamentView tournamentView) { + public void update() { if (!killed) { User user = UserManager.getInstance().getUser(userId); if (user != null) { - user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), tournamentView)); + user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView())); } } } @@ -140,4 +140,22 @@ public class TournamentSession { } } + 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 + } + }