GameStatusThread.java 46 KB

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