Noticias:

No tienes permiso para ver los enlaces. Para poder verlos Registrate o Conectate.

Menú Principal

Item Auction Bid

Iniciado por Swarlog, Jul 26, 2025, 10:43 PM

Tema anterior - Siguiente tema

Swarlog

No puedes ver este adjunto.

CitarCORE:

com.l2jserver.gameserver.model.intemauct.ItemAuctionInstance

/*
 * 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.l2jserver.gameserver.model.itemauction;

import gnu.trove.TIntObjectHashMap;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import com.l2jserver.Config;
import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.datatables.CharNameTable;
import com.l2jserver.gameserver.instancemanager.ItemAuctionManager;
import com.l2jserver.gameserver.model.L2ItemInstance;
import com.l2jserver.gameserver.model.L2ItemInstance.ItemLocation;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.templates.StatsSet;
import com.l2jserver.util.Rnd;

public final class ItemAuctionInstance
{
	static final Logger _log = Logger.getLogger(ItemAuctionInstance.class.getName());
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss dd.MM.yy");
	
	private static final long START_TIME_SPACE = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
	private static final long FINISH_TIME_SPACE = TimeUnit.MILLISECONDS.convert(10, TimeUnit.MINUTES);
	
	private final int _instanceId;
	private final AtomicInteger _auctionIds;
	private final TIntObjectHashMap<ItemAuction> _auctions;
	private final ArrayList<AuctionItem> _items;
	private final AuctionDateGenerator _dateGenerator;
	
	private ItemAuction _currentAuction;
	private ItemAuction _nextAuction;
	private ScheduledFuture<?> _stateTask;
	
	public ItemAuctionInstance(final int instanceId, final AtomicInteger auctionIds, final Node node) throws Exception
	{
		_instanceId = instanceId;
		_auctionIds = auctionIds;
		_auctions = new TIntObjectHashMap<ItemAuction>();
		_items = new ArrayList<AuctionItem>();
		
		final NamedNodeMap nanode = node.getAttributes();
		final StatsSet generatorConfig = new StatsSet();
		for (int i = nanode.getLength(); i-- > 0;)
		{
			final Node n = nanode.item(i);
			if (n != null)
				generatorConfig.set(n.getNodeName(), n.getNodeValue());
		}
		
		_dateGenerator = new AuctionDateGenerator(generatorConfig);
		
		for (Node na = node.getFirstChild(); na != null; na = na.getNextSibling())
		{
			try
			{
				if ("item".equalsIgnoreCase(na.getNodeName()))
				{
					final NamedNodeMap naa = na.getAttributes();
					final int auctionItemId = Integer.parseInt(naa.getNamedItem("auctionItemId").getNodeValue());
					final int auctionLenght = Integer.parseInt(naa.getNamedItem("auctionLenght").getNodeValue());
					final long auctionInitBid = Integer.parseInt(naa.getNamedItem("auctionInitBid").getNodeValue());
					
					final int itemId = Integer.parseInt(naa.getNamedItem("itemId").getNodeValue());
					final int itemCount = Integer.parseInt(naa.getNamedItem("itemCount").getNodeValue());
					
					if (auctionLenght < 1)
						throw new IllegalArgumentException("auctionLenght < 1 for instanceId: " + _instanceId + ", itemId " + itemId);
					
					final StatsSet itemExtra = new StatsSet();
					final AuctionItem item = new AuctionItem(auctionItemId, auctionLenght, auctionInitBid, itemId, itemCount, itemExtra);
					
					if (!item.checkItemExists())
						throw new IllegalArgumentException("Item with id " + itemId + " not found");
					
					for (final AuctionItem tmp : _items)
					{
						if (tmp.getAuctionItemId() == auctionItemId)
							throw new IllegalArgumentException("Dublicated auction item id " + auctionItemId);
					}
					
					_items.add(item);
					
					for (Node nb = na.getFirstChild(); nb != null; nb = nb.getNextSibling())
					{
						if ("extra".equalsIgnoreCase(nb.getNodeName()))
						{
							final NamedNodeMap nab = nb.getAttributes();
							for (int i = nab.getLength(); i-- > 0;)
							{
								final Node n = nab.item(i);
								if (n != null)
									itemExtra.set(n.getNodeName(), n.getNodeValue());
							}
						}
					}
				}
			}
			catch (final IllegalArgumentException e)
			{
				_log.log(Level.WARNING, "ItemAuctionInstance: Failed loading auction item", e);
			}
		}
		
		if (_items.isEmpty())
			throw new IllegalArgumentException("No items defined");
		
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT auctionId FROM item_auction WHERE instanceId=?");
			statement.setInt(1, _instanceId);
			ResultSet rset = statement.executeQuery();
			
			while (rset.next())
			{
				final int auctionId = rset.getInt(1);
				try
				{
					final ItemAuction auction = loadAuction(auctionId);
					if (auction != null)
					{
						_auctions.put(auctionId, auction);
					}
					else
					{
						ItemAuctionManager.deleteAuction(auctionId);
					}
				}
				catch (final SQLException e)
				{
					_log.log(Level.WARNING, "ItemAuctionInstance: Failed loading auction: " + auctionId, e);
				}
			}
		}
		catch (final SQLException e)
		{
			_log.log(Level.SEVERE, "L2ItemAuctionInstance: Failed loading auctions.", e);
			return;
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
		
		_log.log(Level.INFO, "L2ItemAuctionInstance: Loaded " + _items.size() + " item(s) and registered " + _auctions.size() + " auction(s) for instance " + _instanceId + ".");
		checkAndSetCurrentAndNextAuction();
	}
	
	public final ItemAuction getCurrentAuction()
	{
		return _currentAuction;
	}
	
	public final ItemAuction getNextAuction()
	{
		return _nextAuction;
	}
	
	public final void shutdown()
	{
		final ScheduledFuture<?> stateTask = _stateTask;
		if (stateTask != null)
			stateTask.cancel(false);
	}
	
	private final AuctionItem getAuctionItem(final int auctionItemId)
	{
		for (int i = _items.size(); i-- > 0;)
		{
			final AuctionItem item = _items.get(i);
			if (item.getAuctionItemId() == auctionItemId)
				return item;
		}
		return null;
	}
	
	final void checkAndSetCurrentAndNextAuction()
	{
		final ItemAuction[] auctions = _auctions.getValues(new ItemAuction[_auctions.size()]);
		
		ItemAuction currentAuction = null;
		ItemAuction nextAuction = null;
		
		switch (auctions.length)
		{
			case 0:
			{
				nextAuction = createAuction(System.currentTimeMillis() + START_TIME_SPACE);
				break;
			}
			
			case 1:
			{
				switch (auctions[0].getAuctionState())
				{
					case CREATED:
					{
						if (auctions[0].getStartingTime() < (System.currentTimeMillis() + START_TIME_SPACE))
						{
							currentAuction = auctions[0];
							nextAuction = createAuction(System.currentTimeMillis() + START_TIME_SPACE);
						}
						else
						{
							nextAuction = auctions[0];
						}
						break;
					}
					
					case STARTED:
					{
						currentAuction = auctions[0];
						nextAuction = createAuction(Math.max(currentAuction.getEndingTime() + FINISH_TIME_SPACE, System.currentTimeMillis() + START_TIME_SPACE));
						break;
					}
					
					case FINISHED:
					{
						currentAuction = auctions[0];
						nextAuction = createAuction(System.currentTimeMillis() + START_TIME_SPACE);
						break;
					}
					
					default:
						throw new IllegalArgumentException();
				}
				break;
			}
			
			default:
			{
				Arrays.sort(auctions, new Comparator<ItemAuction>() {
					@Override
					//TODO REMOVE override maybe
					public final int compare(final ItemAuction o1, final ItemAuction o2)
					{
						return ((Long) o2.getStartingTime()).compareTo(o1.getStartingTime());
					}
				});
				
				// just to make sure we won`t skip any auction because of little different times
				final long currentTime = System.currentTimeMillis();
				
				for (int i = 0; i < auctions.length; i++)
				{
					final ItemAuction auction = auctions[i];
					if (auction.getAuctionState() == ItemAuctionState.STARTED)
					{
						currentAuction = auction;
						break;
					}
					else if (auction.getStartingTime() <= currentTime)
					{
						currentAuction = auction;
						break; // only first
					}
				}
				
				for (int i = 0; i < auctions.length; i++)
				{
					final ItemAuction auction = auctions[i];
					if (auction.getStartingTime() > currentTime && currentAuction != auction)
					{
						nextAuction = auction;
						break;
					}
				}
				
				if (nextAuction == null)
					nextAuction = createAuction(System.currentTimeMillis() + START_TIME_SPACE);
				break;
			}
		}
		
		_auctions.put(nextAuction.getAuctionId(), nextAuction);
		
		_currentAuction = currentAuction;
		_nextAuction = nextAuction;
		
		if (currentAuction != null && currentAuction.getAuctionState() != ItemAuctionState.FINISHED)
		{
			if (currentAuction.getAuctionState() == ItemAuctionState.STARTED)
				setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleAuctionTask(currentAuction), Math.max(currentAuction.getEndingTime() - System.currentTimeMillis(), 0L)));
			else
				setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleAuctionTask(currentAuction), Math.max(currentAuction.getStartingTime() - System.currentTimeMillis(), 0L)));
			_log.log(Level.INFO, "L2ItemAuctionInstance: Schedule current auction " + currentAuction.getAuctionId() + " for instance " + _instanceId);
		}
		else
		{
			setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleAuctionTask(nextAuction), Math.max(nextAuction.getStartingTime() - System.currentTimeMillis(), 0L)));
			_log.log(Level.INFO, "L2ItemAuctionInstance: Schedule next auction " + nextAuction.getAuctionId() + " on " + DATE_FORMAT.format(new Date(nextAuction.getStartingTime())) + " for instance " + _instanceId);
		}
	}
	
	public final ItemAuction getAuction(final int auctionId)
	{
		return _auctions.get(auctionId);
	}
	
	public final ItemAuction[] getAuctionsByBidder(final int bidderObjId)
	{
		final ItemAuction[] auctions = getAuctions();
		final ArrayList<ItemAuction> stack = new ArrayList<ItemAuction>(auctions.length);
		for (final ItemAuction auction : getAuctions())
		{
			if (auction.getAuctionState() != ItemAuctionState.CREATED)
			{
				final ItemAuctionBid bid = auction.getBidFor(bidderObjId);
				if (bid != null)
					stack.add(auction);
			}
		}
		return stack.toArray(new ItemAuction[stack.size()]);
	}
	
	public final ItemAuction[] getAuctions()
	{
		final ItemAuction[] auctions;
		
		synchronized (_auctions)
		{
			auctions = _auctions.getValues(new ItemAuction[_auctions.size()]);
		}
		
		return auctions;
	}
	
	private final class ScheduleAuctionTask implements Runnable
	{
		private final ItemAuction _auction;
		
		public ScheduleAuctionTask(final ItemAuction auction)
		{
			_auction = auction;
		}
		
		@Override
		public final void run()
		{
			try
			{
				runImpl();
			}
			catch (final Exception e)
			{
				_log.log(Level.SEVERE, "L2ItemAuctionInstance: Failed scheduling auction " + _auction.getAuctionId(), e);
			}
		}
		
		private final void runImpl() throws Exception
		{
			final ItemAuctionState state = _auction.getAuctionState();
			switch (state)
			{
				case CREATED:
				{
					if (!_auction.setAuctionState(state, ItemAuctionState.STARTED))
						throw new IllegalStateException("Could not set auction state: " + ItemAuctionState.STARTED.toString() + ", expected: " + state.toString());
					
					_log.log(Level.INFO, "L2ItemAuctionInstance: Auction " + _auction.getAuctionId() + " has started for instance " + _auction.getInstanceId());
					checkAndSetCurrentAndNextAuction();
					break;
				}
				
				case STARTED:
				{
					switch (_auction.getAuctionEndingExtendState())
					{
						case EXTEND_BY_5_MIN:
						{
							if (_auction.getScheduledAuctionEndingExtendState() == ItemAuctionExtendState.INITIAL)
							{
								_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_5_MIN);
								setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
								return;
							}
							break;
						}
						
						case EXTEND_BY_3_MIN:
						{
							if (_auction.getScheduledAuctionEndingExtendState() != ItemAuctionExtendState.EXTEND_BY_3_MIN)
							{
								_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_3_MIN);
								setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
								return;
							}
							break;
						}
						
						case EXTEND_BY_CONFIG_PHASE_A:
						{
							if (_auction.getScheduledAuctionEndingExtendState() != ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_B)
							{
								_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_B);
								setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
								return;
							}
							break;
						}
						
						case EXTEND_BY_CONFIG_PHASE_B:
						{
							if (_auction.getScheduledAuctionEndingExtendState() != ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A)
							{
								_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A);
								setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
								return;
							}
						}
					}
					
					if (!_auction.setAuctionState(state, ItemAuctionState.FINISHED))
						throw new IllegalStateException("Could not set auction state: " + ItemAuctionState.FINISHED.toString() + ", expected: " + state.toString());
					
					onAuctionFinished(_auction);
					checkAndSetCurrentAndNextAuction();
					break;
				}
				
				default:
					throw new IllegalStateException("Invalid state: " + state);
			}
		}
	}
	
	final void onAuctionFinished(final ItemAuction auction)
	{
		auction.broadcastToAllBiddersInternal(new SystemMessage(SystemMessageId.S1_AUCTION_ENDED).addNumber(auction.getAuctionId()));
		
		final ItemAuctionBid bid = auction.getHighestBid();
		if (bid != null)
		{
			final L2ItemInstance item = auction.createNewItemInstance();
			final L2PcInstance player = bid.getPlayer();
			if (player != null)
			{
				player.getWarehouse().addItem("ItemAuction", item, null, null);
				player.sendPacket(new SystemMessage(SystemMessageId.WON_BID_ITEM_CAN_BE_FOUND_IN_WAREHOUSE));
				
				_log.log(Level.INFO, "L2ItemAuctionInstance: Auction " + auction.getAuctionId() + " has finished. Highest bid by " + player.getName() + " for instance " + _instanceId);
			}
			else
			{
				item.setOwnerId(bid.getPlayerObjId());
				item.setLocation(ItemLocation.WAREHOUSE);
				item.updateDatabase();
				L2World.getInstance().removeObject(item);
				
				_log.log(Level.INFO, "L2ItemAuctionInstance: Auction " + auction.getAuctionId() + " has finished. Highest bid by " + CharNameTable.getInstance().getNameById(bid.getPlayerObjId()) + " for instance " + _instanceId);
			}
			
			// Clean all canceled bids
			auction.clearCanceledBids();
		}
		else
		{
			_log.log(Level.INFO, "L2ItemAuctionInstance: Auction " + auction.getAuctionId() + " has finished. There have not been any bid for instance " + _instanceId);
		}
	}
	
	final void setStateTask(final ScheduledFuture<?> future)
	{
		final ScheduledFuture<?> stateTask = _stateTask;
		if (stateTask != null)
			stateTask.cancel(false);
		
		_stateTask = future;
	}
	
	private final ItemAuction createAuction(final long after)
	{
		final AuctionItem auctionItem = _items.get(Rnd.get(_items.size()));
		final long startingTime = _dateGenerator.nextDate(after);
		final long endingTime = startingTime + TimeUnit.MILLISECONDS.convert(auctionItem.getAuctionLength(), TimeUnit.MINUTES);
		final ItemAuction auction = new ItemAuction(_auctionIds.getAndIncrement(), _instanceId, startingTime, endingTime, auctionItem);
		auction.storeMe();
		return auction;
	}
	
	private final ItemAuction loadAuction(final int auctionId) throws SQLException
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT auctionItemId,startingTime,endingTime,auctionStateId FROM item_auction WHERE auctionId=?");
			statement.setInt(1, auctionId);
			ResultSet rset = statement.executeQuery();
			
			if (!rset.next())
			{
				_log.log(Level.WARNING, "ItemAuctionInstance: Auction data not found for auction: " + auctionId);
				return null;
			}
			
			final int auctionItemId = rset.getInt(1);
			final long startingTime = rset.getLong(2);
			final long endingTime = rset.getLong(3);
			final byte auctionStateId = rset.getByte(4);
			statement.close();
			
			if (startingTime >= endingTime)
			{
				_log.log(Level.WARNING, "ItemAuctionInstance: Invalid starting/ending paramaters for auction: " + auctionId);
				return null;
			}
			
			final AuctionItem auctionItem = getAuctionItem(auctionItemId);
			if (auctionItem == null)
			{
				_log.log(Level.WARNING, "ItemAuctionInstance: AuctionItem: " + auctionItemId + ", not found for auction: " + auctionId);
				return null;
			}
			
			final ItemAuctionState auctionState = ItemAuctionState.stateForStateId(auctionStateId);
			if (auctionState == null)
			{
				_log.log(Level.WARNING, "ItemAuctionInstance: Invalid auctionStateId: " + auctionStateId + ", for auction: " + auctionId);
				return null;
			}
			
			if (auctionState == ItemAuctionState.FINISHED
					&& startingTime < System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(Config.ALT_ITEM_AUCTION_EXPIRED_AFTER, TimeUnit.DAYS))
			{
				_log.log(Level.INFO, "ItemAuctionInstance: Clearing expired auction: " + auctionId);
				statement = con.prepareStatement("DELETE FROM item_auction WHERE auctionId=?");
				statement.setInt(1, auctionId);
				statement.execute();
				statement.close();
				
				statement = con.prepareStatement("DELETE FROM item_auction_bid WHERE auctionId=?");
				statement.setInt(1, auctionId);
				statement.execute();
				statement.close();
				return null;
			}
			
			statement = con.prepareStatement("SELECT playerObjId,playerBid FROM item_auction_bid WHERE auctionId=?");
			statement.setInt(1, auctionId);
			rset = statement.executeQuery();
			
			final ArrayList<ItemAuctionBid> auctionBids = new ArrayList<ItemAuctionBid>();
			
			while (rset.next())
			{
				final int playerObjId = rset.getInt(1);
				final long playerBid = rset.getLong(2);
				final ItemAuctionBid bid = new ItemAuctionBid(playerObjId, playerBid);
				auctionBids.add(bid);
			}
			
			return new ItemAuction(auctionId, _instanceId, startingTime, endingTime, auctionItem, auctionBids, auctionState);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}
}

com.l2jserver.gameserver.model.itemauction.ItemAuctionState

/*
 * 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.l2jserver.gameserver.model.itemauction;

/**
 * @author Forsaiken
 */
public enum ItemAuctionState
{
	CREATED((byte)0),
	STARTED((byte)1),
	FINISHED((byte)2);
	
	private final byte _stateId;
	
	private ItemAuctionState(final byte stateId)
	{
		_stateId = stateId;
	}
	
	public byte getStateId()
	{
		return _stateId;
	}
	
	public static final ItemAuctionState stateForStateId(final byte stateId)
	{
		for (final ItemAuctionState state : ItemAuctionState.values())
		{
			if (state.getStateId() == stateId)
				return state;
		}
		return null;
	}
}

com.l2jserver.gameserver.model.itemauction.ItemAuctionBid

/*
 * 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.l2jserver.gameserver.model.itemauction;

import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;

/**
 * @author Forsaiken
 */
public final class ItemAuctionBid
{
	private final int _playerObjId;
	private long _lastBid;
	
	public ItemAuctionBid(final int playerObjId, final long lastBid)
	{
		_playerObjId = playerObjId;
		_lastBid = lastBid;
	}
	
	public final int getPlayerObjId()
	{
		return _playerObjId;
	}
	
	public final long getLastBid()
	{
		return _lastBid;
	}
	
	final void setLastBid(final long lastBid)
	{
		_lastBid = lastBid;
	}
	
	final void cancelBid()
	{
		_lastBid = -1;
	}
	
	final boolean isCanceled()
	{
		return _lastBid <= 0;
	}
	
	final L2PcInstance getPlayer()
	{
		return L2World.getInstance().getPlayer(_playerObjId);
	}
}

com.l2jserver.gameserver.model.itemauction.ItemAuction

/*
 * 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.l2jserver.gameserver.model.itemauction;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.l2jserver.Config;
import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.instancemanager.ItemAuctionManager;
import com.l2jserver.gameserver.model.ItemInfo;
import com.l2jserver.gameserver.model.L2ItemInstance;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.L2GameServerPacket;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;

/**
 * @author Forsaiken
 */
public final class ItemAuction
{
	static final Logger _log = Logger.getLogger(ItemAuctionManager.class.getName());
	private static final long ENDING_TIME_EXTEND_5 = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES);
	private static final long ENDING_TIME_EXTEND_3 = TimeUnit.MILLISECONDS.convert(3, TimeUnit.MINUTES);
	
	private final int _auctionId;
	private final int _instanceId;
	private final long _startingTime;
	private volatile long _endingTime;
	private final AuctionItem _auctionItem;
	private final ArrayList<ItemAuctionBid> _auctionBids;
	private final Object _auctionStateLock;
	
	private volatile ItemAuctionState _auctionState;
	private volatile ItemAuctionExtendState _scheduledAuctionEndingExtendState;
	private volatile ItemAuctionExtendState _auctionEndingExtendState;
	
	private final ItemInfo _itemInfo;
	
	private ItemAuctionBid _highestBid;
	private int _lastBidPlayerObjId;
	
	public ItemAuction(final int auctionId, final int instanceId, final long startingTime, final long endingTime, final AuctionItem auctionItem)
	{
		this(auctionId, instanceId, startingTime, endingTime, auctionItem, new ArrayList<ItemAuctionBid>(), ItemAuctionState.CREATED);
	}
	
	public ItemAuction(final int auctionId, final int instanceId, final long startingTime, final long endingTime, final AuctionItem auctionItem, final ArrayList<ItemAuctionBid> auctionBids, final ItemAuctionState auctionState)
	{
		_auctionId = auctionId;
		_instanceId = instanceId;
		_startingTime = startingTime;
		_endingTime = endingTime;
		_auctionItem = auctionItem;
		_auctionBids = auctionBids;
		_auctionState = auctionState;
		_auctionStateLock = new Object();
		_scheduledAuctionEndingExtendState = ItemAuctionExtendState.INITIAL;
		_auctionEndingExtendState = ItemAuctionExtendState.INITIAL;
		
		final L2ItemInstance item  = _auctionItem.createNewItemInstance();
		_itemInfo = new ItemInfo(item);
		L2World.getInstance().removeObject(item);
		
		for (final ItemAuctionBid bid : _auctionBids)
		{
			if (_highestBid == null || _highestBid.getLastBid() < bid.getLastBid())
				_highestBid = bid;
		}
	}
	
	public final ItemAuctionState getAuctionState()
	{
		final ItemAuctionState auctionState;
		
		synchronized (_auctionStateLock)
		{
			auctionState = _auctionState;
		}
		
		return auctionState;
	}
	
	public final boolean setAuctionState(final ItemAuctionState expected, final ItemAuctionState wanted)
	{
		synchronized (_auctionStateLock)
		{
			if (_auctionState != expected)
				return false;
			
			_auctionState = wanted;
			storeMe();
			return true;
		}
	}
	
	public final int getAuctionId()
	{
		return _auctionId;
	}
	
	public final int getInstanceId()
	{
		return _instanceId;
	}
	
	public final ItemInfo getItemInfo()
	{
		return _itemInfo;
	}
	
	public final L2ItemInstance createNewItemInstance()
	{
		return _auctionItem.createNewItemInstance();
	}
	
	public final long getAuctionInitBid()
	{
		return _auctionItem.getAuctionInitBid();
	}
	
	public final ItemAuctionBid getHighestBid()
	{
		return _highestBid;
	}
	
	public final ItemAuctionExtendState getAuctionEndingExtendState()
	{
		return _auctionEndingExtendState;
	}
	
	public final ItemAuctionExtendState getScheduledAuctionEndingExtendState()
	{
		return _scheduledAuctionEndingExtendState;
	}
	
	public final void setScheduledAuctionEndingExtendState(ItemAuctionExtendState state)
	{
		_scheduledAuctionEndingExtendState = state;
	}
	
	public final long getStartingTime()
	{
		return _startingTime;
	}
	
	public final long getEndingTime()
	{
		return _endingTime;
	}
	
	public final long getStartingTimeRemaining()
	{
		return Math.max(getEndingTime() - System.currentTimeMillis(), 0L);
	}
	
	public final long getFinishingTimeRemaining()
	{
		return Math.max(getEndingTime() - System.currentTimeMillis(), 0L);
	}
	
	public final void storeMe()
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("INSERT INTO item_auction (auctionId,instanceId,auctionItemId,startingTime,endingTime,auctionStateId) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE auctionStateId=?");
			statement.setInt(1, _auctionId);
			statement.setInt(2, _instanceId);
			statement.setInt(3, _auctionItem.getAuctionItemId());
			statement.setLong(4, _startingTime);
			statement.setLong(5, _endingTime);
			statement.setByte(6, _auctionState.getStateId());
			statement.setByte(7, _auctionState.getStateId());
			statement.execute();
			statement.close();
		}
		catch (final SQLException e)
		{
			_log.log(Level.WARNING, "", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}
	
	public final int getAndSetLastBidPlayerObjectId(final int playerObjId)
	{
		final int lastBid = _lastBidPlayerObjId;
		_lastBidPlayerObjId = playerObjId;
		return lastBid;
	}
	
	private final void updatePlayerBid(final ItemAuctionBid bid, final boolean delete)
	{
		// TODO nBd maybe move such stuff to you db updater :D
		updatePlayerBidInternal(bid, delete);
	}
	
	final void updatePlayerBidInternal(final ItemAuctionBid bid, final boolean delete)
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			final PreparedStatement statement;
			
			if (delete)
			{
				statement = con.prepareStatement("DELETE FROM item_auction_bid WHERE auctionId=? AND playerObjId=?");
				statement.setInt(1, _auctionId);
				statement.setInt(2, bid.getPlayerObjId());
			}
			else
			{
				statement = con.prepareStatement("INSERT INTO item_auction_bid (auctionId,playerObjId,playerBid) VALUES (?,?,?) ON DUPLICATE KEY UPDATE playerBid=?");
				statement.setInt(1, _auctionId);
				statement.setInt(2, bid.getPlayerObjId());
				statement.setLong(3, bid.getLastBid());
				statement.setLong(4, bid.getLastBid());
			}
			
			statement.execute();
			statement.close();
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}
	
	public final void registerBid(final L2PcInstance player, final long newBid)
	{
		if (player == null)
			throw new NullPointerException();
		
		if (newBid < getAuctionInitBid())
		{
			player.sendPacket(new SystemMessage(SystemMessageId.BID_PRICE_MUST_BE_HIGHER));
			return;
		}
		
		if (newBid > 100000000000L)
		{
			player.sendPacket(new SystemMessage(SystemMessageId.BID_CANT_EXCEED_100_BILLION));
			return;
		}
		
		if (getAuctionState() != ItemAuctionState.STARTED)
			return;
		
		final int playerObjId = player.getObjectId();
		
		synchronized (_auctionBids)
		{
			if (_highestBid != null && newBid < _highestBid.getLastBid())
			{
				player.sendPacket(new SystemMessage(SystemMessageId.BID_MUST_BE_HIGHER_THAN_CURRENT_BID));
				return;
			}
			
			ItemAuctionBid bid = getBidFor(playerObjId);
			if (bid == null)
			{
				if (!reduceItemCount(player, newBid))
				{
					player.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_ADENA_FOR_THIS_BID));
					return;
				}
				
				bid = new ItemAuctionBid(playerObjId, newBid);
				_auctionBids.add(bid);
			}
			else
			{
				if (!bid.isCanceled())
				{
					if (newBid < bid.getLastBid()) // just another check
					{
						player.sendPacket(new SystemMessage(SystemMessageId.BID_MUST_BE_HIGHER_THAN_CURRENT_BID));
						return;
					}
					
					if (!reduceItemCount(player, newBid - bid.getLastBid()))
					{
						player.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_ADENA_FOR_THIS_BID));
						return;
					}
				}
				else if (!reduceItemCount(player, newBid))
				{
					player.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_ADENA_FOR_THIS_BID));
					return;
				}
				
				bid.setLastBid(newBid);
			}
			
			onPlayerBid(player, bid);
			updatePlayerBid(bid, false);
			
			player.sendPacket(new SystemMessage(SystemMessageId.SUBMITTED_A_BID).addItemNumber(newBid));
			return;
		}
	}
	
	private final void onPlayerBid(final L2PcInstance player, final ItemAuctionBid bid)
	{
		if (_highestBid == null)
		{
			_highestBid = bid;
		}
		else if (_highestBid.getLastBid() < bid.getLastBid())
		{
			final L2PcInstance old = _highestBid.getPlayer();
			if (old != null)
				old.sendPacket(new SystemMessage(SystemMessageId.YOU_HAVE_BEEN_OUTBID));
			
			_highestBid = bid;
		}
		
		if (getEndingTime() - System.currentTimeMillis() <= (1000 * 60 * 10)) // 10 minutes
		{
			switch (_auctionEndingExtendState)
			{
				case INITIAL:
				{
					_auctionEndingExtendState = ItemAuctionExtendState.EXTEND_BY_5_MIN;
					_endingTime += ENDING_TIME_EXTEND_5;
					broadcastToAllBidders(new SystemMessage(SystemMessageId.BIDDER_EXISTS_AUCTION_TIME_EXTENDED_BY_5_MINUTES));
					break;
				}
				case EXTEND_BY_5_MIN:
				{
					if (getAndSetLastBidPlayerObjectId(player.getObjectId()) != player.getObjectId())
					{
						_auctionEndingExtendState = ItemAuctionExtendState.EXTEND_BY_3_MIN;
						_endingTime += ENDING_TIME_EXTEND_3;
						broadcastToAllBidders(new SystemMessage(SystemMessageId.BIDDER_EXISTS_AUCTION_TIME_EXTENDED_BY_3_MINUTES));
					}
					break;
				}
				case EXTEND_BY_3_MIN:
					if (Config.ALT_ITEM_AUCTION_TIME_EXTENDS_ON_BID > 0)
					{
						if (getAndSetLastBidPlayerObjectId(player.getObjectId()) != player.getObjectId())
						{
							_auctionEndingExtendState = ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A;
							_endingTime += Config.ALT_ITEM_AUCTION_TIME_EXTENDS_ON_BID;
						}
					}
					break;
				case EXTEND_BY_CONFIG_PHASE_A:
				{
					if (getAndSetLastBidPlayerObjectId(player.getObjectId()) != player.getObjectId())
					{
						if (_scheduledAuctionEndingExtendState == ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_B)
						{
							_auctionEndingExtendState = ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_B;
							_endingTime += Config.ALT_ITEM_AUCTION_TIME_EXTENDS_ON_BID;
						}
					}
					break;
				}
				case EXTEND_BY_CONFIG_PHASE_B:
				{
					if (getAndSetLastBidPlayerObjectId(player.getObjectId()) != player.getObjectId())
					{
						if (_scheduledAuctionEndingExtendState == ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A)
						{
							_endingTime += Config.ALT_ITEM_AUCTION_TIME_EXTENDS_ON_BID;
							_auctionEndingExtendState = ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A;
						}
					}
				}
			}
		}
	}
	
	public final void broadcastToAllBidders(final L2GameServerPacket packet)
	{
		ThreadPoolManager.getInstance().executeTask(new Runnable()
		{
			@Override
			public final void run()
			{
				broadcastToAllBiddersInternal(packet);
			}
		});
	}
	
	public final void broadcastToAllBiddersInternal(final L2GameServerPacket packet)
	{
		for (int i = _auctionBids.size(); i-- > 0;)
		{
			final ItemAuctionBid bid = _auctionBids.get(i);
			if (bid != null)
			{
				final L2PcInstance player = bid.getPlayer();
				if (player != null)
					player.sendPacket(packet);
			}
		}
	}
	
	public final boolean cancelBid(final L2PcInstance player)
	{
		if (player == null)
			throw new NullPointerException();
		
		switch (getAuctionState())
		{
			case CREATED:
				return false;
				
			case FINISHED:
				if (_startingTime < System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(Config.ALT_ITEM_AUCTION_EXPIRED_AFTER, TimeUnit.DAYS))
					return false;
				else
					break;
		}
		
		final int playerObjId = player.getObjectId();
		
		synchronized (_auctionBids)
		{
			if (_highestBid == null)
				return false;
			
			final int bidIndex = getBidIndexFor(playerObjId);
			if (bidIndex == -1)
				return false;
			
			final ItemAuctionBid bid = _auctionBids.get(bidIndex);
			if (bid.getPlayerObjId() == _highestBid.getPlayerObjId())
			{
				// can't return winning bid
				if (getAuctionState() == ItemAuctionState.FINISHED)
					return false;
				
				player.sendPacket(new SystemMessage(SystemMessageId.HIGHEST_BID_BUT_RESERVE_NOT_MET));
				return true;
			}
			
			if (bid.isCanceled())
				return false;
			
			increaseItemCount(player, bid.getLastBid());
			bid.cancelBid();
			
			// delete bid from database if auction already finished
			updatePlayerBid(bid, getAuctionState() == ItemAuctionState.FINISHED);
			
			player.sendPacket(new SystemMessage(SystemMessageId.CANCELED_BID));
		}
		return true;
	}
	
	public final void clearCanceledBids()
	{
		if (getAuctionState() != ItemAuctionState.FINISHED)
			throw new IllegalStateException("Attempt to clear canceled bids for non-finished auction");
		
		synchronized (_auctionBids)
		{
			for (ItemAuctionBid bid : _auctionBids)
			{
				if (bid == null || !bid.isCanceled())
					continue;
				updatePlayerBid(bid, true);
			}
		}
	}
	
	private final boolean reduceItemCount(final L2PcInstance player, final long count)
	{
		if (!player.reduceAdena("ItemAuction", count, player, true))
		{
			player.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_ADENA_FOR_THIS_BID));
			return false;
		}
		return true;
	}
	
	private final void increaseItemCount(final L2PcInstance player, final long count)
	{
		player.addAdena("ItemAuction", count, player, true);
	}
	
	/**
	 * Returns the last bid for the given player or -1 if he did not made one yet.
	 * 
	 * @param player The player that made the bid
	 * @return The last bid the player made or -1
	 */
	public final long getLastBid(final L2PcInstance player)
	{
		final ItemAuctionBid bid = getBidFor(player.getObjectId());
		return bid != null ? bid.getLastBid() : -1L;
	}
	
	public final ItemAuctionBid getBidFor(final int playerObjId)
	{
		final int index = getBidIndexFor(playerObjId);
		return index != -1 ? _auctionBids.get(index) : null;
	}
	
	private final int getBidIndexFor(final int playerObjId)
	{
		for (int i = _auctionBids.size(); i-- > 0;)
		{
			final ItemAuctionBid bid = _auctionBids.get(i);
			if (bid != null && bid.getPlayerObjId() == playerObjId)
				return i;
		}
		return -1;
	}
}

com.l2jserver.gameserver.model.itemauction.AuctionItem

/*
 * 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.l2jserver.gameserver.model.itemauction;

import com.l2jserver.gameserver.datatables.ItemTable;
import com.l2jserver.gameserver.model.L2Augmentation;
import com.l2jserver.gameserver.model.L2ItemInstance;
import com.l2jserver.gameserver.templates.StatsSet;
import com.l2jserver.gameserver.templates.item.L2Item;

/**
 * @author Forsaiken
 */
public final class AuctionItem
{
	private final int _auctionItemId;
	private final int _auctionLength;
	private final long _auctionInitBid;
	
	private final int _itemId;
	private final long _itemCount;
	private final StatsSet _itemExtra;
	
	public AuctionItem(final int auctionItemId, final int auctionLength, final long auctionInitBid, final int itemId, final long itemCount, final StatsSet itemExtra)
	{
		_auctionItemId = auctionItemId;
		_auctionLength = auctionLength;
		_auctionInitBid = auctionInitBid;
		
		_itemId = itemId;
		_itemCount = itemCount;
		_itemExtra = itemExtra;
	}
	
	public final boolean checkItemExists()
	{
		final L2Item item = ItemTable.getInstance().getTemplate(_itemId);
		if (item == null)
			return false;
		return true;
	}
	
	public final int getAuctionItemId()
	{
		return _auctionItemId;
	}
	
	public final int getAuctionLength()
	{
		return _auctionLength;
	}
	
	public final long getAuctionInitBid()
	{
		return _auctionInitBid;
	}
	
	public final int getItemId()
	{
		return _itemId;
	}
	
	public final long getItemCount()
	{
		return _itemCount;
	}
	
	public final L2ItemInstance createNewItemInstance()
	{
		final L2ItemInstance item = ItemTable.getInstance().createItem("ItemAuction", _itemId, _itemCount, null, null);
		
		final int enchantLevel = _itemExtra.getInteger("enchant_level", 0);
		item.setEnchantLevel(enchantLevel);
		
		final int augmentationId = _itemExtra.getInteger("augmentation_id", 0);
		if (augmentationId != 0)
		{
			final int augmentationSkillId = _itemExtra.getInteger("augmentation_skill_id", 0);
			final int augmentationSkillLevel = _itemExtra.getInteger("augmentation_skill_lvl", 0);
			item.setAugmentation(new L2Augmentation(augmentationId, augmentationSkillId, augmentationSkillLevel));
		}
		
		return item;
	}
}

com.l2jserver.gameserver.model.itemauction.AuctionDateGenerator

/*
 * 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.l2jserver.gameserver.model.itemauction;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

import com.l2jserver.gameserver.templates.StatsSet;

/**
 * 
 * @author Forsaiken
 *
 */
public final class AuctionDateGenerator
{
	public static final String FIELD_INTERVAL = "interval";
	public static final String FIELD_DAY_OF_WEEK = "day_of_week";
	public static final String FIELD_HOUR_OF_DAY = "hour_of_day";
	public static final String FIELD_MINUTE_OF_HOUR = "minute_of_hour";
	
	private static final long MILLIS_IN_WEEK = TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS);
	
	private final Calendar _calendar;
	
	private int _interval;
	private int _day_of_week;
	private int _hour_of_day;
	private int _minute_of_hour;
	
	public AuctionDateGenerator(final StatsSet config) throws IllegalArgumentException
	{
		_calendar = Calendar.getInstance();
		_interval = config.getInteger(FIELD_INTERVAL, -1);
		//NC week start in Monday.
		final int fixedDayWeek = config.getInteger(FIELD_DAY_OF_WEEK, -1) + 1;
		_day_of_week = (fixedDayWeek > 7) ? 1 : fixedDayWeek;
		_hour_of_day = config.getInteger(FIELD_HOUR_OF_DAY, -1);
		_minute_of_hour = config.getInteger(FIELD_MINUTE_OF_HOUR, -1);
		
		checkDayOfWeek(-1);
		checkHourOfDay(-1);
		checkMinuteOfHour(0);
	}
	
	public synchronized final long nextDate(final long date)
	{
		_calendar.setTimeInMillis(date);
		_calendar.set(Calendar.MILLISECOND, 0);
		_calendar.set(Calendar.SECOND, 0);
		
		_calendar.set(Calendar.MINUTE, _minute_of_hour);
		_calendar.set(Calendar.HOUR_OF_DAY, _hour_of_day);
		if (_day_of_week > 0)
		{
			_calendar.set(Calendar.DAY_OF_WEEK, _day_of_week);
			return calcDestTime(_calendar.getTimeInMillis(), date, MILLIS_IN_WEEK);
		}
		
		return calcDestTime(_calendar.getTimeInMillis(), date, TimeUnit.MILLISECONDS.convert(_interval, TimeUnit.DAYS));
	}
	
	private final long calcDestTime(long time, final long date, final long add)
	{
		if (time < date)
		{
			time += ((date - time) / add) * add;
			if (time < date)
				time += add;
		}
		return time;
	}
	
	private final void checkDayOfWeek(final int defaultValue)
	{
		if (_day_of_week < 1 || _day_of_week > 7)
		{
			if (defaultValue == -1 && _interval < 1)
				throw new IllegalArgumentException("Illegal params for '" + FIELD_DAY_OF_WEEK + "': " + (_day_of_week == -1 ? "not found" : _day_of_week));
			_day_of_week = defaultValue;
		}
		else if (_interval > 1)
			throw new IllegalArgumentException("Illegal params for '" + FIELD_INTERVAL +"' and '" + FIELD_DAY_OF_WEEK + "': you can use only one, not both");
	}
	
	private final void checkHourOfDay(final int defaultValue)
	{
		if (_hour_of_day < 0 || _hour_of_day > 23)
		{
			if (defaultValue == -1)
				throw new IllegalArgumentException("Illegal params for '" + FIELD_HOUR_OF_DAY + "': " + (_hour_of_day == -1 ? "not found" : _hour_of_day));
			_hour_of_day = defaultValue;
		}
	}
	
	private final void checkMinuteOfHour(final int defaultValue)
	{
		if (_minute_of_hour < 0 || _minute_of_hour > 59)
		{
			if (defaultValue == -1)
				throw new IllegalArgumentException("Illegal params for '" + FIELD_MINUTE_OF_HOUR + "': " + (_minute_of_hour == -1 ? "not found" : _minute_of_hour));
			_minute_of_hour = defaultValue;
		}
	}
}

CitarDATA:

handlers.bypasshandlers.ItemAuctionLink

/*
 * 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 handlers.bypasshandlers;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import com.l2jserver.Config;
import com.l2jserver.gameserver.handler.IBypassHandler;
import com.l2jserver.gameserver.instancemanager.ItemAuctionManager;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.itemauction.ItemAuction;
import com.l2jserver.gameserver.model.itemauction.ItemAuctionInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.ExItemAuctionInfoPacket;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;

public class ItemAuctionLink implements IBypassHandler
{
	private static final SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");
	
	private static final String[] COMMANDS =
	{
		"ItemAuction"
	};
	
	public boolean useBypass(String command, L2PcInstance activeChar, L2Character target)
	{
		if (!(target instanceof L2Npc))
			return false;
		
		if (!Config.ALT_ITEM_AUCTION_ENABLED)
		{
			activeChar.sendPacket(new SystemMessage(SystemMessageId.NO_AUCTION_PERIOD));
			return true;
		}
		
		final ItemAuctionInstance au = ItemAuctionManager.getInstance().getManagerInstance(((L2Npc)target).getNpcId());
		if (au == null)
			return false;
		
		try
		{
			StringTokenizer st = new StringTokenizer(command);
			st.nextToken(); // bypass "ItemAuction"
			if (!st.hasMoreTokens())
				return false;
			
			String cmd = st.nextToken();
			if ("show".equalsIgnoreCase(cmd))
			{
				if (!activeChar.getFloodProtectors().getItemAuction().tryPerformAction("RequestInfoItemAuction"))
					return false;
				
				if (activeChar.isItemAuctionPolling())
					return false;
				
				final ItemAuction currentAuction = au.getCurrentAuction();
				final ItemAuction nextAuction = au.getNextAuction();
				
				if (currentAuction == null)
				{
					activeChar.sendPacket(new SystemMessage(SystemMessageId.NO_AUCTION_PERIOD));
					
					if (nextAuction != null) // used only once when database is empty
						activeChar.sendMessage("The next auction will begin on the " + fmt.format(new Date(nextAuction.getStartingTime())) + ".");
					return true;
				}
				
				activeChar.sendPacket(new ExItemAuctionInfoPacket(false, currentAuction, nextAuction));
			}
			else if ("cancel".equalsIgnoreCase(cmd))
			{
				final ItemAuction[] auctions = au.getAuctionsByBidder(activeChar.getObjectId());
				boolean returned = false;
				for (final ItemAuction auction : auctions)
				{
					if (auction.cancelBid(activeChar))
						returned = true;
				}
				if (!returned)
					activeChar.sendPacket(new SystemMessage(SystemMessageId.NO_OFFERINGS_OWN_OR_MADE_BID_FOR));
			}
			else
				return false;
		}
		catch (Exception e)
		{
			_log.severe("Exception in: " + getClass().getSimpleName() + ":" + e.getMessage());
		}
		
		return true;
	}
	
	public String[] getBypassList()
	{
		return COMMANDS;
	}
}