2
0

GameStatusThread.java 54 KB

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