Castle.java 45 KB

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