BaseGameServerRegister.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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.tools.gsregistering;
  16. import java.awt.HeadlessException;
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.math.BigInteger;
  22. import java.sql.Connection;
  23. import java.sql.PreparedStatement;
  24. import java.sql.SQLException;
  25. import java.util.Locale;
  26. import java.util.Map.Entry;
  27. import java.util.Properties;
  28. import java.util.ResourceBundle;
  29. import javax.swing.SwingUtilities;
  30. import javax.swing.UIManager;
  31. import com.l2jserver.Config;
  32. import com.l2jserver.L2DatabaseFactory;
  33. import com.l2jserver.Server;
  34. import com.l2jserver.loginserver.GameServerTable;
  35. import com.l2jserver.tools.i18n.LanguageControl;
  36. import com.l2jserver.util.Util;
  37. /**
  38. * The Class BaseGameServerRegister.
  39. * @author KenM
  40. */
  41. public abstract class BaseGameServerRegister
  42. {
  43. private boolean _loaded = false;
  44. private ResourceBundle _bundle;
  45. /**
  46. * The main method.
  47. * @param args the arguments
  48. */
  49. public static void main(String[] args)
  50. {
  51. Locale locale = null;
  52. boolean gui = true;
  53. boolean interactive = true;
  54. boolean force = false;
  55. boolean fallback = false;
  56. BaseTask task = null;
  57. ResourceBundle bundle = null;
  58. try
  59. {
  60. locale = Locale.getDefault();
  61. bundle = ResourceBundle.getBundle("gsregister.GSRegister", locale, LanguageControl.INSTANCE);
  62. }
  63. catch (Throwable t)
  64. {
  65. System.out.println("FATAL: Failed to load default translation.");
  66. System.exit(666);
  67. }
  68. String arg;
  69. for (int i = 0; i < args.length; i++)
  70. {
  71. arg = args[i];
  72. // --cmd : no gui
  73. if (arg.equals("-c") || arg.equals("--cmd"))
  74. {
  75. gui = false;
  76. }
  77. // --force : Forces GameServer register operations to overwrite a server if necessary
  78. else if (arg.equals("-f") || arg.equals("--force"))
  79. {
  80. force = true;
  81. }
  82. // --fallback : If an register operation fails due to ID already being in use it will then try to register first available ID
  83. else if (arg.equals("-b") || arg.equals("--fallback"))
  84. {
  85. fallback = true;
  86. }
  87. // --register <id> <hexid_dest_dir> : Register GameServer with ID <id> and output hexid on <hexid_dest_dir>
  88. // Fails if <id> already in use, unless -force is used (overwrites)
  89. else if (arg.equals("-r") || arg.equals("--register"))
  90. {
  91. gui = false;
  92. interactive = false;
  93. int id = Integer.parseInt(args[++i]);
  94. String dir = args[++i];
  95. task = new RegisterTask(id, dir, force, fallback);
  96. }
  97. // --unregister <id> : Removes GameServer denoted by <id>
  98. else if (arg.equals("-u") || arg.equals("--unregister"))
  99. {
  100. gui = false;
  101. interactive = false;
  102. String gsId = args[++i];
  103. if (gsId.equalsIgnoreCase("all"))
  104. {
  105. task = new UnregisterAllTask();
  106. }
  107. else
  108. {
  109. try
  110. {
  111. int id = Integer.parseInt(gsId);
  112. task = new UnregisterTask(id);
  113. }
  114. catch (NumberFormatException e)
  115. {
  116. if (bundle != null)
  117. {
  118. System.out.printf(bundle.getString("wrongUnregisterArg") + '\n', gsId);
  119. }
  120. System.exit(1);
  121. }
  122. }
  123. }
  124. // --language <locale> : Sets the app to use the specified locale, overriding auto-detection
  125. else if (arg.equals("-l") || arg.equals("--language"))
  126. {
  127. String loc = args[++i];
  128. Locale[] availableLocales = Locale.getAvailableLocales();
  129. Locale l;
  130. for (int j = 0; (j < availableLocales.length) && (locale == null); j++)
  131. {
  132. l = availableLocales[j];
  133. if (l.toString().equals(loc))
  134. {
  135. locale = l;
  136. }
  137. }
  138. if (locale == null)
  139. {
  140. System.out.println("Specified locale '" + loc + "' was not found, using default behaviour.");
  141. }
  142. else
  143. {
  144. try
  145. {
  146. bundle = ResourceBundle.getBundle("gsregister.GSRegister", locale, LanguageControl.INSTANCE);
  147. }
  148. catch (Throwable t)
  149. {
  150. System.out.println("Failed to load translation ''");
  151. }
  152. }
  153. }
  154. // --help : Prints usage/arguments/credits
  155. else if (arg.equals("-h") || arg.equals("--help"))
  156. {
  157. gui = false;
  158. interactive = false;
  159. BaseGameServerRegister.printHelp(bundle);
  160. }
  161. }
  162. try
  163. {
  164. if (gui)
  165. {
  166. BaseGameServerRegister.startGUI(bundle);
  167. }
  168. else
  169. {
  170. if (interactive)
  171. {
  172. BaseGameServerRegister.startCMD(bundle);
  173. }
  174. else
  175. {
  176. // if there is a task, do it, else the app has already finished
  177. if (task != null)
  178. {
  179. task.setBundle(bundle);
  180. task.run();
  181. }
  182. }
  183. }
  184. }
  185. catch (HeadlessException e)
  186. {
  187. BaseGameServerRegister.startCMD(bundle);
  188. }
  189. }
  190. /**
  191. * Prints the help.
  192. * @param bundle the bundle
  193. */
  194. private static void printHelp(ResourceBundle bundle)
  195. {
  196. String[] help =
  197. {
  198. bundle.getString("purpose"),
  199. "",
  200. bundle.getString("options"),
  201. "-b, --fallback\t\t\t\t" + bundle.getString("fallbackOpt"),
  202. "-c, --cmd\t\t\t\t" + bundle.getString("cmdOpt"),
  203. "-f, --force\t\t\t\t" + bundle.getString("forceOpt"),
  204. "-h, --help\t\t\t\t" + bundle.getString("helpOpt"),
  205. "-l, --language\t\t\t\t" + bundle.getString("languageOpt"),
  206. "-r, --register <id> <hexid_dest_dir>\t" + bundle.getString("registerOpt1"),
  207. "\t\t\t\t\t" + bundle.getString("registerOpt2"),
  208. "\t\t\t\t\t" + bundle.getString("registerOpt3"),
  209. "",
  210. "-u, --unregister <id>|all\t\t" + bundle.getString("unregisterOpt"),
  211. "",
  212. bundle.getString("credits"),
  213. bundle.getString("bugReports") + " http://www.l2jserver.com"
  214. /*
  215. * "-b, --fallback\t\t\t\tIf an register operation fails due to ID already being in use it will then try to register first available ID", "-c, --cmd\t\t\t\tForces application to run in command-line mode even if the GUI is supported.",
  216. * "-f, --force\t\t\t\tForces GameServer register operations to overwrite a server if necessary", "-h, --help\t\t\t\tPrints this help message", "-l, --language <locale>\t\t\t\tAsks the application to use the specified locale, overriding auto-detection",
  217. * "-r, --register <id> <hexid_dest_dir>\tRegister GameServer with ID <id> and output hexid on <hexid_dest_dir>", "\t\t\t\t\tUse a negative value on <id> to register the first available ID", "\t\t\t\t\tFails if <id> already in use, unless --force is used (overwrites)", "",
  218. * "-u, --unregister <id>|all\t\tRemoves GameServer denoted by <id>, use \"all\" for removing all registered GameServers", "", "Copyright (C) L2J Team 2008-2012.", "Report bugs: http://www.l2jserver.com"
  219. */
  220. };
  221. for (String str : help)
  222. {
  223. System.out.println(str);
  224. }
  225. }
  226. /**
  227. * Start the GUI.
  228. * @param bundle the bundle.
  229. */
  230. private static void startGUI(final ResourceBundle bundle)
  231. {
  232. try
  233. {
  234. // avoid that ugly Metal LaF
  235. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  236. }
  237. catch (Exception e)
  238. {
  239. // couldn't care less
  240. }
  241. SwingUtilities.invokeLater(new Runnable()
  242. {
  243. @Override
  244. public void run()
  245. {
  246. GUserInterface gui = new GUserInterface(bundle);
  247. gui.getFrame().setVisible(true);
  248. }
  249. });
  250. }
  251. /**
  252. * Start the CMD.
  253. * @param bundle the bundle.
  254. */
  255. private static void startCMD(final ResourceBundle bundle)
  256. {
  257. GameServerRegister cmdUi = new GameServerRegister(bundle);
  258. try
  259. {
  260. cmdUi.consoleUI();
  261. }
  262. catch (IOException e)
  263. {
  264. cmdUi.showError("I/O exception trying to get input from keyboard.", e);
  265. }
  266. }
  267. /**
  268. * Instantiates a new base game server register.
  269. * @param bundle the bundle.
  270. */
  271. public BaseGameServerRegister(ResourceBundle bundle)
  272. {
  273. setBundle(bundle);
  274. }
  275. /**
  276. * Load.
  277. */
  278. public void load()
  279. {
  280. Server.serverMode = Server.MODE_LOGINSERVER;
  281. Config.load();
  282. GameServerTable.getInstance();
  283. _loaded = true;
  284. }
  285. /**
  286. * Checks if is loaded.
  287. * @return true, if is loaded
  288. */
  289. public boolean isLoaded()
  290. {
  291. return _loaded;
  292. }
  293. /**
  294. * Sets the bundle.
  295. * @param bundle the bundle to set.
  296. */
  297. public void setBundle(ResourceBundle bundle)
  298. {
  299. _bundle = bundle;
  300. }
  301. /**
  302. * Gets the bundle.
  303. * @return the bundle.
  304. */
  305. public ResourceBundle getBundle()
  306. {
  307. return _bundle;
  308. }
  309. /**
  310. * Show the error.
  311. * @param msg the msg.
  312. * @param t the t.
  313. */
  314. public abstract void showError(String msg, Throwable t);
  315. /**
  316. * Unregister the game server.
  317. * @param id the game server id.
  318. * @throws SQLException the SQL exception.
  319. */
  320. public static void unregisterGameServer(int id) throws SQLException
  321. {
  322. Connection con = null;
  323. try
  324. {
  325. con = L2DatabaseFactory.getInstance().getConnection();
  326. final PreparedStatement statement = con.prepareStatement("DELETE FROM gameservers WHERE server_id = ?");
  327. statement.setInt(1, id);
  328. statement.executeUpdate();
  329. GameServerTable.getInstance().getRegisteredGameServers().remove(id);
  330. statement.close();
  331. }
  332. finally
  333. {
  334. L2DatabaseFactory.close(con);
  335. }
  336. }
  337. /**
  338. * Unregister all game servers.
  339. * @throws SQLException the SQL exception
  340. */
  341. public static void unregisterAllGameServers() throws SQLException
  342. {
  343. Connection con = null;
  344. try
  345. {
  346. con = L2DatabaseFactory.getInstance().getConnection();
  347. final PreparedStatement statement = con.prepareStatement("DELETE FROM gameservers");
  348. statement.executeUpdate();
  349. statement.close();
  350. GameServerTable.getInstance().getRegisteredGameServers().clear();
  351. }
  352. finally
  353. {
  354. L2DatabaseFactory.close(con);
  355. }
  356. }
  357. /**
  358. * Register a game server.
  359. * @param id the id of the game server.
  360. * @param outDir the out dir.
  361. * @throws IOException Signals that an I/O exception has occurred.
  362. */
  363. public static void registerGameServer(int id, String outDir) throws IOException
  364. {
  365. byte[] hexId = Util.generateHex(16);
  366. GameServerTable.getInstance().registerServerOnDB(hexId, id, "");
  367. Properties hexSetting = new Properties();
  368. File file = new File(outDir, "hexid.txt");
  369. // Create a new empty file only if it doesn't exist
  370. file.createNewFile();
  371. OutputStream out = new FileOutputStream(file);
  372. hexSetting.setProperty("ServerID", String.valueOf(id));
  373. hexSetting.setProperty("HexID", new BigInteger(hexId).toString(16));
  374. hexSetting.store(out, "The HexId to Auth into LoginServer");
  375. out.close();
  376. }
  377. /**
  378. * Register first available.
  379. * @param outDir the out dir
  380. * @return the int
  381. * @throws IOException Signals that an I/O exception has occurred.
  382. */
  383. public static int registerFirstAvailable(String outDir) throws IOException
  384. {
  385. for (Entry<Integer, String> e : GameServerTable.getInstance().getServerNames().entrySet())
  386. {
  387. if (!GameServerTable.getInstance().hasRegisteredGameServerOnId(e.getKey()))
  388. {
  389. BaseGameServerRegister.registerGameServer(e.getKey(), outDir);
  390. return e.getKey();
  391. }
  392. }
  393. return -1;
  394. }
  395. /**
  396. * The Class BaseTask.
  397. */
  398. private static abstract class BaseTask implements Runnable
  399. {
  400. private ResourceBundle _bundle;
  401. /**
  402. * Sets the bundle.
  403. * @param bundle The bundle to set.
  404. */
  405. public void setBundle(ResourceBundle bundle)
  406. {
  407. _bundle = bundle;
  408. }
  409. /**
  410. * Gets the bundle.
  411. * @return Returns the bundle.
  412. */
  413. public ResourceBundle getBundle()
  414. {
  415. return _bundle;
  416. }
  417. /**
  418. * Show the error.
  419. * @param msg the msg
  420. * @param t the t
  421. */
  422. public void showError(String msg, Throwable t)
  423. {
  424. String title;
  425. if (getBundle() != null)
  426. {
  427. title = getBundle().getString("error");
  428. msg += '\n' + getBundle().getString("reason") + ' ' + t.getLocalizedMessage();
  429. }
  430. else
  431. {
  432. title = "Error";
  433. msg += "\nCause: " + t.getLocalizedMessage();
  434. }
  435. System.out.println(title + ": " + msg);
  436. }
  437. }
  438. /**
  439. * The Class RegisterTask.
  440. */
  441. private static class RegisterTask extends BaseTask
  442. {
  443. private final int _id;
  444. private final String _outDir;
  445. private boolean _force;
  446. private boolean _fallback;
  447. /**
  448. * Instantiates a new register task.
  449. * @param id the id.
  450. * @param outDir the out dir.
  451. * @param force the force.
  452. * @param fallback the fallback.
  453. */
  454. public RegisterTask(int id, String outDir, boolean force, boolean fallback)
  455. {
  456. _id = id;
  457. _outDir = outDir;
  458. _force = force;
  459. _fallback = fallback;
  460. }
  461. /**
  462. * Sets the actions.
  463. * @param force the force.
  464. * @param fallback the fallback.
  465. */
  466. @SuppressWarnings("unused")
  467. public void setActions(boolean force, boolean fallback)
  468. {
  469. _force = force;
  470. _fallback = fallback;
  471. }
  472. @Override
  473. public void run()
  474. {
  475. try
  476. {
  477. if (_id < 0)
  478. {
  479. int registeredId = BaseGameServerRegister.registerFirstAvailable(_outDir);
  480. if (registeredId < 0)
  481. {
  482. System.out.println(getBundle().getString("noFreeId"));
  483. }
  484. else
  485. {
  486. System.out.printf(getBundle().getString("registrationOk") + '\n', registeredId);
  487. }
  488. }
  489. else
  490. {
  491. System.out.printf(getBundle().getString("checkingIdInUse") + '\n', _id);
  492. if (GameServerTable.getInstance().hasRegisteredGameServerOnId(_id))
  493. {
  494. System.out.println(getBundle().getString("yes"));
  495. if (_force)
  496. {
  497. System.out.printf(getBundle().getString("forcingRegistration") + '\n', _id);
  498. BaseGameServerRegister.unregisterGameServer(_id);
  499. BaseGameServerRegister.registerGameServer(_id, _outDir);
  500. System.out.printf(getBundle().getString("registrationOk") + '\n', _id);
  501. }
  502. else if (_fallback)
  503. {
  504. System.out.println(getBundle().getString("fallingBack"));
  505. int registeredId = BaseGameServerRegister.registerFirstAvailable(_outDir);
  506. if (registeredId < 0)
  507. {
  508. System.out.println(getBundle().getString("noFreeId"));
  509. }
  510. else
  511. {
  512. System.out.printf(getBundle().getString("registrationOk") + '\n', registeredId);
  513. }
  514. }
  515. else
  516. {
  517. System.out.println(getBundle().getString("noAction"));
  518. }
  519. }
  520. else
  521. {
  522. System.out.println(getBundle().getString("no"));
  523. BaseGameServerRegister.registerGameServer(_id, _outDir);
  524. }
  525. }
  526. }
  527. catch (SQLException e)
  528. {
  529. showError(getBundle().getString("sqlErrorRegister"), e);
  530. }
  531. catch (IOException e)
  532. {
  533. showError(getBundle().getString("ioErrorRegister"), e);
  534. }
  535. }
  536. }
  537. /**
  538. * The Class UnregisterTask.
  539. */
  540. private static class UnregisterTask extends BaseTask
  541. {
  542. private final int _id;
  543. /**
  544. * Instantiates a new unregister task.
  545. * @param id the task id.
  546. */
  547. public UnregisterTask(int id)
  548. {
  549. _id = id;
  550. }
  551. @Override
  552. public void run()
  553. {
  554. System.out.printf(getBundle().getString("removingGsId") + '\n', _id);
  555. try
  556. {
  557. BaseGameServerRegister.unregisterGameServer(_id);
  558. }
  559. catch (SQLException e)
  560. {
  561. showError(getBundle().getString("sqlErrorRegister"), e);
  562. }
  563. }
  564. }
  565. /**
  566. * The Class UnregisterAllTask.
  567. */
  568. private static class UnregisterAllTask extends BaseTask
  569. {
  570. @Override
  571. public void run()
  572. {
  573. try
  574. {
  575. BaseGameServerRegister.unregisterAllGameServers();
  576. }
  577. catch (SQLException e)
  578. {
  579. showError(getBundle().getString("sqlErrorUnregisterAll"), e);
  580. }
  581. }
  582. }
  583. }