Renamed trunk folder.

This commit is contained in:
MobiusDev
2016-08-14 11:56:36 +00:00
parent 0bb4e57aad
commit 69cbd04d91
19923 changed files with 0 additions and 0 deletions

View File

@ -0,0 +1,620 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.datatables;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import com.l2jmobius.Config;
import com.l2jmobius.commons.database.DatabaseFactory;
import com.l2jmobius.gameserver.ThreadPoolManager;
import com.l2jmobius.gameserver.data.xml.impl.SkillData;
import com.l2jmobius.gameserver.model.L2Clan;
import com.l2jmobius.gameserver.model.L2Object;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.model.skills.Skill;
import com.l2jmobius.gameserver.model.zone.ZoneId;
import com.l2jmobius.gameserver.network.SystemMessageId;
import com.l2jmobius.gameserver.network.serverpackets.SystemMessage;
/**
* @author BiggBoss
*/
public final class BotReportTable
{
// Zoey76: TODO: Split XML parsing from SQL operations, use IGameXmlReader instead of SAXParser.
private static final Logger LOGGER = Logger.getLogger(BotReportTable.class.getName());
private static final int COLUMN_BOT_ID = 1;
private static final int COLUMN_REPORTER_ID = 2;
private static final int COLUMN_REPORT_TIME = 3;
public static final int ATTACK_ACTION_BLOCK_ID = -1;
public static final int TRADE_ACTION_BLOCK_ID = -2;
public static final int PARTY_ACTION_BLOCK_ID = -3;
public static final int ACTION_BLOCK_ID = -4;
public static final int CHAT_BLOCK_ID = -5;
private static final String SQL_LOAD_REPORTED_CHAR_DATA = "SELECT * FROM bot_reported_char_data";
private static final String SQL_INSERT_REPORTED_CHAR_DATA = "INSERT INTO bot_reported_char_data VALUES (?,?,?)";
private static final String SQL_CLEAR_REPORTED_CHAR_DATA = "DELETE FROM bot_reported_char_data";
private Map<Integer, Long> _ipRegistry;
private Map<Integer, ReporterCharData> _charRegistry;
private Map<Integer, ReportedCharData> _reports;
private Map<Integer, PunishHolder> _punishments;
protected BotReportTable()
{
if (Config.BOTREPORT_ENABLE)
{
_ipRegistry = new HashMap<>();
_charRegistry = new ConcurrentHashMap<>();
_reports = new ConcurrentHashMap<>();
_punishments = new ConcurrentHashMap<>();
try
{
final File punishments = new File("./config/BotReportPunishments.xml");
if (!punishments.exists())
{
throw new FileNotFoundException(punishments.getName());
}
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(punishments, new PunishmentsLoader());
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not load punishments from /config/BotReportPunishments.xml", e);
}
loadReportedCharData();
scheduleResetPointTask();
}
}
/**
* Loads all reports of each reported bot into this cache class.<br>
* Warning: Heavy method, used only on server start up
*/
private void loadReportedCharData()
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
Statement st = con.createStatement();
ResultSet rset = st.executeQuery(SQL_LOAD_REPORTED_CHAR_DATA))
{
long lastResetTime = 0;
try
{
final String[] hour = Config.BOTREPORT_RESETPOINT_HOUR;
final Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour[0]));
c.set(Calendar.MINUTE, Integer.parseInt(hour[1]));
if (System.currentTimeMillis() < c.getTimeInMillis())
{
c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) - 1);
}
lastResetTime = c.getTimeInMillis();
}
catch (Exception e)
{
}
while (rset.next())
{
final int botId = rset.getInt(COLUMN_BOT_ID);
final int reporter = rset.getInt(COLUMN_REPORTER_ID);
final long date = rset.getLong(COLUMN_REPORT_TIME);
if (_reports.containsKey(botId))
{
_reports.get(botId).addReporter(reporter, date);
}
else
{
final ReportedCharData rcd = new ReportedCharData();
rcd.addReporter(reporter, date);
_reports.put(rset.getInt(COLUMN_BOT_ID), rcd);
}
if (date > lastResetTime)
{
ReporterCharData rcd = _charRegistry.get(reporter);
if (rcd != null)
{
rcd.setPoints(rcd.getPointsLeft() - 1);
}
else
{
rcd = new ReporterCharData();
rcd.setPoints(6);
_charRegistry.put(reporter, rcd);
}
}
}
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _reports.size() + " bot reports");
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not load reported char data!", e);
}
}
/**
* Save all reports for each reported bot down to database.<br>
* Warning: Heavy method, used only at server shutdown
*/
public void saveReportedCharData()
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement(SQL_INSERT_REPORTED_CHAR_DATA))
{
st.execute(SQL_CLEAR_REPORTED_CHAR_DATA);
for (Map.Entry<Integer, ReportedCharData> entrySet : _reports.entrySet())
{
for (int reporterId : entrySet.getValue()._reporters.keySet())
{
ps.setInt(1, entrySet.getKey());
ps.setInt(2, reporterId);
ps.setLong(3, entrySet.getValue()._reporters.get(reporterId));
ps.execute();
}
}
}
catch (Exception e)
{
LOGGER.log(Level.SEVERE, getClass().getSimpleName() + ": Could not update reported char data in database!", e);
}
}
/**
* Attempts to perform a bot report. R/W to ip and char id registry is synchronized. Triggers bot punish management<br>
* @param reporter (L2PcInstance who issued the report)
* @return True, if the report was registered, False otherwise
*/
public boolean reportBot(L2PcInstance reporter)
{
final L2Object target = reporter.getTarget();
if (target == null)
{
return false;
}
final L2PcInstance bot = target.getActingPlayer();
if ((bot == null) || (target.getObjectId() == reporter.getObjectId()))
{
return false;
}
if (bot.isInsideZone(ZoneId.PEACE) || bot.isInsideZone(ZoneId.PVP))
{
reporter.sendPacket(SystemMessageId.YOU_CANNOT_REPORT_A_CHARACTER_WHO_IS_IN_A_PEACE_ZONE_OR_A_BATTLEGROUND);
return false;
}
if (bot.isInOlympiadMode())
{
reporter.sendPacket(SystemMessageId.THIS_CHARACTER_CANNOT_MAKE_A_REPORT_YOU_CANNOT_MAKE_A_REPORT_WHILE_LOCATED_INSIDE_A_PEACE_ZONE_OR_A_BATTLEGROUND_WHILE_YOU_ARE_AN_OPPOSING_CLAN_MEMBER_DURING_A_CLAN_WAR_OR_WHILE_PARTICIPATING_IN_THE_OLYMPIAD);
return false;
}
if ((bot.getClan() != null) && bot.getClan().isAtWarWith(reporter.getClan()))
{
reporter.sendPacket(SystemMessageId.YOU_CANNOT_REPORT_WHEN_A_CLAN_WAR_HAS_BEEN_DECLARED);
return false;
}
if (bot.getExp() == bot.getStat().getStartingExp())
{
reporter.sendPacket(SystemMessageId.YOU_CANNOT_REPORT_A_CHARACTER_WHO_HAS_NOT_ACQUIRED_ANY_XP_AFTER_CONNECTING);
return false;
}
ReportedCharData rcd = _reports.get(bot.getObjectId());
ReporterCharData rcdRep = _charRegistry.get(reporter.getObjectId());
final int reporterId = reporter.getObjectId();
synchronized (this)
{
if (_reports.containsKey(reporterId))
{
reporter.sendPacket(SystemMessageId.YOU_HAVE_BEEN_REPORTED_AS_AN_ILLEGAL_PROGRAM_USER_AND_CANNOT_REPORT_OTHER_USERS);
return false;
}
final int ip = hashIp(reporter);
if (!timeHasPassed(_ipRegistry, ip))
{
reporter.sendPacket(SystemMessageId.THIS_CHARACTER_CANNOT_MAKE_A_REPORT_THE_TARGET_HAS_ALREADY_BEEN_REPORTED_BY_EITHER_YOUR_CLAN_OR_ALLIANCE_OR_HAS_ALREADY_BEEN_REPORTED_FROM_YOUR_CURRENT_IP);
return false;
}
if (rcd != null)
{
if (rcd.alredyReportedBy(reporterId))
{
reporter.sendPacket(SystemMessageId.YOU_CANNOT_REPORT_THIS_PERSON_AGAIN_AT_THIS_TIME);
return false;
}
if (!Config.BOTREPORT_ALLOW_REPORTS_FROM_SAME_CLAN_MEMBERS && rcd.reportedBySameClan(reporter.getClan()))
{
reporter.sendPacket(SystemMessageId.THIS_CHARACTER_CANNOT_MAKE_A_REPORT_THE_TARGET_HAS_ALREADY_BEEN_REPORTED_BY_EITHER_YOUR_CLAN_OR_ALLIANCE_OR_HAS_ALREADY_BEEN_REPORTED_FROM_YOUR_CURRENT_IP);
return false;
}
}
if (rcdRep != null)
{
if (rcdRep.getPointsLeft() == 0)
{
reporter.sendPacket(SystemMessageId.YOU_HAVE_USED_ALL_AVAILABLE_POINTS_POINTS_ARE_RESET_EVERYDAY_AT_NOON);
return false;
}
final long reuse = (System.currentTimeMillis() - rcdRep.getLastReporTime());
if (reuse < Config.BOTREPORT_REPORT_DELAY)
{
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.YOU_CAN_MAKE_ANOTHER_REPORT_IN_S1_MINUTE_S_YOU_HAVE_S2_POINT_S_REMAINING_ON_THIS_ACCOUNT);
sm.addInt((int) (reuse / 60000));
sm.addInt(rcdRep.getPointsLeft());
reporter.sendPacket(sm);
return false;
}
}
final long curTime = System.currentTimeMillis();
if (rcd == null)
{
rcd = new ReportedCharData();
_reports.put(bot.getObjectId(), rcd);
}
rcd.addReporter(reporterId, curTime);
if (rcdRep == null)
{
rcdRep = new ReporterCharData();
}
rcdRep.registerReport(curTime);
_ipRegistry.put(ip, curTime);
_charRegistry.put(reporterId, rcdRep);
}
SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.C1_WAS_REPORTED_AS_A_BOT);
sm.addCharName(bot);
reporter.sendPacket(sm);
sm = SystemMessage.getSystemMessage(SystemMessageId.YOU_HAVE_USED_A_REPORT_POINT_ON_C1_YOU_HAVE_S2_POINTS_REMAINING_ON_THIS_ACCOUNT);
sm.addCharName(bot);
sm.addInt(rcdRep.getPointsLeft());
reporter.sendPacket(sm);
handleReport(bot, rcd);
return true;
}
/**
* Find the punishs to apply to the given bot and triggers the punish method.
* @param bot (L2PcInstance to be punished)
* @param rcd (RepotedCharData linked to this bot)
*/
private void handleReport(L2PcInstance bot, ReportedCharData rcd)
{
// Report count punishment
punishBot(bot, _punishments.get(rcd.getReportCount()));
// Range punishments
for (int key : _punishments.keySet())
{
if ((key < 0) && (Math.abs(key) <= rcd.getReportCount()))
{
punishBot(bot, _punishments.get(key));
}
}
}
/**
* Applies the given punish to the bot if the action is secure
* @param bot (L2PcInstance to punish)
* @param ph (PunishHolder containing the debuff and a possible system message to send)
*/
private void punishBot(L2PcInstance bot, PunishHolder ph)
{
if (ph != null)
{
ph._punish.applyEffects(bot, bot);
if (ph._systemMessageId > -1)
{
final SystemMessageId id = SystemMessageId.getSystemMessageId(ph._systemMessageId);
if (id != null)
{
bot.sendPacket(id);
}
}
}
}
/**
* Adds a debuff punishment into the punishments record. If skill does not exist, will log it and return
* @param neededReports (report count to trigger this debuff)
* @param skillId
* @param skillLevel
* @param sysMsg (id of a system message to send when applying the punish)
*/
void addPunishment(int neededReports, int skillId, int skillLevel, int sysMsg)
{
final Skill sk = SkillData.getInstance().getSkill(skillId, skillLevel);
if (sk != null)
{
_punishments.put(neededReports, new PunishHolder(sk, sysMsg));
}
else
{
LOGGER.warning(getClass().getSimpleName() + ": Could not add punishment for " + neededReports + " report(s): Skill " + skillId + "-" + skillLevel + " does not exist!");
}
}
void resetPointsAndSchedule()
{
synchronized (_charRegistry)
{
for (ReporterCharData rcd : _charRegistry.values())
{
rcd.setPoints(7);
}
}
scheduleResetPointTask();
}
private void scheduleResetPointTask()
{
try
{
final String[] hour = Config.BOTREPORT_RESETPOINT_HOUR;
final Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour[0]));
c.set(Calendar.MINUTE, Integer.parseInt(hour[1]));
if (System.currentTimeMillis() > c.getTimeInMillis())
{
c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1);
}
ThreadPoolManager.getInstance().scheduleGeneral(new ResetPointTask(), c.getTimeInMillis() - System.currentTimeMillis());
}
catch (Exception e)
{
ThreadPoolManager.getInstance().scheduleGeneral(new ResetPointTask(), 24 * 3600 * 1000);
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not properly schedule bot report points reset task. Scheduled in 24 hours.", e);
}
}
public static BotReportTable getInstance()
{
return SingletonHolder.INSTANCE;
}
/**
* Returns a integer representative number from a connection
* @param player (The L2PcInstance owner of the connection)
* @return int (hashed ip)
*/
private static int hashIp(L2PcInstance player)
{
final String con = player.getClient().getConnectionAddress().getHostAddress();
final String[] rawByte = con.split("\\.");
final int[] rawIp = new int[4];
for (int i = 0; i < 4; i++)
{
rawIp[i] = Integer.parseInt(rawByte[i]);
}
return rawIp[0] | (rawIp[1] << 8) | (rawIp[2] << 16) | (rawIp[3] << 24);
}
/**
* Checks and return if the abstrat barrier specified by an integer (map key) has accomplished the waiting time
* @param map (a Map to study (Int = barrier, Long = fully qualified unix time)
* @param objectId (an existent map key)
* @return true if the time has passed.
*/
private static boolean timeHasPassed(Map<Integer, Long> map, int objectId)
{
if (map.containsKey(objectId))
{
return (System.currentTimeMillis() - map.get(objectId)) > Config.BOTREPORT_REPORT_DELAY;
}
return true;
}
/**
* Represents the info about a reporter
*/
private final class ReporterCharData
{
private long _lastReport;
private byte _reportPoints;
ReporterCharData()
{
_reportPoints = 7;
_lastReport = 0;
}
void registerReport(long time)
{
_reportPoints -= 1;
_lastReport = time;
}
long getLastReporTime()
{
return _lastReport;
}
byte getPointsLeft()
{
return _reportPoints;
}
void setPoints(int points)
{
_reportPoints = (byte) points;
}
}
/**
* Represents the info about a reported character
*/
private final class ReportedCharData
{
Map<Integer, Long> _reporters;
ReportedCharData()
{
_reporters = new HashMap<>();
}
int getReportCount()
{
return _reporters.size();
}
boolean alredyReportedBy(int objectId)
{
return _reporters.containsKey(objectId);
}
void addReporter(int objectId, long reportTime)
{
_reporters.put(objectId, reportTime);
}
boolean reportedBySameClan(L2Clan clan)
{
if (clan == null)
{
return false;
}
for (int reporterId : _reporters.keySet())
{
if (clan.isMember(reporterId))
{
return true;
}
}
return false;
}
}
/**
* SAX loader to parse /config/BotReportPunishments.xml file
*/
private final class PunishmentsLoader extends DefaultHandler
{
PunishmentsLoader()
{
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attr)
{
if (qName.equals("punishment"))
{
int reportCount = -1, skillId = -1, skillLevel = 1, sysMessage = -1;
try
{
reportCount = Integer.parseInt(attr.getValue("neededReportCount"));
skillId = Integer.parseInt(attr.getValue("skillId"));
final String level = attr.getValue("skillLevel");
final String systemMessageId = attr.getValue("sysMessageId");
if (level != null)
{
skillLevel = Integer.parseInt(level);
}
if (systemMessageId != null)
{
sysMessage = Integer.parseInt(systemMessageId);
}
}
catch (Exception e)
{
e.printStackTrace();
}
addPunishment(reportCount, skillId, skillLevel, sysMessage);
}
}
}
class PunishHolder
{
final Skill _punish;
final int _systemMessageId;
PunishHolder(Skill sk, int sysMsg)
{
_punish = sk;
_systemMessageId = sysMsg;
}
}
class ResetPointTask implements Runnable
{
@Override
public void run()
{
resetPointsAndSchedule();
}
}
private static final class SingletonHolder
{
static final BotReportTable INSTANCE = new BotReportTable();
}
}

View File

@ -0,0 +1,128 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.datatables;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.l2jmobius.gameserver.script.DateRange;
import com.l2jmobius.gameserver.script.EventDrop;
/**
* This class manage drop of Special Events created by GM for a defined period.<br>
* During a Special Event all L2Attackable can drop extra Items.<br>
* Those extra Items are defined in the table <b>allNpcDateDrops</b>.<br>
* Each Special Event has a start and end date to stop to drop extra Items automatically.
*/
public class EventDroplist
{
/**
* The table containing all DataDrop object
*/
private static final List<DateDrop> _allNpcDateDrops = new CopyOnWriteArrayList<>();
public static class DateDrop
{
protected final DateRange _dateRange;
private final EventDrop _eventDrop;
public DateDrop(DateRange dateRange, EventDrop eventDrop)
{
_dateRange = dateRange;
_eventDrop = eventDrop;
}
/**
* @return the _eventDrop
*/
public EventDrop getEventDrop()
{
return _eventDrop;
}
/**
* @return the _dateRange
*/
public DateRange getDateRange()
{
return _dateRange;
}
}
/**
* Create and Init a new DateDrop then add it to the allNpcDateDrops of EventDroplist .
* @param itemIdList The table containing all item identifier of this DateDrop
* @param count The table containing min and max value of this DateDrop
* @param chance The chance to obtain this drop
* @param dateRange The DateRange object to add to this DateDrop
*/
public void addGlobalDrop(int[] itemIdList, int[] count, int chance, DateRange dateRange)
{
_allNpcDateDrops.add(new DateDrop(dateRange, new EventDrop(itemIdList, count[0], count[1], chance)));
}
/**
* @param itemId the item Id for the drop
* @param min the minimum drop count
* @param max the maximum drop count
* @param chance the drop chance
* @param dateRange the event drop rate range
*/
public void addGlobalDrop(int itemId, long min, long max, int chance, DateRange dateRange)
{
_allNpcDateDrops.add(new DateDrop(dateRange, new EventDrop(itemId, min, max, chance)));
}
/**
* Adds an event drop for a given date range.
* @param dateRange the date range.
* @param eventDrop the event drop.
*/
public void addGlobalDrop(DateRange dateRange, EventDrop eventDrop)
{
_allNpcDateDrops.add(new DateDrop(dateRange, eventDrop));
}
/**
* @return all DateDrop of EventDroplist allNpcDateDrops within the date range.
*/
public List<DateDrop> getAllDrops()
{
final List<DateDrop> list = new LinkedList<>();
final Date currentDate = new Date();
for (DateDrop drop : _allNpcDateDrops)
{
if (drop._dateRange.isWithinRange(currentDate))
{
list.add(drop);
}
}
return list;
}
public static EventDroplist getInstance()
{
return SingletonHolder._instance;
}
private static class SingletonHolder
{
protected static final EventDroplist _instance = new EventDroplist();
}
}

View File

@ -0,0 +1,443 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.datatables;
import static com.l2jmobius.gameserver.model.itemcontainer.Inventory.ADENA_ID;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.commons.database.DatabaseFactory;
import com.l2jmobius.gameserver.ThreadPoolManager;
import com.l2jmobius.gameserver.data.xml.impl.EnchantItemHPBonusData;
import com.l2jmobius.gameserver.engines.DocumentEngine;
import com.l2jmobius.gameserver.enums.ItemLocation;
import com.l2jmobius.gameserver.idfactory.IdFactory;
import com.l2jmobius.gameserver.model.L2Object;
import com.l2jmobius.gameserver.model.L2World;
import com.l2jmobius.gameserver.model.actor.L2Attackable;
import com.l2jmobius.gameserver.model.actor.instance.L2EventMonsterInstance;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.model.events.EventDispatcher;
import com.l2jmobius.gameserver.model.events.impl.item.OnItemCreate;
import com.l2jmobius.gameserver.model.items.L2Armor;
import com.l2jmobius.gameserver.model.items.L2EtcItem;
import com.l2jmobius.gameserver.model.items.L2Item;
import com.l2jmobius.gameserver.model.items.L2Weapon;
import com.l2jmobius.gameserver.model.items.instance.L2ItemInstance;
import com.l2jmobius.gameserver.util.GMAudit;
/**
* This class serves as a container for all item templates in the game.
*/
public class ItemTable
{
private static Logger LOGGER = Logger.getLogger(ItemTable.class.getName());
private static Logger LOGGER_ITEMS = Logger.getLogger("item");
public static final Map<String, Integer> SLOTS = new HashMap<>();
private L2Item[] _allTemplates;
private final Map<Integer, L2EtcItem> _etcItems = new HashMap<>();
private final Map<Integer, L2Armor> _armors = new HashMap<>();
private final Map<Integer, L2Weapon> _weapons = new HashMap<>();
static
{
SLOTS.put("shirt", L2Item.SLOT_UNDERWEAR);
SLOTS.put("lbracelet", L2Item.SLOT_L_BRACELET);
SLOTS.put("rbracelet", L2Item.SLOT_R_BRACELET);
SLOTS.put("talisman", L2Item.SLOT_DECO);
SLOTS.put("chest", L2Item.SLOT_CHEST);
SLOTS.put("fullarmor", L2Item.SLOT_FULL_ARMOR);
SLOTS.put("head", L2Item.SLOT_HEAD);
SLOTS.put("hair", L2Item.SLOT_HAIR);
SLOTS.put("hairall", L2Item.SLOT_HAIRALL);
SLOTS.put("underwear", L2Item.SLOT_UNDERWEAR);
SLOTS.put("back", L2Item.SLOT_BACK);
SLOTS.put("neck", L2Item.SLOT_NECK);
SLOTS.put("legs", L2Item.SLOT_LEGS);
SLOTS.put("feet", L2Item.SLOT_FEET);
SLOTS.put("gloves", L2Item.SLOT_GLOVES);
SLOTS.put("chest,legs", L2Item.SLOT_CHEST | L2Item.SLOT_LEGS);
SLOTS.put("belt", L2Item.SLOT_BELT);
SLOTS.put("rhand", L2Item.SLOT_R_HAND);
SLOTS.put("lhand", L2Item.SLOT_L_HAND);
SLOTS.put("lrhand", L2Item.SLOT_LR_HAND);
SLOTS.put("rear;lear", L2Item.SLOT_R_EAR | L2Item.SLOT_L_EAR);
SLOTS.put("rfinger;lfinger", L2Item.SLOT_R_FINGER | L2Item.SLOT_L_FINGER);
SLOTS.put("wolf", L2Item.SLOT_WOLF);
SLOTS.put("greatwolf", L2Item.SLOT_GREATWOLF);
SLOTS.put("hatchling", L2Item.SLOT_HATCHLING);
SLOTS.put("strider", L2Item.SLOT_STRIDER);
SLOTS.put("babypet", L2Item.SLOT_BABYPET);
SLOTS.put("brooch", L2Item.SLOT_BROOCH);
SLOTS.put("brooch_jewel", L2Item.SLOT_BROOCH_JEWEL);
SLOTS.put("none", L2Item.SLOT_NONE);
// retail compatibility
SLOTS.put("onepiece", L2Item.SLOT_FULL_ARMOR);
SLOTS.put("hair2", L2Item.SLOT_HAIR2);
SLOTS.put("dhair", L2Item.SLOT_HAIRALL);
SLOTS.put("alldress", L2Item.SLOT_ALLDRESS);
SLOTS.put("deco1", L2Item.SLOT_DECO);
SLOTS.put("waist", L2Item.SLOT_BELT);
}
/**
* @return a reference to this ItemTable object
*/
public static ItemTable getInstance()
{
return SingletonHolder._instance;
}
protected ItemTable()
{
load();
}
private void load()
{
int highest = 0;
_armors.clear();
_etcItems.clear();
_weapons.clear();
for (L2Item item : DocumentEngine.getInstance().loadItems())
{
if (highest < item.getId())
{
highest = item.getId();
}
if (item instanceof L2EtcItem)
{
_etcItems.put(item.getId(), (L2EtcItem) item);
}
else if (item instanceof L2Armor)
{
_armors.put(item.getId(), (L2Armor) item);
}
else
{
_weapons.put(item.getId(), (L2Weapon) item);
}
}
buildFastLookupTable(highest);
LOGGER.info(getClass().getSimpleName() + ": Loaded: " + _etcItems.size() + " Etc Items");
LOGGER.info(getClass().getSimpleName() + ": Loaded: " + _armors.size() + " Armor Items");
LOGGER.info(getClass().getSimpleName() + ": Loaded: " + _weapons.size() + " Weapon Items");
LOGGER.info(getClass().getSimpleName() + ": Loaded: " + (_etcItems.size() + _armors.size() + _weapons.size()) + " Items in total.");
}
/**
* Builds a variable in which all items are putting in in function of their ID.
* @param size
*/
private void buildFastLookupTable(int size)
{
// Create a FastLookUp Table called _allTemplates of size : value of the highest item ID
LOGGER.info(getClass().getSimpleName() + ": Highest item id used: " + size);
_allTemplates = new L2Item[size + 1];
// Insert armor item in Fast Look Up Table
for (L2Armor item : _armors.values())
{
_allTemplates[item.getId()] = item;
}
// Insert weapon item in Fast Look Up Table
for (L2Weapon item : _weapons.values())
{
_allTemplates[item.getId()] = item;
}
// Insert etcItem item in Fast Look Up Table
for (L2EtcItem item : _etcItems.values())
{
_allTemplates[item.getId()] = item;
}
}
/**
* Returns the item corresponding to the item ID
* @param id : int designating the item
* @return L2Item
*/
public L2Item getTemplate(int id)
{
if ((id >= _allTemplates.length) || (id < 0))
{
return null;
}
return _allTemplates[id];
}
/**
* Create the L2ItemInstance corresponding to the Item Identifier and quantitiy add logs the activity. <B><U> Actions</U> :</B>
* <li>Create and Init the L2ItemInstance corresponding to the Item Identifier and quantity</li>
* <li>Add the L2ItemInstance object to _allObjects of L2world</li>
* <li>Logs Item creation according to log settings</li>
* @param process : String Identifier of process triggering this action
* @param itemId : int Item Identifier of the item to be created
* @param count : int Quantity of items to be created for stackable items
* @param actor : L2PcInstance Player requesting the item creation
* @param reference : Object Object referencing current action like NPC selling item or previous item in transformation
* @return L2ItemInstance corresponding to the new item
*/
public L2ItemInstance createItem(String process, int itemId, long count, L2PcInstance actor, Object reference)
{
// Create and Init the L2ItemInstance corresponding to the Item Identifier
final L2ItemInstance item = new L2ItemInstance(IdFactory.getInstance().getNextId(), itemId);
if (process.equalsIgnoreCase("loot"))
{
ScheduledFuture<?> itemLootShedule;
if ((reference instanceof L2Attackable) && ((L2Attackable) reference).isRaid()) // loot privilege for raids
{
final L2Attackable raid = (L2Attackable) reference;
// if in CommandChannel and was killing a World/RaidBoss
if ((raid.getFirstCommandChannelAttacked() != null) && !Config.AUTO_LOOT_RAIDS)
{
item.setOwnerId(raid.getFirstCommandChannelAttacked().getLeaderObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), Config.LOOT_RAIDS_PRIVILEGE_INTERVAL);
item.setItemLootShedule(itemLootShedule);
}
}
else if (!Config.AUTO_LOOT || ((reference instanceof L2EventMonsterInstance) && ((L2EventMonsterInstance) reference).eventDropOnGround()))
{
item.setOwnerId(actor.getObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), 15000);
item.setItemLootShedule(itemLootShedule);
}
}
if (Config.DEBUG)
{
LOGGER.finer(getClass().getSimpleName() + ": Item created: " + item);
}
// Add the L2ItemInstance object to _allObjects of L2world
L2World.getInstance().storeObject(item);
// Set Item parameters
if (item.isStackable() && (count > 1))
{
item.setCount(count);
}
if (Config.LOG_ITEMS && !process.equals("Reset"))
{
if (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getId() == ADENA_ID))))
{
if (item.getEnchantLevel() > 0)
{
LOGGER_ITEMS.info("CREATE:" + process + ", item " + item.getObjectId() + ":+" + item.getEnchantLevel() + " " + item.getItem().getName() + "(" + item.getCount() + "), " + actor + ", " + reference);
}
else
{
LOGGER_ITEMS.info("CREATE:" + process + ", item " + item.getObjectId() + ":" + item.getItem().getName() + "(" + item.getCount() + "), " + actor + ", " + reference);
}
}
}
if (actor != null)
{
if (actor.isGM())
{
String referenceName = "no-reference";
if (reference instanceof L2Object)
{
referenceName = (((L2Object) reference).getName() != null ? ((L2Object) reference).getName() : "no-name");
}
else if (reference instanceof String)
{
referenceName = (String) reference;
}
final String targetName = (actor.getTarget() != null ? actor.getTarget().getName() : "no-target");
if (Config.GMAUDIT)
{
GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + itemId + " count: " + count + " name: " + item.getItemName() + " objId: " + item.getObjectId() + ")", targetName, "L2Object referencing this action is: " + referenceName);
}
}
}
// Notify to scripts
EventDispatcher.getInstance().notifyEventAsync(new OnItemCreate(process, item, actor, reference), item.getItem());
return item;
}
public L2ItemInstance createItem(String process, int itemId, int count, L2PcInstance actor)
{
return createItem(process, itemId, count, actor, null);
}
/**
* Destroys the L2ItemInstance.<br>
* <B><U> Actions</U> :</B>
* <ul>
* <li>Sets L2ItemInstance parameters to be unusable</li>
* <li>Removes the L2ItemInstance object to _allObjects of L2world</li>
* <li>Logs Item deletion according to log settings</li>
* </ul>
* @param process a string identifier of process triggering this action.
* @param item the item instance to be destroyed.
* @param actor the player requesting the item destroy.
* @param reference the object referencing current action like NPC selling item or previous item in transformation.
*/
public void destroyItem(String process, L2ItemInstance item, L2PcInstance actor, Object reference)
{
synchronized (item)
{
final long old = item.getCount();
item.setCount(0);
item.setOwnerId(0);
item.setItemLocation(ItemLocation.VOID);
item.setLastChange(L2ItemInstance.REMOVED);
L2World.getInstance().removeObject(item);
IdFactory.getInstance().releaseId(item.getObjectId());
if (Config.LOG_ITEMS)
{
if (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getId() == ADENA_ID))))
{
if (item.getEnchantLevel() > 0)
{
LOGGER_ITEMS.info("DELETE:" + process + ", item " + item.getObjectId() + ":+" + item.getEnchantLevel() + " " + item.getItem().getName() + "(" + item.getCount() + "), PrevCount(" + old + "), " + actor + ", " + reference);
}
else
{
LOGGER_ITEMS.info("DELETE:" + process + ", item " + item.getObjectId() + ":" + item.getItem().getName() + "(" + item.getCount() + "), PrevCount(" + old + "), " + actor + ", " + reference);
}
}
}
if (actor != null)
{
if (actor.isGM())
{
String referenceName = "no-reference";
if (reference instanceof L2Object)
{
referenceName = (((L2Object) reference).getName() != null ? ((L2Object) reference).getName() : "no-name");
}
else if (reference instanceof String)
{
referenceName = (String) reference;
}
final String targetName = (actor.getTarget() != null ? actor.getTarget().getName() : "no-target");
if (Config.GMAUDIT)
{
GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + item.getId() + " count: " + item.getCount() + " itemObjId: " + item.getObjectId() + ")", targetName, "L2Object referencing this action is: " + referenceName);
}
}
}
// if it's a pet control item, delete the pet as well
if (item.getItem().isPetItem())
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?"))
{
// Delete the pet in db
statement.setInt(1, item.getObjectId());
statement.execute();
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not delete pet objectid:", e);
}
}
}
}
public void reload()
{
load();
EnchantItemHPBonusData.getInstance().load();
}
protected static class ResetOwner implements Runnable
{
L2ItemInstance _item;
public ResetOwner(L2ItemInstance item)
{
_item = item;
}
@Override
public void run()
{
_item.setOwnerId(0);
_item.setItemLootShedule(null);
}
}
public Set<Integer> getAllArmorsId()
{
return _armors.keySet();
}
public Collection<L2Armor> getAllArmors()
{
return _armors.values();
}
public Set<Integer> getAllWeaponsId()
{
return _weapons.keySet();
}
public Collection<L2Weapon> getAllWeapons()
{
return _weapons.values();
}
public Set<Integer> getAllEtcItemsId()
{
return _etcItems.keySet();
}
public Collection<L2EtcItem> getAllEtcItems()
{
return _etcItems.values();
}
public L2Item[] getAllItems()
{
return _allTemplates;
}
public int getArraySize()
{
return _allTemplates.length;
}
private static class SingletonHolder
{
protected static final ItemTable _instance = new ItemTable();
}
}

View File

@ -0,0 +1,291 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.datatables;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.InstanceListManager;
import com.l2jmobius.gameserver.enums.TaxType;
import com.l2jmobius.gameserver.instancemanager.CastleManager;
import com.l2jmobius.gameserver.instancemanager.ZoneManager;
import com.l2jmobius.gameserver.model.actor.instance.L2MerchantInstance;
import com.l2jmobius.gameserver.model.entity.Castle;
/**
* @author KenM
*/
public class MerchantPriceConfigTable implements InstanceListManager
{
// Zoey76: TODO: Implement using IGameXmlReader.
private static Logger LOGGER = Logger.getLogger(MerchantPriceConfigTable.class.getName());
public static MerchantPriceConfigTable getInstance()
{
return SingletonHolder._instance;
}
private static final String MPCS_FILE = "MerchantPriceConfig.xml";
private final Map<Integer, MerchantPriceConfig> _mpcs = new HashMap<>();
private MerchantPriceConfig _defaultMpc;
public MerchantPriceConfig getMerchantPriceConfig(L2MerchantInstance npc)
{
for (MerchantPriceConfig mpc : _mpcs.values())
{
if (ZoneManager.getInstance().getRegion(npc).getZones().containsKey(mpc.getZoneId()))
{
return mpc;
}
}
return _defaultMpc;
}
public MerchantPriceConfig getMerchantPriceConfig(int id)
{
return _mpcs.get(id);
}
public void loadXML() throws SAXException, IOException, ParserConfigurationException
{
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
final File file = new File(Config.DATAPACK_ROOT + "/data/" + MPCS_FILE);
if (file.exists())
{
int defaultPriceConfigId;
final Document doc = factory.newDocumentBuilder().parse(file);
Node n = doc.getDocumentElement();
final Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
if (dpcNode == null)
{
throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
}
defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());
MerchantPriceConfig mpc;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{
mpc = parseMerchantPriceConfig(n);
if (mpc != null)
{
_mpcs.put(mpc.getId(), mpc);
}
}
final MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
if (defaultMpc == null)
{
throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
}
_defaultMpc = defaultMpc;
}
}
private MerchantPriceConfig parseMerchantPriceConfig(Node n)
{
if (n.getNodeName().equals("priceConfig"))
{
final int id;
final int baseTax;
int castleId = -1;
int zoneId = -1;
final String name;
Node node = n.getAttributes().getNamedItem("id");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'id'");
}
id = Integer.parseInt(node.getNodeValue());
node = n.getAttributes().getNamedItem("name");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'name'");
}
name = node.getNodeValue();
node = n.getAttributes().getNamedItem("baseTax");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'baseTax'");
}
baseTax = Integer.parseInt(node.getNodeValue());
node = n.getAttributes().getNamedItem("castleId");
if (node != null)
{
castleId = Integer.parseInt(node.getNodeValue());
}
node = n.getAttributes().getNamedItem("zoneId");
if (node != null)
{
zoneId = Integer.parseInt(node.getNodeValue());
}
return new MerchantPriceConfig(id, name, baseTax, castleId, zoneId);
}
return null;
}
@Override
public void loadInstances()
{
try
{
loadXML();
LOGGER.info("Loaded " + _mpcs.size() + " merchant price configs.");
}
catch (Exception e)
{
LOGGER.severe("Failed loading MerchantPriceConfigTable: " + e);
}
}
@Override
public void updateReferences()
{
for (MerchantPriceConfig mpc : _mpcs.values())
{
mpc.updateReferences();
}
}
@Override
public void activateInstances()
{
}
/**
* @author KenM
*/
public static final class MerchantPriceConfig
{
private final int _id;
private final String _name;
private final int _baseTax;
private final int _castleId;
private Castle _castle;
private final int _zoneId;
public MerchantPriceConfig(int id, String name, int baseTax, int castleId, int zoneId)
{
_id = id;
_name = name;
_baseTax = baseTax;
_castleId = castleId;
_zoneId = zoneId;
}
/**
* @return Returns the id.
*/
public int getId()
{
return _id;
}
/**
* @return Returns the name.
*/
public String getName()
{
return _name;
}
/**
* @return Returns the baseTax.
*/
public int getBaseTax()
{
return _baseTax;
}
/**
* @return Returns the baseTax / 100.0.
*/
public double getBaseTaxRate()
{
return _baseTax / 100.0;
}
/**
* @return Returns the castle.
*/
public Castle getCastle()
{
return _castle;
}
/**
* @return Returns the zoneId.
*/
public int getZoneId()
{
return _zoneId;
}
public boolean hasCastle()
{
return getCastle() != null;
}
public double getCastleTaxRate()
{
return hasCastle() ? getCastle().getTaxRate() : 0.0;
}
public int getTotalTax(TaxType taxType)
{
return hasCastle() ? (getCastle().getTaxPercent(taxType) + getBaseTax()) : getBaseTax();
}
public double getTotalTaxRate(TaxType taxType)
{
return getTotalTax(taxType) / 100.0;
}
public void updateReferences()
{
if (_castleId > 0)
{
_castle = CastleManager.getInstance().getCastleById(_castleId);
}
}
}
private static class SingletonHolder
{
protected static final MerchantPriceConfigTable _instance = new MerchantPriceConfigTable();
}
}

View File

@ -0,0 +1,342 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.datatables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.commons.database.DatabaseFactory;
import com.l2jmobius.gameserver.data.xml.impl.NpcData;
import com.l2jmobius.gameserver.model.L2Spawn;
import com.l2jmobius.gameserver.model.StatsSet;
import com.l2jmobius.gameserver.model.actor.templates.L2NpcTemplate;
/**
* Spawn data retriever.
* @author Zoey76
*/
public final class SpawnTable
{
private static final Logger LOGGER = Logger.getLogger(SpawnTable.class.getName());
// SQL
private static final String SELECT_CUSTOM_SPAWNS = "SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, respawn_random, loc_id, periodOfDay FROM custom_spawnlist";
private static final String INSERT_CUSTOM_SPAWN = "INSERT INTO custom_spawnlist (count,npc_templateid,locx,locy,locz,heading,respawn_delay,respawn_random,loc_id) values(?,?,?,?,?,?,?,?,?)";
private static final String DELETE_CUSTOM_SPAWN = "DELETE FROM custom_spawnlist WHERE locx=? AND locy=? AND locz=? AND npc_templateid=? AND heading=?";
private static final Map<Integer, Set<L2Spawn>> _spawnTable = new ConcurrentHashMap<>();
/**
* Wrapper to load all spawns.
*/
public void load()
{
if (!Config.ALT_DEV_NO_SPAWNS && Config.CUSTOM_SPAWNLIST_TABLE)
{
fillSpawnTable();
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _spawnTable.size() + " custom npc spawns.");
}
}
private boolean checkTemplate(int npcId)
{
final L2NpcTemplate npcTemplate = NpcData.getInstance().getTemplate(npcId);
if (npcTemplate == null)
{
LOGGER.warning(getClass().getSimpleName() + ": Data missing in NPC table for ID: " + npcId + ".");
return false;
}
if (npcTemplate.isType("L2SiegeGuard") || npcTemplate.isType("L2RaidBoss"))
{
// Don't spawn
return false;
}
return true;
}
/**
* Retrieves spawn data from database.
* @return the spawn count
*/
private int fillSpawnTable()
{
int npcSpawnCount = 0;
try (Connection con = DatabaseFactory.getInstance().getConnection();
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(SELECT_CUSTOM_SPAWNS))
{
while (rs.next())
{
final StatsSet spawnInfo = new StatsSet();
final int npcId = rs.getInt("npc_templateid");
// Check basic requirements first
if (!checkTemplate(npcId))
{
// Don't spawn
continue;
}
spawnInfo.set("npcTemplateid", npcId);
spawnInfo.set("count", rs.getInt("count"));
spawnInfo.set("x", rs.getInt("locx"));
spawnInfo.set("y", rs.getInt("locy"));
spawnInfo.set("z", rs.getInt("locz"));
spawnInfo.set("heading", rs.getInt("heading"));
spawnInfo.set("respawnDelay", rs.getInt("respawn_delay"));
spawnInfo.set("respawnRandom", rs.getInt("respawn_random"));
spawnInfo.set("locId", rs.getInt("loc_id"));
spawnInfo.set("periodOfDay", rs.getInt("periodOfDay"));
npcSpawnCount += addSpawn(spawnInfo);
}
}
catch (Exception e)
{
LOGGER.warning(getClass().getSimpleName() + ": Spawn could not be initialized: " + e);
}
return npcSpawnCount;
}
/**
* Creates NPC spawn
* @param spawnInfo StatsSet of spawn parameters
* @param AIData Map of specific AI parameters for this spawn
* @return count NPC instances, spawned by this spawn
*/
private int addSpawn(StatsSet spawnInfo, Map<String, Integer> AIData)
{
L2Spawn spawnDat;
int ret = 0;
try
{
spawnDat = new L2Spawn(spawnInfo.getInt("npcTemplateid"));
spawnDat.setAmount(spawnInfo.getInt("count", 1));
spawnDat.setX(spawnInfo.getInt("x", 0));
spawnDat.setY(spawnInfo.getInt("y", 0));
spawnDat.setZ(spawnInfo.getInt("z", 0));
spawnDat.setHeading(spawnInfo.getInt("heading", -1));
spawnDat.setRespawnDelay(spawnInfo.getInt("respawnDelay", 0), spawnInfo.getInt("respawnRandom", 0));
spawnDat.setLocationId(spawnInfo.getInt("locId", 0));
final String spawnName = spawnInfo.getString("spawnName", "");
if (!spawnName.isEmpty())
{
spawnDat.setName(spawnName);
}
addSpawn(spawnDat);
ret += spawnDat.init();
}
catch (Exception e)
{
// problem with initializing spawn, go to next one
LOGGER.warning(getClass().getSimpleName() + ": Spawn could not be initialized: " + e);
}
return ret;
}
/**
* Wrapper for {@link #addSpawn(StatsSet, Map)}.
* @param spawnInfo StatsSet of spawn parameters
* @return count NPC instances, spawned by this spawn
*/
private int addSpawn(StatsSet spawnInfo)
{
return addSpawn(spawnInfo, null);
}
/**
* Gets the spawn data.
* @return the spawn data
*/
public Map<Integer, Set<L2Spawn>> getSpawnTable()
{
return _spawnTable;
}
/**
* Gets the spawns for the NPC Id.
* @param npcId the NPC Id
* @return the spawn set for the given npcId
*/
public Set<L2Spawn> getSpawns(int npcId)
{
return _spawnTable.getOrDefault(npcId, Collections.emptySet());
}
/**
* Gets the spawn count for the given NPC ID.
* @param npcId the NPC Id
* @return the spawn count
*/
public int getSpawnCount(int npcId)
{
return getSpawns(npcId).size();
}
/**
* Gets a spawn for the given NPC ID.
* @param npcId the NPC Id
* @return a spawn for the given NPC ID or {@code null}
*/
public L2Spawn getAnySpawn(int npcId)
{
return getSpawns(npcId).stream().findFirst().orElse(null);
}
/**
* Adds a new spawn to the spawn table.
* @param spawn the spawn to add
* @param storeInDb if {@code true} it'll be saved in the database
*/
public void addNewSpawn(L2Spawn spawn, boolean storeInDb)
{
addSpawn(spawn);
if (storeInDb)
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement(INSERT_CUSTOM_SPAWN))
{
ps.setInt(1, spawn.getAmount());
ps.setInt(2, spawn.getId());
ps.setInt(3, spawn.getX());
ps.setInt(4, spawn.getY());
ps.setInt(5, spawn.getZ());
ps.setInt(6, spawn.getHeading());
ps.setInt(7, spawn.getRespawnDelay() / 1000);
ps.setInt(8, spawn.getRespawnMaxDelay() - spawn.getRespawnMinDelay());
ps.setInt(9, spawn.getLocationId());
ps.execute();
}
catch (Exception e)
{
LOGGER.warning(getClass().getSimpleName() + ": Could not store spawn in the DB: " + e);
}
}
}
/**
* Delete an spawn from the spawn table.
* @param spawn the spawn to delete
* @param updateDb if {@code true} database will be updated
*/
public void deleteSpawn(L2Spawn spawn, boolean updateDb)
{
if (!removeSpawn(spawn))
{
return;
}
if (updateDb)
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement(DELETE_CUSTOM_SPAWN))
{
ps.setInt(1, spawn.getX());
ps.setInt(2, spawn.getY());
ps.setInt(3, spawn.getZ());
ps.setInt(4, spawn.getId());
ps.setInt(5, spawn.getHeading());
ps.execute();
}
catch (Exception e)
{
LOGGER.warning(getClass().getSimpleName() + ": Spawn " + spawn + " could not be removed from DB: " + e);
}
}
}
/**
* Add a spawn to the spawn set if present, otherwise add a spawn set and add the spawn to the newly created spawn set.
* @param spawn the NPC spawn to add
*/
private void addSpawn(L2Spawn spawn)
{
_spawnTable.computeIfAbsent(spawn.getId(), k -> ConcurrentHashMap.newKeySet(1)).add(spawn);
}
/**
* Remove a spawn from the spawn set, if the spawn set is empty, remove it as well.
* @param spawn the NPC spawn to remove
* @return {@code true} if the spawn was successfully removed, {@code false} otherwise
*/
private boolean removeSpawn(L2Spawn spawn)
{
final Set<L2Spawn> set = _spawnTable.get(spawn.getId());
if (set != null)
{
final boolean removed = set.remove(spawn);
if (set.isEmpty())
{
_spawnTable.remove(spawn.getId());
}
set.forEach(this::notifyRemoved);
return removed;
}
notifyRemoved(spawn);
return false;
}
private void notifyRemoved(L2Spawn spawn)
{
if ((spawn != null) && (spawn.getLastSpawn() != null) && (spawn.getNpcSpawnTemplate() != null))
{
spawn.getNpcSpawnTemplate().notifyDespawnNpc(spawn.getLastSpawn());
}
}
/**
* Execute a procedure over all spawns.<br>
* <font size="4" color="red">Do not use it!</font>
* @param function the function to execute
* @return {@code true} if all procedures were executed, {@code false} otherwise
*/
public boolean forEachSpawn(Function<L2Spawn, Boolean> function)
{
for (Set<L2Spawn> set : _spawnTable.values())
{
for (L2Spawn spawn : set)
{
if (!function.apply(spawn))
{
return false;
}
}
}
return true;
}
public static SpawnTable getInstance()
{
return SingletonHolder._instance;
}
private static class SingletonHolder
{
protected static final SpawnTable _instance = new SpawnTable();
}
}