add some Java8 magic to the server

This commit is contained in:
Ingmar Goudt 2019-01-19 09:31:50 +01:00
parent 9bea7c7df2
commit 50f28a2bf7
7 changed files with 46 additions and 56 deletions

View file

@ -56,9 +56,9 @@ public final class Main {
private static final File extensionFolder = new File("extensions"); private static final File extensionFolder = new File("extensions");
public static final PluginClassLoader classLoader = new PluginClassLoader(); public static final PluginClassLoader classLoader = new PluginClassLoader();
public static TransporterServer server; private static TransporterServer server;
protected static boolean testMode; private static boolean testMode;
protected static boolean fastDbMode; private static boolean fastDbMode;
/** /**
* @param args the command line arguments * @param args the command line arguments
@ -418,8 +418,10 @@ public final class Main {
File[] files = directory.listFiles( File[] files = directory.listFiles(
(dir, name) -> name.endsWith(".game") (dir, name) -> name.endsWith(".game")
); );
for (File file : files) { if(files != null) {
file.delete(); for (File file : files) {
file.delete();
}
} }
} }

View file

@ -1,14 +1,15 @@
package mage.server; package mage.server;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import mage.MageException; import mage.MageException;
import mage.players.net.UserData; import mage.players.net.UserData;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jboss.remoting.callback.InvokerCallbackHandler; import org.jboss.remoting.callback.InvokerCallbackHandler;
import javax.annotation.Nonnull;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -88,18 +89,15 @@ public enum SessionManager {
} }
public boolean setUserData(String userName, String sessionId, UserData userData, String clientVersion, String userIdStr) throws MageException { public boolean setUserData(String userName, String sessionId, UserData userData, String clientVersion, String userIdStr) throws MageException {
Session session = sessions.get(sessionId); return getSession(sessionId)
if (session != null) { .map(session -> session.setUserData(userName,userData, clientVersion, userIdStr))
session.setUserData(userName, userData, clientVersion, userIdStr); .orElse(false);
return true;
}
return false;
} }
public void disconnect(String sessionId, DisconnectReason reason) { public void disconnect(String sessionId, DisconnectReason reason) {
Session session = sessions.get(sessionId); getSession(sessionId).ifPresent(session -> {
if (session != null) { if (!isValidSession(sessionId)) {
if (!sessions.containsKey(sessionId)) {
// session was removed meanwhile by another thread so we can return // session was removed meanwhile by another thread so we can return
return; return;
} }
@ -122,11 +120,11 @@ public enum SessionManager {
default: default:
logger.trace("endSession: unexpected reason " + reason.toString() + " - sessionId: " + sessionId); logger.trace("endSession: unexpected reason " + reason.toString() + " - sessionId: " + sessionId);
} }
});
}
} }
/** /**
* Admin requested the disconnect of a user * Admin requested the disconnect of a user
* *
@ -150,11 +148,9 @@ public enum SessionManager {
} }
private Optional<User> getUserFromSession(String sessionId) { private Optional<User> getUserFromSession(String sessionId) {
Optional<Session> session = getSession(sessionId); return getSession(sessionId)
if (!session.isPresent()) { .flatMap(s -> UserManager.instance.getUser(s.getUserId()));
return Optional.empty();
}
return UserManager.instance.getUser(session.get().getUserId());
} }
public void endUserSession(String sessionId, String userSessionId) { public void endUserSession(String sessionId, String userSessionId) {
@ -164,11 +160,8 @@ public enum SessionManager {
} }
public boolean isAdmin(String sessionId) { public boolean isAdmin(String sessionId) {
Session admin = sessions.get(sessionId); return getSession(sessionId).map(Session::isAdmin).orElse(false);
if (admin != null) {
return admin.isAdmin();
}
return false;
} }
public boolean isValidSession(@Nonnull String sessionId) { public boolean isValidSession(@Nonnull String sessionId) {
@ -185,11 +178,9 @@ public enum SessionManager {
} }
public boolean extendUserSession(String sessionId, String pingInfo) { public boolean extendUserSession(String sessionId, String pingInfo) {
Session session = sessions.get(sessionId); return getSession(sessionId)
if (session != null) { .map(session -> UserManager.instance.extendUserSession(session.getUserId(), pingInfo))
return UserManager.instance.extendUserSession(session.getUserId(), pingInfo); .orElse(false);
}
return false;
} }
public void sendErrorMessageToClient(String sessionId, String message) { public void sendErrorMessageToClient(String sessionId, String message) {

View file

@ -927,12 +927,10 @@ public class TableController {
public boolean isTournamentStillValid() { public boolean isTournamentStillValid() {
if (table.getTournament() != null) { if (table.getTournament() != null) {
if (table.getState() != TableState.WAITING && table.getState() != TableState.READY_TO_START && table.getState() != TableState.STARTING) { if (table.getState() != TableState.WAITING && table.getState() != TableState.READY_TO_START && table.getState() != TableState.STARTING) {
TournamentController tournamentController = TournamentManager.instance.getTournamentController(table.getTournament().getId()); return TournamentManager.instance.getTournamentController(table.getTournament().getId())
if (tournamentController != null) { .map(tc -> tc.isTournamentStillValid(table.getState()))
return tournamentController.isTournamentStillValid(table.getState()); .orElse(false);
} else {
return false;
}
} else { } else {
// check if table creator is still a valid user, if not removeUserFromAllTablesAndChat table // check if table creator is still a valid user, if not removeUserFromAllTablesAndChat table
return UserManager.instance.getUser(userId).isPresent(); return UserManager.instance.getUser(userId).isPresent();

View file

@ -334,10 +334,10 @@ public class User {
} }
for (Iterator<Entry<UUID, UUID>> iterator = userTournaments.entrySet().iterator(); iterator.hasNext();) { for (Iterator<Entry<UUID, UUID>> iterator = userTournaments.entrySet().iterator(); iterator.hasNext();) {
Entry<UUID, UUID> next = iterator.next(); Entry<UUID, UUID> next = iterator.next();
TournamentController tournamentController = TournamentManager.instance.getTournamentController(next.getValue()); Optional<TournamentController> tournamentController = TournamentManager.instance.getTournamentController(next.getValue());
if (tournamentController != null) { if (tournamentController.isPresent()) {
ccTournamentStarted(next.getValue(), next.getKey()); ccTournamentStarted(next.getValue(), next.getKey());
tournamentController.rejoin(next.getKey()); tournamentController.get().rejoin(next.getKey());
} else { } else {
iterator.remove(); // tournament has ended meanwhile iterator.remove(); // tournament has ended meanwhile
} }

View file

@ -70,13 +70,8 @@ public enum UserManager {
final Lock r = lock.readLock(); final Lock r = lock.readLock();
r.lock(); r.lock();
try { try {
Optional<User> u = users.values().stream().filter(user -> user.getName().equals(userName)) return users.values().stream().filter(user -> user.getName().equals(userName))
.findFirst(); .findFirst();
if (u.isPresent()) {
return u;
} else {
return Optional.empty();
}
} finally { } finally {
r.unlock(); r.unlock();
} }
@ -84,7 +79,7 @@ public enum UserManager {
} }
public Collection<User> getUsers() { public Collection<User> getUsers() {
ArrayList<User> userList = new ArrayList<>(); List<User> userList = new ArrayList<>();
final Lock r = lock.readLock(); final Lock r = lock.readLock();
r.lock(); r.lock();
try { try {

View file

@ -16,8 +16,8 @@ public enum TournamentManager {
instance; instance;
private final ConcurrentHashMap<UUID, TournamentController> controllers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, TournamentController> controllers = new ConcurrentHashMap<>();
public TournamentController getTournamentController(UUID tournamentId) { public Optional<TournamentController> getTournamentController(UUID tournamentId) {
return controllers.get(tournamentId); return Optional.ofNullable(controllers.get(tournamentId));
} }
public void createTournamentSession(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) { public void createTournamentSession(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {

View file

@ -54,13 +54,13 @@ public final class FleshAllergy extends CardImpl {
class FleshAllergyWatcher extends Watcher { class FleshAllergyWatcher extends Watcher {
public int creaturesDiedThisTurn = 0; private int creaturesDiedThisTurn = 0;
public FleshAllergyWatcher() { public FleshAllergyWatcher() {
super(FleshAllergyWatcher.class, WatcherScope.GAME); super(FleshAllergyWatcher.class, WatcherScope.GAME);
} }
public FleshAllergyWatcher(final FleshAllergyWatcher watcher) { private FleshAllergyWatcher(final FleshAllergyWatcher watcher) {
super(watcher); super(watcher);
} }
@ -79,6 +79,10 @@ class FleshAllergyWatcher extends Watcher {
} }
} }
public int getCreaturesDiedThisTurn(){
return creaturesDiedThisTurn;
}
@Override @Override
public void reset() { public void reset() {
super.reset(); super.reset();
@ -94,7 +98,7 @@ class FleshAllergyEffect extends OneShotEffect {
staticText = "Its controller loses life equal to the number of creatures that died this turn"; staticText = "Its controller loses life equal to the number of creatures that died this turn";
} }
public FleshAllergyEffect(final FleshAllergyEffect effect) { private FleshAllergyEffect(final FleshAllergyEffect effect) {
super(effect); super(effect);
} }
@ -110,7 +114,7 @@ class FleshAllergyEffect extends OneShotEffect {
if (permanent != null && watcher != null) { if (permanent != null && watcher != null) {
Player player = game.getPlayer(permanent.getControllerId()); Player player = game.getPlayer(permanent.getControllerId());
if (player != null) { if (player != null) {
int amount = watcher.creaturesDiedThisTurn; int amount = watcher.getCreaturesDiedThisTurn();
if (amount > 0) { if (amount > 0) {
player.loseLife(amount, game, false); player.loseLife(amount, game, false);
return true; return true;