GameStatusThread.java 43 KB

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