Castle.java 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  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 != null) && 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. if (clan != null)
  515. {
  516. for (L2PcInstance member : clan.getOnlineMembers(0))
  517. {
  518. giveResidentialSkills(member);
  519. member.sendSkillList();
  520. }
  521. }
  522. }
  523. public void removeOwner(L2Clan clan)
  524. {
  525. if (clan != null)
  526. {
  527. _formerOwner = clan;
  528. if (Config.REMOVE_CASTLE_CIRCLETS)
  529. {
  530. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  531. }
  532. for (L2PcInstance member : clan.getOnlineMembers(0))
  533. {
  534. removeResidentialSkills(member);
  535. member.sendSkillList();
  536. }
  537. clan.setCastleId(0);
  538. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  539. }
  540. updateOwnerInDB(null);
  541. if (getSiege().getIsInProgress())
  542. getSiege().midVictory();
  543. for (Integer fc : _function.keySet())
  544. {
  545. removeFunction(fc);
  546. }
  547. _function.clear();
  548. }
  549. // This method updates the castle tax rate
  550. public void setTaxPercent(L2PcInstance activeChar, int taxPercent)
  551. {
  552. int maxTax;
  553. switch (SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE))
  554. {
  555. case SevenSigns.CABAL_DAWN:
  556. maxTax = 25;
  557. break;
  558. case SevenSigns.CABAL_DUSK:
  559. maxTax = 5;
  560. break;
  561. default: // no owner
  562. maxTax = 15;
  563. }
  564. if (taxPercent < 0 || taxPercent > maxTax)
  565. {
  566. activeChar.sendMessage("Tax value must be between 0 and " + maxTax + ".");
  567. return;
  568. }
  569. setTaxPercent(taxPercent);
  570. activeChar.sendMessage(getName() + " castle tax changed to " + taxPercent + "%.");
  571. }
  572. public void setTaxPercent(int taxPercent)
  573. {
  574. _taxPercent = taxPercent;
  575. _taxRate = _taxPercent / 100.0;
  576. Connection con = null;
  577. try
  578. {
  579. con = L2DatabaseFactory.getInstance().getConnection();
  580. PreparedStatement statement = con.prepareStatement("UPDATE castle SET taxPercent = ? WHERE id = ?");
  581. statement.setInt(1, taxPercent);
  582. statement.setInt(2, getCastleId());
  583. statement.execute();
  584. statement.close();
  585. }
  586. catch (Exception e)
  587. {
  588. _log.log(Level.WARNING, e.getMessage(), e);
  589. }
  590. finally
  591. {
  592. L2DatabaseFactory.close(con);
  593. }
  594. }
  595. /**
  596. * Respawn all doors on castle grounds<BR>
  597. * <BR>
  598. */
  599. public void spawnDoor()
  600. {
  601. spawnDoor(false);
  602. }
  603. /**
  604. * Respawn all doors on castle grounds<BR>
  605. * <BR>
  606. * @param isDoorWeak
  607. */
  608. public void spawnDoor(boolean isDoorWeak)
  609. {
  610. for (int i = 0; i < getDoors().size(); i++)
  611. {
  612. L2DoorInstance door = getDoors().get(i);
  613. if (door.getCurrentHp() <= 0)
  614. {
  615. door.decayMe(); // Kill current if not killed already
  616. door = DoorTable.parseList(_doorDefault.get(i), false);
  617. DoorTable.getInstance().putDoor(door); // Readd the new door to the DoorTable By Erb
  618. if (isDoorWeak)
  619. door.setCurrentHp(door.getMaxHp() / 2);
  620. door.spawnMe(door.getX(), door.getY(), door.getZ());
  621. getDoors().set(i, door);
  622. }
  623. else if (door.getOpen())
  624. door.closeMe();
  625. }
  626. loadDoorUpgrade(); // Check for any upgrade the doors may have
  627. }
  628. // This method upgrade door
  629. public void upgradeDoor(int doorId, int hp, int pDef, int mDef)
  630. {
  631. L2DoorInstance door = getDoor(doorId);
  632. if (door == null)
  633. return;
  634. door.setCurrentHp(door.getMaxHp() + hp);
  635. saveDoorUpgrade(doorId, hp, pDef, mDef);
  636. }
  637. // This method loads castle
  638. private void load()
  639. {
  640. Connection con = null;
  641. try
  642. {
  643. con = L2DatabaseFactory.getInstance().getConnection();
  644. PreparedStatement statement = con.prepareStatement("Select * from castle where id = ?");
  645. statement.setInt(1, getCastleId());
  646. ResultSet rs = statement.executeQuery();
  647. while (rs.next())
  648. {
  649. _name = rs.getString("name");
  650. // _OwnerId = rs.getInt("ownerId");
  651. _siegeDate = Calendar.getInstance();
  652. _siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
  653. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  654. _siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
  655. _isTimeRegistrationOver = rs.getBoolean("regTimeOver");
  656. _taxPercent = rs.getInt("taxPercent");
  657. _treasury = rs.getLong("treasury");
  658. _showNpcCrest = rs.getBoolean("showNpcCrest");
  659. _bloodAlliance = rs.getInt("bloodAlliance");
  660. }
  661. rs.close();
  662. statement.close();
  663. _taxRate = _taxPercent / 100.0;
  664. statement = con.prepareStatement("Select clan_id from clan_data where hasCastle = ?");
  665. statement.setInt(1, getCastleId());
  666. rs = statement.executeQuery();
  667. while (rs.next())
  668. {
  669. _ownerId = rs.getInt("clan_id");
  670. }
  671. if (getOwnerId() > 0)
  672. {
  673. L2Clan clan = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  674. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  675. }
  676. rs.close();
  677. statement.close();
  678. }
  679. catch (Exception e)
  680. {
  681. _log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
  682. }
  683. finally
  684. {
  685. L2DatabaseFactory.close(con);
  686. }
  687. }
  688. /** Load All Functions */
  689. private void loadFunctions()
  690. {
  691. Connection con = null;
  692. try
  693. {
  694. PreparedStatement statement;
  695. ResultSet rs;
  696. con = L2DatabaseFactory.getInstance().getConnection();
  697. statement = con.prepareStatement("SELECT * FROM castle_functions WHERE castle_id = ?");
  698. statement.setInt(1, getCastleId());
  699. rs = statement.executeQuery();
  700. while (rs.next())
  701. {
  702. _function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
  703. }
  704. rs.close();
  705. statement.close();
  706. }
  707. catch (Exception e)
  708. {
  709. _log.log(Level.SEVERE, "Exception: Castle.loadFunctions(): " + e.getMessage(), e);
  710. }
  711. finally
  712. {
  713. L2DatabaseFactory.close(con);
  714. }
  715. }
  716. /**
  717. * Remove function In List and in DB
  718. * @param functionType
  719. */
  720. public void removeFunction(int functionType)
  721. {
  722. _function.remove(functionType);
  723. Connection con = null;
  724. try
  725. {
  726. con = L2DatabaseFactory.getInstance().getConnection();
  727. PreparedStatement statement = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?");
  728. statement.setInt(1, getCastleId());
  729. statement.setInt(2, functionType);
  730. statement.execute();
  731. statement.close();
  732. }
  733. catch (Exception e)
  734. {
  735. _log.log(Level.SEVERE, "Exception: Castle.removeFunctions(int functionType): " + e.getMessage(), e);
  736. }
  737. finally
  738. {
  739. L2DatabaseFactory.close(con);
  740. }
  741. }
  742. public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
  743. {
  744. if (player == null)
  745. return false;
  746. if (Config.DEBUG)
  747. _log.warning("Called Castle.updateFunctions(int type, int lvl, int lease, long rate, boolean addNew) Owner : " + getOwnerId());
  748. if (lease > 0)
  749. if (!player.destroyItemByItemId("Consume", PcInventory.ADENA_ID, lease, null, true))
  750. return false;
  751. if (addNew)
  752. {
  753. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, 0, false));
  754. }
  755. else
  756. {
  757. if (lvl == 0 && lease == 0)
  758. removeFunction(type);
  759. else
  760. {
  761. int diffLease = lease - _function.get(type).getLease();
  762. if (Config.DEBUG)
  763. _log.warning("Called Castle.updateFunctions diffLease : " + diffLease);
  764. if (diffLease > 0)
  765. {
  766. _function.remove(type);
  767. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, -1, false));
  768. }
  769. else
  770. {
  771. _function.get(type).setLease(lease);
  772. _function.get(type).setLvl(lvl);
  773. _function.get(type).dbSave();
  774. }
  775. }
  776. }
  777. return true;
  778. }
  779. public void activateInstance()
  780. {
  781. for (final L2DoorInstance door : _doors)
  782. {
  783. door.spawnMe(door.getX(), door.getY(), door.getZ());
  784. }
  785. }
  786. // This method loads castle door data from database
  787. private void loadDoor()
  788. {
  789. Connection con = null;
  790. try
  791. {
  792. con = L2DatabaseFactory.getInstance().getConnection();
  793. PreparedStatement statement = con.prepareStatement("Select * from castle_door where castleId = ?");
  794. statement.setInt(1, getCastleId());
  795. ResultSet rs = statement.executeQuery();
  796. while (rs.next())
  797. {
  798. // Create list of the door default for use when respawning dead doors
  799. _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");
  800. L2DoorInstance door = DoorTable.parseList(_doorDefault.get(_doorDefault.size() - 1), false);
  801. door.setIsWall(rs.getBoolean("isWall"));
  802. _doors.add(door);
  803. DoorTable.getInstance().putDoor(door);
  804. }
  805. rs.close();
  806. statement.close();
  807. }
  808. catch (Exception e)
  809. {
  810. _log.log(Level.WARNING, "Exception: loadCastleDoor(): " + e.getMessage(), e);
  811. }
  812. finally
  813. {
  814. L2DatabaseFactory.close(con);
  815. }
  816. }
  817. // This method loads castle door upgrade data from database
  818. private void loadDoorUpgrade()
  819. {
  820. Connection con = null;
  821. try
  822. {
  823. con = L2DatabaseFactory.getInstance().getConnection();
  824. PreparedStatement statement = con.prepareStatement("SELECT * FROM castle_doorupgrade WHERE doorId IN (SELECT Id FROM castle_door WHERE castleId = ?)");
  825. statement.setInt(1, getCastleId());
  826. ResultSet rs = statement.executeQuery();
  827. while (rs.next())
  828. {
  829. upgradeDoor(rs.getInt("id"), rs.getInt("hp"), rs.getInt("pDef"), rs.getInt("mDef"));
  830. }
  831. rs.close();
  832. statement.close();
  833. }
  834. catch (Exception e)
  835. {
  836. _log.log(Level.WARNING, "Exception: loadCastleDoorUpgrade(): " + e.getMessage(), e);
  837. }
  838. finally
  839. {
  840. L2DatabaseFactory.close(con);
  841. }
  842. }
  843. private void removeDoorUpgrade()
  844. {
  845. Connection con = null;
  846. try
  847. {
  848. con = L2DatabaseFactory.getInstance().getConnection();
  849. PreparedStatement statement = con.prepareStatement("delete from castle_doorupgrade where doorId in (select id from castle_door where castleId=?)");
  850. statement.setInt(1, getCastleId());
  851. statement.execute();
  852. statement.close();
  853. }
  854. catch (Exception e)
  855. {
  856. _log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
  857. }
  858. finally
  859. {
  860. L2DatabaseFactory.close(con);
  861. }
  862. }
  863. private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
  864. {
  865. Connection con = null;
  866. try
  867. {
  868. con = L2DatabaseFactory.getInstance().getConnection();
  869. PreparedStatement statement = con.prepareStatement("INSERT INTO castle_doorupgrade (doorId, hp, pDef, mDef) values (?,?,?,?)");
  870. statement.setInt(1, doorId);
  871. statement.setInt(2, hp);
  872. statement.setInt(3, pDef);
  873. statement.setInt(4, mDef);
  874. statement.execute();
  875. statement.close();
  876. }
  877. catch (Exception e)
  878. {
  879. _log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
  880. }
  881. finally
  882. {
  883. L2DatabaseFactory.close(con);
  884. }
  885. }
  886. private void updateOwnerInDB(L2Clan clan)
  887. {
  888. if (clan != null)
  889. _ownerId = clan.getClanId(); // Update owner id property
  890. else
  891. {
  892. _ownerId = 0; // Remove owner
  893. resetManor();
  894. }
  895. Connection con = null;
  896. try
  897. {
  898. con = L2DatabaseFactory.getInstance().getConnection();
  899. // NEED TO REMOVE HAS CASTLE FLAG FROM CLAN_DATA
  900. // SHOULD BE CHECKED FROM CASTLE TABLE
  901. PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET hasCastle = 0 WHERE hasCastle = ?");
  902. statement.setInt(1, getCastleId());
  903. statement.execute();
  904. statement.close();
  905. statement = con.prepareStatement("UPDATE clan_data SET hasCastle = ? WHERE clan_id = ?");
  906. statement.setInt(1, getCastleId());
  907. statement.setInt(2, getOwnerId());
  908. statement.execute();
  909. statement.close();
  910. // Announce to clan members
  911. if (clan != null)
  912. {
  913. clan.setCastleId(getCastleId()); // Set has castle flag for new owner
  914. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  915. clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
  916. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  917. }
  918. }
  919. catch (Exception e)
  920. {
  921. _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
  922. }
  923. finally
  924. {
  925. L2DatabaseFactory.close(con);
  926. }
  927. }
  928. public final int getCastleId()
  929. {
  930. return _castleId;
  931. }
  932. public final L2DoorInstance getDoor(int doorId)
  933. {
  934. if (doorId <= 0)
  935. return null;
  936. for (L2DoorInstance door : getDoors())
  937. {
  938. if (door.getDoorId() == doorId)
  939. return door;
  940. }
  941. return null;
  942. }
  943. public final List<L2DoorInstance> getDoors()
  944. {
  945. return _doors;
  946. }
  947. public final String getName()
  948. {
  949. return _name;
  950. }
  951. public final int getOwnerId()
  952. {
  953. return _ownerId;
  954. }
  955. public final Siege getSiege()
  956. {
  957. if (_siege == null)
  958. _siege = new Siege(new Castle[]
  959. {
  960. this
  961. });
  962. return _siege;
  963. }
  964. public final Calendar getSiegeDate()
  965. {
  966. return _siegeDate;
  967. }
  968. public boolean getIsTimeRegistrationOver()
  969. {
  970. return _isTimeRegistrationOver;
  971. }
  972. public void setIsTimeRegistrationOver(boolean val)
  973. {
  974. _isTimeRegistrationOver = val;
  975. }
  976. public Calendar getTimeRegistrationOverDate()
  977. {
  978. if (_siegeTimeRegistrationEndDate == null)
  979. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  980. return _siegeTimeRegistrationEndDate;
  981. }
  982. public final int getTaxPercent()
  983. {
  984. return _taxPercent;
  985. }
  986. public final double getTaxRate()
  987. {
  988. return _taxRate;
  989. }
  990. public final long getTreasury()
  991. {
  992. return _treasury;
  993. }
  994. public final boolean getShowNpcCrest()
  995. {
  996. return _showNpcCrest;
  997. }
  998. public final void setShowNpcCrest(boolean showNpcCrest)
  999. {
  1000. if (_showNpcCrest != showNpcCrest)
  1001. {
  1002. _showNpcCrest = showNpcCrest;
  1003. updateShowNpcCrest();
  1004. }
  1005. }
  1006. public List<SeedProduction> getSeedProduction(int period)
  1007. {
  1008. return (period == CastleManorManager.PERIOD_CURRENT ? _production : _productionNext);
  1009. }
  1010. public List<CropProcure> getCropProcure(int period)
  1011. {
  1012. return (period == CastleManorManager.PERIOD_CURRENT ? _procure : _procureNext);
  1013. }
  1014. public void setSeedProduction(List<SeedProduction> seed, int period)
  1015. {
  1016. if (period == CastleManorManager.PERIOD_CURRENT)
  1017. _production = seed;
  1018. else
  1019. _productionNext = seed;
  1020. }
  1021. public void setCropProcure(List<CropProcure> crop, int period)
  1022. {
  1023. if (period == CastleManorManager.PERIOD_CURRENT)
  1024. _procure = crop;
  1025. else
  1026. _procureNext = crop;
  1027. }
  1028. public SeedProduction getSeed(int seedId, int period)
  1029. {
  1030. for (SeedProduction seed : getSeedProduction(period))
  1031. {
  1032. if (seed.getId() == seedId)
  1033. {
  1034. return seed;
  1035. }
  1036. }
  1037. return null;
  1038. }
  1039. public CropProcure getCrop(int cropId, int period)
  1040. {
  1041. for (CropProcure crop : getCropProcure(period))
  1042. {
  1043. if (crop.getId() == cropId)
  1044. {
  1045. return crop;
  1046. }
  1047. }
  1048. return null;
  1049. }
  1050. public long getManorCost(int period)
  1051. {
  1052. List<CropProcure> procure;
  1053. List<SeedProduction> production;
  1054. if (period == CastleManorManager.PERIOD_CURRENT)
  1055. {
  1056. procure = _procure;
  1057. production = _production;
  1058. }
  1059. else
  1060. {
  1061. procure = _procureNext;
  1062. production = _productionNext;
  1063. }
  1064. long total = 0;
  1065. if (production != null)
  1066. {
  1067. for (SeedProduction seed : production)
  1068. {
  1069. total += L2Manor.getInstance().getSeedBuyPrice(seed.getId()) * seed.getStartProduce();
  1070. }
  1071. }
  1072. if (procure != null)
  1073. {
  1074. for (CropProcure crop : procure)
  1075. {
  1076. total += crop.getPrice() * crop.getStartAmount();
  1077. }
  1078. }
  1079. return total;
  1080. }
  1081. // save manor production data
  1082. public void saveSeedData()
  1083. {
  1084. Connection con = null;
  1085. try
  1086. {
  1087. con = L2DatabaseFactory.getInstance().getConnection();
  1088. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION);
  1089. statement.setInt(1, getCastleId());
  1090. statement.execute();
  1091. statement.close();
  1092. if (_production != null)
  1093. {
  1094. int count = 0;
  1095. StringBuilder query = new StringBuilder();
  1096. query.append("INSERT INTO castle_manor_production VALUES ");
  1097. String values[] = new String[_production.size()];
  1098. for (SeedProduction s : _production)
  1099. {
  1100. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1101. }
  1102. if (values.length > 0)
  1103. {
  1104. query.append(values[0]);
  1105. for (int i = 1; i < values.length; i++)
  1106. {
  1107. query.append(",");
  1108. query.append(values[i]);
  1109. }
  1110. statement = con.prepareStatement(query.toString());
  1111. statement.execute();
  1112. statement.close();
  1113. }
  1114. }
  1115. if (_productionNext != null)
  1116. {
  1117. int count = 0;
  1118. String query = "INSERT INTO castle_manor_production VALUES ";
  1119. String values[] = new String[_productionNext.size()];
  1120. for (SeedProduction s : _productionNext)
  1121. {
  1122. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1123. }
  1124. if (values.length > 0)
  1125. {
  1126. query += values[0];
  1127. for (int i = 1; i < values.length; i++)
  1128. {
  1129. query += "," + values[i];
  1130. }
  1131. statement = con.prepareStatement(query);
  1132. statement.execute();
  1133. statement.close();
  1134. }
  1135. }
  1136. }
  1137. catch (Exception e)
  1138. {
  1139. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1140. }
  1141. finally
  1142. {
  1143. L2DatabaseFactory.close(con);
  1144. }
  1145. }
  1146. // save manor production data for specified period
  1147. public void saveSeedData(int period)
  1148. {
  1149. Connection con = null;
  1150. try
  1151. {
  1152. con = L2DatabaseFactory.getInstance().getConnection();
  1153. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD);
  1154. statement.setInt(1, getCastleId());
  1155. statement.setInt(2, period);
  1156. statement.execute();
  1157. statement.close();
  1158. List<SeedProduction> prod = null;
  1159. prod = getSeedProduction(period);
  1160. if (prod != null)
  1161. {
  1162. int count = 0;
  1163. StringBuilder query = new StringBuilder();
  1164. query.append("INSERT INTO castle_manor_production VALUES ");
  1165. String values[] = new String[prod.size()];
  1166. for (SeedProduction s : prod)
  1167. {
  1168. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + period + ")";
  1169. }
  1170. if (values.length > 0)
  1171. {
  1172. query.append(values[0]);
  1173. for (int i = 1; i < values.length; i++)
  1174. {
  1175. query.append(",").append(values[i]);
  1176. }
  1177. statement = con.prepareStatement(query.toString());
  1178. statement.execute();
  1179. statement.close();
  1180. }
  1181. }
  1182. }
  1183. catch (Exception e)
  1184. {
  1185. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1186. }
  1187. finally
  1188. {
  1189. L2DatabaseFactory.close(con);
  1190. }
  1191. }
  1192. // save crop procure data
  1193. public void saveCropData()
  1194. {
  1195. Connection con = null;
  1196. try
  1197. {
  1198. con = L2DatabaseFactory.getInstance().getConnection();
  1199. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE);
  1200. statement.setInt(1, getCastleId());
  1201. statement.execute();
  1202. statement.close();
  1203. if (_procure != null && _procure.size() > 0)
  1204. {
  1205. int count = 0;
  1206. StringBuilder query = new StringBuilder();
  1207. query.append("INSERT INTO castle_manor_procure VALUES ");
  1208. String values[] = new String[_procure.size()];
  1209. for (CropProcure cp : _procure)
  1210. {
  1211. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1212. }
  1213. if (values.length > 0)
  1214. {
  1215. query.append(values[0]);
  1216. for (int i = 1; i < values.length; i++)
  1217. {
  1218. query.append(",");
  1219. query.append(values[i]);
  1220. }
  1221. statement = con.prepareStatement(query.toString());
  1222. statement.execute();
  1223. statement.close();
  1224. }
  1225. }
  1226. if (_procureNext != null && _procureNext.size() > 0)
  1227. {
  1228. int count = 0;
  1229. String query = "INSERT INTO castle_manor_procure VALUES ";
  1230. String values[] = new String[_procureNext.size()];
  1231. for (CropProcure cp : _procureNext)
  1232. {
  1233. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1234. }
  1235. if (values.length > 0)
  1236. {
  1237. query += values[0];
  1238. for (int i = 1; i < values.length; i++)
  1239. {
  1240. query += "," + values[i];
  1241. }
  1242. statement = con.prepareStatement(query);
  1243. statement.execute();
  1244. statement.close();
  1245. }
  1246. }
  1247. }
  1248. catch (Exception e)
  1249. {
  1250. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1251. }
  1252. finally
  1253. {
  1254. L2DatabaseFactory.close(con);
  1255. }
  1256. }
  1257. // save crop procure data for specified period
  1258. public void saveCropData(int period)
  1259. {
  1260. Connection con = null;
  1261. try
  1262. {
  1263. con = L2DatabaseFactory.getInstance().getConnection();
  1264. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD);
  1265. statement.setInt(1, getCastleId());
  1266. statement.setInt(2, period);
  1267. statement.execute();
  1268. statement.close();
  1269. List<CropProcure> proc = null;
  1270. proc = getCropProcure(period);
  1271. if (proc != null && proc.size() > 0)
  1272. {
  1273. int count = 0;
  1274. StringBuilder query = new StringBuilder();
  1275. query.append("INSERT INTO castle_manor_procure VALUES ");
  1276. String values[] = new String[proc.size()];
  1277. for (CropProcure cp : proc)
  1278. {
  1279. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + period + ")";
  1280. }
  1281. if (values.length > 0)
  1282. {
  1283. query.append(values[0]);
  1284. for (int i = 1; i < values.length; i++)
  1285. {
  1286. query.append(",");
  1287. query.append(values[i]);
  1288. }
  1289. statement = con.prepareStatement(query.toString());
  1290. statement.execute();
  1291. statement.close();
  1292. }
  1293. }
  1294. }
  1295. catch (Exception e)
  1296. {
  1297. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1298. }
  1299. finally
  1300. {
  1301. L2DatabaseFactory.close(con);
  1302. }
  1303. }
  1304. public void updateCrop(int cropId, long amount, int period)
  1305. {
  1306. Connection con = null;
  1307. try
  1308. {
  1309. con = L2DatabaseFactory.getInstance().getConnection();
  1310. PreparedStatement statement = con.prepareStatement(CASTLE_UPDATE_CROP);
  1311. statement.setLong(1, amount);
  1312. statement.setInt(2, cropId);
  1313. statement.setInt(3, getCastleId());
  1314. statement.setInt(4, period);
  1315. statement.execute();
  1316. statement.close();
  1317. }
  1318. catch (Exception e)
  1319. {
  1320. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1321. }
  1322. finally
  1323. {
  1324. L2DatabaseFactory.close(con);
  1325. }
  1326. }
  1327. public void updateSeed(int seedId, long amount, int period)
  1328. {
  1329. Connection con = null;
  1330. try
  1331. {
  1332. con = L2DatabaseFactory.getInstance().getConnection();
  1333. PreparedStatement statement = con.prepareStatement(CASTLE_UPDATE_SEED);
  1334. statement.setLong(1, amount);
  1335. statement.setInt(2, seedId);
  1336. statement.setInt(3, getCastleId());
  1337. statement.setInt(4, period);
  1338. statement.execute();
  1339. statement.close();
  1340. }
  1341. catch (Exception e)
  1342. {
  1343. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1344. }
  1345. finally
  1346. {
  1347. L2DatabaseFactory.close(con);
  1348. }
  1349. }
  1350. public boolean isNextPeriodApproved()
  1351. {
  1352. return _isNextPeriodApproved;
  1353. }
  1354. public void setNextPeriodApproved(boolean val)
  1355. {
  1356. _isNextPeriodApproved = val;
  1357. }
  1358. public void updateClansReputation()
  1359. {
  1360. if (_formerOwner != null)
  1361. {
  1362. if (_formerOwner != ClanTable.getInstance().getClan(getOwnerId()))
  1363. {
  1364. int maxreward = Math.max(0, _formerOwner.getReputationScore());
  1365. _formerOwner.takeReputationScore(Config.LOOSE_CASTLE_POINTS, true);
  1366. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1367. if (owner != null)
  1368. owner.addReputationScore(Math.min(Config.TAKE_CASTLE_POINTS, maxreward), true);
  1369. }
  1370. else
  1371. _formerOwner.addReputationScore(Config.CASTLE_DEFENDED_POINTS, true);
  1372. }
  1373. else
  1374. {
  1375. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1376. if (owner != null)
  1377. {
  1378. owner.addReputationScore(Config.TAKE_CASTLE_POINTS, true);
  1379. }
  1380. }
  1381. }
  1382. public void updateShowNpcCrest()
  1383. {
  1384. Connection con = null;
  1385. try
  1386. {
  1387. con = L2DatabaseFactory.getInstance().getConnection();
  1388. PreparedStatement statement = con.prepareStatement("UPDATE castle SET showNpcCrest = ? WHERE id = ?");
  1389. statement.setString(1, String.valueOf(getShowNpcCrest()));
  1390. statement.setInt(2, getCastleId());
  1391. statement.execute();
  1392. statement.close();
  1393. }
  1394. catch (Exception e)
  1395. {
  1396. _log.info("Error saving showNpcCrest for castle " + getName() + ": " + e.getMessage());
  1397. }
  1398. finally
  1399. {
  1400. L2DatabaseFactory.close(con);
  1401. }
  1402. }
  1403. public FastList<L2Skill> getResidentialSkills()
  1404. {
  1405. return _residentialSkills;
  1406. }
  1407. public void giveResidentialSkills(L2PcInstance player)
  1408. {
  1409. if ((_residentialSkills != null) && !_residentialSkills.isEmpty())
  1410. {
  1411. for (L2Skill sk : _residentialSkills)
  1412. {
  1413. player.addSkill(sk, false);
  1414. }
  1415. }
  1416. Territory territory = TerritoryWarManager.getInstance().getTerritory(getCastleId());
  1417. if (territory != null && territory.getOwnedWardIds().contains(getCastleId() + 80))
  1418. {
  1419. for (int wardId : territory.getOwnedWardIds())
  1420. {
  1421. final FastList<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1422. for (L2SkillLearn s : territorySkills)
  1423. {
  1424. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1425. if (sk != null)
  1426. {
  1427. player.addSkill(sk, false);
  1428. }
  1429. else
  1430. {
  1431. _log.warning("Trying to add a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1432. }
  1433. }
  1434. }
  1435. }
  1436. }
  1437. public void removeResidentialSkills(L2PcInstance player)
  1438. {
  1439. if (_residentialSkills != null && !_residentialSkills.isEmpty())
  1440. {
  1441. for (L2Skill sk : _residentialSkills)
  1442. {
  1443. player.removeSkill(sk, false, true);
  1444. }
  1445. }
  1446. if (TerritoryWarManager.getInstance().getTerritory(getCastleId()) != null)
  1447. {
  1448. for (int wardId : TerritoryWarManager.getInstance().getTerritory(getCastleId()).getOwnedWardIds())
  1449. {
  1450. final FastList<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1451. for (L2SkillLearn s : territorySkills)
  1452. {
  1453. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1454. if (sk != null)
  1455. {
  1456. player.removeSkill(sk, false, true);
  1457. }
  1458. else
  1459. {
  1460. _log.warning("Trying to remove a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1461. }
  1462. }
  1463. }
  1464. }
  1465. }
  1466. /**
  1467. * Register Artefact to castle
  1468. * @param artefact
  1469. */
  1470. public void registerArtefact(L2ArtefactInstance artefact)
  1471. {
  1472. if (Config.DEBUG)
  1473. _log.info("ArtefactId: " + artefact.getObjectId() + " is registered to " + getName() + " castle.");
  1474. _artefacts.add(artefact);
  1475. }
  1476. public List<L2ArtefactInstance> getArtefacts()
  1477. {
  1478. return _artefacts;
  1479. }
  1480. public void resetManor()
  1481. {
  1482. setCropProcure(new FastList<CropProcure>(), CastleManorManager.PERIOD_CURRENT);
  1483. setCropProcure(new FastList<CropProcure>(), CastleManorManager.PERIOD_NEXT);
  1484. setSeedProduction(new FastList<SeedProduction>(), CastleManorManager.PERIOD_CURRENT);
  1485. setSeedProduction(new FastList<SeedProduction>(), CastleManorManager.PERIOD_NEXT);
  1486. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  1487. {
  1488. saveCropData();
  1489. saveSeedData();
  1490. }
  1491. }
  1492. public int getBloodAlliance()
  1493. {
  1494. return _bloodAlliance;
  1495. }
  1496. public void setBloodAlliance(int count)
  1497. {
  1498. _bloodAlliance = count;
  1499. Connection con = null;
  1500. try
  1501. {
  1502. con = L2DatabaseFactory.getInstance().getConnection();
  1503. PreparedStatement statement = con.prepareStatement("UPDATE castle SET bloodAlliance = ? WHERE id = ?");
  1504. statement.setInt(1, _bloodAlliance);
  1505. statement.setInt(2, getCastleId());
  1506. statement.execute();
  1507. statement.close();
  1508. }
  1509. catch (Exception e)
  1510. {
  1511. _log.log(Level.WARNING, e.getMessage(), e);
  1512. }
  1513. finally
  1514. {
  1515. L2DatabaseFactory.close(con);
  1516. }
  1517. }
  1518. }