Castle.java 45 KB

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