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;
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.ArrayList;
import java.util.Calendar;
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 client.MapleCharacter;
import client.MapleClient;
import client.MapleFamily;
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 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.locks.MonitoredLockType;
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.MonitoredReentrantLockFactory;
import net.server.audit.locks.factory.MonitoredWriteLockFactory;
import net.MapleServerHandler;
import net.mina.MapleCodecFactory;
import net.server.channel.Channel;
import net.server.coordinator.session.MapleSessionCoordinator;
import net.server.guild.MapleAlliance;
import net.server.guild.MapleGuild;
import net.server.guild.MapleGuildCharacter;
import net.server.task.BossLogTask;
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.task.*;
import net.server.world.World;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.buffer.SimpleBufferAllocator;
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.filter.codec.ProtocolCodecFilter;
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.MapleSkillbookInformationProvider;
import server.ThreadManager;
@@ -107,6 +71,18 @@ import tools.DatabaseConnection;
import tools.FilePrinter;
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 {
private static Server instance = null;
@@ -209,23 +185,23 @@ public class Server {
}
private void loadPlayerNpcMapStepFromDb() {
try {
List<World> wlist = this.getWorlds();
final List<World> wlist = this.getWorlds();
Connection con = DatabaseConnection.getConnection();
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_field");
ResultSet rs = ps.executeQuery()) {
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int world = rs.getInt("world"), map = rs.getInt("map"), step = rs.getInt("step"), podium = rs.getInt("podium");
while (rs.next()) {
int world = rs.getInt("world");
int map = rs.getInt("map");
int step = rs.getInt("step");
int podium = rs.getInt("podium");
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) {
e.printStackTrace();
}
@@ -265,7 +241,7 @@ public class Server {
public Channel getChannel(int world, int channel) {
try {
return this.getWorld(world).getChannel(channel);
} catch(NullPointerException npe) {
} catch (NullPointerException npe) {
return null;
}
}
@@ -273,7 +249,7 @@ public class Server {
public List<Channel> getChannelsFromWorld(int world) {
try {
return this.getWorld(world).getChannels();
} catch(NullPointerException npe) {
} catch (NullPointerException npe) {
return new ArrayList<>(0);
}
}
@@ -287,7 +263,7 @@ public class Server {
}
}
return channelz;
} catch(NullPointerException npe) {
} catch (NullPointerException npe) {
return new ArrayList<>(0);
}
}
@@ -339,13 +315,19 @@ public class Server {
wldRLock.lock();
try {
if(worldid >= worlds.size()) return -3;
if (worldid >= worlds.size()) {
return -3;
}
channelInfo = channels.get(worldid);
if(channelInfo == null) return -3;
if (channelInfo == null) {
return -3;
}
channelid = channelInfo.size();
if(channelid >= YamlConfig.config.server.CHANNEL_SIZE) return -2;
if (channelid >= YamlConfig.config.server.CHANNEL_SIZE) {
return -2;
}
channelid++;
world = this.getWorld(worldid);
@@ -370,7 +352,7 @@ public class Server {
public int addWorld() {
int newWorld = initWorld();
if(newWorld > -1) {
if (newWorld > -1) {
installWorldPlayerRanking(newWorld);
Set<Integer> accounts;
@@ -381,7 +363,7 @@ public class Server {
lgnRLock.unlock();
}
for(Integer accId : accounts) {
for (Integer accId : accounts) {
loadAccountCharactersView(accId, 0, newWorld);
}
}
@@ -396,7 +378,7 @@ public class Server {
try {
i = worlds.size();
if(i >= YamlConfig.config.server.WLDLIST_SIZE) {
if (i >= YamlConfig.config.server.WLDLIST_SIZE) {
return -1;
}
} finally {
@@ -463,7 +445,9 @@ public class Server {
wldRLock.lock();
try {
if(worldid >= worlds.size()) return false;
if (worldid >= worlds.size()) {
return false;
}
world = worlds.get(worldid);
} finally {
wldRLock.unlock();
@@ -474,7 +458,9 @@ public class Server {
wldWLock.lock();
try {
Map<Integer, String> m = channels.get(worldid);
if(m != null) m.remove(channel);
if (m != null) {
m.remove(channel);
}
} finally {
wldWLock.unlock();
}
@@ -492,7 +478,7 @@ public class Server {
wldRLock.lock();
try {
worldid = worlds.size() - 1;
if(worldid < 0) {
if (worldid < 0) {
return false;
}
@@ -501,7 +487,7 @@ public class Server {
wldRLock.unlock();
}
if(w == null || !w.canUninstall()) {
if (w == null || !w.canUninstall()) {
return false;
}
@@ -557,46 +543,45 @@ public class Server {
}
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;
PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE expiration <= ?");
try (PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE expiration <= ?")) {
ps.setLong(1, timeClear);
ResultSet rs = ps.executeQuery();
try (ResultSet rs = ps.executeQuery()) {
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()) {
ps2.setInt(1, rs.getInt("id"));
ps2.addBatch();
}
ps2.executeBatch();
ps2.close();
ps2 = con.prepareStatement("DELETE FROM nxcode WHERE expiration <= ?");
ps2.setLong(1, timeClear);
ps2.executeUpdate();
ps2.close();
}
rs.close();
ps.close();
try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode WHERE expiration <= ?")) {
ps2.setLong(1, timeClear);
ps2.executeUpdate();
}
}
}
}
}
private void loadCouponRates(Connection c) throws SQLException {
PreparedStatement ps = c.prepareStatement("SELECT couponid, rate FROM nxcoupons");
ResultSet rs = ps.executeQuery();
try (PreparedStatement ps = c.prepareStatement("SELECT couponid, rate FROM nxcoupons");
ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
while (rs.next()) {
int cid = rs.getInt("couponid");
int rate = rs.getInt("rate");
couponRates.put(cid, rate);
}
rs.close();
ps.close();
}
}
public List<Integer> getActiveCoupons() {
@@ -606,9 +591,11 @@ public class Server {
}
public void commitActiveCoupons() {
for(World world: getWorlds()) {
for(MapleCharacter chr: world.getPlayerStorage().getAllCharacters()) {
if(!chr.isLoggedin()) continue;
for (World world : getWorlds()) {
for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) {
if (!chr.isLoggedin()) {
continue;
}
chr.updateCouponRates();
}
@@ -616,12 +603,11 @@ public class Server {
}
public void toggleCoupon(Integer couponId) {
if(ItemConstants.isRateCoupon(couponId)) {
if (ItemConstants.isRateCoupon(couponId)) {
synchronized (activeCoupons) {
if(activeCoupons.contains(couponId)) {
if (activeCoupons.contains(couponId)) {
activeCoupons.remove(couponId);
}
else {
} else {
activeCoupons.add(couponId);
}
@@ -638,9 +624,7 @@ public class Server {
int weekDay = c.get(Calendar.DAY_OF_WEEK);
int hourDay = c.get(Calendar.HOUR_OF_DAY);
Connection con = null;
try {
con = DatabaseConnection.getConnection();
try (Connection con = DatabaseConnection.getConnection()) {
int weekdayMask = (1 << weekDay);
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(4, hourDay);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
activeCoupons.add(rs.getInt("couponid"));
}
rs.close();
ps.close();
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
try {
if(con != null && !con.isClosed()) {
con.close();
}
} catch (SQLException ex2) {
ex2.printStackTrace();
}
}
}
}
@@ -682,10 +654,10 @@ public class Server {
disLock.unlock();
}
while(!processDiseaseAnnounceClients.isEmpty()) {
while (!processDiseaseAnnounceClients.isEmpty()) {
MapleClient c = processDiseaseAnnounceClients.remove(0);
MapleCharacter player = c.getPlayer();
if(player != null && player.isLoggedinWorld()) {
if (player != null && player.isLoggedinWorld()) {
player.announceDiseases();
player.collectDiseases();
}
@@ -694,7 +666,7 @@ public class Server {
disLock.lock();
try {
// 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);
processDiseaseAnnouncePlayers.add(c);
}
@@ -723,11 +695,11 @@ public class Server {
private void installWorldPlayerRanking(int worldid) {
List<Pair<Integer, List<Pair<String, Integer>>>> ranking = updatePlayerRankingFromDB(worldid);
if(!ranking.isEmpty()) {
if (!ranking.isEmpty()) {
wldWLock.lock();
try {
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));
}
@@ -745,7 +717,7 @@ public class Server {
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
wldWLock.lock();
try {
if(playerRanking.size() < worlds.size()) {
if (playerRanking.size() < worlds.size()) {
return;
}
@@ -767,15 +739,15 @@ public class Server {
public void updateWorldPlayerRanking() {
List<Pair<Integer, List<Pair<String, Integer>>>> rankUpdates = updatePlayerRankingFromDB(-1 * (this.getWorldsSize() - 1));
if(!rankUpdates.isEmpty()) {
if (!rankUpdates.isEmpty()) {
wldWLock.lock();
try {
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));
}
for(Pair<Integer, List<Pair<String, Integer>>> wranks : rankUpdates) {
for (Pair<Integer, List<Pair<String, Integer>>> wranks : rankUpdates) {
playerRanking.set(wranks.getLeft(), wranks.getRight());
}
} else {
@@ -798,15 +770,11 @@ public class Server {
List<Pair<Integer, List<Pair<String, Integer>>>> rankSystem = new ArrayList<>();
List<Pair<String, Integer>> rankUpdate = new ArrayList<>(0);
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = null;
try {
con = DatabaseConnection.getConnection();
try (Connection con = DatabaseConnection.getConnection()) {
String worldQuery;
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
if(worldid >= 0) {
if (worldid >= 0) {
worldQuery = (" AND `characters`.`world` = " + worldid);
} else {
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));
}
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();
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");
ResultSet rs = ps.executeQuery()) {
if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) {
int currentWorld = -1;
while(rs.next()) {
while (rs.next()) {
int rsWorld = rs.getInt("world");
if(currentWorld < rsWorld) {
if (currentWorld < rsWorld) {
currentWorld = rsWorld;
rankUpdate = new ArrayList<>(50);
rankSystem.add(new Pair<>(rsWorld, rankUpdate));
@@ -834,30 +802,13 @@ public class Server {
rankUpdate = new ArrayList<>(50);
rankSystem.add(new Pair<>(0, rankUpdate));
while(rs.next()) {
while (rs.next()) {
rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level")));
}
}
ps.close();
rs.close();
con.close();
} catch(SQLException ex) {
}
} catch (SQLException ex) {
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;
@@ -866,7 +817,7 @@ public class Server {
public void init() {
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)));
}
@@ -876,24 +827,22 @@ public class Server {
TimeZone.setDefault(TimeZone.getTimeZone(YamlConfig.config.server.TIMEZONE));
Connection c = null;
try {
c = DatabaseConnection.getConnection();
PreparedStatement ps = c.prepareStatement("UPDATE accounts SET loggedin = 0");
try (Connection con = DatabaseConnection.getConnection()) {
try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = 0")) {
ps.executeUpdate();
ps.close();
ps = c.prepareStatement("UPDATE characters SET HasMerchant = 0");
ps.executeUpdate();
ps.close();
}
cleanNxcodeCoupons(c);
loadCouponRates(c);
try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0")) {
ps.executeUpdate();
}
cleanNxcodeCoupons(con);
loadCouponRates(con);
updateActiveCoupons();
c.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
applyAllNameChanges(); // -- name changes can be missed by INSTANT_NAME_CHANGE --
applyAllWorldTransfers();
//MaplePet.clearMissingPetsFromDb(); // thanks Optimist for noticing this taking too long to run
@@ -917,7 +866,9 @@ public class Server {
NewYearCardRecord.startPendingNewYearCardRequests();
if(YamlConfig.config.server.USE_THREAD_TRACKER) ThreadTracker.getInstance().registerThreadTrackerTask();
if (YamlConfig.config.server.USE_THREAD_TRACKER) {
ThreadTracker.getInstance().registerThreadTrackerTask();
}
try {
Integer worldCount = Math.min(GameConstants.WORLD_NAMES.length, YamlConfig.config.server.WORLDS);
@@ -937,7 +888,7 @@ public class Server {
System.out.println();
if(YamlConfig.config.server.USE_FAMILY_SYSTEM) {
if (YamlConfig.config.server.USE_FAMILY_SYSTEM) {
timeToTake = System.currentTimeMillis();
MapleFamily.loadAllFamilies();
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) {
synchronized (guilds) {
for(MapleGuild mg: guilds.values()) {
if(mg.getName().equalsIgnoreCase(name)) {
for (MapleGuild mg : guilds.values()) {
if (mg.getName().equalsIgnoreCase(name)) {
return mg;
}
}
@@ -1139,7 +1090,7 @@ public class Server {
return null;
}
if(mc != null) {
if (mc != null) {
MapleGuildCharacter mgc = g.getMGC(mc.getId());
if (mgc != null) {
mc.setMGC(mgc);
@@ -1267,7 +1218,7 @@ public class Server {
public void guildMessage(int gid, byte[] packet, int exception) {
MapleGuild g = guilds.get(gid);
if(g != null) {
if (g != null) {
g.broadcast(packet, exception);
}
}
@@ -1286,7 +1237,9 @@ public class Server {
}
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) {
leaveGuild(mgc);
} else {
@@ -1320,7 +1273,7 @@ public class Server {
public boolean isGmOnline(int world) {
for (Channel ch : getChannelsFromWorld(world)) {
for (MapleCharacter player : ch.getPlayerStorage().getAllCharacters()) {
if (player.isGM()){
if (player.isGM()) {
return true;
}
}
@@ -1329,7 +1282,7 @@ public class Server {
}
public void changeFly(Integer accountid, boolean canFly) {
if(canFly) {
if (canFly) {
activeFly.add(accountid);
} else {
activeFly.remove(accountid);
@@ -1374,8 +1327,8 @@ public class Server {
try {
short count = 0;
for(Integer chr : accountChars.get(accountid)) {
if(worldChars.get(chr).equals(worldid)) {
for (Integer chr : accountChars.get(accountid)) {
if (worldChars.get(chr).equals(worldid)) {
count++;
}
}
@@ -1401,7 +1354,9 @@ public class Server {
lgnWLock.lock();
try {
World wserv = this.getWorld(chrView.getWorld());
if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
if (wserv != null) {
wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
}
} finally {
lgnWLock.unlock();
}
@@ -1412,7 +1367,7 @@ public class Server {
lgnWLock.lock();
try {
accountCharacterCount.put(accountid, (short)(accountCharacterCount.get(accountid) + 1));
accountCharacterCount.put(accountid, (short) (accountCharacterCount.get(accountid) + 1));
Set<Integer> accChars = accountChars.get(accountid);
accChars.add(chrid);
@@ -1422,7 +1377,9 @@ public class Server {
MapleCharacter chrView = chr.generateCharacterEntry();
World wserv = this.getWorld(chrView.getWorld());
if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
if (wserv != null) {
wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
}
} finally {
lgnWLock.unlock();
}
@@ -1431,15 +1388,17 @@ public class Server {
public void deleteCharacterEntry(Integer accountid, Integer chrid) {
lgnWLock.lock();
try {
accountCharacterCount.put(accountid, (short)(accountCharacterCount.get(accountid) - 1));
accountCharacterCount.put(accountid, (short) (accountCharacterCount.get(accountid) - 1));
Set<Integer> accChars = accountChars.get(accountid);
accChars.remove(chrid);
Integer world = worldChars.remove(chrid);
if(world != null) {
if (world != null) {
World wserv = this.getWorld(world);
if(wserv != null) wserv.unregisterAccountCharacterView(accountid, chrid);
if (wserv != null) {
wserv.unregisterAccountCharacterView(accountid, chrid);
}
}
} finally {
lgnWLock.unlock();
@@ -1450,9 +1409,11 @@ public class Server {
lgnWLock.lock();
try {
Integer chrid = chr.getId(), accountid = chr.getAccountID(), world = worldChars.get(chr.getId());
if(world != null) {
if (world != null) {
World wserv = this.getWorld(world);
if(wserv != null) wserv.unregisterAccountCharacterView(accountid, chrid);
if (wserv != null) {
wserv.unregisterAccountCharacterView(accountid, chrid);
}
}
worldChars.put(chrid, toWorld);
@@ -1460,7 +1421,9 @@ public class Server {
MapleCharacter chrView = chr.generateCharacterEntry();
World wserv = this.getWorld(toWorld);
if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
if (wserv != null) {
wserv.registerAccountCharacterView(chrView.getAccountID(), chrView);
}
} finally {
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) {
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);
int chrTotal = 0;
@@ -1493,14 +1458,14 @@ public class Server {
lgnRLock.lock();
try {
for(World w : wlist) {
for (World w : wlist) {
List<MapleCharacter> wchars = w.getAccountCharactersView(accountId);
if(wchars == null) {
if(!accountChars.containsKey(accountId)) {
if (wchars == null) {
if (!accountChars.containsKey(accountId)) {
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
} // 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;
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) {
short characterCount = 0;
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<>();
int curWorld = 0;
@@ -1525,9 +1492,9 @@ public class Server {
List<Pair<Item, Integer>> accEquips = ItemFactory.loadEquippedItems(accId, true, true);
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());
if(playerEquips == null) {
if (playerEquips == null) {
playerEquips = new LinkedList<>();
accPlayerEquips.put(ae.getRight(), playerEquips);
}
@@ -1535,17 +1502,20 @@ public class Server {
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);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
characterCount++;
int cworld = rs.getByte("world");
if(cworld >= wlen) continue;
if (cworld >= wlen) {
continue;
}
if(cworld > curWorld) {
if (cworld > curWorld) {
wchars.add(curWorld, chars);
curWorld = cworld;
@@ -1557,7 +1527,6 @@ public class Server {
}
}
}
con.close();
wchars.add(curWorld, chars);
} catch (SQLException sqle) {
@@ -1568,10 +1537,9 @@ public class Server {
}
public void loadAllAccountsCharactersView() {
try {
Connection con = DatabaseConnection.getConnection();
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT id FROM accounts");
ResultSet rs = ps.executeQuery();
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
int accountId = rs.getInt("id");
@@ -1579,10 +1547,6 @@ public class Server {
loadAccountCharactersView(accountId, 0, 0);
}
}
rs.close();
ps.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
@@ -1599,25 +1563,28 @@ public class Server {
private static void applyAllNameChanges() {
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE completionTime IS NULL")) {
ResultSet rs = ps.executeQuery();
PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE completionTime IS NULL");
ResultSet rs = ps.executeQuery()) {
List<Pair<String, String>> changedNames = new LinkedList<Pair<String, String>>(); //logging only
while(rs.next()) {
while (rs.next()) {
con.setAutoCommit(false);
int nameChangeId = rs.getInt("id");
int characterId = rs.getInt("characterId");
String oldName = rs.getString("old");
String newName = rs.getString("new");
boolean success = MapleCharacter.doNameChange(con, characterId, oldName, newName, nameChangeId);
if(!success) con.rollback(); //discard changes
else changedNames.add(new Pair<String, String>(oldName, newName));
if (!success) {
con.rollback(); //discard changes
} else {
changedNames.add(new Pair<String, String>(oldName, newName));
}
con.setAutoCommit(true);
}
//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());
}
} catch(SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
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() {
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM worldtransfers WHERE completionTime IS NULL",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
ResultSet rs = ps.executeQuery();
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = ps.executeQuery()) {
List<Integer> removedTransfers = new LinkedList<Integer>();
while(rs.next()) {
while (rs.next()) {
int nameChangeId = rs.getInt("id");
int characterId = rs.getInt("characterId");
int oldWorld = rs.getInt("from");
int newWorld = rs.getInt("to");
String reason = MapleCharacter.checkWorldTransferEligibility(con, characterId, oldWorld, newWorld); //check if character is still eligible
if(reason != null) {
if (reason != null) {
removedTransfers.add(nameChangeId);
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 = ?")) {
delPs.setInt(1, nameChangeId);
delPs.executeUpdate();
} catch(SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to delete world transfer for character ID " + characterId);
}
@@ -1649,26 +1616,31 @@ public class Server {
}
rs.beforeFirst();
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);
int nameChangeId = rs.getInt("id");
if(removedTransfers.contains(nameChangeId)) continue;
if (removedTransfers.contains(nameChangeId)) {
continue;
}
int characterId = rs.getInt("characterId");
int oldWorld = rs.getInt("from");
int newWorld = rs.getInt("to");
boolean success = MapleCharacter.doWorldTransfer(con, characterId, oldWorld, newWorld, nameChangeId);
if(!success) con.rollback();
else worldTransfers.add(new Pair<Integer, Pair<Integer, Integer>>(characterId, new Pair<Integer, Integer>(oldWorld, newWorld)));
if (!success) {
con.rollback();
} else {
worldTransfers.add(new Pair<Integer, Pair<Integer, Integer>>(characterId, new Pair<Integer, Integer>(oldWorld, newWorld)));
}
con.setAutoCommit(true);
}
//log
for(Pair<Integer, Pair<Integer, Integer>> worldTransferPair : worldTransfers) {
for (Pair<Integer, Pair<Integer, Integer>> worldTransferPair : worldTransfers) {
int charId = worldTransferPair.getLeft();
int oldWorld = worldTransferPair.getRight().getLeft();
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());
}
} catch(SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to retrieve list of pending world transfers.");
}
@@ -1694,7 +1666,9 @@ public class Server {
if (wserv != null) {
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());
Set<Integer> chars = accountChars.get(accId);
if(chars == null) {
if (chars == null) {
chars = new HashSet<>(5);
}
@@ -1728,7 +1702,9 @@ public class Server {
for (MapleCharacter chr : wchars) {
int cid = chr.getId();
if (gmLevel < chr.gmLevel()) gmLevel = chr.gmLevel();
if (gmLevel < chr.gmLevel()) {
gmLevel = chr.gmLevel();
}
chars.add(cid);
worldChars.put(cid, wid);
@@ -1855,13 +1831,13 @@ public class Server {
try {
long timeNow = System.currentTimeMillis();
for(Entry<MapleClient, Long> mc : inLoginState.entrySet()) {
if(timeNow > mc.getValue()) {
for (Entry<MapleClient, Long> mc : inLoginState.entrySet()) {
if (timeNow > mc.getValue()) {
toDisconnect.add(mc.getKey());
}
}
for(MapleClient c : toDisconnect) {
for (MapleClient c : toDisconnect) {
inLoginState.remove(c);
}
} finally {
@@ -1869,7 +1845,7 @@ public class Server {
}
for (MapleClient c : toDisconnect) { // thanks Lei for pointing a deadlock issue with srvLock
if(c.isLoggedIn()) {
if (c.isLoggedIn()) {
c.disconnect(false, false);
} else {
MapleSessionCoordinator.getInstance().closeSession(c.getSession(), true);
@@ -1897,7 +1873,9 @@ public class Server {
private synchronized void shutdownInternal(boolean restart) {
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()) {
w.shutdown();
}
@@ -1923,7 +1901,9 @@ public class Server {
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) {
while (!ch.finishedShutdown()) {