diff --git a/Mage.Client/src/main/java/mage/client/MageFrame.java b/Mage.Client/src/main/java/mage/client/MageFrame.java index 2a676f5d703..059af0566e1 100644 --- a/Mage.Client/src/main/java/mage/client/MageFrame.java +++ b/Mage.Client/src/main/java/mage/client/MageFrame.java @@ -1,30 +1,30 @@ /* -* 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. -*/ + * 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.client; import java.awt.AlphaComposite; @@ -374,7 +374,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private void setWindowTitle() { setTitle(TITLE_NAME + " Client: " + version == null ? "" : version.toString() + " Server: " - + ((client != null && client.isConnected()) ? serverState.getVersion().toString():"")); + + ((client != null && client.isConnected()) ? serverState.getVersion().toString() : "")); } private void addTooltipContainer() { @@ -653,7 +653,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { @Override public void run() { try { - for(Component component :desktopPane.getComponents()) { + for (Component component : desktopPane.getComponents()) { if (component instanceof GamePane && ((GamePane) component).getGameId().equals(gameId)) { setActive((GamePane) component); @@ -722,9 +722,9 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { @Override public void run() { try { - for(Component component :desktopPane.getComponents()) { - if (component instanceof TournamentPane && - ((TournamentPane) component).getTournamentId().equals(tournamentId)) { + for (Component component : desktopPane.getComponents()) { + if (component instanceof TournamentPane + && ((TournamentPane) component).getTournamentId().equals(tournamentId)) { setActive((TournamentPane) component); return; } @@ -776,24 +776,24 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { private void updateDatabase(boolean forceDBComparison, ServerState serverState) { long cardDBVersion = CardRepository.instance.getContentVersionFromDB(); if (forceDBComparison || serverState.getCardsContentVersion() > cardDBVersion) { - List classNames = client.getCards(); //CardRepository.instance.getClassNames(); - List cards = CardRepository.instance.getMissingCards(classNames); - CardRepository.instance.addCards(cards); + List classNames = CardRepository.instance.getClassNames(); + List cardInfoList = client.getMissingCardsData(classNames); + CardRepository.instance.addCards(cardInfoList); CardRepository.instance.setContentVersion(serverState.getCardsContentVersion()); - logger.info("Updating client cards DB - existing cards: " + classNames.size() + " new cards: " + cards.size() + - " content versions - server: " + serverState.getCardsContentVersion() + " client: " + cardDBVersion); + logger.info("Updating client cards DB - existing cards: " + classNames.size() + " new cards: " + cardInfoList.size() + + " content versions - server: " + serverState.getCardsContentVersion() + " client: " + cardDBVersion); } long expansionDBVersion = ExpansionRepository.instance.getContentVersionFromDB(); if (forceDBComparison || serverState.getExpansionsContentVersion() > expansionDBVersion) { List setCodes = ExpansionRepository.instance.getSetCodes(); - List expansions = getMissingExpansionData(setCodes); + List expansions = client.getMissingExpansionsData(setCodes); for (ExpansionInfo expansion : expansions) { ExpansionRepository.instance.add(expansion); } ExpansionRepository.instance.setContentVersion(serverState.getExpansionsContentVersion()); - logger.info("Updating client expansions DB - existing sets: " + setCodes.size() + " new sets: " + expansions.size()+ - " content versions - server: " + serverState.getExpansionsContentVersion() + " client: " + expansionDBVersion); + logger.info("Updating client expansions DB - existing sets: " + setCodes.size() + " new sets: " + expansions.size() + + " content versions - server: " + serverState.getExpansionsContentVersion() + " client: " + expansionDBVersion); } } @@ -841,7 +841,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { setUserPrefsToConnection(connection); logger.debug("connecting (auto): " + proxyType + " " + proxyServer + " " + proxyPort + " " + proxyUsername); - if (connect(connection)) { + if (connect(connection)) { return true; } else { showMessage("Error Connecting", "Unable to connect to server"); @@ -1109,7 +1109,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { this.tablesPane.hideTables(); } - public void showGames(final boolean setActive) { + public void showGames(final boolean setActive) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { @@ -1125,7 +1125,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { if (topPanebefore != null) { setActive(topPanebefore); } - } + } } }); } @@ -1399,20 +1399,20 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { @Override public void disconnected(final boolean errorCall) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setStatusText("Not connected"); - disableButtons(); - hideGames(); - hideTables(); - if (errorCall && JOptionPane.showConfirmDialog(MageFrame.this, "The connection to server was lost. Reconnect?", "Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { - if (performConnect()) { - enableButtons(); - } + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + setStatusText("Not connected"); + disableButtons(); + hideGames(); + hideTables(); + if (errorCall && JOptionPane.showConfirmDialog(MageFrame.this, "The connection to server was lost. Reconnect?", "Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + if (performConnect()) { + enableButtons(); } } - }); + } + }); } public void showMessage(final String title, final String message) { @@ -1437,8 +1437,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { public void inform(String title, String message, MessageType type) { if (type == MessageType.ERROR) { showError(title, message); - } - else { + } else { showMessage(title, message); } } @@ -1698,14 +1697,13 @@ public class MageFrame extends javax.swing.JFrame implements MageClient { sideboard(deck, tableId, time); } } - + @Override public void construct(UUID tableId, DeckView deckView, int time) { Deck deck = DeckUtil.construct(deckView); construct(deck, tableId, time); } - protected void sideboard(Deck deck, UUID tableId, int time) { showDeckEditor(DeckEditorMode.SIDEBOARDING, deck, tableId, time); } diff --git a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java index 5dbdc5539c1..d7bc7ba6c92 100644 --- a/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java +++ b/Mage.Client/src/main/java/mage/client/dialog/PreferencesDialog.java @@ -69,7 +69,6 @@ import mage.players.net.UserGroup; import mage.players.net.UserSkipPrioritySteps; import mage.remote.Connection; import mage.remote.Connection.ProxyType; -import mage.view.UserDataView; import org.apache.log4j.Logger; /** @@ -2722,8 +2721,8 @@ public class PreferencesDialog extends javax.swing.JDialog { } } - public static UserDataView getUserData() { - return new UserDataView(UserGroup.PLAYER, + public static UserData getUserData() { + return new UserData(UserGroup.PLAYER, PreferencesDialog.selectedAvatarId, PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_ABILITY_PICKER_FORCED, "true").equals("true"), PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_ALLOW_REQUEST_SHOW_HAND_CARDS, "true").equals("true"), diff --git a/Mage.Common/src/mage/remote/Connection.java b/Mage.Common/src/mage/remote/Connection.java index 93bcb42a499..1d7b18048cb 100644 --- a/Mage.Common/src/mage/remote/Connection.java +++ b/Mage.Common/src/mage/remote/Connection.java @@ -34,8 +34,7 @@ import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; -import mage.players.net.UserSkipPrioritySteps; -import mage.view.UserDataView; +import mage.players.net.UserData; /** * @@ -56,7 +55,7 @@ public class Connection implements Serializable { private int clientCardDatabaseVersion; private boolean forceDBComparison; - private UserDataView userData; + private UserData userData; // private int avatarId; // private boolean showAbilityPickerForced; @@ -64,8 +63,6 @@ public class Connection implements Serializable { // private boolean confirmEmptyManaPool; // private String flagName; // private UserSkipPrioritySteps userSkipPrioritySteps; - - public ProxyType getProxyType() { return proxyType; } @@ -118,11 +115,11 @@ public class Connection implements Serializable { public boolean isSSL() { return this.ssl; } - + public void setSSL(boolean ssl) { this.ssl = ssl; } - + public String getUsername() { return username; } @@ -189,11 +186,11 @@ public class Connection implements Serializable { return null; } - public void setUserData(UserDataView userData) { - this.userData= userData; + public void setUserData(UserData userData) { + this.userData = userData; } - - public UserDataView getUserData() { + + public UserData getUserData() { return userData; } diff --git a/Mage.Common/src/mage/utils/MageVersion.java b/Mage.Common/src/mage/utils/MageVersion.java index 3186a84a251..a1f9ec6d171 100644 --- a/Mage.Common/src/mage/utils/MageVersion.java +++ b/Mage.Common/src/mage/utils/MageVersion.java @@ -1,102 +1,102 @@ -/* - * 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.utils; - -import java.io.Serializable; - -/** - * - * @author BetaSteward_at_googlemail.com - */ -public class MageVersion implements Serializable, Comparable { - - /** - * - */ - public final static int MAGE_VERSION_MAJOR = 1; - public final static int MAGE_VERSION_MINOR = 4; - public final static int MAGE_VERSION_PATCH = 4; - public final static String MAGE_VERSION_MINOR_PATCH = "v7"; - public final static String MAGE_VERSION_INFO = ""; - - private final int major; - private final int minor; - private final int patch; - private final String minorPatch; // doesn't matter for compatibility - - private String info = ""; - private static MageVersion currentVersion = new MageVersion(MAGE_VERSION_MAJOR, MAGE_VERSION_MINOR, MAGE_VERSION_PATCH, MAGE_VERSION_MINOR_PATCH, MAGE_VERSION_INFO); - - public MageVersion(int major, int minor, int patch, String minorPatch, String info) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.minorPatch = minorPatch; - this.info = info; - } - - public static MageVersion getCurrent() { - return currentVersion; - } - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getPatch() { - return patch; - } - - public String getMinorPatch() { - return minorPatch; - } - - @Override - public String toString() { - return major + "." + minor + "." + patch + info + minorPatch; - } - - @Override - public int compareTo(MageVersion o) { - if (major != o.major) { - return major - o.major; - } - if (minor != o.minor) { - return minor - o.minor; - } - if (patch != o.patch) { - return patch - o.patch; - } - return info.compareTo(o.info); - } - -} +/* + * 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.utils; + +import java.io.Serializable; + +/** + * + * @author BetaSteward_at_googlemail.com + */ +public class MageVersion implements Serializable, Comparable { + + /** + * + */ + public final static int MAGE_VERSION_MAJOR = 1; + public final static int MAGE_VERSION_MINOR = 4; + public final static int MAGE_VERSION_PATCH = 5; + public final static String MAGE_VERSION_MINOR_PATCH = "v0"; + public final static String MAGE_VERSION_INFO = ""; + + private final int major; + private final int minor; + private final int patch; + private final String minorPatch; // doesn't matter for compatibility + + private String info = ""; + private static MageVersion currentVersion = new MageVersion(MAGE_VERSION_MAJOR, MAGE_VERSION_MINOR, MAGE_VERSION_PATCH, MAGE_VERSION_MINOR_PATCH, MAGE_VERSION_INFO); + + public MageVersion(int major, int minor, int patch, String minorPatch, String info) { + this.major = major; + this.minor = minor; + this.patch = patch; + this.minorPatch = minorPatch; + this.info = info; + } + + public static MageVersion getCurrent() { + return currentVersion; + } + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getPatch() { + return patch; + } + + public String getMinorPatch() { + return minorPatch; + } + + @Override + public String toString() { + return major + "." + minor + "." + patch + info + minorPatch; + } + + @Override + public int compareTo(MageVersion o) { + if (major != o.major) { + return major - o.major; + } + if (minor != o.minor) { + return minor - o.minor; + } + if (patch != o.patch) { + return patch - o.patch; + } + return info.compareTo(o.info); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/Client.java b/Mage.Network/src/main/java/org/mage/network/Client.java index 42f93635f7c..032ecacba34 100644 --- a/Mage.Network/src/main/java/org/mage/network/Client.java +++ b/Mage.Network/src/main/java/org/mage/network/Client.java @@ -19,18 +19,20 @@ import java.util.Set; import java.util.UUID; import javax.net.ssl.SSLException; import mage.cards.decks.DeckCardLists; +import mage.cards.repository.CardInfo; +import mage.cards.repository.ExpansionInfo; import mage.constants.ManaType; import mage.constants.PlayerAction; import mage.game.match.MatchOptions; import mage.game.tournament.TournamentOptions; import mage.interfaces.ServerState; +import mage.players.net.UserData; import mage.remote.Connection; import mage.utils.MageVersion; import mage.view.DraftPickView; import mage.view.RoomView; import mage.view.TableView; import mage.view.TournamentView; -import mage.view.UserDataView; import mage.view.UserView; import org.apache.log4j.Logger; import org.mage.network.handlers.PingMessageHandler; @@ -46,9 +48,9 @@ import org.mage.network.messages.MessageType; * @author BetaSteward */ public class Client { - + private static final Logger logger = Logger.getLogger(Client.class); - + private static final int IDLE_PING_TIME = 30; private static final int IDLE_TIMEOUT = 60; @@ -56,9 +58,9 @@ public class Client { // private final MessageHandler h; private final ClientMessageHandler clientMessageHandler; private final ClientRegisteredMessageHandler clientRegisteredMessageHandler; - + private final ClientExceptionHandler exceptionHandler; - + private SslContext sslCtx; private Channel channel; private String username; @@ -66,18 +68,18 @@ public class Client { private int port; private static final EventLoopGroup group = new NioEventLoopGroup(); - + public Client(MageClient client) { this.client = client; // h = new MessageHandler(); clientMessageHandler = new ClientMessageHandler(client); clientRegisteredMessageHandler = new ClientRegisteredMessageHandler(); - + exceptionHandler = new ClientExceptionHandler(this); } - + public boolean connect(Connection connection, MageVersion version) { - + this.username = connection.getUsername(); this.host = connection.getHost(); this.port = connection.getPort(); @@ -88,21 +90,20 @@ public class Client { } else { sslCtx = null; } - Bootstrap b = new Bootstrap(); - b.group(group) - .channel(NioSocketChannel.class) - .handler(new ClientInitializer()); - + Bootstrap bootstrap = new Bootstrap(); + bootstrap.group(group) + .channel(NioSocketChannel.class) + .handler(new ClientInitializer()); + clientRegisteredMessageHandler.setConnection(connection); clientRegisteredMessageHandler.setVersion(version); - channel = b.connect(host, port).sync().channel(); + channel = bootstrap.connect(host, port).sync().channel(); ServerState state = clientRegisteredMessageHandler.registerClient(); if (state.isValid()) { client.clientRegistered(state); client.connected(connection.getUsername() + "@" + host + ":" + port + " "); return true; - } - else { + } else { disconnect(false); } } catch (SSLException | InterruptedException ex) { @@ -117,13 +118,12 @@ public class Client { @Override public void initChannel(SocketChannel ch) throws Exception { - + if (sslCtx != null) { ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port)); } - ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); + ch.pipeline().addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null))); ch.pipeline().addLast(new ObjectEncoder()); - ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(IDLE_TIMEOUT, IDLE_PING_TIME, 0)); ch.pipeline().addLast("heartbeatHandler", new HeartbeatHandler()); ch.pipeline().addLast("pingMessageHandler", new PingMessageHandler()); @@ -135,27 +135,27 @@ public class Client { ch.pipeline().addLast("exceptionHandler", exceptionHandler); } } - + public void disconnect(boolean error) { - + try { channel.disconnect().sync(); client.disconnected(error); - } - catch (InterruptedException ex) { + } catch (InterruptedException ex) { logger.fatal("Error disconnecting", ex); - } + } // finally { // group.shutdownGracefully(); // } } - + public boolean isConnected() { - if (channel != null) + if (channel != null) { return channel.isActive(); + } return false; } - + public void sendChatMessage(UUID chatId, String message) { clientMessageHandler.sendMessage(chatId, message); } @@ -163,7 +163,7 @@ public class Client { public void joinChat(UUID chatId) { clientMessageHandler.joinChat(chatId); } - + public void leaveChat(UUID chatId) { clientMessageHandler.leaveChat(chatId); } @@ -205,6 +205,24 @@ public class Client { return null; } + public List getMissingCardsData(List cards) { + try { + return clientMessageHandler.getMissingCardsData(cards); + } catch (Exception ex) { + logger.error("Error getting missing card data from server", ex); + } + return null; + } + + public List getMissingExpansionsData(List setCodes) { + try { + return clientMessageHandler.getMissingExpansionData(setCodes); + } catch (Exception ex) { + logger.error("Error getting missing expansion set data", ex); + } + return null; + } + public boolean submitDeck(UUID tableId, DeckCardLists deckCardLists) { try { return clientMessageHandler.submitDeck(tableId, deckCardLists); @@ -280,9 +298,9 @@ public class Client { return null; } - public void setPreferences(UserDataView view) { + public void setPreferences(UserData userData) { try { - clientMessageHandler.setPreferences(view); + clientMessageHandler.setPreferences(userData); } catch (Exception ex) { logger.error("Error updating preferences", ex); } @@ -373,7 +391,7 @@ public class Client { logger.error("Error quitting tournament", ex); } } - + public TournamentView getTournament(UUID tournamentId) { try { return clientMessageHandler.getTournament(tournamentId); diff --git a/Mage.Network/src/main/java/org/mage/network/Server.java b/Mage.Network/src/main/java/org/mage/network/Server.java index 9e53525f92a..b2c5e4a8db3 100644 --- a/Mage.Network/src/main/java/org/mage/network/Server.java +++ b/Mage.Network/src/main/java/org/mage/network/Server.java @@ -81,15 +81,15 @@ import org.mage.network.messages.callback.WatchGameCallback; * @author BetaSteward */ public class Server { - + private static final Logger logger = Logger.getLogger(Server.class); private static final int IDLE_PING_TIME = 30; private static final int IDLE_TIMEOUT = 60; // private static final PingMessage ping = new PingMessage(); - + public static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); - + private SslContext sslCtx; private final MageServer server; @@ -97,34 +97,34 @@ public class Server { private final PingMessageHandler pingMessageHandler = new PingMessageHandler(); private final EventExecutorGroup handlersExecutor = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2); private final ServerRequestHandler serverMessageHandler; - + private final ServerExceptionHandler exceptionHandler; - + public Server(MageServer server) { this.server = server; // h = new MessageHandler(); serverMessageHandler = new ServerRequestHandler(server); exceptionHandler = new ServerExceptionHandler(server); } - + public void start(int port, boolean ssl) throws Exception { - + if (ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } - + EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); - + try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .handler(new LoggingHandler(LogLevel.INFO)) - .childHandler(new ServerInitializer()); + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ServerInitializer()); b.bind(port).sync().channel().closeFuture().sync(); } catch (InterruptedException ex) { @@ -133,22 +133,23 @@ public class Server { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } - + } private class ServerInitializer extends ChannelInitializer { - + @Override public void initChannel(SocketChannel ch) throws Exception { - + if (sslCtx != null) { - ch.pipeline().addLast(sslCtx.newHandler(ch.alloc())); + ch.pipeline().addLast(sslCtx.newHandler(ch.alloc())); } - ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null))); + ch.pipeline().addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null))); ch.pipeline().addLast(new ObjectEncoder()); // ch.pipeline().addLast("h", h); ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(IDLE_TIMEOUT, IDLE_PING_TIME, 0)); + ch.pipeline().addLast(handlersExecutor, "heartbeatHandler", new HeartbeatHandler(server)); ch.pipeline().addLast("pingMessageHandler", pingMessageHandler); @@ -157,10 +158,10 @@ public class Server { ch.pipeline().addLast("exceptionHandler", exceptionHandler); } - } - + } + private Channel findChannel(String sessionId) { - for (Channel channel: clients) { + for (Channel channel : clients) { if (channel.id().asLongText().equals(sessionId)) { return channel; } @@ -170,14 +171,16 @@ public class Server { public void sendChatMessage(String sessionId, UUID chatId, ChatMessage message) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new ChatMessageCallback(chatId, message)).addListener(WriteListener.getInstance()); + } } public void informClient(String sessionId, String title, String message, MessageType type) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new InformClientCallback(title, message, type)).addListener(WriteListener.getInstance()); + } } public void informClients(String title, String message, MessageType type) { @@ -187,183 +190,212 @@ public class Server { public void pingClient(String sessionId) { Channel ch = findChannel(sessionId); if (ch != null) { - HeartbeatHandler heartbeatHandler = (HeartbeatHandler)ch.pipeline().get("heartbeatHandler"); + HeartbeatHandler heartbeatHandler = (HeartbeatHandler) ch.pipeline().get("heartbeatHandler"); heartbeatHandler.pingClient(); } } public void joinedTable(String sessionId, UUID roomId, UUID tableId, UUID chatId, boolean owner, boolean tournament) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new JoinedTableCallback(roomId, tableId, chatId, owner, tournament)).addListener(WriteListener.getInstance()); + } } - + public void gameStarted(String sessionId, UUID gameId, UUID playerId) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameStartedCallback(gameId, playerId)).addListener(WriteListener.getInstance()); + } } public void initGame(String sessionId, UUID gameId, GameView gameView) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameInitCallback(gameId, gameView)).addListener(WriteListener.getInstance()); + } } - + public void gameAsk(String sessionId, UUID gameId, GameView gameView, String question, Map options) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameAskCallback(gameId, gameView, question, options)).addListener(WriteListener.getInstance()); + } } public void gameTarget(String sessionId, UUID gameId, GameView gameView, String question, CardsView cardView, Set targets, boolean required, Map options) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameTargetCallback(gameId, gameView, question, cardView, targets, required, options)).addListener(WriteListener.getInstance()); + } } public void gameSelect(String sessionId, UUID gameId, GameView gameView, String message, Map options) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameSelectCallback(gameId, gameView, message, options)).addListener(WriteListener.getInstance()); + } } public void gameChooseAbility(String sessionId, UUID gameId, AbilityPickerView abilities) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameChooseAbilityCallback(gameId, abilities)).addListener(WriteListener.getInstance()); + } } public void gameChoosePile(String sessionId, UUID gameId, String message, CardsView pile1, CardsView pile2) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameChoosePileCallback(gameId, message, pile1, pile2)).addListener(WriteListener.getInstance()); + } } public void gameChooseChoice(String sessionId, UUID gameId, Choice choice) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameChooseChoiceCallback(gameId, choice)).addListener(WriteListener.getInstance()); + } } public void gamePlayMana(String sessionId, UUID gameId, GameView gameView, String message, Map options) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GamePlayManaCallback(gameId, gameView, message, options)).addListener(WriteListener.getInstance()); + } } public void gamePlayXMana(String sessionId, UUID gameId, GameView gameView, String message) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GamePlayXManaCallback(gameId, gameView, message)).addListener(WriteListener.getInstance()); + } } public void gameSelectAmount(String sessionId, UUID gameId, String message, int min, int max) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameSelectAmountCallback(gameId, message, min, max)).addListener(WriteListener.getInstance()); + } } public void endGameInfo(String sessionId, UUID gameId, GameEndView view) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameEndInfoCallback(gameId, view)).addListener(WriteListener.getInstance()); + } } public void userRequestDialog(String sessionId, UUID gameId, UserRequestMessage userRequestMessage) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new UserRequestDialogCallback(gameId, userRequestMessage)).addListener(WriteListener.getInstance()); + } } public void gameUpdate(String sessionId, UUID gameId, GameView view) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameUpdateCallback(gameId, view)).addListener(WriteListener.getInstance()); + } } public void gameInform(String sessionId, UUID gameId, GameClientMessage message) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameInformCallback(gameId, message)).addListener(WriteListener.getInstance()); + } } public void gameInformPersonal(String sessionId, UUID gameId, GameClientMessage message) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameInformPersonalCallback(gameId, message)).addListener(WriteListener.getInstance()); + } } public void gameOver(String sessionId, UUID gameId, String message) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameOverCallback(gameId, message)).addListener(WriteListener.getInstance()); + } } public void gameError(String sessionId, UUID gameId, String message) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new GameErrorCallback(gameId, message)).addListener(WriteListener.getInstance()); + } } public void startDraft(String sessionId, UUID draftId, UUID playerId) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new StartDraftCallback(draftId, playerId)).addListener(WriteListener.getInstance()); + } } public void draftInit(String sessionId, UUID draftId, DraftPickView draftPickView) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new DraftInitCallback(draftId, draftPickView)).addListener(WriteListener.getInstance()); + } } public void draftUpdate(String sessionId, UUID draftId, DraftView draftView) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new DraftUpdateCallback(draftId, draftView)).addListener(WriteListener.getInstance()); + } } public void draftOver(String sessionId, UUID draftId) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new DraftOverCallback(draftId)).addListener(WriteListener.getInstance()); + } } public void draftPick(String sessionId, UUID draftId, DraftPickView draftPickView) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new DraftPickCallback(draftId, draftPickView)).addListener(WriteListener.getInstance()); + } } - + public void sideboard(String sessionId, UUID tableId, DeckView deck, int time, boolean limited) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new SideboardCallback(tableId, deck, time, limited)).addListener(WriteListener.getInstance()); + } } public void construct(String sessionId, UUID tableId, DeckView deck, int time) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new ConstructCallback(tableId, deck, time)).addListener(WriteListener.getInstance()); + } } public void tournamentStarted(String sessionId, UUID tournamentId, UUID playerId) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new TournamentStartedCallback(tournamentId, playerId)).addListener(WriteListener.getInstance()); + } } public void showTournament(String sessionId, UUID tournamentId) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new ShowTournamentCallback(tournamentId)).addListener(WriteListener.getInstance()); + } } public void watchGame(String sessionId, UUID gameId, UUID chatId, GameView game) { Channel ch = findChannel(sessionId); - if (ch != null) + if (ch != null) { ch.writeAndFlush(new WatchGameCallback(gameId, chatId, game)).addListener(WriteListener.getInstance()); + } } public void replayGame(String sessionId, UUID gameId) { diff --git a/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientMessageHandler.java b/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientMessageHandler.java index 90897f784d4..1b41d79e906 100644 --- a/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientMessageHandler.java +++ b/Mage.Network/src/main/java/org/mage/network/handlers/client/ClientMessageHandler.java @@ -9,15 +9,17 @@ import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import mage.cards.decks.DeckCardLists; +import mage.cards.repository.CardInfo; +import mage.cards.repository.ExpansionInfo; import mage.constants.ManaType; import mage.constants.PlayerAction; import mage.game.match.MatchOptions; import mage.game.tournament.TournamentOptions; +import mage.players.net.UserData; import mage.view.DraftPickView; import mage.view.RoomView; import mage.view.TableView; import mage.view.TournamentView; -import mage.view.UserDataView; import org.mage.network.handlers.WriteListener; import org.mage.network.interfaces.MageClient; import org.mage.network.messages.ClientMessage; @@ -26,7 +28,9 @@ import org.mage.network.messages.requests.ChatRoomIdRequest; import org.mage.network.messages.requests.CheatRequest; import org.mage.network.messages.requests.CreateTableRequest; import org.mage.network.messages.requests.CreateTournamentRequest; +import org.mage.network.messages.requests.GetCardInfoRequest; import org.mage.network.messages.requests.GetCardsRequest; +import org.mage.network.messages.requests.GetExpansionInfoRequest; import org.mage.network.messages.requests.GetRoomRequest; import org.mage.network.messages.requests.GetTournamentChatIdRequest; import org.mage.network.messages.requests.GetTournamentRequest; @@ -68,7 +72,7 @@ import org.mage.network.messages.requests.WatchTournamentTableRequest; * @author BetaSteward */ public class ClientMessageHandler extends SimpleChannelInboundHandler { - + private final MageClient client; private ChannelHandlerContext ctx; private final BlockingQueue booleanQueue = new LinkedBlockingQueue<>(); @@ -78,8 +82,10 @@ public class ClientMessageHandler extends SimpleChannelInboundHandler tournamentViewQueue = new LinkedBlockingQueue<>(); private final BlockingQueue draftPickViewQueue = new LinkedBlockingQueue<>(); private final BlockingQueue> stringListQueue = new LinkedBlockingQueue<>(); + private final BlockingQueue> cardInfoListQueue = new LinkedBlockingQueue<>(); + private final BlockingQueue> expansionInfoListQueue = new LinkedBlockingQueue<>(); - public ClientMessageHandler (MageClient client) { + public ClientMessageHandler(MageClient client) { this.client = client; } @@ -87,13 +93,13 @@ public class ClientMessageHandler extends SimpleChannelInboundHandler getServerMessages() throws Exception { stringListQueue.clear(); ctx.writeAndFlush(new ServerMessagesRequest()).addListener(WriteListener.getInstance()); @@ -106,6 +112,18 @@ public class ClientMessageHandler extends SimpleChannelInboundHandler getMissingCardsData(List cards) throws Exception { + cardInfoListQueue.clear(); + ctx.writeAndFlush(new GetCardInfoRequest(cards)).addListener(WriteListener.getInstance()); + return cardInfoListQueue.take(); + } + + public List getMissingExpansionData(List setCodes) throws Exception { + expansionInfoListQueue.clear(); + ctx.writeAndFlush(new GetExpansionInfoRequest(setCodes)).addListener(WriteListener.getInstance()); + return expansionInfoListQueue.take(); + } + public UUID getChatRoomId(UUID roomId) throws Exception { uuidQueue.clear(); ctx.writeAndFlush(new ChatRoomIdRequest(roomId)).addListener(WriteListener.getInstance()); @@ -129,13 +147,13 @@ public class ClientMessageHandler extends SimpleChannelInboundHandler list) { + cardInfoListQueue.offer(list); + } + + public void receiveExpansionInfoList(List list) { + expansionInfoListQueue.offer(list); + } + public void sendPlayerUUID(UUID gameId, UUID id) { ctx.writeAndFlush(new SendPlayerUUIDRequest(gameId, id)).addListener(WriteListener.getInstance()); } @@ -275,8 +300,8 @@ public class ClientMessageHandler extends SimpleChannelInboundHandler getServerMessages(); + List getCards(); + + List getMissingCardData(List cards); + + List getMissingExpansionData(List setCodes); + RoomView getRoom(UUID roomId); + TableView createTable(String sessionId, UUID roomId, MatchOptions options); + boolean joinTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password); + TableView getTable(UUID roomId, UUID tableId); + boolean leaveTable(String sessionId, UUID roomId, UUID tableId); + void removeTable(String sessionId, UUID roomId, UUID tableId); + void swapSeats(String sessionId, UUID roomId, UUID tableId, int seatNum1, int seatNum2); + boolean joinTournamentTable(String sessionId, UUID roomId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password); - + boolean startMatch(String sessionId, UUID roomId, UUID tableId); + void quitMatch(UUID gameId, String sessionId); + UUID joinGame(UUID gameId, String sessionId); + void sendPlayerUUID(UUID gameId, String sessionId, UUID data); + void sendPlayerString(UUID gameId, String sessionId, String data); + void sendPlayerManaType(UUID gameId, UUID playerId, String sessionId, ManaType data); + void sendPlayerBoolean(UUID gameId, String sessionId, Boolean data); + void sendPlayerInteger(UUID gameId, String sessionId, Integer data); + void sendPlayerAction(PlayerAction playerAction, UUID gameId, String sessionId, Serializable data); - + boolean submitDeck(String sessionId, UUID tableId, DeckCardLists deckList); + void updateDeck(String sessionId, UUID tableId, DeckCardLists deckList); - + boolean joinDraft(UUID draftId, String sessionId); + void quitDraft(UUID draftId, String sessionId); + void markCard(UUID draftId, String sessionId, UUID cardPick); + DraftPickView pickCard(UUID draftId, String sessionId, UUID cardPick, Set hiddenCards); TableView createTournamentTable(String sessionId, UUID roomId, TournamentOptions options); + boolean startTournament(String sessionId, UUID roomId, UUID tableId); + UUID getTournamentChatId(UUID tournamentId); + TournamentView getTournament(UUID tournamentId); + boolean joinTournament(UUID tournamentId, String sessionId); + void quitTournament(UUID tournamentId, String sessionId); void watchTable(String sessionId, UUID roomId, UUID tableId); + void watchTournamentTable(String sessionId, UUID tableId); + void stopWatching(UUID gameId, String sessionId); - + void pingTime(long milliSeconds, String sessionId); - + void cheat(UUID gameId, String sessionId, UUID playerId, DeckCardLists deckList); } diff --git a/Mage.Network/src/main/java/org/mage/network/messages/requests/ChatRoomIdRequest.java b/Mage.Network/src/main/java/org/mage/network/messages/requests/ChatRoomIdRequest.java index d692429ff4d..c428d4f5bc1 100644 --- a/Mage.Network/src/main/java/org/mage/network/messages/requests/ChatRoomIdRequest.java +++ b/Mage.Network/src/main/java/org/mage/network/messages/requests/ChatRoomIdRequest.java @@ -11,9 +11,9 @@ import org.mage.network.messages.responses.UUIDResponse; * @author BetaSteward */ public class ChatRoomIdRequest extends ServerRequest { - - private UUID roomId; - + + private final UUID roomId; + public ChatRoomIdRequest(UUID roomId) { this.roomId = roomId; } diff --git a/Mage.Network/src/main/java/org/mage/network/messages/requests/GetCardInfoRequest.java b/Mage.Network/src/main/java/org/mage/network/messages/requests/GetCardInfoRequest.java new file mode 100644 index 00000000000..9bc4fc38be7 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/messages/requests/GetCardInfoRequest.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.mage.network.messages.requests; + +import io.netty.channel.ChannelHandlerContext; +import java.util.List; +import org.mage.network.handlers.WriteListener; +import org.mage.network.interfaces.MageServer; +import org.mage.network.messages.responses.GetCardInfoResponse; + +/** + * + * @author LevelX2 + */ +public class GetCardInfoRequest extends ServerRequest { + + List cards; + + public GetCardInfoRequest(List cards) { + this.cards = cards; + } + + @Override + public void handleMessage(MageServer server, ChannelHandlerContext ctx) { + ctx.writeAndFlush(new GetCardInfoResponse(server.getMissingCardData(cards))).addListener(WriteListener.getInstance()); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/messages/requests/GetExpansionInfoRequest.java b/Mage.Network/src/main/java/org/mage/network/messages/requests/GetExpansionInfoRequest.java new file mode 100644 index 00000000000..164197d4684 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/messages/requests/GetExpansionInfoRequest.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.mage.network.messages.requests; + +import io.netty.channel.ChannelHandlerContext; +import java.util.List; +import org.mage.network.handlers.WriteListener; +import org.mage.network.interfaces.MageServer; +import org.mage.network.messages.responses.GetExpansionInfoResponse; + +/** + * + * @author LevelX2 + */ +public class GetExpansionInfoRequest extends ServerRequest { + + List setCodes; + + public GetExpansionInfoRequest(List setCodes) { + this.setCodes = setCodes; + } + + @Override + public void handleMessage(MageServer server, ChannelHandlerContext ctx) { + ctx.writeAndFlush(new GetExpansionInfoResponse(server.getMissingExpansionData(setCodes))).addListener(WriteListener.getInstance()); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/messages/requests/SetPreferencesRequest.java b/Mage.Network/src/main/java/org/mage/network/messages/requests/SetPreferencesRequest.java index 7bab283a150..c7ecc29c275 100644 --- a/Mage.Network/src/main/java/org/mage/network/messages/requests/SetPreferencesRequest.java +++ b/Mage.Network/src/main/java/org/mage/network/messages/requests/SetPreferencesRequest.java @@ -1,7 +1,7 @@ package org.mage.network.messages.requests; import io.netty.channel.ChannelHandlerContext; -import mage.view.UserDataView; +import mage.players.net.UserData; import org.mage.network.interfaces.MageServer; /** @@ -9,15 +9,16 @@ import org.mage.network.interfaces.MageServer; * @author BetaSteward */ public class SetPreferencesRequest extends ServerRequest { - private final UserDataView view; - public SetPreferencesRequest(UserDataView view) { - this.view = view; + private final UserData userData; + + public SetPreferencesRequest(UserData userData) { + this.userData = userData; } @Override public void handleMessage(MageServer server, ChannelHandlerContext ctx) { - server.setPreferences(getSessionId(ctx), view); + server.setPreferences(getSessionId(ctx), userData); } - + } diff --git a/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardInfoResponse.java b/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardInfoResponse.java new file mode 100644 index 00000000000..258cfa1a13f --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardInfoResponse.java @@ -0,0 +1,30 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.mage.network.messages.responses; + +import java.util.List; +import mage.cards.repository.CardInfo; +import org.mage.network.handlers.client.ClientMessageHandler; +import org.mage.network.messages.ClientMessage; + +/** + * + * @author LevelX2 + */ +public class GetCardInfoResponse extends ClientMessage { + + private final List cardInfo; + + public GetCardInfoResponse(List cardInfo) { + this.cardInfo = cardInfo; + } + + @Override + public void handleMessage(ClientMessageHandler handler) { + handler.receiveCardInfoList(cardInfo); + } + +} diff --git a/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardsResponse.java b/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardsResponse.java index 7152ccce87b..ea6cfc2ad78 100644 --- a/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardsResponse.java +++ b/Mage.Network/src/main/java/org/mage/network/messages/responses/GetCardsResponse.java @@ -9,16 +9,16 @@ import org.mage.network.messages.ClientMessage; * @author BetaSteward */ public class GetCardsResponse extends ClientMessage { - - private List cards; - + + private final List cards; + public GetCardsResponse(List cards) { this.cards = cards; } - + @Override public void handleMessage(ClientMessageHandler handler) { handler.receiveStringList(cards); } - + } diff --git a/Mage.Network/src/main/java/org/mage/network/messages/responses/GetExpansionInfoResponse.java b/Mage.Network/src/main/java/org/mage/network/messages/responses/GetExpansionInfoResponse.java new file mode 100644 index 00000000000..c29414ac459 --- /dev/null +++ b/Mage.Network/src/main/java/org/mage/network/messages/responses/GetExpansionInfoResponse.java @@ -0,0 +1,30 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.mage.network.messages.responses; + +import java.util.List; +import mage.cards.repository.ExpansionInfo; +import org.mage.network.handlers.client.ClientMessageHandler; +import org.mage.network.messages.ClientMessage; + +/** + * + * @author LevelX2 + */ +public class GetExpansionInfoResponse extends ClientMessage { + + private final List expansionInfo; + + public GetExpansionInfoResponse(List expansionInfo) { + this.expansionInfo = expansionInfo; + } + + @Override + public void handleMessage(ClientMessageHandler handler) { + handler.receiveExpansionInfoList(expansionInfo); + } + +} diff --git a/Mage.Server.Tests/src/test/java/org/mage/server/test/TestClient.java b/Mage.Server.Tests/src/test/java/org/mage/server/test/TestClient.java index 4c632b44f32..81f4aecae66 100644 --- a/Mage.Server.Tests/src/test/java/org/mage/server/test/TestClient.java +++ b/Mage.Server.Tests/src/test/java/org/mage/server/test/TestClient.java @@ -9,6 +9,7 @@ import mage.cards.decks.DeckCardLists; import mage.choices.Choice; import mage.game.match.MatchOptions; import mage.interfaces.ServerState; +import mage.players.net.UserData; import mage.players.net.UserGroup; import mage.players.net.UserSkipPrioritySteps; import mage.remote.Connection; @@ -24,7 +25,6 @@ import mage.view.GameEndView; import mage.view.GameView; import mage.view.RoomView; import mage.view.TableView; -import mage.view.UserDataView; import mage.view.UserRequestMessage; import org.apache.log4j.Logger; import org.mage.network.Client; @@ -38,16 +38,16 @@ import org.mage.network.messages.MessageType; public class TestClient implements MageClient { protected static final Logger logger = Logger.getLogger(TestClient.class); - + private Client client; private ServerState serverState; private String userName; private boolean joinedTableFired = false; - + public TestClient() { client = new Client(this); } - + public boolean connect(String userName) { this.userName = userName; Connection connection = new Connection(); @@ -56,18 +56,18 @@ public class TestClient implements MageClient { connection.setSSL(true); connection.setUsername(userName); connection.setForceDBComparison(false); - connection.setUserData(new UserDataView(UserGroup.PLAYER, 51, false, false, false, new UserSkipPrioritySteps(), "world", false, false, false, false, false, false)); + connection.setUserData(new UserData(UserGroup.PLAYER, 10, false, false, false, new UserSkipPrioritySteps(), "world", false, false, false, false, false, false)); return client.connect(connection, MageVersion.getCurrent()); } - + public void disconnect(boolean error) { client.disconnect(error); } - + public boolean isConnected() { return client.isConnected(); } - + @Override public void connected(String message) { } @@ -86,7 +86,7 @@ public class TestClient implements MageClient { UUID mainRoomId = client.getServerState().getMainRoomId(); client.joinChat(client.getRoomChatId(mainRoomId)); } - + public void sendChatMessage(UUID chatId, String message) { client.sendChatMessage(chatId, message); } @@ -115,7 +115,7 @@ public class TestClient implements MageClient { public void joinedTable(UUID roomId, UUID tableId, UUID chatId, boolean owner, boolean tournament) { joinedTableFired = true; } - + public boolean isJoinedTableFired() { return joinedTableFired; } @@ -188,19 +188,19 @@ public class TestClient implements MageClient { public List getServerMessages() { return client.getServerMessages(); } - + public UUID getMainRoomId() { return serverState.getMainRoomId(); } - + public RoomView getRoom(UUID roomId) { return client.getRoom(roomId); } - + public TableView createTable(UUID roomId, MatchOptions options) { return client.createTable(roomId, options); } - + public boolean joinTable(UUID roomId, UUID tableId, String playerName, String playerType, int skill, DeckCardLists deck, String password) { return client.joinTable(roomId, tableId, playerName, playerType, skill, deck, password); } diff --git a/Mage.Server/src/main/java/mage/server/ServerMain.java b/Mage.Server/src/main/java/mage/server/ServerMain.java index bc93bb64289..f41cd7f8499 100644 --- a/Mage.Server/src/main/java/mage/server/ServerMain.java +++ b/Mage.Server/src/main/java/mage/server/ServerMain.java @@ -1,1247 +1,1242 @@ -/* -* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without modification, are -* permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, this list of -* conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright notice, this list -* of conditions and the following disclaimer in the documentation and/or other materials -* provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR -* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -* The views and conclusions contained in the software and documentation are those of the -* authors and should not be interpreted as representing official policies, either expressed -* or implied, of BetaSteward_at_googlemail.com. -*/ - -package mage.server; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.Serializable; -import java.net.BindException; -import java.net.MalformedURLException; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import mage.cards.decks.DeckCardLists; -import mage.cards.repository.CardRepository; -import mage.cards.repository.CardScanner; -import mage.cards.repository.ExpansionRepository; -import mage.choices.Choice; -import mage.constants.ManaType; -import mage.constants.PlayerAction; -import mage.constants.TableState; -import mage.game.Table; -import mage.game.match.MatchOptions; -import mage.game.match.MatchType; -import mage.game.tournament.TournamentOptions; -import mage.game.tournament.TournamentType; -import mage.interfaces.ServerState; -import mage.remote.Connection; -import mage.remote.DisconnectReason; -import mage.server.draft.CubeFactory; -import mage.server.draft.DraftManager; -import mage.server.game.DeckValidatorFactory; -import mage.server.game.GameFactory; -import mage.server.game.GameManager; -import mage.server.game.GamesRoom; -import mage.server.game.GamesRoomManager; -import mage.server.game.PlayerFactory; -import mage.server.services.LogKeys; -import mage.server.services.impl.FeedbackServiceImpl; -import mage.server.services.impl.LogServiceImpl; -import mage.server.tournament.TournamentFactory; -import mage.server.tournament.TournamentManager; -import mage.server.util.ConfigSettings; -import mage.server.util.PluginClassLoader; -import mage.server.util.ServerMessagesUtil; -import mage.server.util.SystemUtil; -import mage.server.util.config.GamePlugin; -import mage.server.util.config.Plugin; -import mage.utils.MageVersion; -import mage.view.AbilityPickerView; -import mage.view.CardsView; -import mage.view.ChatMessage; -import mage.view.ChatMessage.MessageColor; -import mage.view.DeckView; -import mage.view.DraftPickView; -import mage.view.DraftView; -import mage.view.GameClientMessage; -import mage.view.GameEndView; -import mage.view.GameView; -import mage.view.RoomView; -import mage.view.TableView; -import mage.view.TournamentView; -import mage.view.UserDataView; -import mage.view.UserRequestMessage; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.log4j.Logger; -import org.mage.network.Server; -import org.mage.network.interfaces.MageServer; -import org.mage.network.messages.MessageType; - -/** - * - * @author BetaSteward_at_googlemail.com, noxx - */ -public class ServerMain implements MageServer { - - private static final Logger logger = Logger.getLogger(MageServer.class); -// private static final ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); - private static final MageVersion version = MageVersion.getCurrent(); - - private static final String testModeArg = "-testMode="; - private static final String fastDBModeArg = "-fastDbMode="; - private static final String adminPasswordArg = "-adminPassword="; - private static final String pluginFolder = "plugins"; - - public static final PluginClassLoader classLoader = new PluginClassLoader(); - - private final ServerState state; - private final String password; - private final boolean testMode; - - private static ServerMain instance; - private static Server server; - - public ServerMain(String password, boolean testMode) { - this.password = password; - this.testMode = testMode; - ServerMessagesUtil.getInstance().getMessages(); - state = new ServerState( - GameFactory.getInstance().getGameTypes(), - TournamentFactory.getInstance().getTournamentTypes(), - PlayerFactory.getInstance().getPlayerTypes().toArray(new String[PlayerFactory.getInstance().getPlayerTypes().size()]), - DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[DeckValidatorFactory.getInstance().getDeckTypes().size()]), - CubeFactory.getInstance().getDraftCubes().toArray(new String[CubeFactory.getInstance().getDraftCubes().size()]), - testMode, - ServerMain.getVersion(), - CardRepository.instance.getContentVersionConstant(), - ExpansionRepository.instance.getContentVersionConstant(), - GamesRoomManager.getInstance().getMainRoomId() - ); - } - - public static void main(String[] args) { - System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); - logger.info("Starting MAGE server version " + version); - logger.info("Logging level: " + logger.getEffectiveLevel()); - - String adminPassword = ""; - boolean testMode = false; - boolean fastDbMode = false; - - for (String arg: args) { - if (arg.startsWith(testModeArg)) { - testMode = Boolean.valueOf(arg.replace(testModeArg, "")); - } - else if (arg.startsWith(adminPasswordArg)) { - adminPassword = arg.replace(adminPasswordArg, ""); - adminPassword = SystemUtil.sanitize(adminPassword); - } - else if (arg.startsWith(fastDBModeArg)) { - fastDbMode = Boolean.valueOf(arg.replace(fastDBModeArg, "")); - } - } - - logger.info("Loading cards..."); - if (fastDbMode) { - CardScanner.scanned = true; - } else { - CardScanner.scan(); - } - logger.info("Done."); - - deleteSavedGames(); - ConfigSettings config = ConfigSettings.getInstance(); - for (GamePlugin plugin: config.getGameTypes()) { - GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin)); - } - for (GamePlugin plugin: config.getTournamentTypes()) { - TournamentFactory.getInstance().addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin)); - } - for (Plugin plugin: config.getPlayerTypes()) { - PlayerFactory.getInstance().addPlayerType(plugin.getName(), loadPlugin(plugin)); - } - for (Plugin plugin: config.getDraftCubes()) { - CubeFactory.getInstance().addDraftCube(plugin.getName(), loadPlugin(plugin)); - } - for (Plugin plugin: config.getDeckTypes()) { - DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin)); - } - - logger.info("Config - max seconds idle: " + config.getMaxSecondsIdle()); - logger.info("Config - max game threads: " + config.getMaxGameThreads()); - logger.info("Config - max AI opponents: " + config.getMaxAiOpponents()); - logger.info("Config - min user name l.: " + config.getMinUserNameLength()); - logger.info("Config - max user name l.: " + config.getMaxUserNameLength()); - logger.info("Config - save game active: " + (config.isSaveGameActivated() ? "True":"false")); - - try { - instance = new ServerMain(adminPassword, testMode); - server = new Server(instance); - server.start(config.getPort(), config.isUseSSL()); - } - catch (BindException ex) { - logger.fatal("Failed to start server - " + config.getServerName() + " : check that another server is not already running", ex); - } - catch (Exception ex) { - logger.fatal("Failed to start server - " + config.getServerName(), ex); - } - - } - - public static ServerMain getInstance() { - return instance; - } - - @Override - public boolean registerClient(final Connection connection, final String sessionId, final MageVersion version, final String host) { - if (version.compareTo(ServerMain.getVersion()) != 0) { - logger.info("MageVersionException: userName=" + connection.getUsername() + ", version=" + version); - LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, connection.getUsername(), version.toString(), ServerMain.getVersion().toString(), sessionId); - String message = "Wrong client version " + version + ", expecting version " + ServerMain.getVersion() + ". \r\n\r\nPlease download needed version from http://XMage.de or http://www.slightlymagic.net/forum/viewforum.php?f=70"; - server.informClient(sessionId, "Wrong version", message, MessageType.ERROR); - return false; - } - return SessionManager.getInstance().registerUser(sessionId, connection, host); - } - - @Override - public void setPreferences(final String sessionId, final UserDataView userDataView) { - SessionManager.getInstance().setUserData(sessionId, userDataView); - } -// -// @Override -// public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException { -// try { -// if (version.compareTo(Main.getVersion()) != 0) { -// throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); -// } -// if (!password.equals(this.password)) { -// throw new MageException("Wrong password"); -// } -// return SessionManager.getInstance().registerAdmin(sessionId); -// } catch (Exception ex) { -// handleException(ex); -// } -// return false; -// } -// - @Override - public TableView createTable(final String sessionId, final UUID roomId, final MatchOptions options) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options); - if (logger.isDebugEnabled()) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - logger.debug("TABLE created - tableId: " + table.getTableId() + " " + table.getTableName()); - logger.debug("- " + user.getName() + " userId: " + user.getId()); - logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); - } - } - LogServiceImpl.instance.log(LogKeys.KEY_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); - return table; - } - - @Override - public TableView createTournamentTable(final String sessionId, final UUID roomId, final TournamentOptions options) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - // check AI players max - String maxAiOpponents = ConfigSettings.getInstance().getMaxAiOpponents(); - if (maxAiOpponents != null) { - int max = Integer.parseInt(maxAiOpponents); - int aiPlayers = 0; - for (String playerType : options.getPlayerTypes()) { - if (!playerType.equals("Human")) { - aiPlayers++; - } - } - if (aiPlayers > max) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - user.showUserMessage("Create tournament", "It's only allowed to use a maximum of " + max + " AI players."); - } - return null; - } - } - TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(userId, options); - logger.debug("Tournament table " + table.getTableId() + " created"); - LogServiceImpl.instance.log(LogKeys.KEY_TOURNAMENT_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); - return table; - } - - @Override - public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } - - @Override - public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - logger.debug(name + " joins tableId: " + tableId); - if (userId == null) { - logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); - return false; - } - boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); - return ret; - } - - @Override - public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - if (logger.isTraceEnabled()) { - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - logger.trace("join tourn. tableId: " + tableId + " " + name); - } - } - if (userId == null) { - logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); - return false; - } - boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); - return ret; - } - - @Override - public boolean submitDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList); - if (ret) - logger.debug("Session " + sessionId + " submitted deck"); - return ret; - } - - @Override - public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().updateDeck(userId, tableId, deckList); - logger.trace("Session " + sessionId + " updated deck"); - } - - @Override - public RoomView getRoom(UUID roomId) { - GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); - if (room != null) { - return room.getRoomView(); - } else { - return null; - } - } -// -// @Override -// //FIXME: why no sessionId here??? -// public List getFinishedMatches(UUID roomId) throws MageException { -// try { -// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); -// if (room != null) { -// return room.getFinished(); -// } else { -// return null; -// } -// } -// catch (Exception ex) { -// handleException(ex); -// } -// return null; -// } -// -// @Override -// public List getRoomUsers(UUID roomId) throws MageException { -// try { -// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); -// if (room != null) { -// return room.getRoomUsersInfo(); -// } else { -// return null; -// } -// } -// catch (Exception ex) { -// handleException(ex); -// } -// return null; -// } - - @Override - public TableView getTable(UUID roomId, UUID tableId) { - GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); - if (room != null) { - return room.getTable(tableId); - } else { - return null; - } - } - -// @Override -// public boolean ping(String sessionId, String pingInfo) { -// return SessionManager.getInstance().extendUserSession(sessionId, pingInfo); -// } - - public void pingClient(String sessionId) { - server.pingClient(sessionId); - } - - @Override - public void pingTime(long milliSeconds, String sessionId) { - SessionManager.getInstance().recordPingTime(sessionId, milliSeconds); - } - -// -// @Override -// public void deregisterClient(final String sessionId) throws MageException { -// execute("deregisterClient", sessionId, new Action() { -// @Override -// public void execute() { -// SessionManager.getInstance().disconnect(sessionId, true); -// logger.debug("Client deregistered ..."); -// } -// }); -// } -// - @Override - public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) { - if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { - return false; - } - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startMatch(userId, roomId, tableId); - return true; - } -// -// @Override -// public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException { -// execute("startChallenge", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId); -// } -// }); -// } - - @Override - public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) { - if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { - return false; - } - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startTournament(userId, roomId, tableId); - return true; - } - - @Override - public TournamentView getTournament(UUID tournamentId) { - return TournamentManager.getInstance().getTournamentView(tournamentId); - } - -// @Override -// //FIXME: why no sessionId here??? -// public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { -// try { -// callExecutor.execute( -// new Runnable() { -// @Override -// public void run() { -// ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); -// } -// } -// ); -// } -// catch (Exception ex) { -// handleException(ex); -// } -// } - - @Override - public void receiveChatMessage(final UUID chatId, final String sessionId, final String message) { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) - ChatManager.getInstance().broadcast(chatId, user, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); - } - - public void sendChatMessage(String sessionId, UUID chatId, ChatMessage message) { - server.sendChatMessage(sessionId, chatId, message); - } - - @Override - public void joinChat(final UUID chatId, final String sessionId) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) - ChatManager.getInstance().joinChat(chatId, session.getUserId()); - } - - @Override - public void leaveChat(final UUID chatId, final String sessionId) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) - ChatManager.getInstance().leaveChat(chatId, session.getUserId()); - } - -// @Override -// //FIXME: why no sessionId here??? -// public UUID getMainRoomId() throws MageException { -// try { -// return GamesRoomManager.getInstance().getMainRoomId(); -// } -// catch (Exception ex) { -// handleException(ex); -// } -// return null; -// } -// - @Override - public UUID getRoomChatId(UUID roomId) { - return GamesRoomManager.getInstance().getRoom(roomId).getChatId(); - } -// -// @Override -// public boolean isTableOwner(final String sessionId, UUID roomId, final UUID tableId) throws MageException { -// return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() { -// @Override -// public Boolean execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// return TableManager.getInstance().isTableOwner(tableId, userId); -// } -// }); -// } - - @Override - public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); - } - - @Override - public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) { - TableState tableState = TableManager.getInstance().getController(tableId).getTableState(); - if (!tableState.equals(TableState.WAITING) && !tableState.equals(TableState.READY_TO_START)) { - // table was already started, so player can't leave anymore now - return false; - } - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); - return true; - } -// -// @Override -// //FIXME: why no sessionId here??? -// public UUID getTableChatId(UUID tableId) throws MageException { -// try { -// return TableManager.getInstance().getChatId(tableId); -// } -// catch (Exception ex) { -// handleException(ex); -// } -// return null; -// } - - @Override - public UUID joinGame(final UUID gameId, final String sessionId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().joinGame(gameId, userId); - return GameManager.getInstance().getChatId(gameId); - } - - @Override - public boolean joinDraft(final UUID draftId, final String sessionId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - DraftManager.getInstance().joinDraft(draftId, userId); - return true; - } - - @Override - public boolean joinTournament(final UUID tournamentId, final String sessionId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TournamentManager.getInstance().joinTournament(tournamentId, userId); - return true; - } - -// @Override -// //FIXME: why no sessionId here??? -// public UUID getGameChatId(UUID gameId) throws MageException { -// try { -// return GameManager.getInstance().getChatId(gameId); -// } -// catch (Exception ex) { -// handleException(ex); -// } -// return null; -// } - - @Override - public UUID getTournamentChatId(UUID tournamentId) { - return TournamentManager.getInstance().getChatId(tournamentId); - } - - @Override - public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { -// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); - user.sendPlayerUUID(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - - @Override - public void sendPlayerString(final UUID gameId, final String sessionId, final String data) { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerString(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - - @Override - public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerManaType(gameId, playerId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - - @Override - public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerBoolean(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - - @Override - public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerInteger(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } - } - - @Override - public DraftPickView pickCard(final UUID draftId, final String sessionId, final UUID cardPick, final Set hiddenCards) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - return DraftManager.getInstance().sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); - } - return null; - } - - @Override - public void markCard(final UUID draftId, final String sessionId, final UUID cardPick) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); - } - } - - @Override - public void quitMatch(final UUID gameId, final String sessionId) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - GameManager.getInstance().quitMatch(gameId, session.getUserId()); - } else{ - logger.error("Session not found sessionId: "+ sessionId + " gameId:" +gameId); - } - } - - @Override - public void quitTournament(final UUID tournamentId, final String sessionId) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - }else{ - logger.error("Session not found sessionId: "+ sessionId + " tournamentId:" + tournamentId); - } - } - - @Override - public void quitDraft(final UUID draftId, final String sessionId) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: "+ sessionId + " draftId:" + draftId); - return; - } - UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); - Table table = TableManager.getInstance().getTable(tableId); - if (table.isTournament()) { - UUID tournamentId = table.getTournament().getId(); - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - } - } - - @Override - public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Serializable data) { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: "+ sessionId + " gameId:" + gameId); - return; - } - GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); - } - - @Override - public void watchTable(final String sessionId, final UUID roomId, final UUID tableId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId); - } - - @Override - public void watchTournamentTable(final String sessionId, final UUID tableId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().watchTable(userId, tableId); - } - - - @Override - public void stopWatching(final UUID gameId, final String sessionId) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - GameManager.getInstance().stopWatching(gameId, userId); - user.removeGameWatchInfo(gameId); - } - - } - -// @Override -// public void replayGame(final UUID gameId, final String sessionId) throws MageException { -// execute("replayGame", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// ReplayManager.getInstance().replayGame(gameId, userId); -// } -// }); -// } -// -// @Override -// public void startReplay(final UUID gameId, final String sessionId) throws MageException { -// execute("startReplay", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// ReplayManager.getInstance().startReplay(gameId, userId); -// } -// }); -// } -// -// @Override -// public void stopReplay(final UUID gameId, final String sessionId) throws MageException { -// execute("stopReplay", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// ReplayManager.getInstance().stopReplay(gameId, userId); -// } -// }); -// } -// -// @Override -// public void nextPlay(final UUID gameId, final String sessionId) throws MageException { -// execute("nextPlay", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// ReplayManager.getInstance().nextPlay(gameId, userId); -// } -// }); -// } -// -// @Override -// public void previousPlay(final UUID gameId, final String sessionId) throws MageException { -// execute("previousPlay", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// ReplayManager.getInstance().previousPlay(gameId, userId); -// } -// }); -// } -// -// @Override -// public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { -// execute("skipForward", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// ReplayManager.getInstance().skipForward(gameId, userId, moves); -// } -// }); -// } -// - @Override - public ServerState getServerState() { - return state; - } - - @Override - public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) { - if (testMode) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().cheat(gameId, userId, playerId, deckList); - } - } - -// @Override -// public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException { -// return executeWithResult("cheatOne", sessionId, new ActionWithBooleanResult() { -// @Override -// public Boolean execute() { -// if (testMode) { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// return GameManager.getInstance().cheat(gameId, userId, playerId, cardName); -// } -// return false; -// } -// }); -// } - - -// @Override -// public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) throws MageException { -// return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { -// @Override -// public GameView execute() throws MageException { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// return GameManager.getInstance().getGameView(gameId, userId, playerId); -// } -// }); -// } - -// /** -// * Get user data for admin console -// * -// * @param sessionId -// * @return -// * @throws MageException -// */ -// @Override -// public List getUsers(String sessionId) throws MageException { -// return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult>() { -// @Override -// public List execute() throws MageException { -// List users = new ArrayList<>(); -// for (User user : UserManager.getInstance().getUsers()) { -// -// users.add(new UserView(user.getName(), user.getHost(), user.getSessionId(), user.getConnectionTime(), user.getGameInfo())); -// } -// return users; -// } -// }, true); -// } -// - - @Override - public void disconnect(String sessionId, DisconnectReason reason) { - SessionManager.getInstance().disconnect(sessionId, reason); - } - -// @Override -// public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { -// execute("disconnectUser", sessionId, new Action() { -// @Override -// public void execute() { -// SessionManager.getInstance().disconnectUser(sessionId, userSessionId); -// } -// }); -// } -// -// @Override -// public void endUserSession(final String sessionId, final String userSessionId) throws MageException { -// execute("endUserSession", sessionId, new Action() { -// @Override -// public void execute() { -// SessionManager.getInstance().endUserSession(sessionId, userSessionId); -// } -// }); -// } - -// /** -// * Admin console - Remove table -// * -// * @param sessionId -// * @param tableId -// * @throws MageException -// */ -// @Override -// public void removeTable(final String sessionId, final UUID tableId) throws MageException { -// execute("removeTable", sessionId, new Action() { -// @Override -// public void execute() { -// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); -// TableManager.getInstance().removeTable(userId, tableId); -// } -// }); -// } -// - - @Override - public List getCards() { - return CardRepository.instance.getClassNames(); - } - - @Override - public List getServerMessages() { - return ServerMessagesUtil.getInstance().getMessages(); - } - -// @Override -// public Object getServerMessagesCompressed(String sessionId) throws MageException { -// return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { -// @Override -// public Object execute() throws MageException { -// return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); -// } -// }); -// } - - @Override - public void sendFeedbackMessage(final String sessionId, final String title, final String type, final String message, final String email) { - if (title != null && message != null) { - Session session = SessionManager.getInstance().getSession(sessionId); - String host = session.getHost(); - String username = UserManager.getInstance().getUser(session.getUserId()).getName(); - FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); - LogServiceImpl.instance.log(LogKeys.KEY_FEEDBACK_ADDED, sessionId, username, host); - } - } - -// @Override -// public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { -// if (message != null) { -// execute("sendBroadcastMessage", sessionId, new Action() { -// @Override -// public void execute() { -// for (User user : UserManager.getInstance().getUsers()) { -// if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { -// user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); -// } else { -// user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); -// } -// } -// } -// }, true); -// } -// } - - @Override - public void receiveBroadcastMessage(String title, String message, String sessionId) { - if (SessionManager.getInstance().isAdmin(sessionId)) { - if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { - server.informClients(title, message, MessageType.WARNING); - } else { - server.informClients(title, message, MessageType.INFORMATION); - } - } - } - - public void informClient(String sessionId, String title, String message, MessageType type) { - server.informClient(sessionId, title, message, type); - } - -// protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { -// if (checkAdminRights) { -// if (!SessionManager.getInstance().isAdmin(sessionId)) { -// LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); -// return; -// } -// } -// execute(actionName, sessionId, action); -// } -// -// protected void execute(final String actionName, final String sessionId, final Action action) { -// if (SessionManager.getInstance().isValidSession(sessionId)) { -// try { -// callExecutor.execute( -// new Runnable() { -// @Override -// public void run() { -// if (SessionManager.getInstance().isValidSession(sessionId)) { -// try { -// action.execute(); -// } catch (MageException me) { -// throw new RuntimeException(me); -// } -// } else { -// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId); -// } -// } -// } -// ); -// } -// catch (Exception ex) { -// handleException(sessionId, ex); -// } -// } else { -// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); -// } -// } - -// protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action, boolean checkAdminRights) throws MageException { -// if (checkAdminRights) { -// if (!SessionManager.getInstance().isAdmin(sessionId)) { -// LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); -// return action.negativeResult(); -// } -// } -// return executeWithResult(actionName, sessionId, action); -// } - - //TODO: also run in threads with future task -// protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action) throws MageException { -// if (SessionManager.getInstance().isValidSession(sessionId)) { -// try { -// return action.execute(); -// } catch (Exception ex) { -// handleException(ex); -// } -// } else { -// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); -// } -// return action.negativeResult(); -// } - -// @Override -// public List getMissingExpansionData(List codes) { -// List result = new ArrayList<>(); -// for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) { -// if (!codes.contains(expansionInfo.getCode())) { -// result.add(expansionInfo); -// } -// } -// return result; -// } -// -// @Override -// public List getMissingCardsData(List classNames) { -// return CardRepository.instance.getMissingCards(classNames); -// } - - private static Class loadPlugin(Plugin plugin) { - try { - classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); - logger.debug("Loading plugin: " + plugin.getClassName()); - return Class.forName(plugin.getClassName(), true, classLoader); - } catch (ClassNotFoundException ex) { - logger.warn(new StringBuilder("Plugin not Found: ").append(plugin.getClassName()).append(" - ").append(plugin.getJar()).append(" - check plugin folder"), ex); - } catch (MalformedURLException ex) { - logger.fatal("Error loading plugin " + plugin.getJar(), ex); - } - return null; - } - - private static MatchType loadGameType(GamePlugin plugin) { - try { - classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); - logger.debug("Loading game type: " + plugin.getClassName()); - return (MatchType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance(); - } catch (ClassNotFoundException ex) { - logger.warn("Game type not found:" + plugin.getJar() + " - check plugin folder", ex); - } catch (MalformedURLException | InstantiationException | IllegalAccessException ex) { - logger.fatal("Error loading game type " + plugin.getJar(), ex); - } - return null; - } - - private static TournamentType loadTournamentType(GamePlugin plugin) { - try { - classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); - logger.debug("Loading tournament type: " + plugin.getClassName()); - return (TournamentType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance(); - } catch (ClassNotFoundException ex) { - logger.warn("Tournament type not found:" + plugin.getName() + " / "+ plugin.getJar() + " - check plugin folder", ex); - } catch (MalformedURLException | InstantiationException | IllegalAccessException ex) { - logger.fatal("Error loading game type " + plugin.getJar(), ex); - } - return null; - } - - private static void deleteSavedGames() { - File directory = new File("saved/"); - if (!directory.exists()) { - directory.mkdirs(); - } - File[] files = directory.listFiles( - new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".game"); - } - } - ); - for (File file : files) - { - file.delete(); - } - } - - public static MageVersion getVersion() { - return version; - } - - public boolean isTestMode() { - return testMode; - } - - public void joinedTable(String sessionId, UUID roomId, UUID tableId, UUID chatId, boolean owner, boolean tournament) { - server.joinedTable(sessionId, roomId, tableId, chatId, owner, tournament); - } - - public void gameStarted(String sessionId, UUID gameId, UUID playerId) { - server.gameStarted(sessionId, gameId, playerId); - } - - public void initGame(String sessionId, UUID gameId, GameView gameView) { - server.initGame(sessionId, gameId, gameView); - } - - public void gameAsk(String sessionId, UUID gameId, GameView gameView, String question, Map options) { - server.gameAsk(sessionId, gameId, gameView, question, options); - } - - public void gameTarget(String sessionId, UUID gameId, GameView gameView, String question, CardsView cardView, Set targets, boolean required, Map options) { - server.gameTarget(sessionId, gameId, gameView, question, cardView, targets, required, options); - } - - public void gameSelect(String sessionId, UUID gameId, GameView gameView, String message, Map options) { - server.gameSelect(sessionId, gameId, gameView, message, options); - } - - public void gameChooseAbility(String sessionId, UUID gameId, AbilityPickerView abilities) { - server.gameChooseAbility(sessionId, gameId, abilities); - } - - public void gameChoosePile(String sessionId, UUID gameId, String message, CardsView pile1, CardsView pile2) { - server.gameChoosePile(sessionId, gameId, message, pile1, pile2); - } - - public void gameChooseChoice(String sessionId, UUID gameId, Choice choice) { - server.gameChooseChoice(sessionId, gameId, choice); - } - - public void gamePlayMana(String sessionId, UUID gameId, GameView gameView, String message, Map options) { - server.gamePlayMana(sessionId, gameId, gameView, message, options); - } - - public void gamePlayXMana(String sessionId, UUID gameId, GameView gameView, String message) { - server.gamePlayXMana(sessionId, gameId, gameView, message); - } - - public void gameSelectAmount(String sessionId, UUID gameId, String message, int min, int max) { - server.gameSelectAmount(sessionId, gameId, message, min, max); - } - - public void endGameInfo(String sessionId, UUID gameId, GameEndView view) { - server.endGameInfo(sessionId, gameId, view); - } - - public void userRequestDialog(String sessionId, UUID gameId, UserRequestMessage userRequestMessage) { - server.userRequestDialog(sessionId, gameId, userRequestMessage); - } - - public void gameUpdate(String sessionId, UUID gameId, GameView view) { - server.gameUpdate(sessionId, gameId, view); - } - - public void gameInform(String sessionId, UUID gameId, GameClientMessage message) { - server.gameInform(sessionId, gameId, message); - } - - public void gameInformPersonal(String sessionId, UUID gameId, GameClientMessage message) { - server.gameInformPersonal(sessionId, gameId, message); - } - - public void gameOver(String sessionId, UUID gameId, String message) { - server.gameOver(sessionId, gameId, message); - } - - public void gameError(String sessionId, UUID gameId, String message) { - server.gameError(sessionId, gameId, message); - } - - public void startDraft(String sessionId, UUID draftId, UUID playerId) { - server.startDraft(sessionId, draftId, playerId); - } - - public void draftInit(String sessionId, UUID draftId, DraftPickView draftPickView) { - server.draftInit(sessionId, draftId, draftPickView); - } - - public void draftUpdate(String sessionId, UUID draftId, DraftView draftView) { - server.draftUpdate(sessionId, draftId, draftView); - } - - public void draftOver(String sessionId, UUID draftId) { - server.draftOver(sessionId, draftId); - } - - public void draftPick(String sessionId, UUID draftId, DraftPickView draftPickView) { - server.draftPick(sessionId, draftId, draftPickView); - } - - public void sideboard(String sessionId, UUID tableId, DeckView deck, int time, boolean limited) { - server.sideboard(sessionId, tableId, deck, time, limited); - } - - public void construct(String sessionId, UUID tableId, DeckView deck, int time) { - server.construct(sessionId, tableId, deck, time); - } - - public void tournamentStarted(String sessionId, UUID tournamentId, UUID playerId) { - server.tournamentStarted(sessionId, tournamentId, playerId); - } - - public void showTournament(String sessionId, UUID tournamentId) { - server.showTournament(sessionId, tournamentId); - } - - public void watchGame(String sessionId, UUID gameId, UUID chatId, GameView game) { - server.watchGame(sessionId, gameId, chatId, game); - } - - public void replayGame(String sessionId, UUID gameId) { - server.replayGame(sessionId, gameId); - } - - public void replayInit(String sessionId, UUID gameId, GameView gameView) { - server.replayInit(sessionId, gameId, gameView); - } - - public void replayDone(String sessionId, UUID gameId, String result) { - server.replayDone(sessionId, gameId, result); - } - - public void replayUpdate(String sessionId, UUID gameId, GameView gameView) { - server.replayUpdate(sessionId, gameId, gameView); - } - -} +/* + * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of BetaSteward_at_googlemail.com. + */ +package mage.server; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.Serializable; +import java.net.BindException; +import java.net.MalformedURLException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import mage.cards.decks.DeckCardLists; +import mage.cards.repository.CardInfo; +import mage.cards.repository.CardRepository; +import mage.cards.repository.CardScanner; +import mage.cards.repository.ExpansionInfo; +import mage.cards.repository.ExpansionRepository; +import mage.choices.Choice; +import mage.constants.ManaType; +import mage.constants.PlayerAction; +import mage.constants.TableState; +import mage.game.Table; +import mage.game.match.MatchOptions; +import mage.game.match.MatchType; +import mage.game.tournament.TournamentOptions; +import mage.game.tournament.TournamentType; +import mage.interfaces.ServerState; +import mage.players.net.UserData; +import mage.remote.Connection; +import mage.remote.DisconnectReason; +import mage.server.draft.CubeFactory; +import mage.server.draft.DraftManager; +import mage.server.game.DeckValidatorFactory; +import mage.server.game.GameFactory; +import mage.server.game.GameManager; +import mage.server.game.GamesRoom; +import mage.server.game.GamesRoomManager; +import mage.server.game.PlayerFactory; +import mage.server.services.LogKeys; +import mage.server.services.impl.FeedbackServiceImpl; +import mage.server.services.impl.LogServiceImpl; +import mage.server.tournament.TournamentFactory; +import mage.server.tournament.TournamentManager; +import mage.server.util.ConfigSettings; +import mage.server.util.PluginClassLoader; +import mage.server.util.ServerMessagesUtil; +import mage.server.util.SystemUtil; +import mage.server.util.config.GamePlugin; +import mage.server.util.config.Plugin; +import mage.utils.MageVersion; +import mage.view.AbilityPickerView; +import mage.view.CardsView; +import mage.view.ChatMessage; +import mage.view.ChatMessage.MessageColor; +import mage.view.DeckView; +import mage.view.DraftPickView; +import mage.view.DraftView; +import mage.view.GameClientMessage; +import mage.view.GameEndView; +import mage.view.GameView; +import mage.view.RoomView; +import mage.view.TableView; +import mage.view.TournamentView; +import mage.view.UserRequestMessage; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.log4j.Logger; +import org.mage.network.Server; +import org.mage.network.interfaces.MageServer; +import org.mage.network.messages.MessageType; + +/** + * + * @author BetaSteward_at_googlemail.com, noxx + */ +public class ServerMain implements MageServer { + + private static final Logger logger = Logger.getLogger(MageServer.class); +// private static final ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor(); + private static final MageVersion version = MageVersion.getCurrent(); + + private static final String testModeArg = "-testMode="; + private static final String fastDBModeArg = "-fastDbMode="; + private static final String adminPasswordArg = "-adminPassword="; + private static final String pluginFolder = "plugins"; + + public static final PluginClassLoader classLoader = new PluginClassLoader(); + + private final ServerState state; + private final String password; + private final boolean testMode; + + private static ServerMain instance; + private static Server server; + + public ServerMain(String password, boolean testMode) { + this.password = password; + this.testMode = testMode; + ServerMessagesUtil.getInstance().getMessages(); + state = new ServerState( + GameFactory.getInstance().getGameTypes(), + TournamentFactory.getInstance().getTournamentTypes(), + PlayerFactory.getInstance().getPlayerTypes().toArray(new String[PlayerFactory.getInstance().getPlayerTypes().size()]), + DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[DeckValidatorFactory.getInstance().getDeckTypes().size()]), + CubeFactory.getInstance().getDraftCubes().toArray(new String[CubeFactory.getInstance().getDraftCubes().size()]), + testMode, + ServerMain.getVersion(), + CardRepository.instance.getContentVersionConstant(), + ExpansionRepository.instance.getContentVersionConstant(), + GamesRoomManager.getInstance().getMainRoomId() + ); + } + + public static void main(String[] args) { + System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); + logger.info("Starting MAGE server version " + version); + logger.info("Logging level: " + logger.getEffectiveLevel()); + + String adminPassword = ""; + boolean testMode = false; + boolean fastDbMode = false; + + for (String arg : args) { + if (arg.startsWith(testModeArg)) { + testMode = Boolean.valueOf(arg.replace(testModeArg, "")); + } else if (arg.startsWith(adminPasswordArg)) { + adminPassword = arg.replace(adminPasswordArg, ""); + adminPassword = SystemUtil.sanitize(adminPassword); + } else if (arg.startsWith(fastDBModeArg)) { + fastDbMode = Boolean.valueOf(arg.replace(fastDBModeArg, "")); + } + } + + logger.info("Loading cards..."); + if (fastDbMode) { + CardScanner.scanned = true; + } else { + CardScanner.scan(); + } + logger.info("Done."); + + deleteSavedGames(); + ConfigSettings config = ConfigSettings.getInstance(); + for (GamePlugin plugin : config.getGameTypes()) { + GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin)); + } + for (GamePlugin plugin : config.getTournamentTypes()) { + TournamentFactory.getInstance().addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin)); + } + for (Plugin plugin : config.getPlayerTypes()) { + PlayerFactory.getInstance().addPlayerType(plugin.getName(), loadPlugin(plugin)); + } + for (Plugin plugin : config.getDraftCubes()) { + CubeFactory.getInstance().addDraftCube(plugin.getName(), loadPlugin(plugin)); + } + for (Plugin plugin : config.getDeckTypes()) { + DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin)); + } + + logger.info("Config - max seconds idle: " + config.getMaxSecondsIdle()); + logger.info("Config - max game threads: " + config.getMaxGameThreads()); + logger.info("Config - max AI opponents: " + config.getMaxAiOpponents()); + logger.info("Config - min user name l.: " + config.getMinUserNameLength()); + logger.info("Config - max user name l.: " + config.getMaxUserNameLength()); + logger.info("Config - save game active: " + (config.isSaveGameActivated() ? "True" : "false")); + + try { + instance = new ServerMain(adminPassword, testMode); + server = new Server(instance); + server.start(config.getPort(), config.isUseSSL()); + } catch (BindException ex) { + logger.fatal("Failed to start server - " + config.getServerName() + " : check that another server is not already running", ex); + } catch (Exception ex) { + logger.fatal("Failed to start server - " + config.getServerName(), ex); + } + + } + + public static ServerMain getInstance() { + return instance; + } + + @Override + public boolean registerClient(final Connection connection, final String sessionId, final MageVersion version, final String host) { + if (version.compareTo(ServerMain.getVersion()) != 0) { + logger.info("MageVersionException: userName=" + connection.getUsername() + ", version=" + version); + LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, connection.getUsername(), version.toString(), ServerMain.getVersion().toString(), sessionId); + String message = "Wrong client version " + version + ", expecting version " + ServerMain.getVersion() + ". \r\n\r\nPlease download needed version from http://XMage.de or http://www.slightlymagic.net/forum/viewforum.php?f=70"; + server.informClient(sessionId, "Wrong version", message, MessageType.ERROR); + return false; + } + return SessionManager.getInstance().registerUser(sessionId, connection, host); + } + + @Override + public void setPreferences(final String sessionId, final UserData userData) { + SessionManager.getInstance().setUserData(sessionId, userData); + } +// +// @Override +// public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException { +// try { +// if (version.compareTo(Main.getVersion()) != 0) { +// throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion()); +// } +// if (!password.equals(this.password)) { +// throw new MageException("Wrong password"); +// } +// return SessionManager.getInstance().registerAdmin(sessionId); +// } catch (Exception ex) { +// handleException(ex); +// } +// return false; +// } +// + + @Override + public TableView createTable(final String sessionId, final UUID roomId, final MatchOptions options) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options); + if (logger.isDebugEnabled()) { + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + logger.debug("TABLE created - tableId: " + table.getTableId() + " " + table.getTableName()); + logger.debug("- " + user.getName() + " userId: " + user.getId()); + logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); + } + } + LogServiceImpl.instance.log(LogKeys.KEY_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); + return table; + } + + @Override + public TableView createTournamentTable(final String sessionId, final UUID roomId, final TournamentOptions options) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + // check AI players max + String maxAiOpponents = ConfigSettings.getInstance().getMaxAiOpponents(); + if (maxAiOpponents != null) { + int max = Integer.parseInt(maxAiOpponents); + int aiPlayers = 0; + for (String playerType : options.getPlayerTypes()) { + if (!playerType.equals("Human")) { + aiPlayers++; + } + } + if (aiPlayers > max) { + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + user.showUserMessage("Create tournament", "It's only allowed to use a maximum of " + max + " AI players."); + } + return null; + } + } + TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(userId, options); + logger.debug("Tournament table " + table.getTableId() + " created"); + LogServiceImpl.instance.log(LogKeys.KEY_TOURNAMENT_TABLE_CREATED, sessionId, userId.toString(), table.getTableId().toString()); + return table; + } + + @Override + public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); + } + + @Override + public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + logger.debug(name + " joins tableId: " + tableId); + if (userId == null) { + logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); + return false; + } + boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); + return ret; + } + + @Override + public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList, final String password) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + if (logger.isTraceEnabled()) { + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + logger.trace("join tourn. tableId: " + tableId + " " + name); + } + } + if (userId == null) { + logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); + return false; + } + boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); + return ret; + } + + @Override + public boolean submitDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList); + if (ret) { + logger.debug("Session " + sessionId + " submitted deck"); + } + return ret; + } + + @Override + public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().updateDeck(userId, tableId, deckList); + logger.trace("Session " + sessionId + " updated deck"); + } + + @Override + public RoomView getRoom(UUID roomId) { + GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); + if (room != null) { + return room.getRoomView(); + } else { + return null; + } + } +// +// @Override +// //FIXME: why no sessionId here??? +// public List getFinishedMatches(UUID roomId) throws MageException { +// try { +// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); +// if (room != null) { +// return room.getFinished(); +// } else { +// return null; +// } +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// +// @Override +// public List getRoomUsers(UUID roomId) throws MageException { +// try { +// GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); +// if (room != null) { +// return room.getRoomUsersInfo(); +// } else { +// return null; +// } +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } + + @Override + public TableView getTable(UUID roomId, UUID tableId) { + GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); + if (room != null) { + return room.getTable(tableId); + } else { + return null; + } + } + +// @Override +// public boolean ping(String sessionId, String pingInfo) { +// return SessionManager.getInstance().extendUserSession(sessionId, pingInfo); +// } + public void pingClient(String sessionId) { + server.pingClient(sessionId); + } + + @Override + public void pingTime(long milliSeconds, String sessionId) { + SessionManager.getInstance().recordPingTime(sessionId, milliSeconds); + } + +// +// @Override +// public void deregisterClient(final String sessionId) throws MageException { +// execute("deregisterClient", sessionId, new Action() { +// @Override +// public void execute() { +// SessionManager.getInstance().disconnect(sessionId, true); +// logger.debug("Client deregistered ..."); +// } +// }); +// } +// + @Override + public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) { + if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { + return false; + } + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startMatch(userId, roomId, tableId); + return true; + } +// +// @Override +// public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException { +// execute("startChallenge", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId); +// } +// }); +// } + + @Override + public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) { + if (!TableManager.getInstance().getController(tableId).changeTableState(TableState.STARTING)) { + return false; + } + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startTournament(userId, roomId, tableId); + return true; + } + + @Override + public TournamentView getTournament(UUID tournamentId) { + return TournamentManager.getInstance().getTournamentView(tournamentId); + } + +// @Override +// //FIXME: why no sessionId here??? +// public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { +// try { +// callExecutor.execute( +// new Runnable() { +// @Override +// public void run() { +// ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); +// } +// } +// ); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// } + @Override + public void receiveChatMessage(final UUID chatId, final String sessionId, final String message) { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + ChatManager.getInstance().broadcast(chatId, user, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE); + } + } + + public void sendChatMessage(String sessionId, UUID chatId, ChatMessage message) { + server.sendChatMessage(sessionId, chatId, message); + } + + @Override + public void joinChat(final UUID chatId, final String sessionId) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + ChatManager.getInstance().joinChat(chatId, session.getUserId()); + } + } + + @Override + public void leaveChat(final UUID chatId, final String sessionId) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + ChatManager.getInstance().leaveChat(chatId, session.getUserId()); + } + } + +// @Override +// //FIXME: why no sessionId here??? +// public UUID getMainRoomId() throws MageException { +// try { +// return GamesRoomManager.getInstance().getMainRoomId(); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } +// + @Override + public UUID getRoomChatId(UUID roomId) { + return GamesRoomManager.getInstance().getRoom(roomId).getChatId(); + } +// +// @Override +// public boolean isTableOwner(final String sessionId, UUID roomId, final UUID tableId) throws MageException { +// return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return TableManager.getInstance().isTableOwner(tableId, userId); +// } +// }); +// } + + @Override + public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); + } + + @Override + public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) { + TableState tableState = TableManager.getInstance().getController(tableId).getTableState(); + if (!tableState.equals(TableState.WAITING) && !tableState.equals(TableState.READY_TO_START)) { + // table was already started, so player can't leave anymore now + return false; + } + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); + return true; + } +// +// @Override +// //FIXME: why no sessionId here??? +// public UUID getTableChatId(UUID tableId) throws MageException { +// try { +// return TableManager.getInstance().getChatId(tableId); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } + + @Override + public UUID joinGame(final UUID gameId, final String sessionId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().joinGame(gameId, userId); + return GameManager.getInstance().getChatId(gameId); + } + + @Override + public boolean joinDraft(final UUID draftId, final String sessionId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + DraftManager.getInstance().joinDraft(draftId, userId); + return true; + } + + @Override + public boolean joinTournament(final UUID tournamentId, final String sessionId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TournamentManager.getInstance().joinTournament(tournamentId, userId); + return true; + } + +// @Override +// //FIXME: why no sessionId here??? +// public UUID getGameChatId(UUID gameId) throws MageException { +// try { +// return GameManager.getInstance().getChatId(gameId); +// } +// catch (Exception ex) { +// handleException(ex); +// } +// return null; +// } + @Override + public UUID getTournamentChatId(UUID tournamentId) { + return TournamentManager.getInstance().getChatId(tournamentId); + } + + @Override + public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { +// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); + user.sendPlayerUUID(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); + } + } + + @Override + public void sendPlayerString(final UUID gameId, final String sessionId, final String data) { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerString(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); + } + } + + @Override + public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerManaType(gameId, playerId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); + } + } + + @Override + public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerBoolean(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); + } + } + + @Override + public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerInteger(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); + } + } + + @Override + public DraftPickView pickCard(final UUID draftId, final String sessionId, final UUID cardPick, final Set hiddenCards) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + return DraftManager.getInstance().sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); + } else { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); + } + return null; + } + + @Override + public void markCard(final UUID draftId, final String sessionId, final UUID cardPick) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); + } else { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); + } + } + + @Override + public void quitMatch(final UUID gameId, final String sessionId) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + GameManager.getInstance().quitMatch(gameId, session.getUserId()); + } else { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); + } + } + + @Override + public void quitTournament(final UUID tournamentId, final String sessionId) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + TournamentManager.getInstance().quit(tournamentId, session.getUserId()); + } else { + logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); + } + } + + @Override + public void quitDraft(final UUID draftId, final String sessionId) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session == null) { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); + return; + } + UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); + Table table = TableManager.getInstance().getTable(tableId); + if (table.isTournament()) { + UUID tournamentId = table.getTournament().getId(); + TournamentManager.getInstance().quit(tournamentId, session.getUserId()); + } + } + + @Override + public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Serializable data) { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session == null) { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); + return; + } + GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); + } + + @Override + public void watchTable(final String sessionId, final UUID roomId, final UUID tableId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId); + } + + @Override + public void watchTournamentTable(final String sessionId, final UUID tableId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().watchTable(userId, tableId); + } + + @Override + public void stopWatching(final UUID gameId, final String sessionId) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + GameManager.getInstance().stopWatching(gameId, userId); + user.removeGameWatchInfo(gameId); + } + + } + +// @Override +// public void replayGame(final UUID gameId, final String sessionId) throws MageException { +// execute("replayGame", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().replayGame(gameId, userId); +// } +// }); +// } +// +// @Override +// public void startReplay(final UUID gameId, final String sessionId) throws MageException { +// execute("startReplay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().startReplay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void stopReplay(final UUID gameId, final String sessionId) throws MageException { +// execute("stopReplay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().stopReplay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void nextPlay(final UUID gameId, final String sessionId) throws MageException { +// execute("nextPlay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().nextPlay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void previousPlay(final UUID gameId, final String sessionId) throws MageException { +// execute("previousPlay", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().previousPlay(gameId, userId); +// } +// }); +// } +// +// @Override +// public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { +// execute("skipForward", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// ReplayManager.getInstance().skipForward(gameId, userId, moves); +// } +// }); +// } +// + @Override + public ServerState getServerState() { + return state; + } + + @Override + public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) { + if (testMode) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().cheat(gameId, userId, playerId, deckList); + } + } + +// @Override +// public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException { +// return executeWithResult("cheatOne", sessionId, new ActionWithBooleanResult() { +// @Override +// public Boolean execute() { +// if (testMode) { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return GameManager.getInstance().cheat(gameId, userId, playerId, cardName); +// } +// return false; +// } +// }); +// } +// @Override +// public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) throws MageException { +// return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { +// @Override +// public GameView execute() throws MageException { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// return GameManager.getInstance().getGameView(gameId, userId, playerId); +// } +// }); +// } +// /** +// * Get user data for admin console +// * +// * @param sessionId +// * @return +// * @throws MageException +// */ +// @Override +// public List getUsers(String sessionId) throws MageException { +// return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult>() { +// @Override +// public List execute() throws MageException { +// List users = new ArrayList<>(); +// for (User user : UserManager.getInstance().getUsers()) { +// +// users.add(new UserView(user.getName(), user.getHost(), user.getSessionId(), user.getConnectionTime(), user.getGameInfo())); +// } +// return users; +// } +// }, true); +// } +// + @Override + public void disconnect(String sessionId, DisconnectReason reason) { + SessionManager.getInstance().disconnect(sessionId, reason); + } + +// @Override +// public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { +// execute("disconnectUser", sessionId, new Action() { +// @Override +// public void execute() { +// SessionManager.getInstance().disconnectUser(sessionId, userSessionId); +// } +// }); +// } +// +// @Override +// public void endUserSession(final String sessionId, final String userSessionId) throws MageException { +// execute("endUserSession", sessionId, new Action() { +// @Override +// public void execute() { +// SessionManager.getInstance().endUserSession(sessionId, userSessionId); +// } +// }); +// } +// /** +// * Admin console - Remove table +// * +// * @param sessionId +// * @param tableId +// * @throws MageException +// */ +// @Override +// public void removeTable(final String sessionId, final UUID tableId) throws MageException { +// execute("removeTable", sessionId, new Action() { +// @Override +// public void execute() { +// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); +// TableManager.getInstance().removeTable(userId, tableId); +// } +// }); +// } +// + @Override + public List getCards() { + return CardRepository.instance.getClassNames(); + } + + @Override + public List getMissingCardData(List cards) { + return CardRepository.instance.getMissingCards(cards); + } + + @Override + public List getMissingExpansionData(List setCodes) { + return ExpansionRepository.instance.getMissingExpansions(setCodes); + } + + @Override + public List getServerMessages() { + return ServerMessagesUtil.getInstance().getMessages(); + } + +// @Override +// public Object getServerMessagesCompressed(String sessionId) throws MageException { +// return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult() { +// @Override +// public Object execute() throws MageException { +// return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); +// } +// }); +// } + @Override + public void sendFeedbackMessage(final String sessionId, final String title, final String type, final String message, final String email) { + if (title != null && message != null) { + Session session = SessionManager.getInstance().getSession(sessionId); + String host = session.getHost(); + String username = UserManager.getInstance().getUser(session.getUserId()).getName(); + FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); + LogServiceImpl.instance.log(LogKeys.KEY_FEEDBACK_ADDED, sessionId, username, host); + } + } + +// @Override +// public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { +// if (message != null) { +// execute("sendBroadcastMessage", sessionId, new Action() { +// @Override +// public void execute() { +// for (User user : UserManager.getInstance().getUsers()) { +// if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { +// user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); +// } else { +// user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); +// } +// } +// } +// }, true); +// } +// } + @Override + public void receiveBroadcastMessage(String title, String message, String sessionId) { + if (SessionManager.getInstance().isAdmin(sessionId)) { + if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { + server.informClients(title, message, MessageType.WARNING); + } else { + server.informClients(title, message, MessageType.INFORMATION); + } + } + } + + public void informClient(String sessionId, String title, String message, MessageType type) { + server.informClient(sessionId, title, message, type); + } + +// protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { +// if (checkAdminRights) { +// if (!SessionManager.getInstance().isAdmin(sessionId)) { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); +// return; +// } +// } +// execute(actionName, sessionId, action); +// } +// +// protected void execute(final String actionName, final String sessionId, final Action action) { +// if (SessionManager.getInstance().isValidSession(sessionId)) { +// try { +// callExecutor.execute( +// new Runnable() { +// @Override +// public void run() { +// if (SessionManager.getInstance().isValidSession(sessionId)) { +// try { +// action.execute(); +// } catch (MageException me) { +// throw new RuntimeException(me); +// } +// } else { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId); +// } +// } +// } +// ); +// } +// catch (Exception ex) { +// handleException(sessionId, ex); +// } +// } else { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); +// } +// } +// protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action, boolean checkAdminRights) throws MageException { +// if (checkAdminRights) { +// if (!SessionManager.getInstance().isAdmin(sessionId)) { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_ADMIN, actionName, sessionId); +// return action.negativeResult(); +// } +// } +// return executeWithResult(actionName, sessionId, action); +// } + //TODO: also run in threads with future task +// protected T executeWithResult(String actionName, final String sessionId, final ActionWithResult action) throws MageException { +// if (SessionManager.getInstance().isValidSession(sessionId)) { +// try { +// return action.execute(); +// } catch (Exception ex) { +// handleException(ex); +// } +// } else { +// LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId); +// } +// return action.negativeResult(); +// } +// @Override +// public List getMissingExpansionData(List codes) { +// List result = new ArrayList<>(); +// for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) { +// if (!codes.contains(expansionInfo.getCode())) { +// result.add(expansionInfo); +// } +// } +// return result; +// } +// +// @Override +// public List getMissingCardsData(List classNames) { +// return CardRepository.instance.getMissingCards(classNames); +// } + private static Class loadPlugin(Plugin plugin) { + try { + classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); + logger.debug("Loading plugin: " + plugin.getClassName()); + return Class.forName(plugin.getClassName(), true, classLoader); + } catch (ClassNotFoundException ex) { + logger.warn(new StringBuilder("Plugin not Found: ").append(plugin.getClassName()).append(" - ").append(plugin.getJar()).append(" - check plugin folder"), ex); + } catch (MalformedURLException ex) { + logger.fatal("Error loading plugin " + plugin.getJar(), ex); + } + return null; + } + + private static MatchType loadGameType(GamePlugin plugin) { + try { + classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); + logger.debug("Loading game type: " + plugin.getClassName()); + return (MatchType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance(); + } catch (ClassNotFoundException ex) { + logger.warn("Game type not found:" + plugin.getJar() + " - check plugin folder", ex); + } catch (MalformedURLException | InstantiationException | IllegalAccessException ex) { + logger.fatal("Error loading game type " + plugin.getJar(), ex); + } + return null; + } + + private static TournamentType loadTournamentType(GamePlugin plugin) { + try { + classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL()); + logger.debug("Loading tournament type: " + plugin.getClassName()); + return (TournamentType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance(); + } catch (ClassNotFoundException ex) { + logger.warn("Tournament type not found:" + plugin.getName() + " / " + plugin.getJar() + " - check plugin folder", ex); + } catch (MalformedURLException | InstantiationException | IllegalAccessException ex) { + logger.fatal("Error loading game type " + plugin.getJar(), ex); + } + return null; + } + + private static void deleteSavedGames() { + File directory = new File("saved/"); + if (!directory.exists()) { + directory.mkdirs(); + } + File[] files = directory.listFiles( + new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith(".game"); + } + } + ); + for (File file : files) { + file.delete(); + } + } + + public static MageVersion getVersion() { + return version; + } + + public boolean isTestMode() { + return testMode; + } + + public void joinedTable(String sessionId, UUID roomId, UUID tableId, UUID chatId, boolean owner, boolean tournament) { + server.joinedTable(sessionId, roomId, tableId, chatId, owner, tournament); + } + + public void gameStarted(String sessionId, UUID gameId, UUID playerId) { + server.gameStarted(sessionId, gameId, playerId); + } + + public void initGame(String sessionId, UUID gameId, GameView gameView) { + server.initGame(sessionId, gameId, gameView); + } + + public void gameAsk(String sessionId, UUID gameId, GameView gameView, String question, Map options) { + server.gameAsk(sessionId, gameId, gameView, question, options); + } + + public void gameTarget(String sessionId, UUID gameId, GameView gameView, String question, CardsView cardView, Set targets, boolean required, Map options) { + server.gameTarget(sessionId, gameId, gameView, question, cardView, targets, required, options); + } + + public void gameSelect(String sessionId, UUID gameId, GameView gameView, String message, Map options) { + server.gameSelect(sessionId, gameId, gameView, message, options); + } + + public void gameChooseAbility(String sessionId, UUID gameId, AbilityPickerView abilities) { + server.gameChooseAbility(sessionId, gameId, abilities); + } + + public void gameChoosePile(String sessionId, UUID gameId, String message, CardsView pile1, CardsView pile2) { + server.gameChoosePile(sessionId, gameId, message, pile1, pile2); + } + + public void gameChooseChoice(String sessionId, UUID gameId, Choice choice) { + server.gameChooseChoice(sessionId, gameId, choice); + } + + public void gamePlayMana(String sessionId, UUID gameId, GameView gameView, String message, Map options) { + server.gamePlayMana(sessionId, gameId, gameView, message, options); + } + + public void gamePlayXMana(String sessionId, UUID gameId, GameView gameView, String message) { + server.gamePlayXMana(sessionId, gameId, gameView, message); + } + + public void gameSelectAmount(String sessionId, UUID gameId, String message, int min, int max) { + server.gameSelectAmount(sessionId, gameId, message, min, max); + } + + public void endGameInfo(String sessionId, UUID gameId, GameEndView view) { + server.endGameInfo(sessionId, gameId, view); + } + + public void userRequestDialog(String sessionId, UUID gameId, UserRequestMessage userRequestMessage) { + server.userRequestDialog(sessionId, gameId, userRequestMessage); + } + + public void gameUpdate(String sessionId, UUID gameId, GameView view) { + server.gameUpdate(sessionId, gameId, view); + } + + public void gameInform(String sessionId, UUID gameId, GameClientMessage message) { + server.gameInform(sessionId, gameId, message); + } + + public void gameInformPersonal(String sessionId, UUID gameId, GameClientMessage message) { + server.gameInformPersonal(sessionId, gameId, message); + } + + public void gameOver(String sessionId, UUID gameId, String message) { + server.gameOver(sessionId, gameId, message); + } + + public void gameError(String sessionId, UUID gameId, String message) { + server.gameError(sessionId, gameId, message); + } + + public void startDraft(String sessionId, UUID draftId, UUID playerId) { + server.startDraft(sessionId, draftId, playerId); + } + + public void draftInit(String sessionId, UUID draftId, DraftPickView draftPickView) { + server.draftInit(sessionId, draftId, draftPickView); + } + + public void draftUpdate(String sessionId, UUID draftId, DraftView draftView) { + server.draftUpdate(sessionId, draftId, draftView); + } + + public void draftOver(String sessionId, UUID draftId) { + server.draftOver(sessionId, draftId); + } + + public void draftPick(String sessionId, UUID draftId, DraftPickView draftPickView) { + server.draftPick(sessionId, draftId, draftPickView); + } + + public void sideboard(String sessionId, UUID tableId, DeckView deck, int time, boolean limited) { + server.sideboard(sessionId, tableId, deck, time, limited); + } + + public void construct(String sessionId, UUID tableId, DeckView deck, int time) { + server.construct(sessionId, tableId, deck, time); + } + + public void tournamentStarted(String sessionId, UUID tournamentId, UUID playerId) { + server.tournamentStarted(sessionId, tournamentId, playerId); + } + + public void showTournament(String sessionId, UUID tournamentId) { + server.showTournament(sessionId, tournamentId); + } + + public void watchGame(String sessionId, UUID gameId, UUID chatId, GameView game) { + server.watchGame(sessionId, gameId, chatId, game); + } + + public void replayGame(String sessionId, UUID gameId) { + server.replayGame(sessionId, gameId); + } + + public void replayInit(String sessionId, UUID gameId, GameView gameView) { + server.replayInit(sessionId, gameId, gameView); + } + + public void replayDone(String sessionId, UUID gameId, String result) { + server.replayDone(sessionId, gameId, result); + } + + public void replayUpdate(String sessionId, UUID gameId, GameView gameView) { + server.replayUpdate(sessionId, gameId, gameView); + } + +} diff --git a/Mage.Server/src/main/java/mage/server/Session.java b/Mage.Server/src/main/java/mage/server/Session.java index d0c2a512807..0d5a2c1da62 100644 --- a/Mage.Server/src/main/java/mage/server/Session.java +++ b/Mage.Server/src/main/java/mage/server/Session.java @@ -43,7 +43,6 @@ import mage.remote.Connection; import mage.remote.DisconnectReason; import mage.server.game.GamesRoomManager; import mage.server.util.ConfigSettings; -import mage.view.UserDataView; import org.apache.log4j.Logger; /** @@ -155,17 +154,9 @@ public class Session { this.userId = user.getId(); } - public boolean setUserData(User user, UserDataView userDataView) { + public boolean setUserData(User user, UserData userData) { if (user != null) { - UserData userData = user.getUserData(); if (user.getUserData() == null || user.getUserData().getGroupId() == UserGroup.DEFAULT.getGroupId()) { - userData = new UserData(UserGroup.PLAYER, userDataView.getAvatarId(), - userDataView.isShowAbilityPickerForced(), userDataView.isAllowRequestShowHandCards(), - userDataView.confirmEmptyManaPool(), userDataView.getUserSkipPrioritySteps(), - userDataView.getFlagName(), userDataView.askMoveToGraveOrder(), - userDataView.isManaPoolAutomatic(), userDataView.isAllowRequestShowHandCards(), - userDataView.isPassPriorityCast(), userDataView.isPassPriorityActivation(), - userDataView.isAutoOrderTrigger()); user.setUserData(userData); } else { user.getUserData().update(userData); diff --git a/Mage.Server/src/main/java/mage/server/SessionManager.java b/Mage.Server/src/main/java/mage/server/SessionManager.java index 91fbcab25f1..6ee89237d81 100644 --- a/Mage.Server/src/main/java/mage/server/SessionManager.java +++ b/Mage.Server/src/main/java/mage/server/SessionManager.java @@ -27,14 +27,14 @@ */ package mage.server; -import mage.remote.DisconnectReason; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import mage.players.net.UserData; import mage.remote.Connection; +import mage.remote.DisconnectReason; import mage.server.services.LogKeys; import mage.server.services.impl.LogServiceImpl; -import mage.view.UserDataView; import org.apache.log4j.Logger; import org.mage.network.messages.MessageType; @@ -70,18 +70,18 @@ public class SessionManager { Session session = new Session(sessionId); sessions.put(sessionId, session); session.setHost(host); - String returnMessage = session.registerUser(connection); - if (returnMessage == null) { - LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, connection.getUsername(), session.getHost(), sessionId); + String returnMessage = session.registerUser(connection); + if (returnMessage == null) { + LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, connection.getUsername(), session.getHost(), sessionId); - logger.info(connection.getUsername() + " joined server"); - logger.debug("- userId: " + session.getUserId()); - logger.debug("- sessionId: " + sessionId); - logger.debug("- host: " + session.getHost()); - return true; - } - logger.debug(connection.getUsername() + " not registered: " + returnMessage); - ServerMain.getInstance().informClient(sessionId, "Connection Error", returnMessage, MessageType.ERROR); + logger.info(connection.getUsername() + " joined server"); + logger.debug("- userId: " + session.getUserId()); + logger.debug("- sessionId: " + sessionId); + logger.debug("- host: " + session.getHost()); + return true; + } + logger.debug(connection.getUsername() + " not registered: " + returnMessage); + ServerMain.getInstance().informClient(sessionId, "Connection Error", returnMessage, MessageType.ERROR); return false; } @@ -96,10 +96,10 @@ public class SessionManager { return false; } - public boolean setUserData(String sessionId, UserDataView userDataView) { + public boolean setUserData(String sessionId, UserData userData) { Session session = sessions.get(sessionId); if (session != null) { - session.setUserData(UserManager.getInstance().getUser(session.getUserId()), userDataView); + session.setUserData(UserManager.getInstance().getUser(session.getUserId()), userData); return true; } return false; diff --git a/Mage/src/mage/cards/repository/CardInfo.java b/Mage/src/mage/cards/repository/CardInfo.java index 901ab028540..13b9d129ec2 100644 --- a/Mage/src/mage/cards/repository/CardInfo.java +++ b/Mage/src/mage/cards/repository/CardInfo.java @@ -1,329 +1,327 @@ -/* - * 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.cards.repository; - -import com.j256.ormlite.field.DataType; -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import mage.constants.CardType; -import mage.constants.Rarity; -import mage.ObjectColor; -import mage.abilities.SpellAbility; -import mage.cards.Card; -import mage.cards.CardImpl; -import mage.cards.mock.MockCard; -import mage.cards.mock.MockSplitCard; -import mage.constants.SpellAbilityType; -import org.apache.log4j.Logger; - -/** - * - * @author North - */ -@DatabaseTable(tableName = "card") -public class CardInfo { - - private static final int MAX_RULE_LENGTH = 700; - - private static final String SEPARATOR = "@@@"; - @DatabaseField(indexName = "name_index") - protected String name; - @DatabaseField(indexName = "setCode_cardNumber_index") - protected int cardNumber; - @DatabaseField(indexName = "setCode_cardNumber_index") - protected String setCode; - @DatabaseField(unique = true, indexName = "className_index") - protected String className; - @DatabaseField - protected String power; - @DatabaseField - protected String toughness; - @DatabaseField - protected int convertedManaCost; - @DatabaseField(dataType = DataType.ENUM_STRING) - protected Rarity rarity; - @DatabaseField - protected String types; - @DatabaseField - protected String subtypes; - @DatabaseField - protected String supertypes; - @DatabaseField - protected String manaCosts; - @DatabaseField(dataType = DataType.STRING, width = MAX_RULE_LENGTH) - protected String rules; - @DatabaseField - protected boolean black; - @DatabaseField - protected boolean blue; - @DatabaseField - protected boolean green; - @DatabaseField - protected boolean red; - @DatabaseField - protected boolean white; - @DatabaseField - protected boolean splitCard; - @DatabaseField - protected boolean splitCardHalf; - @DatabaseField - protected boolean flipCard; - @DatabaseField - protected boolean doubleFaced; - @DatabaseField(indexName = "name_index") - protected boolean nightCard; - @DatabaseField - protected String flipCardName; - @DatabaseField - protected String secondSideName; - - public CardInfo() { - } - - public CardInfo(Card card) { - this.name = card.getName(); - this.cardNumber = card.getCardNumber(); - this.setCode = card.getExpansionSetCode(); - this.className = card.getClass().getCanonicalName(); - this.power = card.getPower().toString(); - this.toughness = card.getToughness().toString(); - this.convertedManaCost = card.getManaCost().convertedManaCost(); - this.rarity = card.getRarity(); - this.splitCard = card.isSplitCard(); - - this.flipCard = card.isFlipCard(); - this.flipCardName = card.getFlipCardName(); - - this.doubleFaced = card.canTransform() && card.getSecondCardFace() != null; - this.nightCard = card.isNightCard(); - Card secondSide = card.getSecondCardFace(); - if (secondSide != null) { - this.secondSideName = secondSide.getName(); - } - - this.blue = card.getColor(null).isBlue(); - this.black = card.getColor(null).isBlack(); - this.green = card.getColor(null).isGreen(); - this.red = card.getColor(null).isRed(); - this.white = card.getColor(null).isWhite(); - - this.setTypes(card.getCardType()); - this.setSubtypes(card.getSubtype()); - this.setSuperTypes(card.getSupertype()); - this.setManaCosts(card.getManaCost().getSymbols()); - - int length = 0; - for (String rule :card.getRules()) { - length += rule.length(); - } - if (length > MAX_RULE_LENGTH) { - length = 0; - ArrayList shortRules = new ArrayList<>(); - for (String rule :card.getRules()) { - if (length + rule.length() + 3 <= MAX_RULE_LENGTH) { - shortRules.add(rule); - length += rule.length() + 3; - } else { - shortRules.add(rule.substring(0, MAX_RULE_LENGTH - (length + 3))); - break; - } - } - Logger.getLogger(CardInfo.class).warn("Card rule text was cut - cardname: " + card.getName()); - this.setRules(shortRules); - } else { - this.setRules(card.getRules()); - } - - SpellAbility spellAbility = card.getSpellAbility(); - if (spellAbility != null) { - SpellAbilityType spellAbilityType = spellAbility.getSpellAbilityType(); - if (spellAbilityType == SpellAbilityType.SPLIT_LEFT || spellAbilityType == SpellAbilityType.SPLIT_RIGHT) { - this.className = this.setCode + "." + this.name; - this.splitCardHalf = true; - } - } - } - - public Card getCard() { - return CardImpl.createCard(className); - } - - public Card getMockCard() { - if (this.splitCard) { - return new MockSplitCard(this); - } else { - return new MockCard(this); - } - } - - public boolean usesVariousArt() { - return Character.isDigit(className.charAt(className.length() - 1)); - } - - public ObjectColor getColor() { - ObjectColor color = new ObjectColor(); - color.setBlack(black); - color.setBlue(blue); - color.setGreen(green); - color.setRed(red); - color.setWhite(white); - return color; - } - - private String joinList(List items) { - StringBuilder sb = new StringBuilder(); - for (Object item : items) { - sb.append(item.toString()).append(SEPARATOR); - } - return sb.toString(); - } - - private List parseList(String list) { - if (list.isEmpty()) { - return new ArrayList<>(); - } - return Arrays.asList(list.split(SEPARATOR)); - } - - public final List getTypes() { - ArrayList list = new ArrayList<>(); - for (String type : this.types.split(SEPARATOR)) { - try { - list.add(CardType.valueOf(type)); - } catch (IllegalArgumentException e) { - } - } - return list; - } - - public final void setTypes(List types) { - StringBuilder sb = new StringBuilder(); - for (CardType item : types) { - sb.append(item.name()).append(SEPARATOR); - } - this.types = sb.toString(); - } - - public int getConvertedManaCost() { - return convertedManaCost; - } - - public final List getManaCosts() { - return parseList(manaCosts); - } - - public final void setManaCosts(List manaCosts) { - this.manaCosts = joinList(manaCosts); - } - - public String getName() { - return name; - } - - public String getPower() { - return power; - } - - public Rarity getRarity() { - return rarity; - } - - public final List getRules() { - return parseList(rules); - } - - public final void setRules(List rules) { - this.rules = joinList(rules); - } - - public final List getSubTypes() { - return parseList(subtypes); - } - - public final void setSubtypes(List subtypes) { - this.subtypes = joinList(subtypes); - } - - public final List getSupertypes() { - return parseList(supertypes); - } - - public final void setSuperTypes(List superTypes) { - this.supertypes = joinList(superTypes); - } - - public String getToughness() { - return toughness; - } - - public String getSetCode() { - return setCode; - } - - public String getClassName() { - return className; - } - - public int getCardNumber() { - return cardNumber; - } - - public boolean isSplitCard() { - return splitCard; - } - - public boolean isSplitCardHalf() { - return splitCardHalf; - } - - public boolean isFlipCard() { - return flipCard; - } - - public String getFlipCardName() { - return flipCardName; - } - - public boolean isDoubleFaced() { - return doubleFaced; - } - - public boolean isNightCard() { - return nightCard; - } - - public String getSecondSideName() { - return secondSideName; - } -} +/* + * 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.cards.repository; + +import com.j256.ormlite.field.DataType; +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import mage.ObjectColor; +import mage.abilities.SpellAbility; +import mage.cards.Card; +import mage.cards.CardImpl; +import mage.cards.mock.MockCard; +import mage.cards.mock.MockSplitCard; +import mage.constants.CardType; +import mage.constants.Rarity; +import mage.constants.SpellAbilityType; +import org.apache.log4j.Logger; + +/** + * + * @author North + */ +@DatabaseTable(tableName = "card") +public class CardInfo implements Serializable { + + private static final int MAX_RULE_LENGTH = 700; + + private static final String SEPARATOR = "@@@"; + @DatabaseField(indexName = "name_index") + protected String name; + @DatabaseField(indexName = "setCode_cardNumber_index") + protected int cardNumber; + @DatabaseField(indexName = "setCode_cardNumber_index") + protected String setCode; + @DatabaseField(unique = true, indexName = "className_index") + protected String className; + @DatabaseField + protected String power; + @DatabaseField + protected String toughness; + @DatabaseField + protected int convertedManaCost; + @DatabaseField(dataType = DataType.ENUM_STRING) + protected Rarity rarity; + @DatabaseField + protected String types; + @DatabaseField + protected String subtypes; + @DatabaseField + protected String supertypes; + @DatabaseField + protected String manaCosts; + @DatabaseField(dataType = DataType.STRING, width = MAX_RULE_LENGTH) + protected String rules; + @DatabaseField + protected boolean black; + @DatabaseField + protected boolean blue; + @DatabaseField + protected boolean green; + @DatabaseField + protected boolean red; + @DatabaseField + protected boolean white; + @DatabaseField + protected boolean splitCard; + @DatabaseField + protected boolean splitCardHalf; + @DatabaseField + protected boolean flipCard; + @DatabaseField + protected boolean doubleFaced; + @DatabaseField(indexName = "name_index") + protected boolean nightCard; + @DatabaseField + protected String flipCardName; + @DatabaseField + protected String secondSideName; + + public CardInfo() { + } + + public CardInfo(Card card) { + this.name = card.getName(); + this.cardNumber = card.getCardNumber(); + this.setCode = card.getExpansionSetCode(); + this.className = card.getClass().getCanonicalName(); + this.power = card.getPower().toString(); + this.toughness = card.getToughness().toString(); + this.convertedManaCost = card.getManaCost().convertedManaCost(); + this.rarity = card.getRarity(); + this.splitCard = card.isSplitCard(); + + this.flipCard = card.isFlipCard(); + this.flipCardName = card.getFlipCardName(); + + this.doubleFaced = card.canTransform() && card.getSecondCardFace() != null; + this.nightCard = card.isNightCard(); + Card secondSide = card.getSecondCardFace(); + if (secondSide != null) { + this.secondSideName = secondSide.getName(); + } + + this.blue = card.getColor(null).isBlue(); + this.black = card.getColor(null).isBlack(); + this.green = card.getColor(null).isGreen(); + this.red = card.getColor(null).isRed(); + this.white = card.getColor(null).isWhite(); + + this.setTypes(card.getCardType()); + this.setSubtypes(card.getSubtype()); + this.setSuperTypes(card.getSupertype()); + this.setManaCosts(card.getManaCost().getSymbols()); + + int length = 0; + for (String rule : card.getRules()) { + length += rule.length(); + } + if (length > MAX_RULE_LENGTH) { + length = 0; + ArrayList shortRules = new ArrayList<>(); + for (String rule : card.getRules()) { + if (length + rule.length() + 3 <= MAX_RULE_LENGTH) { + shortRules.add(rule); + length += rule.length() + 3; + } else { + shortRules.add(rule.substring(0, MAX_RULE_LENGTH - (length + 3))); + break; + } + } + Logger.getLogger(CardInfo.class).warn("Card rule text was cut - cardname: " + card.getName()); + this.setRules(shortRules); + } else { + this.setRules(card.getRules()); + } + + SpellAbility spellAbility = card.getSpellAbility(); + if (spellAbility != null) { + SpellAbilityType spellAbilityType = spellAbility.getSpellAbilityType(); + if (spellAbilityType == SpellAbilityType.SPLIT_LEFT || spellAbilityType == SpellAbilityType.SPLIT_RIGHT) { + this.className = this.setCode + "." + this.name; + this.splitCardHalf = true; + } + } + } + + public Card getCard() { + return CardImpl.createCard(className); + } + + public Card getMockCard() { + if (this.splitCard) { + return new MockSplitCard(this); + } else { + return new MockCard(this); + } + } + + public boolean usesVariousArt() { + return Character.isDigit(className.charAt(className.length() - 1)); + } + + public ObjectColor getColor() { + ObjectColor color = new ObjectColor(); + color.setBlack(black); + color.setBlue(blue); + color.setGreen(green); + color.setRed(red); + color.setWhite(white); + return color; + } + + private String joinList(List items) { + StringBuilder sb = new StringBuilder(); + for (Object item : items) { + sb.append(item.toString()).append(SEPARATOR); + } + return sb.toString(); + } + + private List parseList(String list) { + if (list.isEmpty()) { + return new ArrayList<>(); + } + return Arrays.asList(list.split(SEPARATOR)); + } + + public final List getTypes() { + ArrayList list = new ArrayList<>(); + for (String type : this.types.split(SEPARATOR)) { + try { + list.add(CardType.valueOf(type)); + } catch (IllegalArgumentException e) { + } + } + return list; + } + + public final void setTypes(List types) { + StringBuilder sb = new StringBuilder(); + for (CardType item : types) { + sb.append(item.name()).append(SEPARATOR); + } + this.types = sb.toString(); + } + + public int getConvertedManaCost() { + return convertedManaCost; + } + + public final List getManaCosts() { + return parseList(manaCosts); + } + + public final void setManaCosts(List manaCosts) { + this.manaCosts = joinList(manaCosts); + } + + public String getName() { + return name; + } + + public String getPower() { + return power; + } + + public Rarity getRarity() { + return rarity; + } + + public final List getRules() { + return parseList(rules); + } + + public final void setRules(List rules) { + this.rules = joinList(rules); + } + + public final List getSubTypes() { + return parseList(subtypes); + } + + public final void setSubtypes(List subtypes) { + this.subtypes = joinList(subtypes); + } + + public final List getSupertypes() { + return parseList(supertypes); + } + + public final void setSuperTypes(List superTypes) { + this.supertypes = joinList(superTypes); + } + + public String getToughness() { + return toughness; + } + + public String getSetCode() { + return setCode; + } + + public String getClassName() { + return className; + } + + public int getCardNumber() { + return cardNumber; + } + + public boolean isSplitCard() { + return splitCard; + } + + public boolean isSplitCardHalf() { + return splitCardHalf; + } + + public boolean isFlipCard() { + return flipCard; + } + + public String getFlipCardName() { + return flipCardName; + } + + public boolean isDoubleFaced() { + return doubleFaced; + } + + public boolean isNightCard() { + return nightCard; + } + + public String getSecondSideName() { + return secondSideName; + } +} diff --git a/Mage/src/mage/cards/repository/ExpansionInfo.java b/Mage/src/mage/cards/repository/ExpansionInfo.java index 8aec9d871ae..553cb3013f2 100644 --- a/Mage/src/mage/cards/repository/ExpansionInfo.java +++ b/Mage/src/mage/cards/repository/ExpansionInfo.java @@ -1,78 +1,79 @@ -package mage.cards.repository; - -import com.j256.ormlite.field.DataType; -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; -import java.util.Date; -import mage.cards.ExpansionSet; -import mage.constants.SetType; - -/** - * - * @author North - */ -@DatabaseTable(tableName = "expansion") -public class ExpansionInfo { - - @DatabaseField(unique = true) - protected String name; - @DatabaseField(unique = true) - protected String code; - @DatabaseField - protected String blockName; - @DatabaseField - protected Date releaseDate; - @DatabaseField(dataType = DataType.ENUM_STRING) - protected SetType type; - @DatabaseField - protected boolean boosters; - @DatabaseField - protected boolean basicLands; - - public ExpansionInfo() { - } - - public ExpansionInfo(ExpansionSet expansionSet) { - this.name = expansionSet.getName(); - this.code = expansionSet.getCode(); - this.blockName = expansionSet.getBlockName(); - this.releaseDate = expansionSet.getReleaseDate(); - this.type = expansionSet.getSetType(); - this.boosters = expansionSet.hasBoosters(); - this.basicLands = expansionSet.hasBasicLands(); - } - - public String getName() { - return name; - } - - public String getCode() { - return code; - } - - public String getBlockName() { - return blockName; - } - - public Date getReleaseDate() { - return releaseDate; - } - - public SetType getType() { - return type; - } - - public boolean hasBoosters() { - return boosters; - } - - public boolean hasBasicLands() { - return basicLands; - } - - @Override - public String toString() { - return name; - } - -} +package mage.cards.repository; + +import com.j256.ormlite.field.DataType; +import com.j256.ormlite.field.DatabaseField; +import com.j256.ormlite.table.DatabaseTable; +import java.io.Serializable; +import java.util.Date; +import mage.cards.ExpansionSet; +import mage.constants.SetType; + +/** + * + * @author North + */ +@DatabaseTable(tableName = "expansion") +public class ExpansionInfo implements Serializable { + + @DatabaseField(unique = true) + protected String name; + @DatabaseField(unique = true) + protected String code; + @DatabaseField + protected String blockName; + @DatabaseField + protected Date releaseDate; + @DatabaseField(dataType = DataType.ENUM_STRING) + protected SetType type; + @DatabaseField + protected boolean boosters; + @DatabaseField + protected boolean basicLands; + + public ExpansionInfo() { + } + + public ExpansionInfo(ExpansionSet expansionSet) { + this.name = expansionSet.getName(); + this.code = expansionSet.getCode(); + this.blockName = expansionSet.getBlockName(); + this.releaseDate = expansionSet.getReleaseDate(); + this.type = expansionSet.getSetType(); + this.boosters = expansionSet.hasBoosters(); + this.basicLands = expansionSet.hasBasicLands(); + } + + public String getName() { + return name; + } + + public String getCode() { + return code; + } + + public String getBlockName() { + return blockName; + } + + public Date getReleaseDate() { + return releaseDate; + } + + public SetType getType() { + return type; + } + + public boolean hasBoosters() { + return boosters; + } + + public boolean hasBasicLands() { + return basicLands; + } + + @Override + public String toString() { + return name; + } + +} diff --git a/Mage/src/mage/cards/repository/ExpansionRepository.java b/Mage/src/mage/cards/repository/ExpansionRepository.java index a50a3d14fb8..7d7a30211f1 100644 --- a/Mage/src/mage/cards/repository/ExpansionRepository.java +++ b/Mage/src/mage/cards/repository/ExpansionRepository.java @@ -1,186 +1,197 @@ -package mage.cards.repository; - -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.dao.DaoManager; -import com.j256.ormlite.jdbc.JdbcConnectionSource; -import com.j256.ormlite.stmt.QueryBuilder; -import com.j256.ormlite.stmt.SelectArg; -import com.j256.ormlite.support.ConnectionSource; -import com.j256.ormlite.table.TableUtils; -import java.io.File; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import org.apache.log4j.Logger; - -/** - * - * @author North - */ -public enum ExpansionRepository { - - instance; - - private static final Logger logger = Logger.getLogger(ExpansionRepository.class); - - private static final String JDBC_URL = "jdbc:h2:file:./db/cards.h2;AUTO_SERVER=TRUE"; - private static final String VERSION_ENTITY_NAME = "expansion"; - private static final long EXPANSION_DB_VERSION = 5; - private static final long EXPANSION_CONTENT_VERSION = 9; - - private Dao expansionDao; - - private ExpansionRepository() { - File file = new File("db"); - if (!file.exists()) { - file.mkdirs(); - } - try { - ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL); - boolean obsolete = RepositoryUtil.isDatabaseObsolete(connectionSource, VERSION_ENTITY_NAME, EXPANSION_DB_VERSION); - - if (obsolete) { - TableUtils.dropTable(connectionSource, ExpansionInfo.class, true); - } - - TableUtils.createTableIfNotExists(connectionSource, ExpansionInfo.class); - expansionDao = DaoManager.createDao(connectionSource, ExpansionInfo.class); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public void add(ExpansionInfo expansion) { - try { - expansionDao.create(expansion); - } catch (SQLException ex) { - } - } - - public List getSetCodes() { - List setCodes = new ArrayList<>(); - try { - List expansions = expansionDao.queryForAll(); - for (ExpansionInfo expansion : expansions) { - setCodes.add(expansion.getCode()); - } - } catch (SQLException ex) { - logger.error("Can't get the expansion set codes from database.", ex); - return setCodes; - } - return setCodes; - } - - public ExpansionInfo[] getWithBoostersSortedByReleaseDate() { - ExpansionInfo[] sets = new ExpansionInfo[0]; - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.orderBy("releaseDate", false); - qb.where().eq("boosters", new SelectArg(true)); - List expansions = expansionDao.query(qb.prepare()); - sets = expansions.toArray(new ExpansionInfo[0]); - } catch (SQLException ex) { - } - return sets; - } - - public List getSetsWithBasicLandsByReleaseDate() { - List sets = new LinkedList<>(); - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.orderBy("releaseDate", false); - qb.where().eq("basicLands", new SelectArg(true)); - sets = expansionDao.query(qb.prepare()); - } catch (SQLException ex) { - } - return sets; - } - - public List getSetsFromBlock(String blockName) { - List sets = new LinkedList<>(); - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.where().eq("blockName", new SelectArg(blockName)); - return expansionDao.query(qb.prepare()); - } catch (SQLException ex) { - } - return sets; - } - - public ExpansionInfo getSetByCode(String setCode) { - ExpansionInfo set = null; - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.where().eq("code", new SelectArg(setCode)); - List expansions = expansionDao.query(qb.prepare()); - if (expansions.size() > 0) { - set = expansions.get(0); - } - } catch (SQLException ex) { - } - return set; - } - - public ExpansionInfo getSetByName(String setName) { - ExpansionInfo set = null; - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.where().eq("name", new SelectArg(setName)); - List expansions = expansionDao.query(qb.prepare()); - if (expansions.size() > 0) { - set = expansions.get(0); - } - } catch (SQLException ex) { - } - return set; - } - - public List getAll() { - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.orderBy("releaseDate", true); - return expansionDao.query(qb.prepare()); - } catch (SQLException ex) { - } - return new ArrayList<>(); - } - - public List getAllSetNames() { - try { - QueryBuilder qb = expansionDao.queryBuilder(); - qb.orderBy("releaseDate", true); - List expansions = expansionDao.query(qb.prepare()); - List setNames = new LinkedList<>(); - for (ExpansionInfo expansionInfo : expansions) { - setNames.add(expansionInfo.getName()); - } - return setNames; - } catch (SQLException ex) { - } - return new ArrayList<>(); - } - - public long getContentVersionFromDB() { - try { - ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL); - return RepositoryUtil.getDatabaseVersion(connectionSource, VERSION_ENTITY_NAME + "Content"); - } catch (SQLException ex) { - ex.printStackTrace(); - } - return 0; - } - - public void setContentVersion(long version) { - try { - ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL); - RepositoryUtil.updateVersion(connectionSource, VERSION_ENTITY_NAME + "Content", version); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public long getContentVersionConstant() { - return EXPANSION_CONTENT_VERSION; - } -} +package mage.cards.repository; + +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.jdbc.JdbcConnectionSource; +import com.j256.ormlite.stmt.QueryBuilder; +import com.j256.ormlite.stmt.SelectArg; +import com.j256.ormlite.support.ConnectionSource; +import com.j256.ormlite.table.TableUtils; +import java.io.File; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import org.apache.log4j.Logger; + +/** + * + * @author North + */ +public enum ExpansionRepository { + + instance; + + private static final Logger logger = Logger.getLogger(ExpansionRepository.class); + + private static final String JDBC_URL = "jdbc:h2:file:./db/cards.h2;AUTO_SERVER=TRUE"; + private static final String VERSION_ENTITY_NAME = "expansion"; + private static final long EXPANSION_DB_VERSION = 5; + private static final long EXPANSION_CONTENT_VERSION = 9; + + private Dao expansionDao; + + private ExpansionRepository() { + File file = new File("db"); + if (!file.exists()) { + file.mkdirs(); + } + try { + ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL); + boolean obsolete = RepositoryUtil.isDatabaseObsolete(connectionSource, VERSION_ENTITY_NAME, EXPANSION_DB_VERSION); + + if (obsolete) { + TableUtils.dropTable(connectionSource, ExpansionInfo.class, true); + } + + TableUtils.createTableIfNotExists(connectionSource, ExpansionInfo.class); + expansionDao = DaoManager.createDao(connectionSource, ExpansionInfo.class); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public void add(ExpansionInfo expansion) { + try { + expansionDao.create(expansion); + } catch (SQLException ex) { + } + } + + public List getSetCodes() { + List setCodes = new ArrayList<>(); + try { + List expansions = expansionDao.queryForAll(); + for (ExpansionInfo expansion : expansions) { + setCodes.add(expansion.getCode()); + } + } catch (SQLException ex) { + logger.error("Can't get the expansion set codes from database.", ex); + return setCodes; + } + return setCodes; + } + + public ExpansionInfo[] getWithBoostersSortedByReleaseDate() { + ExpansionInfo[] sets = new ExpansionInfo[0]; + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.orderBy("releaseDate", false); + qb.where().eq("boosters", new SelectArg(true)); + List expansions = expansionDao.query(qb.prepare()); + sets = expansions.toArray(new ExpansionInfo[0]); + } catch (SQLException ex) { + } + return sets; + } + + public List getSetsWithBasicLandsByReleaseDate() { + List sets = new LinkedList<>(); + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.orderBy("releaseDate", false); + qb.where().eq("basicLands", new SelectArg(true)); + sets = expansionDao.query(qb.prepare()); + } catch (SQLException ex) { + } + return sets; + } + + public List getSetsFromBlock(String blockName) { + List sets = new LinkedList<>(); + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.where().eq("blockName", new SelectArg(blockName)); + return expansionDao.query(qb.prepare()); + } catch (SQLException ex) { + } + return sets; + } + + public ExpansionInfo getSetByCode(String setCode) { + ExpansionInfo set = null; + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.where().eq("code", new SelectArg(setCode)); + List expansions = expansionDao.query(qb.prepare()); + if (expansions.size() > 0) { + set = expansions.get(0); + } + } catch (SQLException ex) { + } + return set; + } + + public ExpansionInfo getSetByName(String setName) { + ExpansionInfo set = null; + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.where().eq("name", new SelectArg(setName)); + List expansions = expansionDao.query(qb.prepare()); + if (expansions.size() > 0) { + set = expansions.get(0); + } + } catch (SQLException ex) { + } + return set; + } + + public List getAll() { + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.orderBy("releaseDate", true); + return expansionDao.query(qb.prepare()); + } catch (SQLException ex) { + } + return new ArrayList<>(); + } + + public List getMissingExpansions(List setCodes) { + try { + QueryBuilder queryBuilder = expansionDao.queryBuilder(); + queryBuilder.where().not().in("code", setCodes); + + return expansionDao.query(queryBuilder.prepare()); + } catch (SQLException ex) { + } + return new ArrayList<>(); + } + + public List getAllSetNames() { + try { + QueryBuilder qb = expansionDao.queryBuilder(); + qb.orderBy("releaseDate", true); + List expansions = expansionDao.query(qb.prepare()); + List setNames = new LinkedList<>(); + for (ExpansionInfo expansionInfo : expansions) { + setNames.add(expansionInfo.getName()); + } + return setNames; + } catch (SQLException ex) { + } + return new ArrayList<>(); + } + + public long getContentVersionFromDB() { + try { + ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL); + return RepositoryUtil.getDatabaseVersion(connectionSource, VERSION_ENTITY_NAME + "Content"); + } catch (SQLException ex) { + ex.printStackTrace(); + } + return 0; + } + + public void setContentVersion(long version) { + try { + ConnectionSource connectionSource = new JdbcConnectionSource(JDBC_URL); + RepositoryUtil.updateVersion(connectionSource, VERSION_ENTITY_NAME + "Content", version); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + public long getContentVersionConstant() { + return EXPANSION_CONTENT_VERSION; + } +}