Improved code. Sad storki. Thank me later.
package com.l2jserver;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Logger;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.model.World;
import com.l2jserver.gameserver.model.actor.instance.Player;
public class ItemDeliveryManager implements Runnable
{
private static Logger _log = Logger.getLogger(ItemDeliveryManager.class.getName());
private final static String UPDATE = "UPDATE user_item_delivery SET status=1 WHERE id=?;";
private final static String SELECT = "SELECT id, item_id, item_count, char_name FROM user_item_delivery WHERE status=0;";
private static final Duration DURATION = Duration.ofSeconds(30);
protected ItemDeliveryManager()
{
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this, DURATION.toMillis(), DURATION.toMillis());
}
@Override
public void run()
{
try (Connection con = ConnectionPool.getInstance().getConnection(); PreparedStatement statement = con.prepareStatement(SELECT); ResultSet rset = statement.executeQuery())
{
while (rset.next())
{
final int id = rset.getInt("id");
final int itemId = rset.getInt("item_id");
final long count = rset.getInt("item_count");
final String char_name = rset.getString("char_name");
if (itemId > 0 && count > 0 && Objects.nonNull(char_name))
{
Optional.ofNullable(World.getInstance().getPlayer(selectPlayer(char_name))).ifPresent(s -> updateDelivery(id, s, itemId, count));
}
}
}
catch (final Exception e)
{
_log.warning("Check delivery items failed. " + e.getMessage());
}
}
private void updateDelivery(final int id, final Player activeChar, final int itemId, final long count)
{
activeChar.addItem(getClass().getSimpleName(), itemId, count, activeChar, true);
try (Connection con = ConnectionPool.getInstance().getConnection(); PreparedStatement statement = con.prepareStatement(UPDATE))
{
statement.setInt(1, id);
statement.execute();
}
catch (final SQLException e)
{
_log.warning("Failed to update item delivery id: " + id);
}
}
private int selectPlayer(final String name)
{
try (Connection con = ConnectionPool.getInstance().getConnection(); PreparedStatement statement = con.prepareStatement("SELECT * FROM `characters` WHERE `char_name`=? LIMIT 1;"))
{
statement.setString(1, name);
try (ResultSet rs = statement.executeQuery())
{
if (rs.next())
{
return rs.getInt("charId");
}
}
}
catch (final SQLException e)
{
_log.warning("Failed to get char id from: " + name + " " + e.getMessage());
}
return 0;
}
public static ItemDeliveryManager getInstance()
{
return SingletonHolder._instance;
}
private static class SingletonHolder
{
protected static final ItemDeliveryManager _instance = new ItemDeliveryManager();
}
}