GameStatusThread.java 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.status;
  16. import gnu.trove.TObjectProcedure;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.InputStreamReader;
  24. import java.io.OutputStreamWriter;
  25. import java.io.PrintWriter;
  26. import java.lang.management.ManagementFactory;
  27. import java.lang.management.ThreadInfo;
  28. import java.lang.management.ThreadMXBean;
  29. import java.net.InetAddress;
  30. import java.net.Socket;
  31. import java.sql.Connection;
  32. import java.sql.PreparedStatement;
  33. import java.sql.SQLException;
  34. import java.text.DecimalFormat;
  35. import java.text.SimpleDateFormat;
  36. import java.util.Calendar;
  37. import java.util.Map;
  38. import java.util.Map.Entry;
  39. import java.util.NoSuchElementException;
  40. import java.util.Properties;
  41. import java.util.StringTokenizer;
  42. import javolution.util.FastComparator;
  43. import javolution.util.FastTable;
  44. import com.l2jserver.Config;
  45. import com.l2jserver.L2DatabaseFactory;
  46. import com.l2jserver.gameserver.Announcements;
  47. import com.l2jserver.gameserver.GameTimeController;
  48. import com.l2jserver.gameserver.GmListTable;
  49. import com.l2jserver.gameserver.LoginServerThread;
  50. import com.l2jserver.gameserver.Shutdown;
  51. import com.l2jserver.gameserver.ThreadPoolManager;
  52. import com.l2jserver.gameserver.cache.HtmCache;
  53. import com.l2jserver.gameserver.datatables.ItemTable;
  54. import com.l2jserver.gameserver.datatables.MultiSell;
  55. import com.l2jserver.gameserver.datatables.NpcTable;
  56. import com.l2jserver.gameserver.datatables.SkillTable;
  57. import com.l2jserver.gameserver.datatables.SpawnTable;
  58. import com.l2jserver.gameserver.datatables.TeleportLocationTable;
  59. import com.l2jserver.gameserver.instancemanager.DayNightSpawnManager;
  60. import com.l2jserver.gameserver.instancemanager.Manager;
  61. import com.l2jserver.gameserver.instancemanager.QuestManager;
  62. import com.l2jserver.gameserver.instancemanager.RaidBossSpawnManager;
  63. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  64. import com.l2jserver.gameserver.model.L2ItemInstance;
  65. import com.l2jserver.gameserver.model.L2ItemInstance.ItemLocation;
  66. import com.l2jserver.gameserver.model.L2Object;
  67. import com.l2jserver.gameserver.model.L2World;
  68. import com.l2jserver.gameserver.model.TradeList;
  69. import com.l2jserver.gameserver.model.TradeList.TradeItem;
  70. import com.l2jserver.gameserver.model.actor.L2Character;
  71. import com.l2jserver.gameserver.model.actor.L2Npc;
  72. import com.l2jserver.gameserver.model.actor.L2Summon;
  73. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  74. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  75. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  76. import com.l2jserver.gameserver.model.itemcontainer.Inventory;
  77. import com.l2jserver.gameserver.network.SystemMessageId;
  78. import com.l2jserver.gameserver.network.clientpackets.Say2;
  79. import com.l2jserver.gameserver.network.serverpackets.CharInfo;
  80. import com.l2jserver.gameserver.network.serverpackets.CreatureSay;
  81. import com.l2jserver.gameserver.network.serverpackets.ExBrExtraUserInfo;
  82. import com.l2jserver.gameserver.network.serverpackets.InventoryUpdate;
  83. import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
  84. import com.l2jserver.gameserver.network.serverpackets.UserInfo;
  85. import com.l2jserver.gameserver.taskmanager.DecayTaskManager;
  86. import com.l2jserver.gameserver.util.GMAudit;
  87. public class GameStatusThread extends Thread
  88. {
  89. //private static final Logger _log = Logger.getLogger(AdminTeleport.class.getName());
  90. private final Socket _cSocket;
  91. private final PrintWriter _print;
  92. private final BufferedReader _read;
  93. private final int _uptime;
  94. private void telnetOutput(int type, String text)
  95. {
  96. if (Config.DEVELOPER)
  97. {
  98. if (type == 1)
  99. System.out.println("TELNET | " + text);
  100. else if (type == 2)
  101. System.out.print("TELNET | " + text);
  102. else if (type == 3)
  103. System.out.print(text);
  104. else if (type == 4)
  105. System.out.println(text);
  106. else
  107. System.out.println("TELNET | " + text);
  108. }
  109. else
  110. {
  111. //only print output if the message is rejected
  112. if (type == 5)
  113. System.out.println("TELNET | " + text);
  114. }
  115. }
  116. private boolean isValidIP(Socket client)
  117. {
  118. boolean result = false;
  119. InetAddress ClientIP = client.getInetAddress();
  120. // convert IP to String, and compare with list
  121. String clientStringIP = ClientIP.getHostAddress();
  122. telnetOutput(1, "Connection from: " + clientStringIP);
  123. // read and loop thru list of IPs, compare with newIP
  124. if (Config.DEVELOPER)
  125. telnetOutput(2, "");
  126. InputStream telnetIS = null;
  127. try
  128. {
  129. Properties telnetSettings = new Properties();
  130. telnetIS = new FileInputStream(new File(Config.TELNET_FILE));
  131. telnetSettings.load(telnetIS);
  132. String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost,::1");
  133. if (Config.DEVELOPER)
  134. telnetOutput(3, "Comparing ip to list...");
  135. // compare
  136. String ipToCompare = null;
  137. for (String ip : HostList.split(","))
  138. {
  139. if (!result)
  140. {
  141. ipToCompare = InetAddress.getByName(ip).getHostAddress();
  142. if (clientStringIP.equals(ipToCompare))
  143. result = true;
  144. if (Config.DEVELOPER)
  145. telnetOutput(3, clientStringIP + " = " + ipToCompare + "(" + ip + ") = " + result);
  146. }
  147. }
  148. }
  149. catch (IOException e)
  150. {
  151. if (Config.DEVELOPER)
  152. telnetOutput(4, "");
  153. telnetOutput(1, "Error: " + e);
  154. }
  155. finally
  156. {
  157. try
  158. {
  159. telnetIS.close();
  160. }
  161. catch (Exception e)
  162. {
  163. }
  164. }
  165. if (Config.DEVELOPER)
  166. telnetOutput(4, "Allow IP: " + result);
  167. return result;
  168. }
  169. public GameStatusThread(Socket client, int uptime, String StatusPW) throws IOException
  170. {
  171. this.setPriority(Thread.MAX_PRIORITY);
  172. _cSocket = client;
  173. _uptime = uptime;
  174. _print = new PrintWriter(_cSocket.getOutputStream());
  175. _read = new BufferedReader(new InputStreamReader(_cSocket.getInputStream()));
  176. if (isValidIP(client))
  177. {
  178. telnetOutput(1, client.getInetAddress().getHostAddress() + " accepted.");
  179. _print.println("Welcome To The L2J Telnet Session.");
  180. _print.println("Please Insert Your Password!");
  181. _print.print("Password: ");
  182. _print.flush();
  183. String tmpLine = _read.readLine();
  184. if (tmpLine == null)
  185. {
  186. _print.println("Error.");
  187. _print.println("Disconnected...");
  188. _print.flush();
  189. _cSocket.close();
  190. }
  191. else
  192. {
  193. if (tmpLine.compareTo(StatusPW) != 0)
  194. {
  195. _print.println("Incorrect Password!");
  196. _print.println("Disconnected...");
  197. _print.flush();
  198. _cSocket.close();
  199. }
  200. else
  201. {
  202. _print.println("Password Correct!");
  203. _print.println("[L2J Game Server]");
  204. _print.print("");
  205. _print.flush();
  206. start();
  207. }
  208. }
  209. }
  210. else
  211. {
  212. telnetOutput(5, "Connection attempt from " + client.getInetAddress().getHostAddress() + " rejected.");
  213. _cSocket.close();
  214. }
  215. }
  216. @Override
  217. public void run()
  218. {
  219. String _usrCommand = "";
  220. try
  221. {
  222. while (_usrCommand.compareTo("quit") != 0 && _usrCommand.compareTo("exit") != 0)
  223. {
  224. _usrCommand = _read.readLine();
  225. if (_usrCommand == null)
  226. {
  227. _cSocket.close();
  228. break;
  229. }
  230. if (_usrCommand.equals("help"))
  231. {
  232. _print.println("The following is a list of all available commands: ");
  233. _print.println("help - shows this help.");
  234. _print.println("status - displays basic server statistics.");
  235. _print.println("gamestat privatestore - displays info about stores");
  236. _print.println("performance - shows server performance statistics.");
  237. _print.println("forcegc - forced garbage collection.");
  238. _print.println("purge - removes finished threads from thread pools.");
  239. _print.println("memusage - displays memory amounts in JVM.");
  240. _print.println("announce <text> - announces <text> in game.");
  241. _print.println("msg <nick> <text> - Sends a whisper to char <nick> with <text>.");
  242. _print.println("gmchat <text> - Sends a message to all GMs with <text>.");
  243. _print.println("gmlist - lists all gms online.");
  244. _print.println("kick - kick player <name> from server.");
  245. _print.println("shutdown <time> - shuts down server in <time> seconds.");
  246. _print.println("restart <time> - restarts down server in <time> seconds.");
  247. _print.println("abort - aborts shutdown/restart.");
  248. _print.println("give <player> <itemid> <amount>");
  249. _print.println("enchant <player> <itemType> <enchant> (itemType: 1 - Helmet, 2 - Chest, 3 - Gloves, 4 - Feet, 5 - Legs, 6 - Right Hand, 7 - Left Hand, 8 - Left Ear, 9 - Right Ear , 10 - Left Finger, 11 - Right Finger, 12- Necklace, 13 - Underwear, 14 - Back, 15 - Belt, 0 - No Enchant)");
  250. _print.println("debug <cmd> - executes the debug command (see 'help debug').");
  251. _print.println("reload <type> - reload data");
  252. _print.println("jail <player> [time]");
  253. _print.println("unjail <player>");
  254. _print.println("quit - closes telnet session.");
  255. }
  256. else if (_usrCommand.equals("help debug"))
  257. {
  258. _print.println("The following is a list of all available debug commands: ");
  259. _print.println("full - Dumps complete debug information to an file (recommended)");
  260. _print.println("decay - prints info about the DecayManager");
  261. _print.println("PacketTP - prints info about the General Packet ThreadPool");
  262. _print.println("IOPacketTP - prints info about the I/O Packet ThreadPool");
  263. _print.println("GeneralTP - prints info about the General ThreadPool");
  264. }
  265. else if (_usrCommand.equals("status"))
  266. {
  267. _print.print(this.getServerStatus());
  268. _print.flush();
  269. }
  270. else if (_usrCommand.equals("cleanvoiditems"))
  271. {
  272. L2World.getInstance().forEachObject(new CleanVoidItems());
  273. _print.flush();
  274. }
  275. else if (_usrCommand.equals("forcegc"))
  276. {
  277. System.gc();
  278. StringBuilder sb = new StringBuilder();
  279. sb.append("RAM Used: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576)); // 1024 * 1024 = 1048576
  280. _print.println(sb.toString());
  281. }
  282. else if (_usrCommand.equals("performance"))
  283. {
  284. for (String line : ThreadPoolManager.getInstance().getStats())
  285. {
  286. _print.println(line);
  287. }
  288. _print.flush();
  289. }
  290. else if (_usrCommand.equals("purge"))
  291. {
  292. ThreadPoolManager.getInstance().purge();
  293. _print.println("STATUS OF THREAD POOLS AFTER PURGE COMMAND:");
  294. _print.println("");
  295. for (String line : ThreadPoolManager.getInstance().getStats())
  296. {
  297. _print.println(line);
  298. }
  299. _print.flush();
  300. }
  301. else if (_usrCommand.startsWith("memusage"))
  302. {
  303. double max = Runtime.getRuntime().maxMemory() / 1024; // maxMemory is the upper
  304. // limit the jvm can use
  305. double allocated = Runtime.getRuntime().totalMemory() / 1024; // totalMemory the
  306. // size of the
  307. // current
  308. // allocation pool
  309. double nonAllocated = max - allocated; // non allocated memory till jvm limit
  310. double cached = Runtime.getRuntime().freeMemory() / 1024; // freeMemory the
  311. // unused memory in
  312. // the allocation pool
  313. double used = allocated - cached; // really used memory
  314. double useable = max - used; // allocated, but non-used and non-allocated memory
  315. DecimalFormat df = new DecimalFormat(" (0.0000'%')");
  316. DecimalFormat df2 = new DecimalFormat(" # 'KB'");
  317. _print.println("+----");// ...
  318. _print.println("| Allowed Memory:" + df2.format(max));
  319. _print.println("| |= Allocated Memory:" + df2.format(allocated) + df.format(allocated / max * 100));
  320. _print.println("| |= Non-Allocated Memory:" + df2.format(nonAllocated) + df.format(nonAllocated / max * 100));
  321. _print.println("| Allocated Memory:" + df2.format(allocated));
  322. _print.println("| |= Used Memory:" + df2.format(used) + df.format(used / max * 100));
  323. _print.println("| |= Unused (cached) Memory:" + df2.format(cached) + df.format(cached / max * 100));
  324. _print.println("| Useable Memory:" + df2.format(useable) + df.format(useable / max * 100)); // ...
  325. _print.println("+----");
  326. }
  327. else if (_usrCommand.startsWith("announce"))
  328. {
  329. try
  330. {
  331. _usrCommand = _usrCommand.substring(9);
  332. Announcements.getInstance().announceToAll(_usrCommand);
  333. _print.println("Announcement Sent!");
  334. }
  335. catch (StringIndexOutOfBoundsException e)
  336. {
  337. _print.println("Please Enter Some Text To Announce!");
  338. }
  339. }
  340. else if (_usrCommand.startsWith("msg"))
  341. {
  342. try
  343. {
  344. String val = _usrCommand.substring(4);
  345. StringTokenizer st = new StringTokenizer(val);
  346. String name = st.nextToken();
  347. String message = val.substring(name.length() + 1);
  348. L2PcInstance reciever = L2World.getInstance().getPlayer(name);
  349. CreatureSay cs = new CreatureSay(0, Say2.TELL, "Telnet Priv", message);
  350. if (reciever != null)
  351. {
  352. reciever.sendPacket(cs);
  353. _print.println("Telnet Priv->" + name + ": " + message);
  354. _print.println("Message Sent!");
  355. }
  356. else
  357. {
  358. _print.println("Unable To Find Username: " + name);
  359. }
  360. }
  361. catch (StringIndexOutOfBoundsException e)
  362. {
  363. _print.println("Please Enter Some Text!");
  364. }
  365. }
  366. else if (_usrCommand.startsWith("gmchat"))
  367. {
  368. try
  369. {
  370. _usrCommand = _usrCommand.substring(7);
  371. CreatureSay cs = new CreatureSay(0, Say2.ALLIANCE, "Telnet GM Broadcast from " + _cSocket.getInetAddress().getHostAddress(), _usrCommand);
  372. GmListTable.broadcastToGMs(cs);
  373. _print.println("Your Message Has Been Sent To " + getOnlineGMS() + " GM(s).");
  374. }
  375. catch (StringIndexOutOfBoundsException e)
  376. {
  377. _print.println("Please Enter Some Text To Announce!");
  378. }
  379. }
  380. else if (_usrCommand.equals("gmlist"))
  381. {
  382. int igm = 0;
  383. String gmList = "";
  384. for (String player : GmListTable.getInstance().getAllGmNames(true))
  385. {
  386. gmList = gmList + ", " + player;
  387. igm++;
  388. }
  389. _print.println("There are currently " + igm + " GM(s) online...");
  390. if (!gmList.isEmpty())
  391. _print.println(gmList);
  392. }
  393. /*else if (_usrCommand.startsWith("unblock"))
  394. {
  395. try
  396. {
  397. _usrCommand = _usrCommand.substring(8);
  398. if (LoginServer.getInstance().unblockIp(_usrCommand))
  399. {
  400. _log.warning("IP removed via TELNET by host: " + _csocket.getInetAddress().getHostAddress());
  401. _print.println("The IP " + _usrCommand + " has been removed from the hack protection list!");
  402. }
  403. else
  404. {
  405. _print.println("IP not found in hack protection list...");
  406. }
  407. //TODO: with packet
  408. }
  409. catch (StringIndexOutOfBoundsException e)
  410. {
  411. _print.println("Please Enter the IP to Unblock!");
  412. }
  413. }*/
  414. else if (_usrCommand.startsWith("kick"))
  415. {
  416. try
  417. {
  418. _usrCommand = _usrCommand.substring(5);
  419. L2PcInstance player = L2World.getInstance().getPlayer(_usrCommand);
  420. if (player != null)
  421. {
  422. player.sendMessage("You are kicked by gm");
  423. player.logout();
  424. _print.println("Player kicked");
  425. }
  426. }
  427. catch (StringIndexOutOfBoundsException e)
  428. {
  429. _print.println("Please enter player name to kick");
  430. }
  431. }
  432. else if (_usrCommand.startsWith("shutdown"))
  433. {
  434. try
  435. {
  436. int val = Integer.parseInt(_usrCommand.substring(9));
  437. Shutdown.getInstance().startTelnetShutdown(_cSocket.getInetAddress().getHostAddress(), val, false);
  438. _print.println("Server Will Shutdown In " + val + " Seconds!");
  439. _print.println("Type \"abort\" To Abort Shutdown!");
  440. }
  441. catch (StringIndexOutOfBoundsException e)
  442. {
  443. _print.println("Please Enter * amount of seconds to shutdown!");
  444. }
  445. catch (Exception NumberFormatException)
  446. {
  447. _print.println("Numbers Only!");
  448. }
  449. }
  450. else if (_usrCommand.startsWith("restart"))
  451. {
  452. try
  453. {
  454. int val = Integer.parseInt(_usrCommand.substring(8));
  455. Shutdown.getInstance().startTelnetShutdown(_cSocket.getInetAddress().getHostAddress(), val, true);
  456. _print.println("Server Will Restart In " + val + " Seconds!");
  457. _print.println("Type \"abort\" To Abort Restart!");
  458. }
  459. catch (StringIndexOutOfBoundsException e)
  460. {
  461. _print.println("Please Enter * amount of seconds to restart!");
  462. }
  463. catch (Exception NumberFormatException)
  464. {
  465. _print.println("Numbers Only!");
  466. }
  467. }
  468. else if (_usrCommand.startsWith("abort"))
  469. {
  470. Shutdown.getInstance().telnetAbort(_cSocket.getInetAddress().getHostAddress());
  471. _print.println("OK! - Shutdown/Restart Aborted.");
  472. }
  473. else if (_usrCommand.equals("quit"))
  474. { /* Do Nothing :p - Just here to save us from the "Command Not Understood" Text */
  475. }
  476. else if (_usrCommand.startsWith("give"))
  477. {
  478. StringTokenizer st = new StringTokenizer(_usrCommand.substring(5));
  479. try
  480. {
  481. L2PcInstance player = L2World.getInstance().getPlayer(st.nextToken());
  482. int itemId = Integer.parseInt(st.nextToken());
  483. int amount = Integer.parseInt(st.nextToken());
  484. if (player != null)
  485. {
  486. L2ItemInstance item = player.getInventory().addItem("Status-Give", itemId, amount, null, null);
  487. InventoryUpdate iu = new InventoryUpdate();
  488. iu.addItem(item);
  489. player.sendPacket(iu);
  490. SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.YOU_PICKED_UP_S1_S2);
  491. sm.addItemName(itemId);
  492. sm.addItemNumber(amount);
  493. player.sendPacket(sm);
  494. _print.println("ok");
  495. GMAudit.auditGMAction("Telnet Admin", "Give Item", player.getName(), "item: " + itemId + " amount: " + amount);
  496. }
  497. else
  498. {
  499. _print.println("Player not found");
  500. }
  501. }
  502. catch (Exception e)
  503. {
  504. }
  505. }
  506. else if (_usrCommand.startsWith("enchant"))
  507. {
  508. StringTokenizer st = new StringTokenizer(_usrCommand.substring(8), " ");
  509. int enchant = 0, itemType = 0;
  510. try
  511. {
  512. L2PcInstance player = L2World.getInstance().getPlayer(st.nextToken());
  513. itemType = Integer.parseInt(st.nextToken());
  514. enchant = Integer.parseInt(st.nextToken());
  515. switch (itemType)
  516. {
  517. case 1:
  518. itemType = Inventory.PAPERDOLL_HEAD;
  519. break;
  520. case 2:
  521. itemType = Inventory.PAPERDOLL_CHEST;
  522. break;
  523. case 3:
  524. itemType = Inventory.PAPERDOLL_GLOVES;
  525. break;
  526. case 4:
  527. itemType = Inventory.PAPERDOLL_FEET;
  528. break;
  529. case 5:
  530. itemType = Inventory.PAPERDOLL_LEGS;
  531. break;
  532. case 6:
  533. itemType = Inventory.PAPERDOLL_RHAND;
  534. break;
  535. case 7:
  536. itemType = Inventory.PAPERDOLL_LHAND;
  537. break;
  538. case 8:
  539. itemType = Inventory.PAPERDOLL_LEAR;
  540. break;
  541. case 9:
  542. itemType = Inventory.PAPERDOLL_REAR;
  543. break;
  544. case 10:
  545. itemType = Inventory.PAPERDOLL_LFINGER;
  546. break;
  547. case 11:
  548. itemType = Inventory.PAPERDOLL_RFINGER;
  549. break;
  550. case 12:
  551. itemType = Inventory.PAPERDOLL_NECK;
  552. break;
  553. case 13:
  554. itemType = Inventory.PAPERDOLL_UNDER;
  555. break;
  556. case 14:
  557. itemType = Inventory.PAPERDOLL_CLOAK;
  558. break;
  559. case 15:
  560. itemType = Inventory.PAPERDOLL_BELT;
  561. break;
  562. default:
  563. itemType = 0;
  564. }
  565. if (enchant > 65535)
  566. enchant = 65535;
  567. else if (enchant < 0)
  568. enchant = 0;
  569. boolean success = false;
  570. if (player != null && itemType > 0)
  571. {
  572. success = setEnchant(player, enchant, itemType);
  573. if (success)
  574. _print.println("Item enchanted successfully.");
  575. }
  576. else if (!success)
  577. _print.println("Item failed to enchant.");
  578. }
  579. catch (Exception e)
  580. {
  581. }
  582. }
  583. else if (_usrCommand.startsWith("jail"))
  584. {
  585. StringTokenizer st = new StringTokenizer(_usrCommand.substring(5));
  586. try
  587. {
  588. String playerName = st.nextToken();
  589. L2PcInstance playerObj = L2World.getInstance().getPlayer(playerName);
  590. int delay = 0;
  591. try
  592. {
  593. delay = Integer.parseInt(st.nextToken());
  594. }
  595. catch (NumberFormatException nfe)
  596. {
  597. }
  598. catch (NoSuchElementException nsee)
  599. {
  600. }
  601. //L2PcInstance playerObj = L2World.getInstance().getPlayer(player);
  602. if (playerObj != null)
  603. {
  604. playerObj.setPunishLevel(L2PcInstance.PunishLevel.JAIL, delay);
  605. _print.println("Character " + playerObj.getName() + " jailed for " + (delay > 0 ? delay + " minutes." : "ever!"));
  606. }
  607. else
  608. jailOfflinePlayer(playerName, delay);
  609. }
  610. catch (NoSuchElementException nsee)
  611. {
  612. _print.println("Specify a character name.");
  613. }
  614. catch (Exception e)
  615. {
  616. if (Config.DEBUG)
  617. e.printStackTrace();
  618. }
  619. }
  620. else if (_usrCommand.startsWith("unjail"))
  621. {
  622. StringTokenizer st = new StringTokenizer(_usrCommand.substring(7));
  623. try
  624. {
  625. String playerName = st.nextToken();
  626. L2PcInstance playerObj = L2World.getInstance().getPlayer(playerName);
  627. if (playerObj != null)
  628. {
  629. playerObj.setPunishLevel(L2PcInstance.PunishLevel.NONE, 0);
  630. _print.println("Character " + playerObj.getName() + " removed from jail");
  631. }
  632. else
  633. unjailOfflinePlayer(playerName);
  634. }
  635. catch (NoSuchElementException nsee)
  636. {
  637. _print.println("Specify a character name.");
  638. }
  639. catch (Exception e)
  640. {
  641. if (Config.DEBUG)
  642. e.printStackTrace();
  643. }
  644. }
  645. else if (_usrCommand.startsWith("debug") && _usrCommand.length() > 6)
  646. {
  647. StringTokenizer st = new StringTokenizer(_usrCommand.substring(6));
  648. FileOutputStream fos = null;
  649. OutputStreamWriter out = null;
  650. try
  651. {
  652. String dbg = st.nextToken();
  653. if (dbg.equals("decay"))
  654. {
  655. _print.print(DecayTaskManager.getInstance().toString());
  656. }
  657. else if (dbg.equals("ai"))
  658. {
  659. /*
  660. _print.println("AITaskManagerStats");
  661. for(String line : AITaskManager.getInstance().getStats())
  662. {
  663. _print.println(line);
  664. }
  665. */
  666. }
  667. else if (dbg.equals("aiflush"))
  668. {
  669. //AITaskManager.getInstance().flush();
  670. }
  671. else if (dbg.equals("PacketTP"))
  672. {
  673. String str = ThreadPoolManager.getInstance().getPacketStats();
  674. _print.println(str);
  675. int i = 0;
  676. File f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
  677. while (f.exists())
  678. {
  679. i++;
  680. f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
  681. }
  682. f.getParentFile().mkdirs();
  683. fos = new FileOutputStream(f);
  684. out = new OutputStreamWriter(fos, "UTF-8");
  685. out.write(str);
  686. }
  687. else if (dbg.equals("IOPacketTP"))
  688. {
  689. String str = ThreadPoolManager.getInstance().getIOPacketStats();
  690. _print.println(str);
  691. int i = 0;
  692. File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
  693. while (f.exists())
  694. {
  695. i++;
  696. f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
  697. }
  698. f.getParentFile().mkdirs();
  699. fos = new FileOutputStream(f);
  700. out = new OutputStreamWriter(fos, "UTF-8");
  701. out.write(str);
  702. }
  703. else if (dbg.equals("GeneralTP"))
  704. {
  705. String str = ThreadPoolManager.getInstance().getGeneralStats();
  706. _print.println(str);
  707. int i = 0;
  708. File f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
  709. while (f.exists())
  710. {
  711. i++;
  712. f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
  713. }
  714. f.getParentFile().mkdirs();
  715. fos = new FileOutputStream(f);
  716. out = new OutputStreamWriter(fos, "UTF-8");
  717. out.write(str);
  718. }
  719. else if (dbg.equals("full"))
  720. {
  721. this.debugAll();
  722. }
  723. }
  724. catch (Exception e)
  725. {
  726. }
  727. finally
  728. {
  729. try
  730. {
  731. out.close();
  732. }
  733. catch (Exception e)
  734. {
  735. }
  736. try
  737. {
  738. fos.close();
  739. }
  740. catch (Exception e)
  741. {
  742. }
  743. }
  744. }
  745. else if (_usrCommand.startsWith("reload"))
  746. {
  747. StringTokenizer st = new StringTokenizer(_usrCommand.substring(7));
  748. try
  749. {
  750. String type = st.nextToken();
  751. if (type.equals("multisell"))
  752. {
  753. _print.print("Reloading multisell... ");
  754. MultiSell.getInstance().reload();
  755. _print.println("done");
  756. }
  757. else if (type.equals("skill"))
  758. {
  759. _print.print("Reloading skills... ");
  760. SkillTable.getInstance().reload();
  761. _print.println("done");
  762. }
  763. else if (type.equals("npc"))
  764. {
  765. _print.print("Reloading npc templates... ");
  766. NpcTable.getInstance().reloadAllNpc();
  767. QuestManager.getInstance().reloadAllQuests();
  768. _print.println("done");
  769. }
  770. else if (type.equals("html"))
  771. {
  772. _print.print("Reloading html cache... ");
  773. HtmCache.getInstance().reload();
  774. _print.println("done");
  775. }
  776. else if (type.equals("item"))
  777. {
  778. _print.print("Reloading item templates... ");
  779. ItemTable.getInstance().reload();
  780. _print.println("done");
  781. }
  782. else if (type.equals("instancemanager"))
  783. {
  784. _print.print("Reloading instance managers... ");
  785. Manager.reloadAll();
  786. _print.println("done");
  787. }
  788. else if (type.equals("zone"))
  789. {
  790. _print.print("Reloading zone tables... ");
  791. ZoneManager.getInstance().reload();
  792. _print.println("done");
  793. }
  794. else if (type.equals("teleports"))
  795. {
  796. _print.print("Reloading telport location table... ");
  797. TeleportLocationTable.getInstance().reloadAll();
  798. _print.println("done");
  799. }
  800. else if (type.equals("spawns"))
  801. {
  802. _print.print("Reloading spawns... ");
  803. RaidBossSpawnManager.getInstance().cleanUp();
  804. DayNightSpawnManager.getInstance().cleanUp();
  805. L2World.getInstance().deleteVisibleNpcSpawns();
  806. NpcTable.getInstance().reloadAllNpc();
  807. SpawnTable.getInstance().reloadAll();
  808. RaidBossSpawnManager.getInstance().reloadBosses();
  809. _print.println("done\n");
  810. }
  811. }
  812. catch (Exception e)
  813. {
  814. }
  815. }
  816. else if (_usrCommand.startsWith("gamestat"))
  817. {
  818. StringTokenizer st = new StringTokenizer(_usrCommand.substring(9));
  819. try
  820. {
  821. String type = st.nextToken();
  822. // name;type;x;y;itemId:enchant:price...
  823. if (type.equals("privatestore"))
  824. {
  825. for (L2PcInstance player : L2World.getInstance().getAllPlayersArray())
  826. {
  827. if (player.getPrivateStoreType() == 0)
  828. continue;
  829. TradeList list = null;
  830. String content = "";
  831. if (player.getPrivateStoreType() == 1) // sell
  832. {
  833. list = player.getSellList();
  834. for (TradeItem item : list.getItems())
  835. {
  836. content += item.getItem().getItemId() + ":" + item.getEnchant() + ":" + item.getPrice() + ":";
  837. }
  838. content = player.getName() + ";" + "sell;" + player.getX() + ";" + player.getY() + ";" + content;
  839. _print.println(content);
  840. continue;
  841. }
  842. else if (player.getPrivateStoreType() == 3) // buy
  843. {
  844. list = player.getBuyList();
  845. for (TradeItem item : list.getItems())
  846. {
  847. content += item.getItem().getItemId() + ":" + item.getEnchant() + ":" + item.getPrice() + ":";
  848. }
  849. content = player.getName() + ";" + "buy;" + player.getX() + ";" + player.getY() + ";" + content;
  850. _print.println(content);
  851. continue;
  852. }
  853. }
  854. }
  855. }
  856. catch (Exception e)
  857. {
  858. }
  859. }
  860. else if (_usrCommand.length() == 0)
  861. { /* Do Nothing Again - Same reason as the quit part */
  862. }
  863. _print.print("");
  864. _print.flush();
  865. }
  866. if (!_cSocket.isClosed())
  867. {
  868. _print.println("Bye Bye!");
  869. _print.flush();
  870. _cSocket.close();
  871. }
  872. telnetOutput(1, "Connection from " + _cSocket.getInetAddress().getHostAddress() + " was closed by client.");
  873. }
  874. catch (IOException e)
  875. {
  876. e.printStackTrace();
  877. }
  878. }
  879. private boolean setEnchant(L2PcInstance activeChar, int ench, int armorType)
  880. {
  881. // now we need to find the equipped weapon of the targeted character...
  882. int curEnchant = 0; // display purposes only
  883. L2ItemInstance itemInstance = null;
  884. // only attempt to enchant if there is a weapon equipped
  885. L2ItemInstance parmorInstance = activeChar.getInventory().getPaperdollItem(armorType);
  886. if (parmorInstance != null && parmorInstance.getLocationSlot() == armorType)
  887. {
  888. itemInstance = parmorInstance;
  889. }
  890. else
  891. {
  892. // for bows/crossbows and double handed weapons
  893. parmorInstance = activeChar.getInventory().getPaperdollItem(Inventory.PAPERDOLL_RHAND);
  894. if (parmorInstance != null && parmorInstance.getLocationSlot() == Inventory.PAPERDOLL_RHAND)
  895. itemInstance = parmorInstance;
  896. }
  897. if (itemInstance != null)
  898. {
  899. curEnchant = itemInstance.getEnchantLevel();
  900. // set enchant value
  901. activeChar.getInventory().unEquipItemInSlot(armorType);
  902. itemInstance.setEnchantLevel(ench);
  903. activeChar.getInventory().equipItem(itemInstance);
  904. // send packets
  905. InventoryUpdate iu = new InventoryUpdate();
  906. iu.addModifiedItem(itemInstance);
  907. activeChar.sendPacket(iu);
  908. activeChar.broadcastPacket(new CharInfo(activeChar));
  909. activeChar.sendPacket(new UserInfo(activeChar));
  910. activeChar.broadcastPacket(new ExBrExtraUserInfo(activeChar));
  911. // informations
  912. activeChar.sendMessage("Changed enchantment of " + activeChar.getName() + "'s " + itemInstance.getItem().getName() + " from " + curEnchant + " to " + ench + ".");
  913. activeChar.sendMessage("Admin has changed the enchantment of your " + itemInstance.getItem().getName() + " from " + curEnchant + " to " + ench + ".");
  914. // log
  915. GMAudit.auditGMAction("TelnetAdministrator", "enchant", activeChar.getName(), itemInstance.getItem().getName() + "(" + itemInstance.getObjectId() + ")" + " from " + curEnchant + " to " + ench);
  916. return true;
  917. }
  918. return false;
  919. }
  920. private void jailOfflinePlayer(String name, int delay)
  921. {
  922. Connection con = null;
  923. try
  924. {
  925. con = L2DatabaseFactory.getInstance().getConnection();
  926. PreparedStatement statement = con.prepareStatement("UPDATE characters SET x=?, y=?, z=?, punish_level=?, punish_timer=? WHERE char_name=?");
  927. statement.setInt(1, -114356);
  928. statement.setInt(2, -249645);
  929. statement.setInt(3, -2984);
  930. statement.setInt(4, L2PcInstance.PunishLevel.JAIL.value());
  931. statement.setLong(5, delay * 60000L);
  932. statement.setString(6, name);
  933. statement.execute();
  934. int count = statement.getUpdateCount();
  935. statement.close();
  936. if (count == 0)
  937. _print.println("Character not found!");
  938. else
  939. _print.println("Character " + name + " jailed for " + (delay > 0 ? delay + " minutes." : "ever!"));
  940. }
  941. catch (SQLException se)
  942. {
  943. _print.println("SQLException while jailing player");
  944. if (Config.DEBUG)
  945. se.printStackTrace();
  946. }
  947. finally
  948. {
  949. L2DatabaseFactory.close(con);
  950. }
  951. }
  952. private void unjailOfflinePlayer(String name)
  953. {
  954. Connection con = null;
  955. try
  956. {
  957. con = L2DatabaseFactory.getInstance().getConnection();
  958. PreparedStatement statement = con.prepareStatement("UPDATE characters SET x=?, y=?, z=?, punish_level=?, punish_timer=? WHERE char_name=?");
  959. statement.setInt(1, 17836);
  960. statement.setInt(2, 170178);
  961. statement.setInt(3, -3507);
  962. statement.setInt(4, 0);
  963. statement.setLong(5, 0);
  964. statement.setString(6, name);
  965. statement.execute();
  966. int count = statement.getUpdateCount();
  967. statement.close();
  968. if (count == 0)
  969. _print.println("Character not found!");
  970. else
  971. _print.println("Character " + name + " set free.");
  972. }
  973. catch (SQLException se)
  974. {
  975. _print.println("SQLException while jailing player");
  976. if (Config.DEBUG)
  977. se.printStackTrace();
  978. }
  979. finally
  980. {
  981. L2DatabaseFactory.close(con);
  982. }
  983. }
  984. private int getOnlineGMS()
  985. {
  986. return GmListTable.getInstance().getAllGms(true).size();
  987. }
  988. private String getUptime(int time)
  989. {
  990. int uptime = (int) System.currentTimeMillis() - time;
  991. uptime = uptime / 1000;
  992. int h = uptime / 3600;
  993. int m = (uptime - (h * 3600)) / 60;
  994. int s = ((uptime - (h * 3600)) - (m * 60));
  995. return h + "hrs " + m + "mins " + s + "secs";
  996. }
  997. private String gameTime()
  998. {
  999. int t = GameTimeController.getInstance().getGameTime();
  1000. int h = t / 60;
  1001. int m = t % 60;
  1002. SimpleDateFormat format = new SimpleDateFormat("H:mm");
  1003. Calendar cal = Calendar.getInstance();
  1004. cal.set(Calendar.HOUR_OF_DAY, h);
  1005. cal.set(Calendar.MINUTE, m);
  1006. return format.format(cal.getTime());
  1007. }
  1008. public String getServerStatus()
  1009. {
  1010. int playerCount = 0, objectCount = 0;
  1011. int max = LoginServerThread.getInstance().getMaxPlayer();
  1012. playerCount = L2World.getInstance().getAllPlayersCount();
  1013. objectCount = L2World.getInstance().getAllVisibleObjectsCount();
  1014. int itemCount = 0;
  1015. int itemVoidCount = 0;
  1016. int monsterCount = 0;
  1017. int minionCount = 0;
  1018. int minionsGroupCount = 0;
  1019. int npcCount = 0;
  1020. int charCount = 0;
  1021. int pcCount = 0;
  1022. int detachedCount = 0;
  1023. int doorCount = 0;
  1024. int summonCount = 0;
  1025. int AICount = 0;
  1026. for (L2Object obj : L2World.getInstance().getAllVisibleObjectsArray())
  1027. {
  1028. if (obj == null)
  1029. continue;
  1030. if (obj instanceof L2Character)
  1031. if (((L2Character) obj).hasAI())
  1032. AICount++;
  1033. if (obj instanceof L2ItemInstance)
  1034. if (((L2ItemInstance) obj).getLocation() == L2ItemInstance.ItemLocation.VOID)
  1035. itemVoidCount++;
  1036. else
  1037. itemCount++;
  1038. else if (obj instanceof L2MonsterInstance)
  1039. {
  1040. monsterCount++;
  1041. if (((L2MonsterInstance) obj).hasMinions())
  1042. {
  1043. minionCount += ((L2MonsterInstance) obj).getMinionList().countSpawnedMinions();
  1044. minionsGroupCount += ((L2MonsterInstance) obj).getMinionList().lazyCountSpawnedMinionsGroups();
  1045. }
  1046. }
  1047. else if (obj instanceof L2Npc)
  1048. npcCount++;
  1049. else if (obj instanceof L2PcInstance)
  1050. {
  1051. pcCount++;
  1052. if (((L2PcInstance) obj).getClient() != null && ((L2PcInstance) obj).getClient().isDetached())
  1053. detachedCount++;
  1054. }
  1055. else if (obj instanceof L2Summon)
  1056. summonCount++;
  1057. else if (obj instanceof L2DoorInstance)
  1058. doorCount++;
  1059. else if (obj instanceof L2Character)
  1060. charCount++;
  1061. }
  1062. StringBuilder sb = new StringBuilder();
  1063. sb.append("Server Status: ");
  1064. sb.append("\r\n ---> Player Count: " + playerCount + "/" + max);
  1065. sb.append("\r\n ---> Offline Count: " + detachedCount + "/" + playerCount);
  1066. sb.append("\r\n +--> Object Count: " + objectCount);
  1067. sb.append("\r\n +--> AI Count: " + AICount);
  1068. sb.append("\r\n +.... L2Item(Void): " + itemVoidCount);
  1069. sb.append("\r\n +.......... L2Item: " + itemCount);
  1070. sb.append("\r\n +....... L2Monster: " + monsterCount);
  1071. sb.append("\r\n +......... Minions: " + minionCount);
  1072. sb.append("\r\n +.. Minions Groups: " + minionsGroupCount);
  1073. sb.append("\r\n +........... L2Npc: " + npcCount);
  1074. sb.append("\r\n +............ L2Pc: " + pcCount);
  1075. sb.append("\r\n +........ L2Summon: " + summonCount);
  1076. sb.append("\r\n +.......... L2Door: " + doorCount);
  1077. sb.append("\r\n +.......... L2Char: " + charCount);
  1078. sb.append("\r\n ---> Ingame Time: " + gameTime());
  1079. sb.append("\r\n ---> Server Uptime: " + getUptime(_uptime));
  1080. sb.append("\r\n ---> GM Count: " + getOnlineGMS());
  1081. sb.append("\r\n ---> Threads: " + Thread.activeCount());
  1082. sb.append("\r\n RAM Used: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576)); // 1024 * 1024 = 1048576
  1083. sb.append("\r\n");
  1084. return sb.toString();
  1085. }
  1086. @SuppressWarnings("serial")
  1087. public void debugAll() throws IOException
  1088. {
  1089. Calendar cal = Calendar.getInstance();
  1090. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
  1091. StringBuilder sb = new StringBuilder();
  1092. sb.append(sdf.format(cal.getTime()));
  1093. sb.append("\n\nL2J Server Version: " + Config.SERVER_VERSION);
  1094. sb.append("\nDP Revision: " + Config.DATAPACK_VERSION);
  1095. sb.append("\n\n");
  1096. sb.append(this.getServerStatus());
  1097. sb.append("\n\n");
  1098. sb.append("\n## Java Platform Information ##");
  1099. sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name"));
  1100. sb.append("\nJava Version: " + System.getProperty("java.version"));
  1101. sb.append("\nJava Class Version: " + System.getProperty("java.class.version"));
  1102. sb.append("\n");
  1103. sb.append("\n## Virtual Machine Information ##");
  1104. sb.append("\nVM Name: " + System.getProperty("java.vm.name"));
  1105. sb.append("\nVM Version: " + System.getProperty("java.vm.version"));
  1106. sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor"));
  1107. sb.append("\nVM Info: " + System.getProperty("java.vm.info"));
  1108. sb.append("\n");
  1109. sb.append("\n## OS Information ##");
  1110. sb.append("\nName: " + System.getProperty("os.name"));
  1111. sb.append("\nArchiteture: " + System.getProperty("os.arch"));
  1112. sb.append("\nVersion: " + System.getProperty("os.version"));
  1113. sb.append("\n");
  1114. sb.append("\n## Runtime Information ##");
  1115. sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors());
  1116. sb.append("\nCurrent Free Heap Size: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " mb");
  1117. sb.append("\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb");
  1118. sb.append("\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb");
  1119. sb.append("\n");
  1120. sb.append("\n## Class Path Information ##\n");
  1121. String cp = System.getProperty("java.class.path");
  1122. String[] libs = cp.split(File.pathSeparator);
  1123. for (String lib : libs)
  1124. {
  1125. sb.append(lib);
  1126. sb.append("\n");
  1127. }
  1128. sb.append("\n");
  1129. sb.append("## Threads Information ##\n");
  1130. Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces();
  1131. FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<Entry<Thread, StackTraceElement[]>>();
  1132. entries.setValueComparator(new FastComparator<Entry<Thread, StackTraceElement[]>>()
  1133. {
  1134. @Override
  1135. public boolean areEqual(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  1136. {
  1137. return e1.getKey().getName().equals(e2.getKey().getName());
  1138. }
  1139. @Override
  1140. public int compare(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  1141. {
  1142. return e1.getKey().getName().compareTo(e2.getKey().getName());
  1143. }
  1144. @Override
  1145. public int hashCodeOf(Entry<Thread, StackTraceElement[]> e)
  1146. {
  1147. return e.hashCode();
  1148. }
  1149. });
  1150. entries.addAll(allThread.entrySet());
  1151. entries.sort();
  1152. for (Entry<Thread, StackTraceElement[]> entry : entries)
  1153. {
  1154. StackTraceElement[] stes = entry.getValue();
  1155. Thread t = entry.getKey();
  1156. sb.append("--------------\n");
  1157. sb.append(t.toString() + " (" + t.getId() + ")\n");
  1158. sb.append("State: " + t.getState() + "\n");
  1159. sb.append("isAlive: " + t.isAlive() + " | isDaemon: " + t.isDaemon() + " | isInterrupted: " + t.isInterrupted() + "\n");
  1160. sb.append("\n");
  1161. for (StackTraceElement ste : stes)
  1162. {
  1163. sb.append(ste.toString());
  1164. sb.append("\n");
  1165. }
  1166. sb.append("\n");
  1167. }
  1168. sb.append("\n");
  1169. this.checkForDeadlocks(sb);
  1170. sb.append("\n\n## Thread Pool Manager Statistics ##\n");
  1171. for (String line : ThreadPoolManager.getInstance().getStats())
  1172. {
  1173. sb.append(line);
  1174. sb.append("\n");
  1175. }
  1176. int i = 0;
  1177. File f = new File("./log/Debug-" + i + ".txt");
  1178. while (f.exists())
  1179. {
  1180. i++;
  1181. f = new File("./log/Debug-" + i + ".txt");
  1182. }
  1183. f.getParentFile().mkdirs();
  1184. FileOutputStream fos = new FileOutputStream(f);
  1185. OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
  1186. out.write(sb.toString());
  1187. out.flush();
  1188. out.close();
  1189. fos.close();
  1190. _print.println("Debug output saved to log/" + f.getName());
  1191. _print.flush();
  1192. }
  1193. private void checkForDeadlocks(StringBuilder sb)
  1194. {
  1195. ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
  1196. long[] ids = findDeadlockedThreads(mbean);
  1197. if (ids != null && ids.length > 0)
  1198. {
  1199. Thread[] threads = new Thread[ids.length];
  1200. for (int i = 0; i < threads.length; i++)
  1201. {
  1202. threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i]));
  1203. }
  1204. sb.append("Deadlocked Threads:\n");
  1205. sb.append("-------------------\n");
  1206. for (Thread thread : threads)
  1207. {
  1208. System.err.println(thread);
  1209. for (StackTraceElement ste : thread.getStackTrace())
  1210. {
  1211. sb.append("\t" + ste);
  1212. sb.append("\n");
  1213. }
  1214. }
  1215. }
  1216. }
  1217. private long[] findDeadlockedThreads(ThreadMXBean mbean)
  1218. {
  1219. // JDK 1.5 only supports the findMonitorDeadlockedThreads()
  1220. // method, so you need to comment out the following three lines
  1221. if (mbean.isSynchronizerUsageSupported())
  1222. {
  1223. return mbean.findDeadlockedThreads();
  1224. }
  1225. else
  1226. {
  1227. return mbean.findMonitorDeadlockedThreads();
  1228. }
  1229. }
  1230. private Thread findMatchingThread(ThreadInfo inf)
  1231. {
  1232. for (Thread thread : Thread.getAllStackTraces().keySet())
  1233. {
  1234. if (thread.getId() == inf.getThreadId())
  1235. {
  1236. return thread;
  1237. }
  1238. }
  1239. throw new IllegalStateException("Deadlocked Thread not found");
  1240. }
  1241. private final class CleanVoidItems implements TObjectProcedure<L2Object>
  1242. {
  1243. @Override
  1244. public final boolean execute(final L2Object obj)
  1245. {
  1246. L2ItemInstance item = null;
  1247. if (obj instanceof L2ItemInstance)
  1248. item = (L2ItemInstance) obj;
  1249. if (item != null && item.getLocation() == ItemLocation.VOID)
  1250. {
  1251. _print.println("Item: name="+item.getName()+" lastChange="+item.getLastChange()+" objId"+item.getObjectId()+";");
  1252. L2World.getInstance().removeObject(item);
  1253. }
  1254. return true;
  1255. }
  1256. }
  1257. }