refactor: use try-with-resources for various server db operations

This commit is contained in:
P0nk
2021-04-04 15:35:17 +02:00
parent 3ca9311cb0
commit e322b05707

View File

@@ -21,28 +21,22 @@
*/ */
package net.server; package net.server;
import java.io.IOException; import client.MapleCharacter;
import java.net.InetSocketAddress; import client.MapleClient;
import java.security.Security; import client.MapleFamily;
import java.sql.Connection; import client.SkillFactory;
import java.sql.PreparedStatement; import client.command.CommandsExecutor;
import java.sql.ResultSet; import client.inventory.Item;
import java.sql.SQLException; import client.inventory.ItemFactory;
import java.util.ArrayList; import client.inventory.manipulator.MapleCashidGenerator;
import java.util.Calendar; import client.newyear.NewYearCardRecord;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import config.YamlConfig; import config.YamlConfig;
import constants.game.GameConstants;
import constants.inventory.ItemConstants;
import constants.net.OpcodeConstants;
import constants.net.ServerConstants;
import net.MapleServerHandler;
import net.mina.MapleCodecFactory;
import net.server.audit.ThreadTracker; import net.server.audit.ThreadTracker;
import net.server.audit.locks.MonitoredLockType; import net.server.audit.locks.MonitoredLockType;
import net.server.audit.locks.MonitoredReadLock; import net.server.audit.locks.MonitoredReadLock;
@@ -51,28 +45,13 @@ import net.server.audit.locks.MonitoredWriteLock;
import net.server.audit.locks.factory.MonitoredReadLockFactory; import net.server.audit.locks.factory.MonitoredReadLockFactory;
import net.server.audit.locks.factory.MonitoredReentrantLockFactory; import net.server.audit.locks.factory.MonitoredReentrantLockFactory;
import net.server.audit.locks.factory.MonitoredWriteLockFactory; import net.server.audit.locks.factory.MonitoredWriteLockFactory;
import net.MapleServerHandler;
import net.mina.MapleCodecFactory;
import net.server.channel.Channel; import net.server.channel.Channel;
import net.server.coordinator.session.MapleSessionCoordinator; import net.server.coordinator.session.MapleSessionCoordinator;
import net.server.guild.MapleAlliance; import net.server.guild.MapleAlliance;
import net.server.guild.MapleGuild; import net.server.guild.MapleGuild;
import net.server.guild.MapleGuildCharacter; import net.server.guild.MapleGuildCharacter;
import net.server.task.BossLogTask; import net.server.task.*;
import net.server.task.CharacterDiseaseTask;
import net.server.task.CouponTask;
import net.server.task.EventRecallCoordinatorTask;
import net.server.task.DueyFredrickTask;
import net.server.task.InvitationTask;
import net.server.task.LoginCoordinatorTask;
import net.server.task.LoginStorageTask;
import net.server.task.RankingCommandTask;
import net.server.task.RankingLoginTask;
import net.server.task.ReleaseLockTask;
import net.server.task.RespawnTask;
import net.server.world.World; import net.server.world.World;
import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.buffer.SimpleBufferAllocator; import org.apache.mina.core.buffer.SimpleBufferAllocator;
import org.apache.mina.core.filterchain.IoFilter; import org.apache.mina.core.filterchain.IoFilter;
@@ -80,21 +59,6 @@ import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import client.MapleClient;
import client.MapleFamily;
import client.MapleCharacter;
import client.SkillFactory;
import client.command.CommandsExecutor;
import client.inventory.Item;
import client.inventory.ItemFactory;
import client.inventory.manipulator.MapleCashidGenerator;
import client.newyear.NewYearCardRecord;
import constants.inventory.ItemConstants;
import constants.game.GameConstants;
import constants.net.OpcodeConstants;
import constants.net.ServerConstants;
import java.util.TimeZone;
import server.CashShop.CashItemFactory; import server.CashShop.CashItemFactory;
import server.MapleSkillbookInformationProvider; import server.MapleSkillbookInformationProvider;
import server.ThreadManager; import server.ThreadManager;
@@ -107,6 +71,18 @@ import tools.DatabaseConnection;
import tools.FilePrinter; import tools.FilePrinter;
import tools.Pair; import tools.Pair;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.Security;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
public class Server { public class Server {
private static Server instance = null; private static Server instance = null;
@@ -209,23 +185,23 @@ public class Server {
} }
private void loadPlayerNpcMapStepFromDb() { private void loadPlayerNpcMapStepFromDb() {
try { final List<World> wlist = this.getWorlds();
List<World> wlist = this.getWorlds();
Connection con = DatabaseConnection.getConnection(); try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_field"); PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_field");
ResultSet rs = ps.executeQuery()) {
ResultSet rs = ps.executeQuery(); while (rs.next()) {
while(rs.next()) { int world = rs.getInt("world");
int world = rs.getInt("world"), map = rs.getInt("map"), step = rs.getInt("step"), podium = rs.getInt("podium"); int map = rs.getInt("map");
int step = rs.getInt("step");
int podium = rs.getInt("podium");
World w = wlist.get(world); World w = wlist.get(world);
if(w != null) w.setPlayerNpcMapData(map, step, podium); if (w != null) {
w.setPlayerNpcMapData(map, step, podium);
}
} }
rs.close();
ps.close();
con.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -265,7 +241,7 @@ public class Server {
public Channel getChannel(int world, int channel) { public Channel getChannel(int world, int channel) {
try { try {
return this.getWorld(world).getChannel(channel); return this.getWorld(world).getChannel(channel);
} catch(NullPointerException npe) { } catch (NullPointerException npe) {
return null; return null;
} }
} }
@@ -273,7 +249,7 @@ public class Server {
public List<Channel> getChannelsFromWorld(int world) { public List<Channel> getChannelsFromWorld(int world) {
try { try {
return this.getWorld(world).getChannels(); return this.getWorld(world).getChannels();
} catch(NullPointerException npe) { } catch (NullPointerException npe) {
return new ArrayList<>(0); return new ArrayList<>(0);
} }
} }
@@ -287,7 +263,7 @@ public class Server {
} }
} }
return channelz; return channelz;
} catch(NullPointerException npe) { } catch (NullPointerException npe) {
return new ArrayList<>(0); return new ArrayList<>(0);
} }
} }
@@ -339,13 +315,19 @@ public class Server {
wldRLock.lock(); wldRLock.lock();
try { try {
if(worldid >= worlds.size()) return -3; if (worldid >= worlds.size()) {
return -3;
}
channelInfo = channels.get(worldid); channelInfo = channels.get(worldid);
if(channelInfo == null) return -3; if (channelInfo == null) {
return -3;
}
channelid = channelInfo.size(); channelid = channelInfo.size();
if(channelid >= YamlConfig.config.server.CHANNEL_SIZE) return -2; if (channelid >= YamlConfig.config.server.CHANNEL_SIZE) {
return -2;
}
channelid++; channelid++;
world = this.getWorld(worldid); world = this.getWorld(worldid);
@@ -370,7 +352,7 @@ public class Server {
public int addWorld() { public int addWorld() {
int newWorld = initWorld(); int newWorld = initWorld();
if(newWorld > -1) { if (newWorld > -1) {
installWorldPlayerRanking(newWorld); installWorldPlayerRanking(newWorld);
Set<Integer> accounts; Set<Integer> accounts;
@@ -381,7 +363,7 @@ public class Server {
lgnRLock.unlock(); lgnRLock.unlock();
} }
for(Integer accId : accounts) { for (Integer accId : accounts) {
loadAccountCharactersView(accId, 0, newWorld); loadAccountCharactersView(accId, 0, newWorld);
} }
} }
@@ -396,7 +378,7 @@ public class Server {
try { try {
i = worlds.size(); i = worlds.size();
if(i >= YamlConfig.config.server.WLDLIST_SIZE) { if (i >= YamlConfig.config.server.WLDLIST_SIZE) {
return -1; return -1;
} }
} finally { } finally {
@@ -463,7 +445,9 @@ public class Server {
wldRLock.lock(); wldRLock.lock();
try { try {
if(worldid >= worlds.size()) return false; if (worldid >= worlds.size()) {
return false;
}
world = worlds.get(worldid); world = worlds.get(worldid);
} finally { } finally {
wldRLock.unlock(); wldRLock.unlock();
@@ -474,7 +458,9 @@ public class Server {
wldWLock.lock(); wldWLock.lock();
try { try {
Map<Integer, String> m = channels.get(worldid); Map<Integer, String> m = channels.get(worldid);
if(m != null) m.remove(channel); if (m != null) {
m.remove(channel);
}
} finally { } finally {
wldWLock.unlock(); wldWLock.unlock();
} }
@@ -492,7 +478,7 @@ public class Server {
wldRLock.lock(); wldRLock.lock();
try { try {
worldid = worlds.size() - 1; worldid = worlds.size() - 1;
if(worldid < 0) { if (worldid < 0) {
return false; return false;
} }
@@ -501,7 +487,7 @@ public class Server {
wldRLock.unlock(); wldRLock.unlock();
} }
if(w == null || !w.canUninstall()) { if (w == null || !w.canUninstall()) {
return false; return false;
} }
@@ -557,46 +543,45 @@ public class Server {
} }
public static void cleanNxcodeCoupons(Connection con) throws SQLException { public static void cleanNxcodeCoupons(Connection con) throws SQLException {
if (!YamlConfig.config.server.USE_CLEAR_OUTDATED_COUPONS) return; if (!YamlConfig.config.server.USE_CLEAR_OUTDATED_COUPONS) {
return;
}
long timeClear = System.currentTimeMillis() - 14 * 24 * 60 * 60 * 1000; long timeClear = System.currentTimeMillis() - 14 * 24 * 60 * 60 * 1000;
PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE expiration <= ?"); try (PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE expiration <= ?")) {
ps.setLong(1, timeClear); ps.setLong(1, timeClear);
ResultSet rs = ps.executeQuery();
try (ResultSet rs = ps.executeQuery()) {
if (!rs.isLast()) { if (!rs.isLast()) {
PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode_items WHERE codeid = ?"); try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode_items WHERE codeid = ?")) {
while (rs.next()) { while (rs.next()) {
ps2.setInt(1, rs.getInt("id")); ps2.setInt(1, rs.getInt("id"));
ps2.addBatch(); ps2.addBatch();
} }
ps2.executeBatch(); ps2.executeBatch();
ps2.close();
ps2 = con.prepareStatement("DELETE FROM nxcode WHERE expiration <= ?");
ps2.setLong(1, timeClear);
ps2.executeUpdate();
ps2.close();
} }
rs.close(); try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode WHERE expiration <= ?")) {
ps.close(); ps2.setLong(1, timeClear);
ps2.executeUpdate();
}
}
}
}
} }
private void loadCouponRates(Connection c) throws SQLException { private void loadCouponRates(Connection c) throws SQLException {
PreparedStatement ps = c.prepareStatement("SELECT couponid, rate FROM nxcoupons"); try (PreparedStatement ps = c.prepareStatement("SELECT couponid, rate FROM nxcoupons");
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery()) {
while(rs.next()) { while (rs.next()) {
int cid = rs.getInt("couponid"); int cid = rs.getInt("couponid");
int rate = rs.getInt("rate"); int rate = rs.getInt("rate");
couponRates.put(cid, rate); couponRates.put(cid, rate);
} }
}
rs.close();
ps.close();
} }
public List<Integer> getActiveCoupons() { public List<Integer> getActiveCoupons() {
@@ -606,9 +591,11 @@ public class Server {
} }
public void commitActiveCoupons() { public void commitActiveCoupons() {
for(World world: getWorlds()) { for (World world : getWorlds()) {
for(MapleCharacter chr: world.getPlayerStorage().getAllCharacters()) { for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
if(!chr.isLoggedin()) continue; if (!chr.isLoggedin()) {
continue;
}
chr.updateCouponRates(); chr.updateCouponRates();
} }
@@ -616,12 +603,11 @@ public class Server {
} }
public void toggleCoupon(Integer couponId) { public void toggleCoupon(Integer couponId) {
if(ItemConstants.isRateCoupon(couponId)) { if (ItemConstants.isRateCoupon(couponId)) {
synchronized (activeCoupons) { synchronized (activeCoupons) {
if(activeCoupons.contains(couponId)) { if (activeCoupons.contains(couponId)) {
activeCoupons.remove(couponId); activeCoupons.remove(couponId);
} } else {
else {
activeCoupons.add(couponId); activeCoupons.add(couponId);
} }
@@ -638,9 +624,7 @@ public class Server {
int weekDay = c.get(Calendar.DAY_OF_WEEK); int weekDay = c.get(Calendar.DAY_OF_WEEK);
int hourDay = c.get(Calendar.HOUR_OF_DAY); int hourDay = c.get(Calendar.HOUR_OF_DAY);
Connection con = null; try (Connection con = DatabaseConnection.getConnection()) {
try {
con = DatabaseConnection.getConnection();
int weekdayMask = (1 << weekDay); int weekdayMask = (1 << weekDay);
PreparedStatement ps = con.prepareStatement("SELECT couponid FROM nxcoupons WHERE (activeday & ?) = ? AND starthour <= ? AND endhour > ?"); PreparedStatement ps = con.prepareStatement("SELECT couponid FROM nxcoupons WHERE (activeday & ?) = ? AND starthour <= ? AND endhour > ?");
@@ -649,25 +633,13 @@ public class Server {
ps.setInt(3, hourDay); ps.setInt(3, hourDay);
ps.setInt(4, hourDay); ps.setInt(4, hourDay);
ResultSet rs = ps.executeQuery(); try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) { while (rs.next()) {
activeCoupons.add(rs.getInt("couponid")); activeCoupons.add(rs.getInt("couponid"));
} }
}
rs.close();
ps.close();
con.close();
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
try {
if(con != null && !con.isClosed()) {
con.close();
}
} catch (SQLException ex2) {
ex2.printStackTrace();
}
} }
} }
} }
@@ -682,10 +654,10 @@ public class Server {
disLock.unlock(); disLock.unlock();
} }
while(!processDiseaseAnnounceClients.isEmpty()) { while (!processDiseaseAnnounceClients.isEmpty()) {
MapleClient c = processDiseaseAnnounceClients.remove(0); MapleClient c = processDiseaseAnnounceClients.remove(0);
MapleCharacter player = c.getPlayer(); MapleCharacter player = c.getPlayer();
if(player != null && player.isLoggedinWorld()) { if (player != null && player.isLoggedinWorld()) {
player.announceDiseases(); player.announceDiseases();
player.collectDiseases(); player.collectDiseases();
} }
@@ -694,7 +666,7 @@ public class Server {
disLock.lock(); disLock.lock();
try { try {
// this is to force the system to wait for at least one complete tick before releasing disease info for the registered clients // this is to force the system to wait for at least one complete tick before releasing disease info for the registered clients
while(!registeredDiseaseAnnouncePlayers.isEmpty()) { while (!registeredDiseaseAnnouncePlayers.isEmpty()) {
MapleClient c = registeredDiseaseAnnouncePlayers.remove(0); MapleClient c = registeredDiseaseAnnouncePlayers.remove(0);
processDiseaseAnnouncePlayers.add(c); processDiseaseAnnouncePlayers.add(c);
} }
@@ -723,11 +695,11 @@ public class Server {
private void installWorldPlayerRanking(int worldid) { private void installWorldPlayerRanking(int worldid) {
List<Pair<Integer, List<Pair<String, Integer>>>> ranking = updatePlayerRankingFromDB(worldid); List<Pair<Integer, List<Pair<String, Integer>>>> ranking = updatePlayerRankingFromDB(worldid);
if(!ranking.isEmpty()) { if (!ranking.isEmpty()) {
wldWLock.lock(); wldWLock.lock();
try { try {
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
for(int i = playerRanking.size(); i <= worldid; i++) { for (int i = playerRanking.size(); i <= worldid; i++) {
playerRanking.add(new ArrayList<Pair<String, Integer>>(0)); playerRanking.add(new ArrayList<Pair<String, Integer>>(0));
} }
@@ -745,7 +717,7 @@ public class Server {
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
wldWLock.lock(); wldWLock.lock();
try { try {
if(playerRanking.size() < worlds.size()) { if (playerRanking.size() < worlds.size()) {
return; return;
} }
@@ -767,15 +739,15 @@ public class Server {
public void updateWorldPlayerRanking() { public void updateWorldPlayerRanking() {
List<Pair<Integer, List<Pair<String, Integer>>>> rankUpdates = updatePlayerRankingFromDB(-1 * (this.getWorldsSize() - 1)); List<Pair<Integer, List<Pair<String, Integer>>>> rankUpdates = updatePlayerRankingFromDB(-1 * (this.getWorldsSize() - 1));
if(!rankUpdates.isEmpty()) { if (!rankUpdates.isEmpty()) {
wldWLock.lock(); wldWLock.lock();
try { try {
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
for(int i = playerRanking.size(); i <= rankUpdates.get(rankUpdates.size() - 1).getLeft(); i++) { for (int i = playerRanking.size(); i <= rankUpdates.get(rankUpdates.size() - 1).getLeft(); i++) {
playerRanking.add(new ArrayList<Pair<String, Integer>>(0)); playerRanking.add(new ArrayList<Pair<String, Integer>>(0));
} }
for(Pair<Integer, List<Pair<String, Integer>>> wranks : rankUpdates) { for (Pair<Integer, List<Pair<String, Integer>>> wranks : rankUpdates) {
playerRanking.set(wranks.getLeft(), wranks.getRight()); playerRanking.set(wranks.getLeft(), wranks.getRight());
} }
} else { } else {
@@ -798,15 +770,11 @@ public class Server {
List<Pair<Integer, List<Pair<String, Integer>>>> rankSystem = new ArrayList<>(); List<Pair<Integer, List<Pair<String, Integer>>>> rankSystem = new ArrayList<>();
List<Pair<String, Integer>> rankUpdate = new ArrayList<>(0); List<Pair<String, Integer>> rankUpdate = new ArrayList<>(0);
PreparedStatement ps = null; try (Connection con = DatabaseConnection.getConnection()) {
ResultSet rs = null;
Connection con = null;
try {
con = DatabaseConnection.getConnection();
String worldQuery; String worldQuery;
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
if(worldid >= 0) { if (worldid >= 0) {
worldQuery = (" AND `characters`.`world` = " + worldid); worldQuery = (" AND `characters`.`world` = " + worldid);
} else { } else {
worldQuery = (" AND `characters`.`world` >= 0 AND `characters`.`world` <= " + -worldid); worldQuery = (" AND `characters`.`world` >= 0 AND `characters`.`world` <= " + -worldid);
@@ -815,14 +783,14 @@ public class Server {
worldQuery = (" AND `characters`.`world` >= 0 AND `characters`.`world` <= " + Math.abs(worldid)); worldQuery = (" AND `characters`.`world` >= 0 AND `characters`.`world` <= " + Math.abs(worldid));
} }
ps = con.prepareStatement("SELECT `characters`.`name`, `characters`.`level`, `characters`.`world` FROM `characters` LEFT JOIN accounts ON accounts.id = characters.accountid WHERE `characters`.`gm` < 2 AND `accounts`.`banned` = '0'" + worldQuery + " ORDER BY " + (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING ? "world, " : "") + "level DESC, exp DESC, lastExpGainTime ASC LIMIT 50"); try (PreparedStatement ps = con.prepareStatement("SELECT `characters`.`name`, `characters`.`level`, `characters`.`world` FROM `characters` LEFT JOIN accounts ON accounts.id = characters.accountid WHERE `characters`.`gm` < 2 AND `accounts`.`banned` = '0'" + worldQuery + " ORDER BY " + (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING ? "world, " : "") + "level DESC, exp DESC, lastExpGainTime ASC LIMIT 50");
rs = ps.executeQuery(); ResultSet rs = ps.executeQuery()) {
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
int currentWorld = -1; int currentWorld = -1;
while(rs.next()) { while (rs.next()) {
int rsWorld = rs.getInt("world"); int rsWorld = rs.getInt("world");
if(currentWorld < rsWorld) { if (currentWorld < rsWorld) {
currentWorld = rsWorld; currentWorld = rsWorld;
rankUpdate = new ArrayList<>(50); rankUpdate = new ArrayList<>(50);
rankSystem.add(new Pair<>(rsWorld, rankUpdate)); rankSystem.add(new Pair<>(rsWorld, rankUpdate));
@@ -834,30 +802,13 @@ public class Server {
rankUpdate = new ArrayList<>(50); rankUpdate = new ArrayList<>(50);
rankSystem.add(new Pair<>(0, rankUpdate)); rankSystem.add(new Pair<>(0, rankUpdate));
while(rs.next()) { while (rs.next()) {
rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level"))); rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level")));
} }
} }
}
ps.close(); } catch (SQLException ex) {
rs.close();
con.close();
} catch(SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
} finally {
try {
if(ps != null && !ps.isClosed()) {
ps.close();
}
if(rs != null && !rs.isClosed()) {
rs.close();
}
if(con != null && !con.isClosed()) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} }
return rankSystem; return rankSystem;
@@ -866,7 +817,7 @@ public class Server {
public void init() { public void init() {
System.out.println("Cosmic v" + ServerConstants.VERSION + " starting up.\r\n"); System.out.println("Cosmic v" + ServerConstants.VERSION + " starting up.\r\n");
if(YamlConfig.config.server.SHUTDOWNHOOK) { if (YamlConfig.config.server.SHUTDOWNHOOK) {
Runtime.getRuntime().addShutdownHook(new Thread(shutdown(false))); Runtime.getRuntime().addShutdownHook(new Thread(shutdown(false)));
} }
@@ -876,24 +827,22 @@ public class Server {
TimeZone.setDefault(TimeZone.getTimeZone(YamlConfig.config.server.TIMEZONE)); TimeZone.setDefault(TimeZone.getTimeZone(YamlConfig.config.server.TIMEZONE));
Connection c = null; try (Connection con = DatabaseConnection.getConnection()) {
try { try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = 0")) {
c = DatabaseConnection.getConnection();
PreparedStatement ps = c.prepareStatement("UPDATE accounts SET loggedin = 0");
ps.executeUpdate(); ps.executeUpdate();
ps.close(); }
ps = c.prepareStatement("UPDATE characters SET HasMerchant = 0");
ps.executeUpdate();
ps.close();
cleanNxcodeCoupons(c); try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0")) {
loadCouponRates(c); ps.executeUpdate();
}
cleanNxcodeCoupons(con);
loadCouponRates(con);
updateActiveCoupons(); updateActiveCoupons();
c.close();
} catch (SQLException sqle) { } catch (SQLException sqle) {
sqle.printStackTrace(); sqle.printStackTrace();
} }
applyAllNameChanges(); // -- name changes can be missed by INSTANT_NAME_CHANGE -- applyAllNameChanges(); // -- name changes can be missed by INSTANT_NAME_CHANGE --
applyAllWorldTransfers(); applyAllWorldTransfers();
//MaplePet.clearMissingPetsFromDb(); // thanks Optimist for noticing this taking too long to run //MaplePet.clearMissingPetsFromDb(); // thanks Optimist for noticing this taking too long to run
@@ -917,7 +866,9 @@ public class Server {
NewYearCardRecord.startPendingNewYearCardRequests(); NewYearCardRecord.startPendingNewYearCardRequests();
if(YamlConfig.config.server.USE_THREAD_TRACKER) ThreadTracker.getInstance().registerThreadTrackerTask(); if (YamlConfig.config.server.USE_THREAD_TRACKER) {
ThreadTracker.getInstance().registerThreadTrackerTask();
}
try { try {
Integer worldCount = Math.min(GameConstants.WORLD_NAMES.length, YamlConfig.config.server.WORLDS); Integer worldCount = Math.min(GameConstants.WORLD_NAMES.length, YamlConfig.config.server.WORLDS);
@@ -937,7 +888,7 @@ public class Server {
System.out.println(); System.out.println();
if(YamlConfig.config.server.USE_FAMILY_SYSTEM) { if (YamlConfig.config.server.USE_FAMILY_SYSTEM) {
timeToTake = System.currentTimeMillis(); timeToTake = System.currentTimeMillis();
MapleFamily.loadAllFamilies(); MapleFamily.loadAllFamilies();
System.out.println("Families loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds\r\n"); System.out.println("Families loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds\r\n");
@@ -1103,8 +1054,8 @@ public class Server {
public MapleGuild getGuildByName(String name) { public MapleGuild getGuildByName(String name) {
synchronized (guilds) { synchronized (guilds) {
for(MapleGuild mg: guilds.values()) { for (MapleGuild mg : guilds.values()) {
if(mg.getName().equalsIgnoreCase(name)) { if (mg.getName().equalsIgnoreCase(name)) {
return mg; return mg;
} }
} }
@@ -1139,7 +1090,7 @@ public class Server {
return null; return null;
} }
if(mc != null) { if (mc != null) {
MapleGuildCharacter mgc = g.getMGC(mc.getId()); MapleGuildCharacter mgc = g.getMGC(mc.getId());
if (mgc != null) { if (mgc != null) {
mc.setMGC(mgc); mc.setMGC(mgc);
@@ -1267,7 +1218,7 @@ public class Server {
public void guildMessage(int gid, byte[] packet, int exception) { public void guildMessage(int gid, byte[] packet, int exception) {
MapleGuild g = guilds.get(gid); MapleGuild g = guilds.get(gid);
if(g != null) { if (g != null) {
g.broadcast(packet, exception); g.broadcast(packet, exception);
} }
} }
@@ -1286,7 +1237,9 @@ public class Server {
} }
public void deleteGuildCharacter(MapleGuildCharacter mgc) { public void deleteGuildCharacter(MapleGuildCharacter mgc) {
if(mgc.getCharacter() != null) setGuildMemberOnline(mgc.getCharacter(), false, (byte) -1); if (mgc.getCharacter() != null) {
setGuildMemberOnline(mgc.getCharacter(), false, (byte) -1);
}
if (mgc.getGuildRank() > 1) { if (mgc.getGuildRank() > 1) {
leaveGuild(mgc); leaveGuild(mgc);
} else { } else {
@@ -1320,7 +1273,7 @@ public class Server {
public boolean isGmOnline(int world) { public boolean isGmOnline(int world) {
for (Channel ch : getChannelsFromWorld(world)) { for (Channel ch : getChannelsFromWorld(world)) {
for (MapleCharacter player : ch.getPlayerStorage().getAllCharacters()) { for (MapleCharacter player : ch.getPlayerStorage().getAllCharacters()) {
if (player.isGM()){ if (player.isGM()) {
return true; return true;
} }
} }
@@ -1329,7 +1282,7 @@ public class Server {
} }
public void changeFly(Integer accountid, boolean canFly) { public void changeFly(Integer accountid, boolean canFly) {
if(canFly) { if (canFly) {
activeFly.add(accountid); activeFly.add(accountid);
} else { } else {
activeFly.remove(accountid); activeFly.remove(accountid);
@@ -1374,8 +1327,8 @@ public class Server {
try { try {
short count = 0; short count = 0;
for(Integer chr : accountChars.get(accountid)) { for (Integer chr : accountChars.get(accountid)) {
if(worldChars.get(chr).equals(worldid)) { if (worldChars.get(chr).equals(worldid)) {
count++; count++;
} }
} }
@@ -1401,7 +1354,9 @@ public class Server {
lgnWLock.lock(); lgnWLock.lock();
try { try {
World wserv = this.getWorld(chrView.getWorld()); World wserv = this.getWorld(chrView.getWorld());
if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); if (wserv != null) {
wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
}
} finally { } finally {
lgnWLock.unlock(); lgnWLock.unlock();
} }
@@ -1412,7 +1367,7 @@ public class Server {
lgnWLock.lock(); lgnWLock.lock();
try { try {
accountCharacterCount.put(accountid, (short)(accountCharacterCount.get(accountid) + 1)); accountCharacterCount.put(accountid, (short) (accountCharacterCount.get(accountid) + 1));
Set<Integer> accChars = accountChars.get(accountid); Set<Integer> accChars = accountChars.get(accountid);
accChars.add(chrid); accChars.add(chrid);
@@ -1422,7 +1377,9 @@ public class Server {
MapleCharacter chrView = chr.generateCharacterEntry(); MapleCharacter chrView = chr.generateCharacterEntry();
World wserv = this.getWorld(chrView.getWorld()); World wserv = this.getWorld(chrView.getWorld());
if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); if (wserv != null) {
wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
}
} finally { } finally {
lgnWLock.unlock(); lgnWLock.unlock();
} }
@@ -1431,15 +1388,17 @@ public class Server {
public void deleteCharacterEntry(Integer accountid, Integer chrid) { public void deleteCharacterEntry(Integer accountid, Integer chrid) {
lgnWLock.lock(); lgnWLock.lock();
try { try {
accountCharacterCount.put(accountid, (short)(accountCharacterCount.get(accountid) - 1)); accountCharacterCount.put(accountid, (short) (accountCharacterCount.get(accountid) - 1));
Set<Integer> accChars = accountChars.get(accountid); Set<Integer> accChars = accountChars.get(accountid);
accChars.remove(chrid); accChars.remove(chrid);
Integer world = worldChars.remove(chrid); Integer world = worldChars.remove(chrid);
if(world != null) { if (world != null) {
World wserv = this.getWorld(world); World wserv = this.getWorld(world);
if(wserv != null) wserv.unregisterAccountCharacterView(accountid, chrid); if (wserv != null) {
wserv.unregisterAccountCharacterView(accountid, chrid);
}
} }
} finally { } finally {
lgnWLock.unlock(); lgnWLock.unlock();
@@ -1450,9 +1409,11 @@ public class Server {
lgnWLock.lock(); lgnWLock.lock();
try { try {
Integer chrid = chr.getId(), accountid = chr.getAccountID(), world = worldChars.get(chr.getId()); Integer chrid = chr.getId(), accountid = chr.getAccountID(), world = worldChars.get(chr.getId());
if(world != null) { if (world != null) {
World wserv = this.getWorld(world); World wserv = this.getWorld(world);
if(wserv != null) wserv.unregisterAccountCharacterView(accountid, chrid); if (wserv != null) {
wserv.unregisterAccountCharacterView(accountid, chrid);
}
} }
worldChars.put(chrid, toWorld); worldChars.put(chrid, toWorld);
@@ -1460,7 +1421,9 @@ public class Server {
MapleCharacter chrView = chr.generateCharacterEntry(); MapleCharacter chrView = chr.generateCharacterEntry();
World wserv = this.getWorld(toWorld); World wserv = this.getWorld(toWorld);
if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); if (wserv != null) {
wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
}
} finally { } finally {
lgnWLock.unlock(); lgnWLock.unlock();
} }
@@ -1485,7 +1448,9 @@ public class Server {
public Pair<Pair<Integer, List<MapleCharacter>>, List<Pair<Integer, List<MapleCharacter>>>> loadAccountCharlist(Integer accountId, int visibleWorlds) { public Pair<Pair<Integer, List<MapleCharacter>>, List<Pair<Integer, List<MapleCharacter>>>> loadAccountCharlist(Integer accountId, int visibleWorlds) {
List<World> wlist = this.getWorlds(); List<World> wlist = this.getWorlds();
if(wlist.size() > visibleWorlds) wlist = wlist.subList(0, visibleWorlds); if (wlist.size() > visibleWorlds) {
wlist = wlist.subList(0, visibleWorlds);
}
List<Pair<Integer, List<MapleCharacter>>> accChars = new ArrayList<>(wlist.size() + 1); List<Pair<Integer, List<MapleCharacter>>> accChars = new ArrayList<>(wlist.size() + 1);
int chrTotal = 0; int chrTotal = 0;
@@ -1493,14 +1458,14 @@ public class Server {
lgnRLock.lock(); lgnRLock.lock();
try { try {
for(World w : wlist) { for (World w : wlist) {
List<MapleCharacter> wchars = w.getAccountCharactersView(accountId); List<MapleCharacter> wchars = w.getAccountCharactersView(accountId);
if(wchars == null) { if (wchars == null) {
if(!accountChars.containsKey(accountId)) { if (!accountChars.containsKey(accountId)) {
accountCharacterCount.put(accountId, (short) 0); accountCharacterCount.put(accountId, (short) 0);
accountChars.put(accountId, new HashSet<Integer>()); // not advisable at all to write on the map on a read-protected environment accountChars.put(accountId, new HashSet<Integer>()); // not advisable at all to write on the map on a read-protected environment
} // yet it's known there's no problem since no other point in the source does } // yet it's known there's no problem since no other point in the source does
} else if(!wchars.isEmpty()) { // this action. } else if (!wchars.isEmpty()) { // this action.
lastwchars = wchars; lastwchars = wchars;
accChars.add(new Pair<>(w.getId(), wchars)); accChars.add(new Pair<>(w.getId(), wchars));
@@ -1517,7 +1482,9 @@ public class Server {
private static Pair<Short, List<List<MapleCharacter>>> loadAccountCharactersViewFromDb(int accId, int wlen) { private static Pair<Short, List<List<MapleCharacter>>> loadAccountCharactersViewFromDb(int accId, int wlen) {
short characterCount = 0; short characterCount = 0;
List<List<MapleCharacter>> wchars = new ArrayList<>(wlen); List<List<MapleCharacter>> wchars = new ArrayList<>(wlen);
for(int i = 0; i < wlen; i++) wchars.add(i, new LinkedList<MapleCharacter>()); for (int i = 0; i < wlen; i++) {
wchars.add(i, new LinkedList<MapleCharacter>());
}
List<MapleCharacter> chars = new LinkedList<>(); List<MapleCharacter> chars = new LinkedList<>();
int curWorld = 0; int curWorld = 0;
@@ -1525,9 +1492,9 @@ public class Server {
List<Pair<Item, Integer>> accEquips = ItemFactory.loadEquippedItems(accId, true, true); List<Pair<Item, Integer>> accEquips = ItemFactory.loadEquippedItems(accId, true, true);
Map<Integer, List<Item>> accPlayerEquips = new HashMap<>(); Map<Integer, List<Item>> accPlayerEquips = new HashMap<>();
for(Pair<Item, Integer> ae : accEquips) { for (Pair<Item, Integer> ae : accEquips) {
List<Item> playerEquips = accPlayerEquips.get(ae.getRight()); List<Item> playerEquips = accPlayerEquips.get(ae.getRight());
if(playerEquips == null) { if (playerEquips == null) {
playerEquips = new LinkedList<>(); playerEquips = new LinkedList<>();
accPlayerEquips.put(ae.getRight(), playerEquips); accPlayerEquips.put(ae.getRight(), playerEquips);
} }
@@ -1535,17 +1502,20 @@ public class Server {
playerEquips.add(ae.getLeft()); playerEquips.add(ae.getLeft());
} }
Connection con = DatabaseConnection.getConnection();
try (PreparedStatement ps = con.prepareStatement("SELECT * FROM characters WHERE accountid = ? ORDER BY world, id")) { try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM characters WHERE accountid = ? ORDER BY world, id")) {
ps.setInt(1, accId); ps.setInt(1, accId);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { while (rs.next()) {
characterCount++; characterCount++;
int cworld = rs.getByte("world"); int cworld = rs.getByte("world");
if(cworld >= wlen) continue; if (cworld >= wlen) {
continue;
}
if(cworld > curWorld) { if (cworld > curWorld) {
wchars.add(curWorld, chars); wchars.add(curWorld, chars);
curWorld = cworld; curWorld = cworld;
@@ -1557,7 +1527,6 @@ public class Server {
} }
} }
} }
con.close();
wchars.add(curWorld, chars); wchars.add(curWorld, chars);
} catch (SQLException sqle) { } catch (SQLException sqle) {
@@ -1568,10 +1537,9 @@ public class Server {
} }
public void loadAllAccountsCharactersView() { public void loadAllAccountsCharactersView() {
try { try (Connection con = DatabaseConnection.getConnection();
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT id FROM accounts"); PreparedStatement ps = con.prepareStatement("SELECT id FROM accounts");
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery()) {
while (rs.next()) { while (rs.next()) {
int accountId = rs.getInt("id"); int accountId = rs.getInt("id");
@@ -1579,10 +1547,6 @@ public class Server {
loadAccountCharactersView(accountId, 0, 0); loadAccountCharactersView(accountId, 0, 0);
} }
} }
rs.close();
ps.close();
con.close();
} catch (SQLException se) { } catch (SQLException se) {
se.printStackTrace(); se.printStackTrace();
} }
@@ -1599,25 +1563,28 @@ public class Server {
private static void applyAllNameChanges() { private static void applyAllNameChanges() {
try (Connection con = DatabaseConnection.getConnection(); try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE completionTime IS NULL")) { PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE completionTime IS NULL");
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery()) {
List<Pair<String, String>> changedNames = new LinkedList<Pair<String, String>>(); //logging only List<Pair<String, String>> changedNames = new LinkedList<Pair<String, String>>(); //logging only
while(rs.next()) { while (rs.next()) {
con.setAutoCommit(false); con.setAutoCommit(false);
int nameChangeId = rs.getInt("id"); int nameChangeId = rs.getInt("id");
int characterId = rs.getInt("characterId"); int characterId = rs.getInt("characterId");
String oldName = rs.getString("old"); String oldName = rs.getString("old");
String newName = rs.getString("new"); String newName = rs.getString("new");
boolean success = MapleCharacter.doNameChange(con, characterId, oldName, newName, nameChangeId); boolean success = MapleCharacter.doNameChange(con, characterId, oldName, newName, nameChangeId);
if(!success) con.rollback(); //discard changes if (!success) {
else changedNames.add(new Pair<String, String>(oldName, newName)); con.rollback(); //discard changes
} else {
changedNames.add(new Pair<String, String>(oldName, newName));
}
con.setAutoCommit(true); con.setAutoCommit(true);
} }
//log //log
for(Pair<String, String> namePair : changedNames) { for (Pair<String, String> namePair : changedNames) {
FilePrinter.print(FilePrinter.CHANGE_CHARACTER_NAME, "Name change applied : from \"" + namePair.getLeft() + "\" to \"" + namePair.getRight() + "\" at " + Calendar.getInstance().getTime().toString()); FilePrinter.print(FilePrinter.CHANGE_CHARACTER_NAME, "Name change applied : from \"" + namePair.getLeft() + "\" to \"" + namePair.getRight() + "\" at " + Calendar.getInstance().getTime().toString());
} }
} catch(SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to retrieve list of pending name changes."); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to retrieve list of pending name changes.");
} }
@@ -1626,22 +1593,22 @@ public class Server {
private static void applyAllWorldTransfers() { private static void applyAllWorldTransfers() {
try (Connection con = DatabaseConnection.getConnection(); try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM worldtransfers WHERE completionTime IS NULL", PreparedStatement ps = con.prepareStatement("SELECT * FROM worldtransfers WHERE completionTime IS NULL",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery()) {
List<Integer> removedTransfers = new LinkedList<Integer>(); List<Integer> removedTransfers = new LinkedList<Integer>();
while(rs.next()) { while (rs.next()) {
int nameChangeId = rs.getInt("id"); int nameChangeId = rs.getInt("id");
int characterId = rs.getInt("characterId"); int characterId = rs.getInt("characterId");
int oldWorld = rs.getInt("from"); int oldWorld = rs.getInt("from");
int newWorld = rs.getInt("to"); int newWorld = rs.getInt("to");
String reason = MapleCharacter.checkWorldTransferEligibility(con, characterId, oldWorld, newWorld); //check if character is still eligible String reason = MapleCharacter.checkWorldTransferEligibility(con, characterId, oldWorld, newWorld); //check if character is still eligible
if(reason != null) { if (reason != null) {
removedTransfers.add(nameChangeId); removedTransfers.add(nameChangeId);
FilePrinter.print(FilePrinter.WORLD_TRANSFER, "World transfer cancelled : Character ID " + characterId + " at " + Calendar.getInstance().getTime().toString() + ", Reason : " + reason); FilePrinter.print(FilePrinter.WORLD_TRANSFER, "World transfer cancelled : Character ID " + characterId + " at " + Calendar.getInstance().getTime().toString() + ", Reason : " + reason);
try (PreparedStatement delPs = con.prepareStatement("DELETE FROM worldtransfers WHERE id = ?")) { try (PreparedStatement delPs = con.prepareStatement("DELETE FROM worldtransfers WHERE id = ?")) {
delPs.setInt(1, nameChangeId); delPs.setInt(1, nameChangeId);
delPs.executeUpdate(); delPs.executeUpdate();
} catch(SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to delete world transfer for character ID " + characterId); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to delete world transfer for character ID " + characterId);
} }
@@ -1649,26 +1616,31 @@ public class Server {
} }
rs.beforeFirst(); rs.beforeFirst();
List<Pair<Integer, Pair<Integer, Integer>>> worldTransfers = new LinkedList<Pair<Integer, Pair<Integer, Integer>>>(); //logging only <charid, <oldWorld, newWorld>> List<Pair<Integer, Pair<Integer, Integer>>> worldTransfers = new LinkedList<Pair<Integer, Pair<Integer, Integer>>>(); //logging only <charid, <oldWorld, newWorld>>
while(rs.next()) { while (rs.next()) {
con.setAutoCommit(false); con.setAutoCommit(false);
int nameChangeId = rs.getInt("id"); int nameChangeId = rs.getInt("id");
if(removedTransfers.contains(nameChangeId)) continue; if (removedTransfers.contains(nameChangeId)) {
continue;
}
int characterId = rs.getInt("characterId"); int characterId = rs.getInt("characterId");
int oldWorld = rs.getInt("from"); int oldWorld = rs.getInt("from");
int newWorld = rs.getInt("to"); int newWorld = rs.getInt("to");
boolean success = MapleCharacter.doWorldTransfer(con, characterId, oldWorld, newWorld, nameChangeId); boolean success = MapleCharacter.doWorldTransfer(con, characterId, oldWorld, newWorld, nameChangeId);
if(!success) con.rollback(); if (!success) {
else worldTransfers.add(new Pair<Integer, Pair<Integer, Integer>>(characterId, new Pair<Integer, Integer>(oldWorld, newWorld))); con.rollback();
} else {
worldTransfers.add(new Pair<Integer, Pair<Integer, Integer>>(characterId, new Pair<Integer, Integer>(oldWorld, newWorld)));
}
con.setAutoCommit(true); con.setAutoCommit(true);
} }
//log //log
for(Pair<Integer, Pair<Integer, Integer>> worldTransferPair : worldTransfers) { for (Pair<Integer, Pair<Integer, Integer>> worldTransferPair : worldTransfers) {
int charId = worldTransferPair.getLeft(); int charId = worldTransferPair.getLeft();
int oldWorld = worldTransferPair.getRight().getLeft(); int oldWorld = worldTransferPair.getRight().getLeft();
int newWorld = worldTransferPair.getRight().getRight(); int newWorld = worldTransferPair.getRight().getRight();
FilePrinter.print(FilePrinter.WORLD_TRANSFER, "World transfer applied : Character ID " + charId + " from World " + oldWorld + " to World " + newWorld + " at " + Calendar.getInstance().getTime().toString()); FilePrinter.print(FilePrinter.WORLD_TRANSFER, "World transfer applied : Character ID " + charId + " from World " + oldWorld + " to World " + newWorld + " at " + Calendar.getInstance().getTime().toString());
} }
} catch(SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to retrieve list of pending world transfers."); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to retrieve list of pending world transfers.");
} }
@@ -1694,7 +1666,9 @@ public class Server {
if (wserv != null) { if (wserv != null) {
for (MapleCharacter chr : wserv.getAllCharactersView()) { for (MapleCharacter chr : wserv.getAllCharactersView()) {
if (gmLevel < chr.gmLevel()) gmLevel = chr.gmLevel(); if (gmLevel < chr.gmLevel()) {
gmLevel = chr.gmLevel();
}
} }
} }
} }
@@ -1717,7 +1691,7 @@ public class Server {
accountCharacterCount.put(accId, accCharacters.getLeft()); accountCharacterCount.put(accId, accCharacters.getLeft());
Set<Integer> chars = accountChars.get(accId); Set<Integer> chars = accountChars.get(accId);
if(chars == null) { if (chars == null) {
chars = new HashSet<>(5); chars = new HashSet<>(5);
} }
@@ -1728,7 +1702,9 @@ public class Server {
for (MapleCharacter chr : wchars) { for (MapleCharacter chr : wchars) {
int cid = chr.getId(); int cid = chr.getId();
if (gmLevel < chr.gmLevel()) gmLevel = chr.gmLevel(); if (gmLevel < chr.gmLevel()) {
gmLevel = chr.gmLevel();
}
chars.add(cid); chars.add(cid);
worldChars.put(cid, wid); worldChars.put(cid, wid);
@@ -1855,13 +1831,13 @@ public class Server {
try { try {
long timeNow = System.currentTimeMillis(); long timeNow = System.currentTimeMillis();
for(Entry<MapleClient, Long> mc : inLoginState.entrySet()) { for (Entry<MapleClient, Long> mc : inLoginState.entrySet()) {
if(timeNow > mc.getValue()) { if (timeNow > mc.getValue()) {
toDisconnect.add(mc.getKey()); toDisconnect.add(mc.getKey());
} }
} }
for(MapleClient c : toDisconnect) { for (MapleClient c : toDisconnect) {
inLoginState.remove(c); inLoginState.remove(c);
} }
} finally { } finally {
@@ -1869,7 +1845,7 @@ public class Server {
} }
for (MapleClient c : toDisconnect) { // thanks Lei for pointing a deadlock issue with srvLock for (MapleClient c : toDisconnect) { // thanks Lei for pointing a deadlock issue with srvLock
if(c.isLoggedIn()) { if (c.isLoggedIn()) {
c.disconnect(false, false); c.disconnect(false, false);
} else { } else {
MapleSessionCoordinator.getInstance().closeSession(c.getSession(), true); MapleSessionCoordinator.getInstance().closeSession(c.getSession(), true);
@@ -1897,7 +1873,9 @@ public class Server {
private synchronized void shutdownInternal(boolean restart) { private synchronized void shutdownInternal(boolean restart) {
System.out.println((restart ? "Restarting" : "Shutting down") + " the server!\r\n"); System.out.println((restart ? "Restarting" : "Shutting down") + " the server!\r\n");
if (getWorlds() == null) return;//already shutdown if (getWorlds() == null) {
return;//already shutdown
}
for (World w : getWorlds()) { for (World w : getWorlds()) {
w.shutdown(); w.shutdown();
} }
@@ -1923,7 +1901,9 @@ public class Server {
List<Channel> allChannels = getAllChannels(); List<Channel> allChannels = getAllChannels();
if(YamlConfig.config.server.USE_THREAD_TRACKER) ThreadTracker.getInstance().cancelThreadTrackerTask(); if (YamlConfig.config.server.USE_THREAD_TRACKER) {
ThreadTracker.getInstance().cancelThreadTrackerTask();
}
for (Channel ch : allChannels) { for (Channel ch : allChannels) {
while (!ch.finishedShutdown()) { while (!ch.finishedShutdown()) {