CursedWeaponsManager.java 16 KB

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