CastleManorManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. * Copyright (C) 2004-2013 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.instancemanager;
  20. import java.sql.Connection;
  21. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.util.ArrayList;
  24. import java.util.Calendar;
  25. import java.util.List;
  26. import java.util.concurrent.ScheduledFuture;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;
  29. import javolution.util.FastList;
  30. import com.l2jserver.Config;
  31. import com.l2jserver.L2DatabaseFactory;
  32. import com.l2jserver.gameserver.ThreadPoolManager;
  33. import com.l2jserver.gameserver.datatables.ClanTable;
  34. import com.l2jserver.gameserver.datatables.ManorData;
  35. import com.l2jserver.gameserver.model.CropProcure;
  36. import com.l2jserver.gameserver.model.L2Clan;
  37. import com.l2jserver.gameserver.model.L2World;
  38. import com.l2jserver.gameserver.model.SeedProduction;
  39. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  40. import com.l2jserver.gameserver.model.entity.Castle;
  41. import com.l2jserver.gameserver.model.itemcontainer.ClanWarehouse;
  42. import com.l2jserver.gameserver.model.itemcontainer.ItemContainer;
  43. import com.l2jserver.gameserver.network.SystemMessageId;
  44. import com.l2jserver.util.Rnd;
  45. /**
  46. * Class for Castle Manor Manager load manor data from DB update/reload/delete, handles all schedule for manor.
  47. * @author l3x
  48. */
  49. public final class CastleManorManager
  50. {
  51. protected static final Logger _log = Logger.getLogger(CastleManorManager.class.getName());
  52. public static final int PERIOD_CURRENT = 0;
  53. public static final int PERIOD_NEXT = 1;
  54. private static final String CASTLE_MANOR_LOAD_PROCURE = "SELECT * FROM castle_manor_procure WHERE castle_id=?";
  55. private static final String CASTLE_MANOR_LOAD_PRODUCTION = "SELECT * FROM castle_manor_production WHERE castle_id=?";
  56. private static final int NEXT_PERIOD_APPROVE = Config.ALT_MANOR_APPROVE_TIME; // 6:00
  57. private static final int NEXT_PERIOD_APPROVE_MIN = Config.ALT_MANOR_APPROVE_MIN; //
  58. private static final int MANOR_REFRESH = Config.ALT_MANOR_REFRESH_TIME; // 20:00
  59. private static final int MANOR_REFRESH_MIN = Config.ALT_MANOR_REFRESH_MIN; //
  60. protected static final long MAINTENANCE_PERIOD = Config.ALT_MANOR_MAINTENANCE_PERIOD; // 6 mins
  61. private Calendar _manorRefresh;
  62. private Calendar _periodApprove;
  63. private boolean _underMaintenance;
  64. private boolean _disabled;
  65. protected ScheduledFuture<?> _scheduledManorRefresh;
  66. protected ScheduledFuture<?> _scheduledMaintenanceEnd;
  67. protected ScheduledFuture<?> _scheduledNextPeriodapprove;
  68. protected CastleManorManager()
  69. {
  70. load(); // load data from database
  71. init(); // schedule all manor related events
  72. _underMaintenance = false;
  73. _disabled = !Config.ALLOW_MANOR;
  74. boolean isApproved;
  75. if (_periodApprove.getTimeInMillis() > _manorRefresh.getTimeInMillis())
  76. {
  77. // Next approve period already scheduled
  78. isApproved = (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis());
  79. }
  80. else
  81. {
  82. isApproved = ((_periodApprove.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) && (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()));
  83. }
  84. for (Castle c : CastleManager.getInstance().getCastles())
  85. {
  86. c.setNextPeriodApproved(isApproved);
  87. }
  88. }
  89. private void load()
  90. {
  91. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  92. PreparedStatement statementProduction = con.prepareStatement(CASTLE_MANOR_LOAD_PRODUCTION);
  93. PreparedStatement statementProcure = con.prepareStatement(CASTLE_MANOR_LOAD_PROCURE))
  94. {
  95. for (Castle castle : CastleManager.getInstance().getCastles())
  96. {
  97. FastList<SeedProduction> production = new FastList<>();
  98. FastList<SeedProduction> productionNext = new FastList<>();
  99. FastList<CropProcure> procure = new FastList<>();
  100. FastList<CropProcure> procureNext = new FastList<>();
  101. // restore seed production info
  102. statementProduction.setInt(1, castle.getCastleId());
  103. try (ResultSet rs = statementProduction.executeQuery())
  104. {
  105. statementProduction.clearParameters();
  106. while (rs.next())
  107. {
  108. int seedId = rs.getInt("seed_id");
  109. int canProduce = rs.getInt("can_produce");
  110. int startProduce = rs.getInt("start_produce");
  111. int price = rs.getInt("seed_price");
  112. int period = rs.getInt("period");
  113. if (period == PERIOD_CURRENT)
  114. {
  115. production.add(new SeedProduction(seedId, canProduce, price, startProduce));
  116. }
  117. else
  118. {
  119. productionNext.add(new SeedProduction(seedId, canProduce, price, startProduce));
  120. }
  121. }
  122. }
  123. castle.setSeedProduction(production, PERIOD_CURRENT);
  124. castle.setSeedProduction(productionNext, PERIOD_NEXT);
  125. // restore procure info
  126. statementProcure.setInt(1, castle.getCastleId());
  127. try (ResultSet rs = statementProcure.executeQuery())
  128. {
  129. statementProcure.clearParameters();
  130. while (rs.next())
  131. {
  132. int cropId = rs.getInt("crop_id");
  133. int canBuy = rs.getInt("can_buy");
  134. int startBuy = rs.getInt("start_buy");
  135. int rewardType = rs.getInt("reward_type");
  136. int price = rs.getInt("price");
  137. int period = rs.getInt("period");
  138. if (period == PERIOD_CURRENT)
  139. {
  140. procure.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  141. }
  142. else
  143. {
  144. procureNext.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  145. }
  146. }
  147. }
  148. castle.setCropProcure(procure, PERIOD_CURRENT);
  149. castle.setCropProcure(procureNext, PERIOD_NEXT);
  150. if (!procure.isEmpty() || !procureNext.isEmpty() || !production.isEmpty() || !productionNext.isEmpty())
  151. {
  152. _log.info(getClass().getSimpleName() + ": " + castle.getName() + ": Data loaded");
  153. }
  154. }
  155. }
  156. catch (Exception e)
  157. {
  158. _log.info("Error restoring manor data: " + e.getMessage());
  159. }
  160. }
  161. private void init()
  162. {
  163. _manorRefresh = Calendar.getInstance();
  164. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  165. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  166. _periodApprove = Calendar.getInstance();
  167. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  168. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  169. updateManorRefresh();
  170. updatePeriodApprove();
  171. }
  172. public void updateManorRefresh()
  173. {
  174. _log.info("Manor System: Manor refresh updated");
  175. _scheduledManorRefresh = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  176. {
  177. @Override
  178. public void run()
  179. {
  180. if (!isDisabled())
  181. {
  182. setUnderMaintenance(true);
  183. _log.info("Manor System: Under maintenance mode started");
  184. _scheduledMaintenanceEnd = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  185. {
  186. @Override
  187. public void run()
  188. {
  189. _log.info("Manor System: Next period started");
  190. setNextPeriod();
  191. try
  192. {
  193. save();
  194. }
  195. catch (Exception e)
  196. {
  197. _log.log(Level.WARNING, "Manor System: Failed to save manor data: " + e.getMessage(), e);
  198. }
  199. setUnderMaintenance(false);
  200. }
  201. }, MAINTENANCE_PERIOD);
  202. }
  203. updateManorRefresh();
  204. }
  205. }, getMillisToManorRefresh());
  206. }
  207. public void updatePeriodApprove()
  208. {
  209. _log.info("Manor System: Manor period approve updated");
  210. _scheduledNextPeriodapprove = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  211. {
  212. @Override
  213. public void run()
  214. {
  215. if (!isDisabled())
  216. {
  217. approveNextPeriod();
  218. _log.info("Manor System: Next period approved");
  219. }
  220. updatePeriodApprove();
  221. }
  222. }, getMillisToNextPeriodApprove());
  223. }
  224. public long getMillisToManorRefresh()
  225. {
  226. // use safe interval 120s to prevent double run
  227. if ((_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) < 120000)
  228. {
  229. setNewManorRefresh();
  230. }
  231. _log.info("Manor System: New Schedule for manor refresh @ " + _manorRefresh.getTime());
  232. return (_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  233. }
  234. public void setNewManorRefresh()
  235. {
  236. _manorRefresh = Calendar.getInstance();
  237. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  238. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  239. _manorRefresh.set(Calendar.SECOND, 0);
  240. _manorRefresh.add(Calendar.HOUR_OF_DAY, 24);
  241. }
  242. public long getMillisToNextPeriodApprove()
  243. {
  244. // use safe interval 120s to prevent double run
  245. if ((_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) < 120000)
  246. {
  247. setNewPeriodApprove();
  248. }
  249. _log.info("Manor System: New Schedule for period approve @ " + _periodApprove.getTime());
  250. return (_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  251. }
  252. public void setNewPeriodApprove()
  253. {
  254. _periodApprove = Calendar.getInstance();
  255. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  256. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  257. _periodApprove.set(Calendar.SECOND, 0);
  258. _periodApprove.add(Calendar.HOUR_OF_DAY, 24);
  259. }
  260. public void setNextPeriod()
  261. {
  262. for (Castle c : CastleManager.getInstance().getCastles())
  263. {
  264. if (c.getOwnerId() <= 0)
  265. {
  266. continue;
  267. }
  268. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  269. if (clan == null)
  270. {
  271. continue;
  272. }
  273. ItemContainer cwh = clan.getWarehouse();
  274. if (!(cwh instanceof ClanWarehouse))
  275. {
  276. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  277. continue;
  278. }
  279. for (CropProcure crop : c.getCropProcure(PERIOD_CURRENT))
  280. {
  281. if (crop.getStartAmount() == 0)
  282. {
  283. continue;
  284. }
  285. // adding bought crops to clan warehouse
  286. if ((crop.getStartAmount() - crop.getAmount()) > 0)
  287. {
  288. long count = crop.getStartAmount() - crop.getAmount();
  289. count = (count * 90) / 100;
  290. if (count < 1)
  291. {
  292. if (Rnd.nextInt(99) < 90)
  293. {
  294. count = 1;
  295. }
  296. }
  297. if (count > 0)
  298. {
  299. cwh.addItem("Manor", ManorData.getInstance().getMatureCrop(crop.getId()), count, null, null);
  300. }
  301. }
  302. // reserved and not used money giving back to treasury
  303. if (crop.getAmount() > 0)
  304. {
  305. c.addToTreasuryNoTax(crop.getAmount() * crop.getPrice());
  306. }
  307. }
  308. c.setSeedProduction(c.getSeedProduction(PERIOD_NEXT), PERIOD_CURRENT);
  309. c.setCropProcure(c.getCropProcure(PERIOD_NEXT), PERIOD_CURRENT);
  310. if (c.getTreasury() < c.getManorCost(PERIOD_CURRENT))
  311. {
  312. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  313. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  314. }
  315. else
  316. {
  317. FastList<SeedProduction> production = new FastList<>();
  318. for (SeedProduction s : c.getSeedProduction(PERIOD_CURRENT))
  319. {
  320. s.setCanProduce(s.getStartProduce());
  321. production.add(s);
  322. }
  323. c.setSeedProduction(production, PERIOD_NEXT);
  324. FastList<CropProcure> procure = new FastList<>();
  325. for (CropProcure cr : c.getCropProcure(PERIOD_CURRENT))
  326. {
  327. cr.setAmount(cr.getStartAmount());
  328. procure.add(cr);
  329. }
  330. c.setCropProcure(procure, PERIOD_NEXT);
  331. }
  332. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  333. {
  334. c.saveCropData();
  335. c.saveSeedData();
  336. }
  337. // Sending notification to a clan leader
  338. L2PcInstance clanLeader = null;
  339. clanLeader = L2World.getInstance().getPlayer(clan.getLeader().getName());
  340. if (clanLeader != null)
  341. {
  342. clanLeader.sendPacket(SystemMessageId.THE_MANOR_INFORMATION_HAS_BEEN_UPDATED);
  343. }
  344. c.setNextPeriodApproved(false);
  345. }
  346. }
  347. public void approveNextPeriod()
  348. {
  349. for (Castle c : CastleManager.getInstance().getCastles())
  350. {
  351. boolean notFunc = false;
  352. if (c.getOwnerId() <= 0)
  353. { // Castle has no owner
  354. c.setCropProcure(new FastList<CropProcure>(), PERIOD_NEXT);
  355. c.setSeedProduction(new FastList<SeedProduction>(), PERIOD_NEXT);
  356. }
  357. else if (c.getTreasury() < c.getManorCost(PERIOD_NEXT))
  358. {
  359. notFunc = true;
  360. _log.info("Manor for castle " + c.getName() + " disabled, not enough adena in treasury: " + c.getTreasury() + ", " + c.getManorCost(PERIOD_NEXT) + " required.");
  361. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  362. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  363. }
  364. else
  365. {
  366. ItemContainer cwh = ClanTable.getInstance().getClan(c.getOwnerId()).getWarehouse();
  367. if (!(cwh instanceof ClanWarehouse))
  368. {
  369. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  370. continue;
  371. }
  372. int slots = 0;
  373. for (CropProcure crop : c.getCropProcure(PERIOD_NEXT))
  374. {
  375. if (crop.getStartAmount() > 0)
  376. {
  377. if (cwh.getItemByItemId(ManorData.getInstance().getMatureCrop(crop.getId())) == null)
  378. {
  379. slots++;
  380. }
  381. }
  382. }
  383. if (!cwh.validateCapacity(slots))
  384. {
  385. notFunc = true;
  386. _log.info("Manor for castle " + c.getName() + " disabled, not enough free slots in clan warehouse: " + (Config.WAREHOUSE_SLOTS_CLAN - cwh.getSize()) + ", but " + slots + " required.");
  387. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  388. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  389. }
  390. }
  391. c.setNextPeriodApproved(true);
  392. c.addToTreasuryNoTax((-1) * c.getManorCost(PERIOD_NEXT));
  393. if (notFunc)
  394. {
  395. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  396. L2PcInstance clanLeader = null;
  397. if (clan != null)
  398. {
  399. clanLeader = L2World.getInstance().getPlayer(clan.getLeaderId());
  400. }
  401. if (clanLeader != null)
  402. {
  403. clanLeader.sendPacket(SystemMessageId.THE_AMOUNT_IS_NOT_SUFFICIENT_AND_SO_THE_MANOR_IS_NOT_IN_OPERATION);
  404. }
  405. }
  406. }
  407. }
  408. private List<SeedProduction> getNewSeedsList(int castleId)
  409. {
  410. List<SeedProduction> seeds = new ArrayList<>();
  411. List<Integer> seedsIds = ManorData.getInstance().getSeedsForCastle(castleId);
  412. for (int sd : seedsIds)
  413. {
  414. seeds.add(new SeedProduction(sd));
  415. }
  416. return seeds;
  417. }
  418. private List<CropProcure> getNewCropsList(int castleId)
  419. {
  420. List<CropProcure> crops = new ArrayList<>();
  421. List<Integer> cropsIds = ManorData.getInstance().getCropsForCastle(castleId);
  422. for (int cr : cropsIds)
  423. {
  424. crops.add(new CropProcure(cr));
  425. }
  426. return crops;
  427. }
  428. public boolean isUnderMaintenance()
  429. {
  430. return _underMaintenance;
  431. }
  432. public void setUnderMaintenance(boolean mode)
  433. {
  434. _underMaintenance = mode;
  435. }
  436. public boolean isDisabled()
  437. {
  438. return _disabled;
  439. }
  440. public void setDisabled(boolean mode)
  441. {
  442. _disabled = mode;
  443. }
  444. public SeedProduction getNewSeedProduction(int id, long amount, long price, long sales)
  445. {
  446. return new SeedProduction(id, amount, price, sales);
  447. }
  448. public CropProcure getNewCropProcure(int id, long amount, int type, long price, long buy)
  449. {
  450. return new CropProcure(id, amount, type, buy, price);
  451. }
  452. public void save()
  453. {
  454. for (Castle c : CastleManager.getInstance().getCastles())
  455. {
  456. c.saveSeedData();
  457. c.saveCropData();
  458. }
  459. }
  460. public static final CastleManorManager getInstance()
  461. {
  462. return SingletonHolder._instance;
  463. }
  464. private static class SingletonHolder
  465. {
  466. protected static final CastleManorManager _instance = new CastleManorManager();
  467. }
  468. }