CursedWeaponsManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 net.sf.l2j.gameserver.instancemanager;
  16. import java.io.File;
  17. import java.sql.Connection;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.sql.SQLException;
  21. import java.util.Collection;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import javax.xml.parsers.DocumentBuilderFactory;
  27. import javolution.util.FastMap;
  28. import net.sf.l2j.Config;
  29. import net.sf.l2j.L2DatabaseFactory;
  30. import net.sf.l2j.gameserver.model.CursedWeapon;
  31. import net.sf.l2j.gameserver.model.L2Attackable;
  32. import net.sf.l2j.gameserver.model.L2Character;
  33. import net.sf.l2j.gameserver.model.L2ItemInstance;
  34. import net.sf.l2j.gameserver.model.L2World;
  35. import net.sf.l2j.gameserver.model.actor.instance.L2FeedableBeastInstance;
  36. import net.sf.l2j.gameserver.model.actor.instance.L2FestivalMonsterInstance;
  37. import net.sf.l2j.gameserver.model.actor.instance.L2GrandBossInstance;
  38. import net.sf.l2j.gameserver.model.actor.instance.L2GuardInstance;
  39. import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
  40. import net.sf.l2j.gameserver.model.actor.instance.L2RiftInvaderInstance;
  41. import net.sf.l2j.gameserver.model.actor.instance.L2SiegeGuardInstance;
  42. import net.sf.l2j.gameserver.network.SystemMessageId;
  43. import net.sf.l2j.gameserver.serverpackets.SystemMessage;
  44. import org.w3c.dom.Document;
  45. import org.w3c.dom.NamedNodeMap;
  46. import org.w3c.dom.Node;
  47. /**
  48. *
  49. * @author Micht
  50. */
  51. public class CursedWeaponsManager
  52. {
  53. private static final Logger _log = Logger.getLogger(CursedWeaponsManager.class.getName());
  54. // =========================================================
  55. private static CursedWeaponsManager _instance;
  56. public static final CursedWeaponsManager getInstance()
  57. {
  58. if (_instance == null)
  59. {
  60. _instance = new CursedWeaponsManager();
  61. }
  62. return _instance;
  63. }
  64. // =========================================================
  65. // Data Field
  66. private Map<Integer, CursedWeapon> _cursedWeapons;
  67. // =========================================================
  68. // Constructor
  69. public CursedWeaponsManager()
  70. {
  71. _log.info("Initializing CursedWeaponsManager");
  72. _cursedWeapons = new FastMap<Integer, CursedWeapon>();
  73. if (!Config.ALLOW_CURSED_WEAPONS) return;
  74. load();
  75. restore();
  76. controlPlayers();
  77. _log.info("Loaded : "+_cursedWeapons.size() + " cursed weapon(s).");
  78. }
  79. // =========================================================
  80. // Method - Private
  81. public final void reload()
  82. {
  83. _instance = new CursedWeaponsManager();
  84. }
  85. private final void load()
  86. {
  87. if (Config.DEBUG)
  88. _log.info(" Parsing ... ");
  89. try
  90. {
  91. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  92. factory.setValidating(false);
  93. factory.setIgnoringComments(true);
  94. File file = new File(Config.DATAPACK_ROOT+"/data/cursedWeapons.xml");
  95. if (!file.exists())
  96. {
  97. if (Config.DEBUG)
  98. _log.info("NO FILE");
  99. return;
  100. }
  101. Document doc = factory.newDocumentBuilder().parse(file);
  102. for (Node n=doc.getFirstChild(); n != null; n = n.getNextSibling())
  103. {
  104. if ("list".equalsIgnoreCase(n.getNodeName()))
  105. {
  106. for (Node d=n.getFirstChild(); d != null; d = d.getNextSibling())
  107. {
  108. if ("item".equalsIgnoreCase(d.getNodeName()))
  109. {
  110. NamedNodeMap attrs = d.getAttributes();
  111. int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
  112. int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue());
  113. String name = attrs.getNamedItem("name").getNodeValue();
  114. CursedWeapon cw = new CursedWeapon(id, skillId, name);
  115. int val;
  116. for (Node cd=d.getFirstChild(); cd != null; cd = cd.getNextSibling())
  117. {
  118. if ("dropRate".equalsIgnoreCase(cd.getNodeName()))
  119. {
  120. attrs = cd.getAttributes();
  121. val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
  122. cw.setDropRate(val);
  123. } else if ("duration".equalsIgnoreCase(cd.getNodeName()))
  124. {
  125. attrs = cd.getAttributes();
  126. val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
  127. cw.setDuration(val);
  128. } else if ("durationLost".equalsIgnoreCase(cd.getNodeName()))
  129. {
  130. attrs = cd.getAttributes();
  131. val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
  132. cw.setDurationLost(val);
  133. } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName()))
  134. {
  135. attrs = cd.getAttributes();
  136. val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
  137. cw.setDisapearChance(val);
  138. } else if ("stageKills".equalsIgnoreCase(cd.getNodeName()))
  139. {
  140. attrs = cd.getAttributes();
  141. val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
  142. cw.setStageKills(val);
  143. }
  144. }
  145. // Store cursed weapon
  146. _cursedWeapons.put(id, cw);
  147. }
  148. }
  149. }
  150. }
  151. if (Config.DEBUG)
  152. _log.info("OK");
  153. }
  154. catch (Exception e)
  155. {
  156. _log.log(Level.SEVERE, "Error parsing cursed weapons file.", e);
  157. if (Config.DEBUG)
  158. _log.warning("ERROR");
  159. return ;
  160. }
  161. }
  162. private final void restore()
  163. {
  164. if (Config.DEBUG)
  165. _log.info(" Restoring ... ");
  166. java.sql.Connection con = null;
  167. try
  168. {
  169. // Retrieve the L2PcInstance from the characters table of the database
  170. con = L2DatabaseFactory.getInstance().getConnection();
  171. PreparedStatement statement = con.prepareStatement("SELECT itemId, charId, playerKarma, playerPkKills, nbKills, endTime FROM cursed_weapons");
  172. ResultSet rset = statement.executeQuery();
  173. while(rset.next())
  174. {
  175. int itemId = rset.getInt("itemId");
  176. int playerId = rset.getInt("charId");
  177. int playerKarma = rset.getInt("playerKarma");
  178. int playerPkKills = rset.getInt("playerPkKills");
  179. int nbKills = rset.getInt("nbKills");
  180. long endTime = rset.getLong("endTime");
  181. CursedWeapon cw = _cursedWeapons.get(itemId);
  182. cw.setPlayerId(playerId);
  183. cw.setPlayerKarma(playerKarma);
  184. cw.setPlayerPkKills(playerPkKills);
  185. cw.setNbKills(nbKills);
  186. cw.setEndTime(endTime);
  187. cw.reActivate();
  188. }
  189. rset.close();
  190. statement.close();
  191. if (Config.DEBUG)
  192. _log.info("OK");
  193. }
  194. catch (Exception e)
  195. {
  196. _log.warning("Could not restore CursedWeapons data: " + e);
  197. if (Config.DEBUG)
  198. _log.warning("ERROR");
  199. return;
  200. }
  201. finally
  202. {
  203. try { con.close(); } catch (Exception e) {}
  204. }
  205. }
  206. private final void controlPlayers()
  207. {
  208. if (Config.DEBUG)
  209. _log.info(" Checking players ... ");
  210. java.sql.Connection con = null;
  211. try
  212. {
  213. // Retrieve the L2PcInstance from the characters table of the database
  214. con = L2DatabaseFactory.getInstance().getConnection();
  215. PreparedStatement statement = null;
  216. ResultSet rset = null;
  217. // TODO: See comments below...
  218. // This entire for loop should NOT be necessary, since it is already handled by
  219. // CursedWeapon.endOfLife(). However, if we indeed *need* to duplicate it for safety,
  220. // then we'd better make sure that it FULLY cleans up inactive cursed weapons!
  221. // Undesired effects result otherwise, such as player with no zariche but with karma
  222. // or a lost-child entry in the cursedweapons table, without a corresponding one in items...
  223. for (CursedWeapon cw : _cursedWeapons.values())
  224. {
  225. if (cw.isActivated()) continue;
  226. // Do an item check to be sure that the cursed weapon isn't hold by someone
  227. int itemId = cw.getItemId();
  228. try
  229. {
  230. statement = con.prepareStatement("SELECT owner_id FROM items WHERE item_id=?");
  231. statement.setInt(1, itemId);
  232. rset = statement.executeQuery();
  233. if (rset.next())
  234. {
  235. // A player has the cursed weapon in his inventory ...
  236. int playerId = rset.getInt("owner_id");
  237. _log.info("PROBLEM : Player "+playerId+" owns the cursed weapon "+itemId+" but he shouldn't.");
  238. // Delete the item
  239. statement = con.prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?");
  240. statement.setInt(1, playerId);
  241. statement.setInt(2, itemId);
  242. if (statement.executeUpdate() != 1)
  243. {
  244. _log.warning("Error while deleting cursed weapon "+itemId+" from userId "+playerId);
  245. }
  246. statement.close();
  247. // Delete the skill
  248. /*
  249. statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id=");
  250. statement.setInt(1, playerId);
  251. statement.setInt(2, cw.getSkillId());
  252. if (statement.executeUpdate() != 1)
  253. {
  254. _log.warning("Error while deleting cursed weapon "+itemId+" skill from userId "+playerId);
  255. }
  256. */
  257. // Restore the player's old karma and pk count
  258. statement = con.prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId=?");
  259. statement.setInt(1, cw.getPlayerKarma());
  260. statement.setInt(2, cw.getPlayerPkKills());
  261. statement.setInt(3, playerId);
  262. if (statement.executeUpdate() != 1)
  263. {
  264. _log.warning("Error while updating karma & pkkills for userId "+cw.getPlayerId());
  265. }
  266. // clean up the cursedweapons table.
  267. removeFromDb(itemId);
  268. }
  269. rset.close();
  270. statement.close();
  271. } catch (SQLException sqlE)
  272. {}
  273. // close the statement to avoid multiply prepared statement errors in following iterations.
  274. try { con.close(); } catch (Exception e) {}
  275. }
  276. }
  277. catch (Exception e)
  278. {
  279. _log.warning("Could not check CursedWeapons data: " + e);
  280. if (Config.DEBUG)
  281. _log.warning("ERROR");
  282. return;
  283. }
  284. finally
  285. {
  286. try { con.close(); } catch (Exception e) {}
  287. }
  288. if (Config.DEBUG)
  289. _log.info("DONE");
  290. }
  291. // =========================================================
  292. // Properties - Public
  293. public synchronized void checkDrop(L2Attackable attackable, L2PcInstance player)
  294. {
  295. if (attackable instanceof L2SiegeGuardInstance
  296. || attackable instanceof L2RiftInvaderInstance
  297. || attackable instanceof L2FestivalMonsterInstance
  298. || attackable instanceof L2GuardInstance
  299. || attackable instanceof L2GrandBossInstance
  300. || attackable instanceof L2FeedableBeastInstance
  301. )return;
  302. for (CursedWeapon cw : _cursedWeapons.values())
  303. {
  304. if (cw.isActive()) continue;
  305. if (cw.checkDrop(attackable, player)) break;
  306. }
  307. }
  308. public void activate(L2PcInstance player, L2ItemInstance item)
  309. {
  310. CursedWeapon cw = _cursedWeapons.get(item.getItemId());
  311. if (player.isCursedWeaponEquipped()) // cannot own 2 cursed swords
  312. {
  313. CursedWeapon cw2 = _cursedWeapons.get(player.getCursedWeaponEquippedId());
  314. /* TODO: give the bonus level in a more appropriate manner.
  315. * The following code adds "_stageKills" levels. This will also show in the char status.
  316. * I do not have enough info to know if the bonus should be shown in the pk count, or if it
  317. * should be a full "_stageKills" bonus or just the remaining from the current count till the
  318. * of the current stage...
  319. * This code is a TEMP fix, so that the cursed weapon's bonus level can be observed with as
  320. * little change in the code as possible, until proper info arises.
  321. */
  322. cw2.setNbKills(cw2.getStageKills()-1);
  323. cw2.increaseKills();
  324. // erase the newly obtained cursed weapon
  325. cw.setPlayer(player); // NECESSARY in order to find which inventory the weapon is in!
  326. cw.endOfLife(); // expire the weapon and clean up.
  327. }
  328. else cw.activate(player, item);
  329. }
  330. public void drop(int itemId, L2Character killer)
  331. {
  332. CursedWeapon cw = _cursedWeapons.get(itemId);
  333. cw.dropIt(killer);
  334. }
  335. public void increaseKills(int itemId)
  336. {
  337. CursedWeapon cw = _cursedWeapons.get(itemId);
  338. cw.increaseKills();
  339. }
  340. public int getLevel(int itemId)
  341. {
  342. CursedWeapon cw = _cursedWeapons.get(itemId);
  343. return cw.getLevel();
  344. }
  345. public static void announce(SystemMessage sm)
  346. {
  347. for (L2PcInstance player : L2World.getInstance().getAllPlayers())
  348. {
  349. if (player == null) continue;
  350. player.sendPacket(sm);
  351. }
  352. if (Config.DEBUG)
  353. _log.info("MessageID: "+sm.getMessageID());
  354. }
  355. public void checkPlayer(L2PcInstance player)
  356. {
  357. if (player == null)
  358. return;
  359. for (CursedWeapon cw : _cursedWeapons.values())
  360. {
  361. if (cw.isActivated() && player.getObjectId() == cw.getPlayerId())
  362. {
  363. cw.setPlayer(player);
  364. cw.setItem(player.getInventory().getItemByItemId(cw.getItemId()));
  365. cw.giveSkill();
  366. player.setCursedWeaponEquippedId(cw.getItemId());
  367. SystemMessage sm = new SystemMessage(SystemMessageId.S2_MINUTE_OF_USAGE_TIME_ARE_LEFT_FOR_S1);
  368. sm.addString(cw.getName());
  369. //sm.addItemName(cw.getItemId());
  370. sm.addNumber((int)((cw.getEndTime() - System.currentTimeMillis()) / 60000));
  371. player.sendPacket(sm);
  372. }
  373. }
  374. }
  375. public int checkOwnsWeaponId(int ownerId)
  376. {
  377. for (CursedWeapon cw : _cursedWeapons.values())
  378. if (cw.isActivated() && ownerId == cw.getPlayerId())
  379. return cw.getItemId();
  380. return -1;
  381. }
  382. public static void removeFromDb(int itemId)
  383. {
  384. Connection con = null;
  385. try
  386. {
  387. con = L2DatabaseFactory.getInstance().getConnection();
  388. // Delete datas
  389. PreparedStatement statement = con.prepareStatement("DELETE FROM cursed_weapons WHERE itemId = ?");
  390. statement.setInt(1, itemId);
  391. statement.executeUpdate();
  392. statement.close();
  393. con.close();
  394. }
  395. catch (SQLException e)
  396. {
  397. _log.severe("CursedWeaponsManager: Failed to remove data: " + e);
  398. }
  399. finally
  400. {
  401. try { con.close(); } catch (Exception e) {}
  402. }
  403. }
  404. public void saveData()
  405. {
  406. for (CursedWeapon cw : _cursedWeapons.values())
  407. {
  408. cw.saveData();
  409. }
  410. }
  411. // =========================================================
  412. public boolean isCursed(int itemId)
  413. {
  414. return _cursedWeapons.containsKey(itemId);
  415. }
  416. public Collection<CursedWeapon> getCursedWeapons()
  417. {
  418. return _cursedWeapons.values();
  419. }
  420. public Set<Integer> getCursedWeaponsIds()
  421. {
  422. return _cursedWeapons.keySet();
  423. }
  424. public CursedWeapon getCursedWeapon(int itemId)
  425. {
  426. return _cursedWeapons.get(itemId);
  427. }
  428. public void givePassive(int itemId)
  429. {
  430. try { _cursedWeapons.get(itemId).giveSkill(); } catch (Exception e) {/***/}
  431. }
  432. }