Castle.java 44 KB

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