Castle.java 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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.gameserver.model.entity;
  16. import java.sql.Connection;
  17. import java.sql.PreparedStatement;
  18. import java.sql.ResultSet;
  19. import java.sql.Statement;
  20. import java.util.ArrayList;
  21. import java.util.Calendar;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import javolution.util.FastMap;
  27. import com.l2jserver.Config;
  28. import com.l2jserver.L2DatabaseFactory;
  29. import com.l2jserver.gameserver.CastleUpdater;
  30. import com.l2jserver.gameserver.SevenSigns;
  31. import com.l2jserver.gameserver.ThreadPoolManager;
  32. import com.l2jserver.gameserver.datatables.ClanTable;
  33. import com.l2jserver.gameserver.datatables.DoorTable;
  34. import com.l2jserver.gameserver.datatables.ManorData;
  35. import com.l2jserver.gameserver.datatables.SkillTable;
  36. import com.l2jserver.gameserver.datatables.SkillTreesData;
  37. import com.l2jserver.gameserver.instancemanager.CastleManager;
  38. import com.l2jserver.gameserver.instancemanager.CastleManorManager;
  39. import com.l2jserver.gameserver.instancemanager.CastleManorManager.CropProcure;
  40. import com.l2jserver.gameserver.instancemanager.CastleManorManager.SeedProduction;
  41. import com.l2jserver.gameserver.instancemanager.FortManager;
  42. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager;
  43. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager.Territory;
  44. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  45. import com.l2jserver.gameserver.model.L2Clan;
  46. import com.l2jserver.gameserver.model.L2Object;
  47. import com.l2jserver.gameserver.model.L2SkillLearn;
  48. import com.l2jserver.gameserver.model.actor.instance.L2ArtefactInstance;
  49. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  50. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  51. import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
  52. import com.l2jserver.gameserver.model.skills.L2Skill;
  53. import com.l2jserver.gameserver.model.zone.type.L2CastleZone;
  54. import com.l2jserver.gameserver.model.zone.type.L2ResidenceTeleportZone;
  55. import com.l2jserver.gameserver.model.zone.type.L2SiegeZone;
  56. import com.l2jserver.gameserver.network.serverpackets.PlaySound;
  57. import com.l2jserver.gameserver.network.serverpackets.PledgeShowInfoUpdate;
  58. import gnu.trove.map.hash.TIntIntHashMap;
  59. public class Castle
  60. {
  61. protected static final Logger _log = Logger.getLogger(Castle.class.getName());
  62. private List<CropProcure> _procure = new ArrayList<>();
  63. private List<SeedProduction> _production = new ArrayList<>();
  64. private List<CropProcure> _procureNext = new ArrayList<>();
  65. private List<SeedProduction> _productionNext = new ArrayList<>();
  66. private boolean _isNextPeriodApproved = false;
  67. private static final String CASTLE_MANOR_DELETE_PRODUCTION = "DELETE FROM castle_manor_production WHERE castle_id=?;";
  68. private static final String CASTLE_MANOR_DELETE_PRODUCTION_PERIOD = "DELETE FROM castle_manor_production WHERE castle_id=? AND period=?;";
  69. private static final String CASTLE_MANOR_DELETE_PROCURE = "DELETE FROM castle_manor_procure WHERE castle_id=?;";
  70. private static final String CASTLE_MANOR_DELETE_PROCURE_PERIOD = "DELETE FROM castle_manor_procure WHERE castle_id=? AND period=?;";
  71. private static final String CASTLE_UPDATE_CROP = "UPDATE castle_manor_procure SET can_buy=? WHERE crop_id=? AND castle_id=? AND period=?";
  72. private static final String CASTLE_UPDATE_SEED = "UPDATE castle_manor_production SET can_produce=? WHERE seed_id=? AND castle_id=? AND period=?";
  73. private int _castleId = 0;
  74. private final List<L2DoorInstance> _doors = new ArrayList<>();
  75. private String _name = "";
  76. private int _ownerId = 0;
  77. private Siege _siege = null;
  78. private Calendar _siegeDate;
  79. private boolean _isTimeRegistrationOver = true; // true if Castle Lords set the time, or 24h is elapsed after the siege
  80. private Calendar _siegeTimeRegistrationEndDate; // last siege end date + 1 day
  81. private int _taxPercent = 0;
  82. private double _taxRate = 0;
  83. private long _treasury = 0;
  84. private boolean _showNpcCrest = false;
  85. private L2SiegeZone _zone = null;
  86. private L2CastleZone _castleZone = null;
  87. private L2ResidenceTeleportZone _teleZone;
  88. private L2Clan _formerOwner = null;
  89. private final List<L2ArtefactInstance> _artefacts = new ArrayList<>(1);
  90. private final TIntIntHashMap _engrave = new TIntIntHashMap(1);
  91. private final Map<Integer, CastleFunction> _function;
  92. private final List<L2Skill> _residentialSkills = new ArrayList<>();
  93. private int _bloodAlliance = 0;
  94. /** Castle Functions */
  95. public static final int FUNC_TELEPORT = 1;
  96. public static final int FUNC_RESTORE_HP = 2;
  97. public static final int FUNC_RESTORE_MP = 3;
  98. public static final int FUNC_RESTORE_EXP = 4;
  99. public static final int FUNC_SUPPORT = 5;
  100. public class CastleFunction
  101. {
  102. private final int _type;
  103. private int _lvl;
  104. protected int _fee;
  105. protected int _tempFee;
  106. private final long _rate;
  107. private long _endDate;
  108. protected boolean _inDebt;
  109. public boolean _cwh;
  110. public CastleFunction(int type, int lvl, int lease, int tempLease, long rate, long time, boolean cwh)
  111. {
  112. _type = type;
  113. _lvl = lvl;
  114. _fee = lease;
  115. _tempFee = tempLease;
  116. _rate = rate;
  117. _endDate = time;
  118. initializeTask(cwh);
  119. }
  120. public int getType()
  121. {
  122. return _type;
  123. }
  124. public int getLvl()
  125. {
  126. return _lvl;
  127. }
  128. public int getLease()
  129. {
  130. return _fee;
  131. }
  132. public long getRate()
  133. {
  134. return _rate;
  135. }
  136. public long getEndTime()
  137. {
  138. return _endDate;
  139. }
  140. public void setLvl(int lvl)
  141. {
  142. _lvl = lvl;
  143. }
  144. public void setLease(int lease)
  145. {
  146. _fee = lease;
  147. }
  148. public void setEndTime(long time)
  149. {
  150. _endDate = time;
  151. }
  152. private void initializeTask(boolean cwh)
  153. {
  154. if (getOwnerId() <= 0)
  155. {
  156. return;
  157. }
  158. long currentTime = System.currentTimeMillis();
  159. if (_endDate > currentTime)
  160. {
  161. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
  162. }
  163. else
  164. {
  165. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
  166. }
  167. }
  168. private class FunctionTask implements Runnable
  169. {
  170. public FunctionTask(boolean cwh)
  171. {
  172. _cwh = cwh;
  173. }
  174. @Override
  175. public void run()
  176. {
  177. try
  178. {
  179. if (getOwnerId() <= 0)
  180. {
  181. return;
  182. }
  183. if ((ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().getAdena() >= _fee) || !_cwh)
  184. {
  185. int fee = _fee;
  186. if (getEndTime() == -1)
  187. {
  188. fee = _tempFee;
  189. }
  190. setEndTime(System.currentTimeMillis() + getRate());
  191. dbSave();
  192. if (_cwh)
  193. {
  194. ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CS_function_fee", PcInventory.ADENA_ID, fee, null, null);
  195. }
  196. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
  197. }
  198. else
  199. {
  200. removeFunction(getType());
  201. }
  202. }
  203. catch (Exception e)
  204. {
  205. _log.log(Level.SEVERE, "", e);
  206. }
  207. }
  208. }
  209. public void dbSave()
  210. {
  211. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  212. PreparedStatement ps = con.prepareStatement("REPLACE INTO castle_functions (castle_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)"))
  213. {
  214. ps.setInt(1, getCastleId());
  215. ps.setInt(2, getType());
  216. ps.setInt(3, getLvl());
  217. ps.setInt(4, getLease());
  218. ps.setLong(5, getRate());
  219. ps.setLong(6, getEndTime());
  220. ps.execute();
  221. }
  222. catch (Exception e)
  223. {
  224. _log.log(Level.SEVERE, "Exception: Castle.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): " + e.getMessage(), e);
  225. }
  226. }
  227. }
  228. public Castle(int castleId)
  229. {
  230. _castleId = castleId;
  231. /*
  232. * if (_castleId == 7 || castleId == 9) // Goddard and Schuttgart _nbArtifact = 2;
  233. */
  234. load();
  235. _function = new FastMap<>();
  236. final List<L2SkillLearn> residentialSkills = SkillTreesData.getInstance().getAvailableResidentialSkills(castleId);
  237. for (L2SkillLearn s : residentialSkills)
  238. {
  239. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  240. if (sk != null)
  241. {
  242. _residentialSkills.add(sk);
  243. }
  244. else
  245. {
  246. _log.warning("Castle Id: " + castleId + " has a null residential skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  247. }
  248. }
  249. if (getOwnerId() != 0)
  250. {
  251. loadFunctions();
  252. }
  253. }
  254. /**
  255. * Return function with id
  256. * @param type
  257. * @return
  258. */
  259. public CastleFunction getFunction(int type)
  260. {
  261. if (_function.containsKey(type))
  262. {
  263. return _function.get(type);
  264. }
  265. return null;
  266. }
  267. public synchronized void engrave(L2Clan clan, L2Object target)
  268. {
  269. if (!_artefacts.contains(target))
  270. {
  271. return;
  272. }
  273. _engrave.put(target.getObjectId(), clan.getClanId());
  274. if (_engrave.size() == _artefacts.size())
  275. {
  276. for (L2ArtefactInstance art : _artefacts)
  277. {
  278. if (_engrave.get(art.getObjectId()) != clan.getClanId())
  279. {
  280. return;
  281. }
  282. }
  283. _engrave.clear();
  284. setOwner(clan);
  285. }
  286. }
  287. // This method add to the treasury
  288. /**
  289. * Add amount to castle instance's treasury (warehouse).
  290. * @param amount
  291. */
  292. public void addToTreasury(long amount)
  293. {
  294. // check if owned
  295. if (getOwnerId() <= 0)
  296. {
  297. return;
  298. }
  299. if (_name.equalsIgnoreCase("Schuttgart") || _name.equalsIgnoreCase("Goddard"))
  300. {
  301. Castle rune = CastleManager.getInstance().getCastle("rune");
  302. if (rune != null)
  303. {
  304. long runeTax = (long) (amount * rune.getTaxRate());
  305. if (rune.getOwnerId() > 0)
  306. {
  307. rune.addToTreasury(runeTax);
  308. }
  309. amount -= runeTax;
  310. }
  311. }
  312. if (!_name.equalsIgnoreCase("aden") && !_name.equalsIgnoreCase("Rune") && !_name.equalsIgnoreCase("Schuttgart") && !_name.equalsIgnoreCase("Goddard")) // If current castle instance is not Aden, Rune, Goddard or Schuttgart.
  313. {
  314. Castle aden = CastleManager.getInstance().getCastle("aden");
  315. if (aden != null)
  316. {
  317. long adenTax = (long) (amount * aden.getTaxRate()); // Find out what Aden gets from the current castle instance's income
  318. if (aden.getOwnerId() > 0)
  319. {
  320. aden.addToTreasury(adenTax); // Only bother to really add the tax to the treasury if not npc owned
  321. }
  322. amount -= adenTax; // Subtract Aden's income from current castle instance's income
  323. }
  324. }
  325. addToTreasuryNoTax(amount);
  326. }
  327. /**
  328. * Add amount to castle instance's treasury (warehouse), no tax paying.
  329. * @param amount
  330. * @return
  331. */
  332. public boolean addToTreasuryNoTax(long amount)
  333. {
  334. if (getOwnerId() <= 0)
  335. {
  336. return false;
  337. }
  338. if (amount < 0)
  339. {
  340. amount *= -1;
  341. if (_treasury < amount)
  342. {
  343. return false;
  344. }
  345. _treasury -= amount;
  346. }
  347. else
  348. {
  349. if ((_treasury + amount) > PcInventory.MAX_ADENA)
  350. {
  351. _treasury = PcInventory.MAX_ADENA;
  352. }
  353. else
  354. {
  355. _treasury += amount;
  356. }
  357. }
  358. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  359. PreparedStatement ps = con.prepareStatement("UPDATE castle SET treasury = ? WHERE id = ?"))
  360. {
  361. ps.setLong(1, getTreasury());
  362. ps.setInt(2, getCastleId());
  363. ps.execute();
  364. }
  365. catch (Exception e)
  366. {
  367. _log.log(Level.WARNING, e.getMessage(), e);
  368. }
  369. return true;
  370. }
  371. /**
  372. * Move non clan members off castle area and to nearest town.
  373. */
  374. public void banishForeigners()
  375. {
  376. getCastleZone().banishForeigners(getOwnerId());
  377. }
  378. /**
  379. * Return true if object is inside the zone
  380. * @param x
  381. * @param y
  382. * @param z
  383. * @return
  384. */
  385. public boolean checkIfInZone(int x, int y, int z)
  386. {
  387. return getZone().isInsideZone(x, y, z);
  388. }
  389. public L2SiegeZone getZone()
  390. {
  391. if (_zone == null)
  392. {
  393. for (L2SiegeZone zone : ZoneManager.getInstance().getAllZones(L2SiegeZone.class))
  394. {
  395. if (zone.getSiegeObjectId() == getCastleId())
  396. {
  397. _zone = zone;
  398. break;
  399. }
  400. }
  401. }
  402. return _zone;
  403. }
  404. public L2CastleZone getCastleZone()
  405. {
  406. if (_castleZone == null)
  407. {
  408. for (L2CastleZone zone : ZoneManager.getInstance().getAllZones(L2CastleZone.class))
  409. {
  410. if (zone.getCastleId() == getCastleId())
  411. {
  412. _castleZone = zone;
  413. break;
  414. }
  415. }
  416. }
  417. return _castleZone;
  418. }
  419. public L2ResidenceTeleportZone getTeleZone()
  420. {
  421. if (_teleZone == null)
  422. {
  423. for (L2ResidenceTeleportZone zone : ZoneManager.getInstance().getAllZones(L2ResidenceTeleportZone.class))
  424. {
  425. if (zone.getResidenceId() == getCastleId())
  426. {
  427. _teleZone = zone;
  428. break;
  429. }
  430. }
  431. }
  432. return _teleZone;
  433. }
  434. public void oustAllPlayers()
  435. {
  436. getTeleZone().oustAllPlayers();
  437. }
  438. /**
  439. * Get the objects distance to this castle
  440. * @param obj
  441. * @return
  442. */
  443. public double getDistance(L2Object obj)
  444. {
  445. return getZone().getDistanceToZone(obj);
  446. }
  447. public void closeDoor(L2PcInstance activeChar, int doorId)
  448. {
  449. openCloseDoor(activeChar, doorId, false);
  450. }
  451. public void openDoor(L2PcInstance activeChar, int doorId)
  452. {
  453. openCloseDoor(activeChar, doorId, true);
  454. }
  455. public void openCloseDoor(L2PcInstance activeChar, int doorId, boolean open)
  456. {
  457. if (activeChar.getClanId() != getOwnerId())
  458. {
  459. return;
  460. }
  461. L2DoorInstance door = getDoor(doorId);
  462. if (door != null)
  463. {
  464. if (open)
  465. {
  466. door.openMe();
  467. }
  468. else
  469. {
  470. door.closeMe();
  471. }
  472. }
  473. }
  474. // This method is used to begin removing all castle upgrades
  475. public void removeUpgrade()
  476. {
  477. removeDoorUpgrade();
  478. for (Integer fc : _function.keySet())
  479. {
  480. removeFunction(fc);
  481. }
  482. _function.clear();
  483. }
  484. // This method updates the castle tax rate
  485. public void setOwner(L2Clan clan)
  486. {
  487. // Remove old owner
  488. if ((getOwnerId() > 0) && ((clan == null) || (clan.getClanId() != getOwnerId())))
  489. {
  490. L2Clan oldOwner = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  491. if (oldOwner != null)
  492. {
  493. if (_formerOwner == null)
  494. {
  495. _formerOwner = oldOwner;
  496. if (Config.REMOVE_CASTLE_CIRCLETS)
  497. {
  498. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  499. }
  500. }
  501. try
  502. {
  503. L2PcInstance oldleader = oldOwner.getLeader().getPlayerInstance();
  504. if (oldleader != null)
  505. {
  506. if (oldleader.getMountType() == 2)
  507. {
  508. oldleader.dismount();
  509. }
  510. }
  511. }
  512. catch (Exception e)
  513. {
  514. _log.log(Level.WARNING, "Exception in setOwner: " + e.getMessage(), e);
  515. }
  516. oldOwner.setCastleId(0); // Unset has castle flag for old owner
  517. for (L2PcInstance member : oldOwner.getOnlineMembers(0))
  518. {
  519. removeResidentialSkills(member);
  520. member.sendSkillList();
  521. }
  522. }
  523. }
  524. updateOwnerInDB(clan); // Update in database
  525. setShowNpcCrest(false);
  526. // if clan have fortress, remove it
  527. if ((clan != null) && (clan.getFortId() > 0))
  528. {
  529. FortManager.getInstance().getFortByOwner(clan).removeOwner(true);
  530. }
  531. if (getSiege().getIsInProgress())
  532. {
  533. getSiege().midVictory(); // Mid victory phase of siege
  534. }
  535. TerritoryWarManager.getInstance().getTerritory(_castleId).setOwnerClan(clan);
  536. if (clan != null)
  537. {
  538. for (L2PcInstance member : clan.getOnlineMembers(0))
  539. {
  540. giveResidentialSkills(member);
  541. member.sendSkillList();
  542. }
  543. }
  544. }
  545. public void removeOwner(L2Clan clan)
  546. {
  547. if (clan != null)
  548. {
  549. _formerOwner = clan;
  550. if (Config.REMOVE_CASTLE_CIRCLETS)
  551. {
  552. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  553. }
  554. for (L2PcInstance member : clan.getOnlineMembers(0))
  555. {
  556. removeResidentialSkills(member);
  557. member.sendSkillList();
  558. }
  559. clan.setCastleId(0);
  560. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  561. }
  562. updateOwnerInDB(null);
  563. if (getSiege().getIsInProgress())
  564. {
  565. getSiege().midVictory();
  566. }
  567. for (Integer fc : _function.keySet())
  568. {
  569. removeFunction(fc);
  570. }
  571. _function.clear();
  572. }
  573. // This method updates the castle tax rate
  574. public void setTaxPercent(L2PcInstance activeChar, int taxPercent)
  575. {
  576. int maxTax;
  577. switch (SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE))
  578. {
  579. case SevenSigns.CABAL_DAWN:
  580. maxTax = 25;
  581. break;
  582. case SevenSigns.CABAL_DUSK:
  583. maxTax = 5;
  584. break;
  585. default: // no owner
  586. maxTax = 15;
  587. }
  588. if ((taxPercent < 0) || (taxPercent > maxTax))
  589. {
  590. activeChar.sendMessage("Tax value must be between 0 and " + maxTax + ".");
  591. return;
  592. }
  593. setTaxPercent(taxPercent);
  594. activeChar.sendMessage(getName() + " castle tax changed to " + taxPercent + "%.");
  595. }
  596. public void setTaxPercent(int taxPercent)
  597. {
  598. _taxPercent = taxPercent;
  599. _taxRate = _taxPercent / 100.0;
  600. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  601. PreparedStatement ps = con.prepareStatement("UPDATE castle SET taxPercent = ? WHERE id = ?"))
  602. {
  603. ps.setInt(1, taxPercent);
  604. ps.setInt(2, getCastleId());
  605. ps.execute();
  606. }
  607. catch (Exception e)
  608. {
  609. _log.log(Level.WARNING, e.getMessage(), e);
  610. }
  611. }
  612. /**
  613. * Respawn all doors on castle grounds.
  614. */
  615. public void spawnDoor()
  616. {
  617. spawnDoor(false);
  618. }
  619. /**
  620. * Respawn all doors on castle grounds<BR>
  621. * <BR>
  622. * @param isDoorWeak
  623. */
  624. public void spawnDoor(boolean isDoorWeak)
  625. {
  626. for (L2DoorInstance door : _doors)
  627. {
  628. if (door.isDead())
  629. {
  630. door.doRevive();
  631. if (isDoorWeak)
  632. {
  633. door.setCurrentHp(door.getMaxHp() / 2);
  634. }
  635. else
  636. {
  637. door.setCurrentHp(door.getMaxHp());
  638. }
  639. }
  640. if (door.getOpen())
  641. {
  642. door.closeMe();
  643. }
  644. }
  645. loadDoorUpgrade(); // Check for any upgrade the doors may have
  646. }
  647. // This method upgrade door
  648. public void upgradeDoor(int doorId, int hp, int pDef, int mDef)
  649. {
  650. L2DoorInstance door = getDoor(doorId);
  651. if (door == null)
  652. {
  653. return;
  654. }
  655. door.setCurrentHp(door.getMaxHp() + hp);
  656. saveDoorUpgrade(doorId, hp, pDef, mDef);
  657. }
  658. // This method loads castle
  659. private void load()
  660. {
  661. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  662. PreparedStatement ps1 = con.prepareStatement("SELECT * FROM castle WHERE id = ?");
  663. PreparedStatement ps2 = con.prepareStatement("SELECT clan_id FROM clan_data WHERE hasCastle = ?"))
  664. {
  665. ps1.setInt(1, getCastleId());
  666. try (ResultSet rs = ps1.executeQuery())
  667. {
  668. while (rs.next())
  669. {
  670. _name = rs.getString("name");
  671. // _OwnerId = rs.getInt("ownerId");
  672. _siegeDate = Calendar.getInstance();
  673. _siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
  674. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  675. _siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
  676. _isTimeRegistrationOver = rs.getBoolean("regTimeOver");
  677. _taxPercent = rs.getInt("taxPercent");
  678. _treasury = rs.getLong("treasury");
  679. _showNpcCrest = rs.getBoolean("showNpcCrest");
  680. _bloodAlliance = rs.getInt("bloodAlliance");
  681. }
  682. }
  683. _taxRate = _taxPercent / 100.0;
  684. ps2.setInt(1, getCastleId());
  685. try (ResultSet rs = ps2.executeQuery())
  686. {
  687. while (rs.next())
  688. {
  689. _ownerId = rs.getInt("clan_id");
  690. }
  691. }
  692. if (getOwnerId() > 0)
  693. {
  694. L2Clan clan = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  695. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  696. }
  697. }
  698. catch (Exception e)
  699. {
  700. _log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
  701. }
  702. }
  703. /** Load All Functions */
  704. private void loadFunctions()
  705. {
  706. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  707. PreparedStatement ps = con.prepareStatement("SELECT * FROM castle_functions WHERE castle_id = ?"))
  708. {
  709. ps.setInt(1, getCastleId());
  710. try (ResultSet rs = ps.executeQuery())
  711. {
  712. while (rs.next())
  713. {
  714. _function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
  715. }
  716. }
  717. }
  718. catch (Exception e)
  719. {
  720. _log.log(Level.SEVERE, "Exception: Castle.loadFunctions(): " + e.getMessage(), e);
  721. }
  722. }
  723. /**
  724. * Remove function In List and in DB
  725. * @param functionType
  726. */
  727. public void removeFunction(int functionType)
  728. {
  729. _function.remove(functionType);
  730. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  731. PreparedStatement ps = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?"))
  732. {
  733. ps.setInt(1, getCastleId());
  734. ps.setInt(2, functionType);
  735. ps.execute();
  736. }
  737. catch (Exception e)
  738. {
  739. _log.log(Level.SEVERE, "Exception: Castle.removeFunctions(int functionType): " + e.getMessage(), e);
  740. }
  741. }
  742. public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
  743. {
  744. if (player == null)
  745. {
  746. return false;
  747. }
  748. if (lease > 0)
  749. {
  750. if (!player.destroyItemByItemId("Consume", PcInventory.ADENA_ID, lease, null, true))
  751. {
  752. return false;
  753. }
  754. }
  755. if (addNew)
  756. {
  757. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, 0, false));
  758. }
  759. else
  760. {
  761. if ((lvl == 0) && (lease == 0))
  762. {
  763. removeFunction(type);
  764. }
  765. else
  766. {
  767. int diffLease = lease - _function.get(type).getLease();
  768. if (diffLease > 0)
  769. {
  770. _function.remove(type);
  771. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, -1, false));
  772. }
  773. else
  774. {
  775. _function.get(type).setLease(lease);
  776. _function.get(type).setLvl(lvl);
  777. _function.get(type).dbSave();
  778. }
  779. }
  780. }
  781. return true;
  782. }
  783. public void activateInstance()
  784. {
  785. loadDoor();
  786. }
  787. // This method loads castle door data from database
  788. private void loadDoor()
  789. {
  790. for (L2DoorInstance door : DoorTable.getInstance().getDoors())
  791. {
  792. if ((door.getCastle() != null) && (door.getCastle().getCastleId() == getCastleId()))
  793. {
  794. _doors.add(door);
  795. }
  796. }
  797. }
  798. // This method loads castle door upgrade data from database
  799. private void loadDoorUpgrade()
  800. {
  801. StringBuilder doorIds = new StringBuilder(100);
  802. for (L2DoorInstance door : getDoors())
  803. {
  804. doorIds.append(door.getDoorId()).append(',');
  805. }
  806. doorIds.deleteCharAt(doorIds.length() - 1);
  807. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  808. Statement s = con.createStatement();
  809. ResultSet rs = s.executeQuery("SELECT * FROM castle_doorupgrade WHERE doorId IN (" + doorIds.toString() + ")"))
  810. {
  811. while (rs.next())
  812. {
  813. upgradeDoor(rs.getInt("id"), rs.getInt("hp"), rs.getInt("pDef"), rs.getInt("mDef"));
  814. }
  815. }
  816. catch (Exception e)
  817. {
  818. _log.log(Level.WARNING, "Exception: loadCastleDoorUpgrade(): " + e.getMessage(), e);
  819. }
  820. }
  821. private void removeDoorUpgrade()
  822. {
  823. StringBuilder doorIds = new StringBuilder(100);
  824. for (L2DoorInstance door : getDoors())
  825. {
  826. doorIds.append(door.getDoorId()).append(',');
  827. }
  828. doorIds.deleteCharAt(doorIds.length() - 1);
  829. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  830. Statement s = con.createStatement())
  831. {
  832. s.executeQuery("DELETE FROM castle_doorupgrade WHERE doorId IN (" + doorIds.toString() + ")");
  833. }
  834. catch (Exception e)
  835. {
  836. _log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
  837. }
  838. }
  839. private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
  840. {
  841. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  842. PreparedStatement ps = con.prepareStatement("INSERT INTO castle_doorupgrade (doorId, hp, pDef, mDef) values (?,?,?,?)"))
  843. {
  844. ps.setInt(1, doorId);
  845. ps.setInt(2, hp);
  846. ps.setInt(3, pDef);
  847. ps.setInt(4, mDef);
  848. ps.execute();
  849. }
  850. catch (Exception e)
  851. {
  852. _log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
  853. }
  854. }
  855. private void updateOwnerInDB(L2Clan clan)
  856. {
  857. if (clan != null)
  858. {
  859. _ownerId = clan.getClanId(); // Update owner id property
  860. }
  861. else
  862. {
  863. _ownerId = 0; // Remove owner
  864. resetManor();
  865. }
  866. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  867. {
  868. // NEED TO REMOVE HAS CASTLE FLAG FROM CLAN_DATA
  869. // SHOULD BE CHECKED FROM CASTLE TABLE
  870. PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET hasCastle = 0 WHERE hasCastle = ?");
  871. statement.setInt(1, getCastleId());
  872. statement.execute();
  873. statement.close();
  874. statement = con.prepareStatement("UPDATE clan_data SET hasCastle = ? WHERE clan_id = ?");
  875. statement.setInt(1, getCastleId());
  876. statement.setInt(2, getOwnerId());
  877. statement.execute();
  878. statement.close();
  879. // Announce to clan members
  880. if (clan != null)
  881. {
  882. clan.setCastleId(getCastleId()); // Set has castle flag for new owner
  883. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  884. clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
  885. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  886. }
  887. }
  888. catch (Exception e)
  889. {
  890. _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
  891. }
  892. }
  893. public final int getCastleId()
  894. {
  895. return _castleId;
  896. }
  897. public final L2DoorInstance getDoor(int doorId)
  898. {
  899. if (doorId <= 0)
  900. {
  901. return null;
  902. }
  903. for (L2DoorInstance door : getDoors())
  904. {
  905. if (door.getDoorId() == doorId)
  906. {
  907. return door;
  908. }
  909. }
  910. return null;
  911. }
  912. public final List<L2DoorInstance> getDoors()
  913. {
  914. return _doors;
  915. }
  916. public final String getName()
  917. {
  918. return _name;
  919. }
  920. public final int getOwnerId()
  921. {
  922. return _ownerId;
  923. }
  924. public final Siege getSiege()
  925. {
  926. if (_siege == null)
  927. {
  928. _siege = new Siege(new Castle[]
  929. {
  930. this
  931. });
  932. }
  933. return _siege;
  934. }
  935. public final Calendar getSiegeDate()
  936. {
  937. return _siegeDate;
  938. }
  939. public boolean getIsTimeRegistrationOver()
  940. {
  941. return _isTimeRegistrationOver;
  942. }
  943. public void setIsTimeRegistrationOver(boolean val)
  944. {
  945. _isTimeRegistrationOver = val;
  946. }
  947. public Calendar getTimeRegistrationOverDate()
  948. {
  949. if (_siegeTimeRegistrationEndDate == null)
  950. {
  951. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  952. }
  953. return _siegeTimeRegistrationEndDate;
  954. }
  955. public final int getTaxPercent()
  956. {
  957. return _taxPercent;
  958. }
  959. public final double getTaxRate()
  960. {
  961. return _taxRate;
  962. }
  963. public final long getTreasury()
  964. {
  965. return _treasury;
  966. }
  967. public final boolean getShowNpcCrest()
  968. {
  969. return _showNpcCrest;
  970. }
  971. public final void setShowNpcCrest(boolean showNpcCrest)
  972. {
  973. if (_showNpcCrest != showNpcCrest)
  974. {
  975. _showNpcCrest = showNpcCrest;
  976. updateShowNpcCrest();
  977. }
  978. }
  979. public List<SeedProduction> getSeedProduction(int period)
  980. {
  981. return (period == CastleManorManager.PERIOD_CURRENT ? _production : _productionNext);
  982. }
  983. public List<CropProcure> getCropProcure(int period)
  984. {
  985. return (period == CastleManorManager.PERIOD_CURRENT ? _procure : _procureNext);
  986. }
  987. public void setSeedProduction(List<SeedProduction> seed, int period)
  988. {
  989. if (period == CastleManorManager.PERIOD_CURRENT)
  990. {
  991. _production = seed;
  992. }
  993. else
  994. {
  995. _productionNext = seed;
  996. }
  997. }
  998. public void setCropProcure(List<CropProcure> crop, int period)
  999. {
  1000. if (period == CastleManorManager.PERIOD_CURRENT)
  1001. {
  1002. _procure = crop;
  1003. }
  1004. else
  1005. {
  1006. _procureNext = crop;
  1007. }
  1008. }
  1009. public SeedProduction getSeed(int seedId, int period)
  1010. {
  1011. for (SeedProduction seed : getSeedProduction(period))
  1012. {
  1013. if (seed.getId() == seedId)
  1014. {
  1015. return seed;
  1016. }
  1017. }
  1018. return null;
  1019. }
  1020. public CropProcure getCrop(int cropId, int period)
  1021. {
  1022. for (CropProcure crop : getCropProcure(period))
  1023. {
  1024. if (crop.getId() == cropId)
  1025. {
  1026. return crop;
  1027. }
  1028. }
  1029. return null;
  1030. }
  1031. public long getManorCost(int period)
  1032. {
  1033. List<CropProcure> procure;
  1034. List<SeedProduction> production;
  1035. if (period == CastleManorManager.PERIOD_CURRENT)
  1036. {
  1037. procure = _procure;
  1038. production = _production;
  1039. }
  1040. else
  1041. {
  1042. procure = _procureNext;
  1043. production = _productionNext;
  1044. }
  1045. long total = 0;
  1046. if (production != null)
  1047. {
  1048. for (SeedProduction seed : production)
  1049. {
  1050. total += ManorData.getInstance().getSeedBuyPrice(seed.getId()) * seed.getStartProduce();
  1051. }
  1052. }
  1053. if (procure != null)
  1054. {
  1055. for (CropProcure crop : procure)
  1056. {
  1057. total += crop.getPrice() * crop.getStartAmount();
  1058. }
  1059. }
  1060. return total;
  1061. }
  1062. // save manor production data
  1063. public void saveSeedData()
  1064. {
  1065. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1066. {
  1067. try (PreparedStatement ps1 = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION))
  1068. {
  1069. ps1.setInt(1, getCastleId());
  1070. ps1.execute();
  1071. }
  1072. if (_production != null)
  1073. {
  1074. int count = 0;
  1075. StringBuilder query = new StringBuilder();
  1076. query.append("INSERT INTO castle_manor_production VALUES ");
  1077. String values[] = new String[_production.size()];
  1078. for (SeedProduction s : _production)
  1079. {
  1080. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1081. }
  1082. if (values.length > 0)
  1083. {
  1084. query.append(values[0]);
  1085. for (int i = 1; i < values.length; i++)
  1086. {
  1087. query.append(',');
  1088. query.append(values[i]);
  1089. }
  1090. try (PreparedStatement ps2 = con.prepareStatement(query.toString()))
  1091. {
  1092. ps2.execute();
  1093. }
  1094. }
  1095. }
  1096. if (_productionNext != null)
  1097. {
  1098. int count = 0;
  1099. String query = "INSERT INTO castle_manor_production VALUES ";
  1100. String values[] = new String[_productionNext.size()];
  1101. for (SeedProduction s : _productionNext)
  1102. {
  1103. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1104. }
  1105. if (values.length > 0)
  1106. {
  1107. query += values[0];
  1108. for (int i = 1; i < values.length; i++)
  1109. {
  1110. query += "," + values[i];
  1111. }
  1112. try (PreparedStatement ps3 = con.prepareStatement(query))
  1113. {
  1114. ps3.execute();
  1115. }
  1116. }
  1117. }
  1118. }
  1119. catch (Exception e)
  1120. {
  1121. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1122. }
  1123. }
  1124. // save manor production data for specified period
  1125. public void saveSeedData(int period)
  1126. {
  1127. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1128. {
  1129. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD);
  1130. statement.setInt(1, getCastleId());
  1131. statement.setInt(2, period);
  1132. statement.execute();
  1133. statement.close();
  1134. List<SeedProduction> prod = null;
  1135. prod = getSeedProduction(period);
  1136. if (prod != null)
  1137. {
  1138. int count = 0;
  1139. StringBuilder query = new StringBuilder();
  1140. query.append("INSERT INTO castle_manor_production VALUES ");
  1141. String values[] = new String[prod.size()];
  1142. for (SeedProduction s : prod)
  1143. {
  1144. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + period + ")";
  1145. }
  1146. if (values.length > 0)
  1147. {
  1148. query.append(values[0]);
  1149. for (int i = 1; i < values.length; i++)
  1150. {
  1151. query.append(',').append(values[i]);
  1152. }
  1153. statement = con.prepareStatement(query.toString());
  1154. statement.execute();
  1155. statement.close();
  1156. }
  1157. }
  1158. }
  1159. catch (Exception e)
  1160. {
  1161. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1162. }
  1163. }
  1164. // save crop procure data
  1165. public void saveCropData()
  1166. {
  1167. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1168. {
  1169. try (PreparedStatement ps1 = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE))
  1170. {
  1171. ps1.setInt(1, getCastleId());
  1172. ps1.execute();
  1173. }
  1174. if (!_procure.isEmpty())
  1175. {
  1176. int count = 0;
  1177. StringBuilder query = new StringBuilder();
  1178. query.append("INSERT INTO castle_manor_procure VALUES ");
  1179. String values[] = new String[_procure.size()];
  1180. for (CropProcure cp : _procure)
  1181. {
  1182. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1183. }
  1184. if (values.length > 0)
  1185. {
  1186. query.append(values[0]);
  1187. for (int i = 1; i < values.length; i++)
  1188. {
  1189. query.append(',');
  1190. query.append(values[i]);
  1191. }
  1192. try (PreparedStatement ps2 = con.prepareStatement(query.toString()))
  1193. {
  1194. ps2.execute();
  1195. }
  1196. }
  1197. }
  1198. if (!_procureNext.isEmpty())
  1199. {
  1200. int count = 0;
  1201. String query = "INSERT INTO castle_manor_procure VALUES ";
  1202. String values[] = new String[_procureNext.size()];
  1203. for (CropProcure cp : _procureNext)
  1204. {
  1205. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1206. }
  1207. if (values.length > 0)
  1208. {
  1209. query += values[0];
  1210. for (int i = 1; i < values.length; i++)
  1211. {
  1212. query += "," + values[i];
  1213. }
  1214. try (PreparedStatement ps3 = con.prepareStatement(query))
  1215. {
  1216. ps3.execute();
  1217. }
  1218. }
  1219. }
  1220. }
  1221. catch (Exception e)
  1222. {
  1223. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1224. }
  1225. }
  1226. // save crop procure data for specified period
  1227. public void saveCropData(int period)
  1228. {
  1229. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1230. {
  1231. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD);
  1232. statement.setInt(1, getCastleId());
  1233. statement.setInt(2, period);
  1234. statement.execute();
  1235. statement.close();
  1236. List<CropProcure> proc = null;
  1237. proc = getCropProcure(period);
  1238. if ((proc != null) && (proc.size() > 0))
  1239. {
  1240. int count = 0;
  1241. StringBuilder query = new StringBuilder();
  1242. query.append("INSERT INTO castle_manor_procure VALUES ");
  1243. String values[] = new String[proc.size()];
  1244. for (CropProcure cp : proc)
  1245. {
  1246. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + period + ")";
  1247. }
  1248. if (values.length > 0)
  1249. {
  1250. query.append(values[0]);
  1251. for (int i = 1; i < values.length; i++)
  1252. {
  1253. query.append(',');
  1254. query.append(values[i]);
  1255. }
  1256. statement = con.prepareStatement(query.toString());
  1257. statement.execute();
  1258. statement.close();
  1259. }
  1260. }
  1261. }
  1262. catch (Exception e)
  1263. {
  1264. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1265. }
  1266. }
  1267. public void updateCrop(int cropId, long amount, int period)
  1268. {
  1269. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1270. PreparedStatement ps = con.prepareStatement(CASTLE_UPDATE_CROP))
  1271. {
  1272. ps.setLong(1, amount);
  1273. ps.setInt(2, cropId);
  1274. ps.setInt(3, getCastleId());
  1275. ps.setInt(4, period);
  1276. ps.execute();
  1277. }
  1278. catch (Exception e)
  1279. {
  1280. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1281. }
  1282. }
  1283. public void updateSeed(int seedId, long amount, int period)
  1284. {
  1285. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1286. PreparedStatement ps = con.prepareStatement(CASTLE_UPDATE_SEED))
  1287. {
  1288. ps.setLong(1, amount);
  1289. ps.setInt(2, seedId);
  1290. ps.setInt(3, getCastleId());
  1291. ps.setInt(4, period);
  1292. ps.execute();
  1293. }
  1294. catch (Exception e)
  1295. {
  1296. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1297. }
  1298. }
  1299. public boolean isNextPeriodApproved()
  1300. {
  1301. return _isNextPeriodApproved;
  1302. }
  1303. public void setNextPeriodApproved(boolean val)
  1304. {
  1305. _isNextPeriodApproved = val;
  1306. }
  1307. public void updateClansReputation()
  1308. {
  1309. if (_formerOwner != null)
  1310. {
  1311. if (_formerOwner != ClanTable.getInstance().getClan(getOwnerId()))
  1312. {
  1313. int maxreward = Math.max(0, _formerOwner.getReputationScore());
  1314. _formerOwner.takeReputationScore(Config.LOOSE_CASTLE_POINTS, true);
  1315. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1316. if (owner != null)
  1317. {
  1318. owner.addReputationScore(Math.min(Config.TAKE_CASTLE_POINTS, maxreward), true);
  1319. }
  1320. }
  1321. else
  1322. {
  1323. _formerOwner.addReputationScore(Config.CASTLE_DEFENDED_POINTS, true);
  1324. }
  1325. }
  1326. else
  1327. {
  1328. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1329. if (owner != null)
  1330. {
  1331. owner.addReputationScore(Config.TAKE_CASTLE_POINTS, true);
  1332. }
  1333. }
  1334. }
  1335. public void updateShowNpcCrest()
  1336. {
  1337. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1338. PreparedStatement ps = con.prepareStatement("UPDATE castle SET showNpcCrest = ? WHERE id = ?"))
  1339. {
  1340. ps.setString(1, String.valueOf(getShowNpcCrest()));
  1341. ps.setInt(2, getCastleId());
  1342. ps.execute();
  1343. }
  1344. catch (Exception e)
  1345. {
  1346. _log.info("Error saving showNpcCrest for castle " + getName() + ": " + e.getMessage());
  1347. }
  1348. }
  1349. public List<L2Skill> getResidentialSkills()
  1350. {
  1351. return _residentialSkills;
  1352. }
  1353. public void giveResidentialSkills(L2PcInstance player)
  1354. {
  1355. for (L2Skill sk : _residentialSkills)
  1356. {
  1357. player.addSkill(sk, false);
  1358. }
  1359. Territory territory = TerritoryWarManager.getInstance().getTerritory(getCastleId());
  1360. if ((territory != null) && territory.getOwnedWardIds().contains(getCastleId() + 80))
  1361. {
  1362. for (int wardId : territory.getOwnedWardIds())
  1363. {
  1364. final List<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1365. for (L2SkillLearn s : territorySkills)
  1366. {
  1367. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1368. if (sk != null)
  1369. {
  1370. player.addSkill(sk, false);
  1371. }
  1372. else
  1373. {
  1374. _log.warning("Trying to add a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. public void removeResidentialSkills(L2PcInstance player)
  1381. {
  1382. for (L2Skill sk : _residentialSkills)
  1383. {
  1384. player.removeSkill(sk, false, true);
  1385. }
  1386. if (TerritoryWarManager.getInstance().getTerritory(getCastleId()) != null)
  1387. {
  1388. for (int wardId : TerritoryWarManager.getInstance().getTerritory(getCastleId()).getOwnedWardIds())
  1389. {
  1390. final List<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1391. for (L2SkillLearn s : territorySkills)
  1392. {
  1393. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1394. if (sk != null)
  1395. {
  1396. player.removeSkill(sk, false, true);
  1397. }
  1398. else
  1399. {
  1400. _log.warning("Trying to remove a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. /**
  1407. * Register Artefact to castle
  1408. * @param artefact
  1409. */
  1410. public void registerArtefact(L2ArtefactInstance artefact)
  1411. {
  1412. _artefacts.add(artefact);
  1413. }
  1414. public List<L2ArtefactInstance> getArtefacts()
  1415. {
  1416. return _artefacts;
  1417. }
  1418. public void resetManor()
  1419. {
  1420. setCropProcure(new ArrayList<CropProcure>(), CastleManorManager.PERIOD_CURRENT);
  1421. setCropProcure(new ArrayList<CropProcure>(), CastleManorManager.PERIOD_NEXT);
  1422. setSeedProduction(new ArrayList<SeedProduction>(), CastleManorManager.PERIOD_CURRENT);
  1423. setSeedProduction(new ArrayList<SeedProduction>(), CastleManorManager.PERIOD_NEXT);
  1424. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  1425. {
  1426. saveCropData();
  1427. saveSeedData();
  1428. }
  1429. }
  1430. public int getBloodAlliance()
  1431. {
  1432. return _bloodAlliance;
  1433. }
  1434. public void setBloodAlliance(int count)
  1435. {
  1436. _bloodAlliance = count;
  1437. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1438. PreparedStatement statement = con.prepareStatement("UPDATE castle SET bloodAlliance = ? WHERE id = ?"))
  1439. {
  1440. statement.setInt(1, _bloodAlliance);
  1441. statement.setInt(2, getCastleId());
  1442. statement.execute();
  1443. }
  1444. catch (Exception e)
  1445. {
  1446. _log.log(Level.WARNING, e.getMessage(), e);
  1447. }
  1448. }
  1449. @Override
  1450. public String toString()
  1451. {
  1452. return _name + "(" + _castleId + ")";
  1453. }
  1454. }