Search in sources :

Example 1 with MessengerException

use of games.strategy.engine.message.MessengerException in project triplea by triplea-game.

the class DelegateExecutionManager method createOutboundImplementation.

/**
 * Used to create an object the exits delegate execution.
 *
 * <p>
 * Objects on this method will decrement the thread lock count when called, and will increment it again when execution
 * is finished.
 * </p>
 */
public Object createOutboundImplementation(final Object implementor, final Class<?>[] interfaces) {
    assertGameNotOver();
    final InvocationHandler ih = (proxy, method, args) -> {
        assertGameNotOver();
        final boolean threadLocks = currentThreadHasReadLock();
        if (threadLocks) {
            leaveDelegateExecution();
        }
        try {
            return method.invoke(implementor, args);
        } catch (final MessengerException me) {
            throw new GameOverException("Game Over!");
        } catch (final InvocationTargetException ite) {
            assertGameNotOver();
            throw ite;
        } finally {
            if (threadLocks) {
                enterDelegateExecution();
            }
        }
    };
    return Proxy.newProxyInstance(implementor.getClass().getClassLoader(), interfaces, ih);
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) Proxy(java.lang.reflect.Proxy) GameOverException(games.strategy.engine.GameOverException) WrappedInvocationHandler(games.strategy.triplea.util.WrappedInvocationHandler) MessengerException(games.strategy.engine.message.MessengerException) InvocationHandler(java.lang.reflect.InvocationHandler) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Method(java.lang.reflect.Method) Preconditions.checkState(com.google.common.base.Preconditions.checkState) InvocationTargetException(java.lang.reflect.InvocationTargetException) MessengerException(games.strategy.engine.message.MessengerException) GameOverException(games.strategy.engine.GameOverException) WrappedInvocationHandler(games.strategy.triplea.util.WrappedInvocationHandler) InvocationHandler(java.lang.reflect.InvocationHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 2 with MessengerException

use of games.strategy.engine.message.MessengerException in project triplea by triplea-game.

the class DefaultPlayerBridge method getRemoteDelegate.

@Override
public IRemote getRemoteDelegate() {
    if (game.isGameOver()) {
        throw new GameOverException("Game Over");
    }
    try {
        game.getData().acquireReadLock();
        try {
            final IDelegate delegate = game.getData().getDelegateList().getDelegate(currentDelegate);
            if (delegate == null) {
                final String errorMessage = "IDelegate in DefaultPlayerBridge.getRemote() cannot be null. CurrentStep: " + stepName + ", and CurrentDelegate: " + currentDelegate;
                // for some reason, client isn't getting or seeing the errors, so make sure we print it to err
                // too
                System.err.println(errorMessage);
                // Veqryn: hope that this suffices...?
                throw new IllegalStateException(errorMessage);
            }
            final RemoteName remoteName;
            try {
                remoteName = ServerGame.getRemoteName(delegate);
            } catch (final Exception e) {
                final String errorMessage = "IDelegate IRemote interface class returned null or was not correct interface. CurrentStep: " + stepName + ", and CurrentDelegate: " + currentDelegate;
                // for some reason, client isn't getting or seeing the errors, so make sure we print it to err
                // too
                System.err.println(errorMessage);
                ClientLogger.logQuietly(errorMessage, e);
                throw new IllegalStateException(errorMessage, e);
            }
            return getRemoteThatChecksForGameOver(game.getRemoteMessenger().getRemote(remoteName));
        } finally {
            game.getData().releaseReadLock();
        }
    } catch (final MessengerException me) {
        throw new GameOverException("Game Over!");
    }
}
Also used : RemoteName(games.strategy.engine.message.RemoteName) MessengerException(games.strategy.engine.message.MessengerException) GameOverException(games.strategy.engine.GameOverException) IDelegate(games.strategy.engine.delegate.IDelegate) RemoteNotFoundException(games.strategy.engine.message.RemoteNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GameOverException(games.strategy.engine.GameOverException) MessengerException(games.strategy.engine.message.MessengerException)

Example 3 with MessengerException

use of games.strategy.engine.message.MessengerException in project triplea by triplea-game.

the class ServerLauncher method launchInNewThread.

@Override
protected void launchInNewThread(final Component parent) {
    try {
        // the order of this stuff does matter
        serverModel.setServerLauncher(this);
        serverReady = new ServerReady(clientCount);
        if (inGameLobbyWatcher != null) {
            inGameLobbyWatcher.setGameStatus(GameDescription.GameStatus.LAUNCHING, null);
        }
        serverModel.allowRemoveConnections();
        ui = parent;
        if (headless) {
            HeadlessGameServer.log("Game Status: Launching");
        }
        remoteMessenger.registerRemote(serverReady, ClientModel.CLIENT_READY_CHANNEL);
        gameData.doPreGameStartDataModifications(playerListing);
        abortLaunch = testShouldWeAbort();
        final byte[] gameDataAsBytes = gameData.toBytes();
        final Set<IGamePlayer> localPlayerSet = gameData.getGameLoader().createPlayers(playerListing.getLocalPlayerTypes());
        final Messengers messengers = new Messengers(messenger, remoteMessenger, channelMessenger);
        serverGame = new ServerGame(gameData, localPlayerSet, remotePlayers, messengers);
        serverGame.setInGameLobbyWatcher(inGameLobbyWatcher);
        if (headless) {
            HeadlessGameServer.setServerGame(serverGame);
        }
        // tell the clients to start,
        // later we will wait for them to all
        // signal that they are ready.
        ((IClientChannel) channelMessenger.getChannelBroadcastor(IClientChannel.CHANNEL_NAME)).doneSelectingPlayers(gameDataAsBytes, serverGame.getPlayerManager().getPlayerMapping());
        final boolean useSecureRandomSource = !remotePlayers.isEmpty();
        if (useSecureRandomSource) {
            // server game.
            // try to find an opponent to be the other side of the crypto random source.
            final PlayerID remotePlayer = serverGame.getPlayerManager().getRemoteOpponent(messenger.getLocalNode(), gameData);
            final CryptoRandomSource randomSource = new CryptoRandomSource(remotePlayer, serverGame);
            serverGame.setRandomSource(randomSource);
        }
        try {
            gameData.getGameLoader().startGame(serverGame, localPlayerSet, headless);
        } catch (final Exception e) {
            ClientLogger.logError("Failed to launch", e);
            abortLaunch = true;
            if (gameLoadingWindow != null) {
                gameLoadingWindow.doneWait();
            }
        }
        if (headless) {
            HeadlessGameServer.log("Game Successfully Loaded. " + (abortLaunch ? "Aborting Launch." : "Starting Game."));
        }
        if (abortLaunch) {
            serverReady.countDownAll();
        }
        if (!serverReady.await(ClientSetting.SERVER_START_GAME_SYNC_WAIT_TIME.intValue(), TimeUnit.SECONDS)) {
            System.out.println("Waiting for clients to be ready timed out!");
            abortLaunch = true;
        }
        remoteMessenger.unregisterRemote(ClientModel.CLIENT_READY_CHANNEL);
        new Thread(() -> {
            try {
                isLaunching = false;
                abortLaunch = testShouldWeAbort();
                if (!abortLaunch) {
                    if (useSecureRandomSource) {
                        warmUpCryptoRandomSource();
                    }
                    if (gameLoadingWindow != null) {
                        gameLoadingWindow.doneWait();
                    }
                    if (headless) {
                        HeadlessGameServer.log("Starting Game Delegates.");
                    }
                    serverGame.startGame();
                } else {
                    stopGame();
                    if (!headless) {
                        SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(ui, "Problem during startup, game aborted."));
                    } else {
                        System.out.println("Problem during startup, game aborted.");
                    }
                }
            } catch (final MessengerException me) {
                // if just connection lost, no need to scare the user with some giant stack trace
                if (me instanceof ConnectionLostException) {
                    System.out.println("Game Player disconnection: " + me.getMessage());
                } else {
                    me.printStackTrace(System.out);
                }
                // wait for the connection handler to notice, and shut us down
                try {
                    // we are already aborting the launch
                    if (!abortLaunch) {
                        if (!errorLatch.await(ClientSetting.SERVER_OBSERVER_JOIN_WAIT_TIME.intValue(), TimeUnit.SECONDS)) {
                            System.err.println("Waiting on error latch timed out!");
                        }
                    }
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                stopGame();
            } catch (final Exception e) {
                e.printStackTrace(System.err);
                if (headless) {
                    System.out.println(DebugUtils.getThreadDumps());
                    HeadlessGameServer.sendChat("If this is a repeatable issue or error, please make a copy of this savegame " + "and contact a Mod and/or file a bug report.");
                }
                stopGame();
            }
            // having an oddball issue with the zip stream being closed while parsing to load default game. might be
            // caused by closing of stream while unloading map resources.
            Interruptibles.sleep(200);
            // either game ended, or aborted, or a player left or disconnected
            if (headless) {
                try {
                    System.out.println("Game ended, going back to waiting.");
                    // if we do not do this, we can get into an infinite loop of launching a game,
                    // then crashing out, then launching, etc.
                    serverModel.setAllPlayersToNullNodes();
                    final File f1 = new File(ClientSetting.SAVE_GAMES_FOLDER_PATH.value(), SaveGameFileChooser.getAutoSaveFileName());
                    if (f1.exists()) {
                        gameSelectorModel.load(f1, null);
                    } else {
                        gameSelectorModel.resetGameDataToNull();
                    }
                } catch (final Exception e1) {
                    ClientLogger.logQuietly("Failed to load game", e1);
                    gameSelectorModel.resetGameDataToNull();
                }
            } else {
                gameSelectorModel.loadDefaultGameNewThread();
            }
            if (parent != null) {
                SwingUtilities.invokeLater(() -> JOptionPane.getFrameForComponent(parent).setVisible(true));
            }
            serverModel.setServerLauncher(null);
            serverModel.newGame();
            if (inGameLobbyWatcher != null) {
                inGameLobbyWatcher.setGameStatus(GameDescription.GameStatus.WAITING_FOR_PLAYERS, null);
            }
            if (headless) {
                // tell headless server to wait for new connections:
                HeadlessGameServer.waitForUsersHeadlessInstance();
                HeadlessGameServer.log("Game Status: Waiting For Players");
            }
        }, "Triplea, start server game").start();
    } finally {
        if (gameLoadingWindow != null) {
            gameLoadingWindow.doneWait();
        }
        if (inGameLobbyWatcher != null) {
            inGameLobbyWatcher.setGameStatus(GameDescription.GameStatus.IN_PROGRESS, serverGame);
        }
        if (headless) {
            HeadlessGameServer.log("Game Status: In Progress");
        }
    }
}
Also used : IGamePlayer(games.strategy.engine.gamePlayer.IGamePlayer) PlayerID(games.strategy.engine.data.PlayerID) ConnectionLostException(games.strategy.engine.message.ConnectionLostException) Messengers(games.strategy.net.Messengers) ServerGame(games.strategy.engine.framework.ServerGame) MessengerException(games.strategy.engine.message.MessengerException) MessengerException(games.strategy.engine.message.MessengerException) ConnectionLostException(games.strategy.engine.message.ConnectionLostException) CryptoRandomSource(games.strategy.engine.random.CryptoRandomSource) IClientChannel(games.strategy.engine.framework.startup.mc.IClientChannel) File(java.io.File)

Example 4 with MessengerException

use of games.strategy.engine.message.MessengerException in project triplea by triplea-game.

the class DefaultPlayerBridge method getRemotePersistentDelegate.

@Override
public IRemote getRemotePersistentDelegate(final String name) {
    if (game.isGameOver()) {
        throw new GameOverException("Game Over");
    }
    try {
        game.getData().acquireReadLock();
        try {
            final IDelegate delegate = game.getData().getDelegateList().getDelegate(name);
            if (delegate == null) {
                final String errorMessage = "IDelegate in DefaultPlayerBridge.getRemote() cannot be null. Looking for delegate named: " + name;
                // for some reason, client isn't getting or seeing the errors, so make sure we print it to err
                System.err.println(errorMessage);
                // too
                throw new IllegalStateException(errorMessage);
            }
            if (!(delegate instanceof IPersistentDelegate)) {
                return null;
            }
            return getRemoteThatChecksForGameOver(game.getRemoteMessenger().getRemote(ServerGame.getRemoteName(delegate)));
        } finally {
            game.getData().releaseReadLock();
        }
    } catch (final MessengerException me) {
        throw new GameOverException("Game Over!");
    }
}
Also used : IPersistentDelegate(games.strategy.engine.delegate.IPersistentDelegate) MessengerException(games.strategy.engine.message.MessengerException) GameOverException(games.strategy.engine.GameOverException) IDelegate(games.strategy.engine.delegate.IDelegate)

Aggregations

MessengerException (games.strategy.engine.message.MessengerException)4 GameOverException (games.strategy.engine.GameOverException)3 IDelegate (games.strategy.engine.delegate.IDelegate)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 PlayerID (games.strategy.engine.data.PlayerID)1 IPersistentDelegate (games.strategy.engine.delegate.IPersistentDelegate)1 ServerGame (games.strategy.engine.framework.ServerGame)1 IClientChannel (games.strategy.engine.framework.startup.mc.IClientChannel)1 IGamePlayer (games.strategy.engine.gamePlayer.IGamePlayer)1 ConnectionLostException (games.strategy.engine.message.ConnectionLostException)1 RemoteName (games.strategy.engine.message.RemoteName)1 RemoteNotFoundException (games.strategy.engine.message.RemoteNotFoundException)1 CryptoRandomSource (games.strategy.engine.random.CryptoRandomSource)1 Messengers (games.strategy.net.Messengers)1 WrappedInvocationHandler (games.strategy.triplea.util.WrappedInvocationHandler)1 File (java.io.File)1 InvocationHandler (java.lang.reflect.InvocationHandler)1 Method (java.lang.reflect.Method)1 Proxy (java.lang.reflect.Proxy)1