BaseGameServerRegister.java 16 KB

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