GameStatusThread.java 55 KB

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