2
0

GameStatusThread.java 57 KB

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