GameStatusThread.java 43 KB

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