BaseGameServerRegister.java 15 KB

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