[Epilogue] Rastprguev top developer

kick

Предвестник
Administrator
Сообщения
6 958
Розыгрыши
21
Решения
1
Репутация
6 039
Реакции
6 785
Баллы
2 688
Решил посмотреть топ сурс, специально для этого раздела с этой шары [Epilogue] Rastprguev top developer share source Jan 2k15
Код:
package l2s.database;

import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l2s.Config;
import l2s.Server;
import l2s.database.connectingpool.ConnectingPoolDBCP;
import l2s.database.connectingpool.IConnectingPool;

public class L2DatabaseFactory
{
    private static L2DatabaseFactory _instance;
    private static L2DatabaseFactory _instanceLogin;

    private final static Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());

    private final ConcurrentHashMap<String, ThreadConnection> _connections = new ConcurrentHashMap<String, ThreadConnection>();

    private IConnectingPool _connection_pool;

    public enum ConnectingPoolType
    {
        DBCP;
    }

    public L2DatabaseFactory(final String poolName, final String driver, final String url, final String login, final String pass, final int poolSize, final int idleTimeOut, final int idleTestPeriod) throws SQLException
    {
        switch (Config.DATABASE_TYPE_CONNECTING_POOL)
        {
            case DBCP:
                _connection_pool = new ConnectingPoolDBCP(poolName, driver, url, login, pass, poolSize, idleTimeOut, idleTestPeriod);
                break;
            default:
            {
                Server.exit(0, "L2DatabaseFactory: wrong type connecting pool!");
            }
        }
    }

    public static L2DatabaseFactory getInstance() throws SQLException
    {
        if(_instance == null)
        {
            _instance = new L2DatabaseFactory("GameServer", Config.DATABASE_DRIVER, Config.DATABASE_URL, Config.DATABASE_LOGIN, Config.DATABASE_PASSWORD, Config.DATABASE_MAX_CONNECTIONS, Config.DATABASE_MAX_IDLE_TIMEOUT, Config.DATABASE_IDLE_TEST_PERIOD);
            if(Config.DATABASE_URL.equalsIgnoreCase(Config.ACCOUNTS_DATABASE_URL))
                _instanceLogin = _instance;
        }
        return _instance;
    }

    public static L2DatabaseFactory getInstanceLogin() throws SQLException
    {
        if(_instanceLogin == null)
        {
            if(Config.DATABASE_URL.equalsIgnoreCase(Config.ACCOUNTS_DATABASE_URL))
                return getInstance();
            _instanceLogin = new L2DatabaseFactory("LoginServer", Config.DATABASE_DRIVER, Config.ACCOUNTS_DATABASE_URL, Config.ACCOUNTS_DATABASE_LOGIN, Config.ACCOUNTS_DATABASE_PASSWORD, 2, Config.DATABASE_MAX_IDLE_TIMEOUT, Config.DATABASE_IDLE_TEST_PERIOD);
        }
        return _instanceLogin;
    }

    public ThreadConnection getConnection() throws SQLException
    {
        ThreadConnection connection;
        if(Config.USE_DATABASE_LAYER)
        {
            final String key = generateKey();

            connection = _connections.get(key);
            if(connection == null)
                try
                {
                    connection = new ThreadConnection(_connection_pool.getConnection(), this);
                }
                catch(final SQLException e)
                {
                    _log.warning("Couldn't create connection. Cause: " + e.getMessage());
                }
            else
                connection.updateCounter();

            if(connection != null)
                synchronized (_connections)
                {
                    _connections.put(key, connection);
                }
        }
        else
            connection = new ThreadConnection(_connection_pool.getConnection(), this);
        return connection;
    }

    public ConcurrentHashMap<String, ThreadConnection> getConnections()
    {
        return _connections;
    }

    public void shutdown()
    {
        _connections.clear();
        try
        {
            _connection_pool.shutdown();
            _connection_pool = null;
        }
        catch(final Exception e)
        {
            _log.log(Level.WARNING, "", e);
        }
    }

    public String generateKey()
    {
        return String.valueOf(Thread.currentThread().hashCode());
    }

    public String getStats()
    {
        return _connection_pool.getStats();
    }
}
Код:
package l2s.database;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

public class FiltredPreparedStatement implements FiltredStatementInterface
{
    private transient final PreparedStatement myStatement;

    public FiltredPreparedStatement(final PreparedStatement statement)
    {
        myStatement = statement;
    }

    public ResultSet executeQuery() throws SQLException
    {
        return myStatement.executeQuery();
    }

     
    public void close()
    {
        try
        {
            myStatement.close();
        }
        catch(final SQLException e)
        {
            e.printStackTrace();
        }
    }

    public boolean execute() throws SQLException
    {
        return myStatement.execute();
    }

    public ResultSet executeQuery(final String sql) throws SQLException
    {
        return myStatement.executeQuery(sql);
    }

    public void setInt(final int index, final int val) throws SQLException
    {
        myStatement.setInt(index, val);
    }

    public void setString(final int index, final String val) throws SQLException
    {
        myStatement.setString(index, val);
    }

    public void setLong(final int index, final long val) throws SQLException
    {
        myStatement.setLong(index, val);
    }

    public void setNull(final int index, final int val) throws SQLException
    {
        myStatement.setNull(index, val);
    }

    public void setDouble(final int index, final double val) throws SQLException
    {
        myStatement.setDouble(index, val);
    }

    public void setBytes(final int index, final byte[] data) throws SQLException
    {
        myStatement.setBytes(index, data);
    }

    public int executeUpdate() throws SQLException
    {
        return myStatement.executeUpdate();
    }

    public void setBoolean(final int index, final boolean val) throws SQLException
    {
        myStatement.setBoolean(index, val);
    }

    public void setEscapeProcessing(final boolean val) throws SQLException
    {
        myStatement.setEscapeProcessing(val);
    }

    public void setByte(final int index, final byte val) throws SQLException
    {
        myStatement.setByte(index, val);
    }

    public void setDate(final int index, final Date value) throws SQLException
    {
        myStatement.setDate(index, value);
    }

    public void setTimestamp(final int index, final Timestamp timestamp) throws SQLException
    {
        myStatement.setTimestamp(index, timestamp);
    }

    public ResultSet getGeneratedKeys() throws SQLException
    {
        return myStatement.getGeneratedKeys();
    }

    public void setVars(final Object... vars) throws SQLException
    {
        Number n;
        long long_val;
        double double_val;
        for(int i = 0; i < vars.length; i++)
            if(vars[i] instanceof Number)
            {
                n = (Number) vars[i];
                long_val = n.longValue();
                double_val = n.doubleValue();
                if(long_val == double_val)
                    setLong(i + 1, long_val);
                else
                    setDouble(i + 1, double_val);
            }
            else if(vars[i] instanceof String)
                setString(i + 1, (String) vars[i]);
    }
}
package l2s.database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class FiltredStatement implements FiltredStatementInterface
{
private final Statement myStatement;

public FiltredStatement(final Statement statement)
{
myStatement = statement;
}

public int executeUpdate(final String sql) throws SQLException
{
return myStatement.executeUpdate(sql);
}


public void close()
{
try
{
myStatement.close();
}
catch(final SQLException e)
{
e.printStackTrace();
}
}

public void addBatch(final String sql) throws SQLException
{
myStatement.addBatch(sql);
}

public int[] executeBatch() throws SQLException
{
return myStatement.executeBatch();
}

public ResultSet executeQuery(final String sql) throws SQLException
{
return myStatement.executeQuery(sql);
}
}
Код:
package l2s.database;

public interface FiltredStatementInterface
{
    public void close();
}
Код:
package l2s.database;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Logger;

public class ThreadConnection
{
    private final static Logger _log = Logger.getLogger(ThreadConnection.class.getName());

    private transient final Connection myConnection;
    private final L2DatabaseFactory myFactory;
    private int counter = 1;

    public ThreadConnection(final Connection con, final L2DatabaseFactory f)
    {
        myConnection = con;
        myFactory = f;
    }

    public void updateCounter()
    {
        counter++;
    }

    public FiltredPreparedStatement prepareStatement(final String sql) throws SQLException
    {
        return new FiltredPreparedStatement(myConnection.prepareStatement(sql));
    }

    public FiltredPreparedStatement prepareStatement(final String sql, final int Statement) throws SQLException
    {
        return new FiltredPreparedStatement(myConnection.prepareStatement(sql, Statement));
    }

    public void close()
    {
        counter--;
        if(counter == 0)
            try
            {
                synchronized (myFactory.getConnections())
                {
                    myConnection.close();
                    final String key = myFactory.generateKey();
                    myFactory.getConnections().remove(key);
                }
            }
            catch(final Exception e)
            {
                _log.warning("Couldn't close connection. Cause: " + e.getMessage());
            }
    }

    public FiltredStatement createStatement() throws SQLException
    {
        return new FiltredStatement(myConnection.createStatement());
    }
}
Код:
package l2s.database.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import l2s.Config;
import l2s.commons.text.Strings;
import l2s.database.FiltredStatement;
import l2s.database.FiltredStatementInterface;
import l2s.database.L2DatabaseFactory;
import l2s.database.ThreadConnection;

public class DbUtils
{
    private static final Logger _log = Logger.getLogger(DbUtils.class.getName());

    public static String mysql_server_version = null;

    public static String getMySqlServerVersion()
    {
        if(mysql_server_version != null)
            return mysql_server_version;

        ThreadConnection con = null;
        FiltredStatement statement = null;
        ResultSet rs = null;
        try
        {
            con = L2DatabaseFactory.getInstance().getConnection();
            statement = con.createStatement();
            rs = statement.executeQuery("SELECT VERSION() AS mysql_version");

            rs.next();
            mysql_server_version = rs.getString("mysql_version");
        }
        catch(final Exception e)
        {
            _log.log(Level.WARNING, "DbUtils: getMySqlServerVersion error: ", e);
            mysql_server_version = "UNKNOW";
        }
        finally
        {
            DbUtils.closeQuietly(con, statement, rs);
        }

        return mysql_server_version;
    }

    public static void optimizeTables()
    {
        if(!Config.ALLOW_OPTIMIZE_TABLES)
            return;

        ThreadConnection con = null;
        FiltredStatement st = null;
        ResultSet rs = null;
        try
        {
            con = L2DatabaseFactory.getInstance().getConnection();
            st = con.createStatement();;

            final ArrayList<String> tablesList = new ArrayList<String>();

            rs = st.executeQuery("SHOW FULL TABLES");
            while (rs.next())
            {
                final String tableType = rs.getString(2/* "Table_type" */);
                if(tableType.equals("VIEW"))
                    continue;

                tablesList.add(rs.getString(1));
            }
            rs.close();

            final String all_tables = Strings.joinStrings(",", tablesList.toArray(new String[tablesList.size()]));

            rs = st.executeQuery("CHECK TABLE " + all_tables);
            while (rs.next())
            {
                final String table = rs.getString("Table");
                final String msgType = rs.getString("Msg_type");
                final String msgText = rs.getString("Msg_text");

                if(msgType.equals("status"))
                    if(msgText.equals("OK"))
                        continue;

                _log.log(Level.WARNING, "DbUtils: CHECK TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();
            _log.info("DbUtils: Database tables have been checked.");

            rs = st.executeQuery("ANALYZE TABLE " + all_tables);
            while (rs.next())
            {
                final String table = rs.getString("Table");
                final String msgType = rs.getString("Msg_type");
                final String msgText = rs.getString("Msg_text");

                if(msgType.equals("status"))
                    if(msgText.equals("OK") || msgText.equals("Table is already up to date"))
                        continue;

                if(msgType.equals("note"))
                    if(msgText.equals("The storage engine for the table doesn't support analyze"))
                        continue;

                _log.log(Level.WARNING, "DbUtils: ANALYZE TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();
            _log.info("DbUtils: Database tables have been analyzed.");

            rs = st.executeQuery("OPTIMIZE TABLE " + all_tables);
            while (rs.next())
            {
                final String table = rs.getString("Table");
                final String msgType = rs.getString("Msg_type");
                final String msgText = rs.getString("Msg_text");

                if(msgType.equals("status"))
                    if(msgText.equals("OK") || msgText.equals("Table is already up to date"))
                        continue;

                if(msgType.equals("note"))
                    if(msgText.equals("Table does not support optimize, doing recreate + analyze instead"))
                        continue;

                _log.log(Level.WARNING, "DbUtils: OPTIMIZE TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            _log.info("DbUtils: Database tables have been optimized.");
        }
        catch(final Exception e)
        {
            _log.log(Level.WARNING, "DbUtils: Cannot optimize database tables!", e);
        }
        finally
        {
            closeQuietly(con, st, rs);
        }
    }
   
    public static void closeDatabaseCSR(ThreadConnection conn, FiltredStatementInterface stmt, ResultSet rs)
    {
        closeResultSet(rs);
        closeStatement(stmt);
        closeConnection(conn);
    }
   
    public static void closeResultSet(ResultSet rs)
    {
        if(rs != null)
            try
            {
                rs.close();
            }
            catch(SQLException e)
            {}
    }
   
    public static void closeStatement(FiltredStatementInterface stmt)
    {
        if(stmt != null)
            stmt.close();
    }
   
    public static void closeConnection(ThreadConnection conn)
    {
        if(conn != null)
            conn.close();
    }

    public static void repairTables()
    {
        if(!Config.ALLOW_REPAIR_TABLES)
            return;

        ThreadConnection con = null;
        FiltredStatement st = null;
        ResultSet rs = null;
        try
        {
            con = L2DatabaseFactory.getInstance().getConnection();
            st = con.createStatement();;

            final ArrayList<String> tablesList = new ArrayList<String>();

            rs = st.executeQuery("SHOW FULL TABLES");
            while (rs.next())
            {
                final String tableType = rs.getString(2/* "Table_type" */);
                if(tableType.equals("VIEW"))
                    continue;

                tablesList.add(rs.getString(1));
            }
            rs.close();

            final String all_tables = Strings.joinStrings(",", tablesList.toArray(new String[tablesList.size()]));

            rs = st.executeQuery("REPAIR TABLE " + all_tables + " EXTENDED");
            while (rs.next())
            {
                final String table = rs.getString("Table");
                final String msgType = rs.getString("Msg_type");
                final String msgText = rs.getString("Msg_text");

                if(msgType.equals("status"))
                    if(msgText.equals("OK"))
                        continue;

                if(msgType.equals("note"))
                    if(msgText.equals("The storage engine for the table doesn't support repair"))
                        continue;

                _log.log(Level.WARNING, "DbUtils: REPAIR TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            _log.info("DbUtils: Database tables have been repaired.");
        }
        catch(final Exception e)
        {
            _log.log(Level.WARNING, "DbUtils: Cannot optimize database tables!", e);
        }
        finally
        {
            closeQuietly(con, st, rs);
        }
    }

    public static void close(final ThreadConnection conn)
    {
        if(conn == null)
            return;
        conn.close();
    }


    public static void close(final ResultSet rs)
    {
        if(rs == null)
            return;
        try
        {
            rs.close();
        }
        catch(final SQLException e)
        {
            _log.log(Level.WARNING, "Failed to close ResultSet!", e);
        }
    }

    public static void close(final FiltredStatementInterface stmt)
    {
        if(stmt == null)
            return;
        stmt.close();
    }

    public static void close(final FiltredStatementInterface stmt, final ResultSet rs)
    {
        close(rs);
        close(stmt);
    }

    public static void closeQuietly(final ThreadConnection conn)
    {
        close(conn);
    }

    public static void closeQuietly(final ResultSet rs)
    {
        close(rs);
    }

    public static void closeQuietly(final FiltredStatementInterface stmt)
    {
        close(stmt);
    }

    public static void closeQuietly(final ThreadConnection conn, final FiltredStatementInterface stmt)
    {
        closeQuietly(stmt);
        closeQuietly(conn);
    }

    public static void closeQuietly(final FiltredStatementInterface stmt, final ResultSet rs)
    {
        closeQuietly(rs);
        closeQuietly(stmt);
    }

    public static void closeQuietly(final ThreadConnection conn, final FiltredStatementInterface stmt, final ResultSet rs)
    {
        closeQuietly(rs);
        closeQuietly(stmt);
        closeQuietly(conn);
    }
}
Гавнокод в работе, а удалить и выпилить это не судьба наверное особенно и переписать например на java.sql.*
 
Код:
package l2s.extensions.multilang;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.HashMap;

import javolution.text.TextBuilder;

public class ASCIIBuilder
{
    private static final String targetDir = "data/localization/ascii";
    private static final String encoding = "latin1";

    public static void createPropASCII(File f)
    {
        HashMap<String, String> map = new HashMap<String, String>();

        try
        {
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
            TextBuilder tb = new TextBuilder();

            String s;
            String buf;
            int index;
            while ((s = lnr.readLine()) != null)
            {
                try
                {
                    tb.append(s);
                    if(!tb.toString().endsWith("\\"))
                    {
                        buf = tb.toString().replace("\\", "");
                        index = buf.indexOf("=");
                        map.put(buf.substring(0, index), buf.substring(index + 1));
                        tb.clear();
                    }
                }
                catch(Exception e)
                {
                    tb.clear();
                }
            }
            lnr.close();
        }
        catch(Exception e)
        {
            e.printStackTrace(System.err);
        }

        for(String s : map.keySet())
            map.put(s, convertString(map.get(s)));

        File dir = new File(targetDir);
        if(dir.exists())
            dir.delete();
        dir.mkdir();

        File target = new File(targetDir + "/" + f.getName());

        if(!target.exists())
            try
            {
                target.createNewFile();
            }
            catch(IOException e)
            {
                e.printStackTrace(System.err);
            }

        try
        {
   
            FileOutputStream fos = new FileOutputStream(target);
            for(String q : map.keySet())
            {
                fos.write(q.getBytes(encoding));
                fos.write("=".getBytes(encoding));
                fos.write(map.get(q).getBytes(encoding));
                fos.write("\n".getBytes(encoding));
            }
            fos.close();
        }
        catch(IOException e)
        {
            e.printStackTrace(System.err);
        }
    }

    private static String convertString(String s)
    {
        TextBuilder tb = new TextBuilder();

        for(char c : s.toCharArray())
            if(c > 127) 
            {
                tb.append("\\u");
                String hex = Integer.toHexString(c);
                int lenght = hex.length();
                for(int i = lenght; i < 4; i++)
                    tb.append("0");
                tb.append(hex);
            }
            else
                tb.append(c);

        return tb.toString();
    }
}
Код:
public class PropertiesFilter implements FilenameFilter
{
     
    public boolean accept(File dir, String name)
    {
        return name.endsWith(".properties");
    }
}
Код:
package l2s.extensions.multilang;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Locale;
import java.util.ResourceBundle;

import l2s.game.model.L2Object;
import l2s.game.model.L2Skill;
import l2s.game.model.actor.L2Character;
import l2s.game.model.actor.L2Player;
import l2s.game.model.instances.L2ItemInstance;
import l2s.game.tables.ItemTable;
import l2s.game.tables.SkillTable;
import l2s.game.templates.L2Item;
import l2s.util.Log;

public class CustomMessage
{
    private static final String localizationDirSrc = "data/localization/";
    private static final String localizationDirASCII = "data/localization/ascii/";

    private static URLClassLoader loader;

    static
    {
        reload();
    }

    public synchronized static void reload()
    {
        File src = new File(localizationDirSrc);
        for(File prop : src.listFiles(new PropertiesFilter()))
            ASCIIBuilder.createPropASCII(prop);

        try
        {
            loader = new URLClassLoader(new URL[] { new File(localizationDirASCII).toURI().toURL() });
            en = ResourceBundle.getBundle("messages", new Locale("en"), loader);
            ru = ResourceBundle.getBundle("messages", new Locale("ru"), loader);
        }
        catch(MalformedURLException e)
        {
            e.printStackTrace(System.err);
        }
    }

    private static ResourceBundle en;
    private static ResourceBundle ru;

    private String _text;
    private int mark = 0;

    public CustomMessage(String address, L2Object player, Object... args)
    {
        if(player != null && player.isPlayer())
            getString(address, ((L2Player) player).getLang());
        add(args);
    }

    public CustomMessage(String address, String language, Object... args)
    {
        getString(address, language);
        add(args);
    }

    private void getString(String address, String lang)
    {
        if(lang != null)
            lang = lang.toLowerCase();
        else
            lang = "en";

        ResourceBundle rb;
        if(lang.equals("ru"))
            rb = ru;
        else
            rb = en;

        try
        {
            _text = rb.getString(address);
        }
        catch(Exception e)
        {
            Log.addDev("Custom message with address: \"" + address + "\" is unsupported!", "dev_custom_message");
            _text = "Custom message with address: \"" + address + "\" is unsupported!";
        }

        if(_text == null)
        {
            Log.addDev("Custom message with address: \"" + address + "\" not found!", "dev_custom_message");
            _text = "Custom message with address: \"" + address + "\" not found!";
        }
    }

    public CustomMessage add(Object... args)
    {
        for(Object arg : args)
            if(arg instanceof String)
                addString((String) arg);
            else if(arg instanceof Integer)
                addNumber(((Integer) arg).intValue());
            else if(arg instanceof Long)
                addNumber(((Long) arg).longValue());
            else if(arg instanceof L2Item)
                addItemName((L2Item) arg);
            else if(arg instanceof L2ItemInstance)
                addItemName((L2ItemInstance) arg);
            else if(arg instanceof L2Character)
                addCharName((L2Character) arg);
            else if(arg instanceof L2Skill)
                addSkillName((L2Skill) arg);
            else
            {
                System.out.println("unknown CustomMessage arg type: " + arg);
                Thread.dumpStack();
            }
        return this;
    }

    public CustomMessage addNumber(long number)
    {
        _text = _text.replace("{" + mark + "}", String.valueOf(number));
        mark++;
        return this;
    }

    public CustomMessage addString(String str)
    {
        _text = _text.replace("{" + mark + "}", str);
        mark++;
        return this;
    }

    public CustomMessage addSkillName(L2Skill skill)
    {
        _text = _text.replace("{" + mark + "}", skill.getName());
        mark++;
        return this;
    }

    public CustomMessage addSkillName(short skillId, short skillLevel)
    {
        return addSkillName(SkillTable.getInstance().getInfo(skillId, skillLevel));
    }

    public CustomMessage addItemName(L2Item item)
    {
        _text = _text.replace("{" + mark + "}", item.getName());
        mark++;
        return this;
    }

    public CustomMessage addItemName(int itemId)
    {
        return addItemName(ItemTable.getInstance().getTemplate(itemId));
    }

    public CustomMessage addItemName(L2ItemInstance item)
    {
        return addItemName(item.getItem());
    }

    public CustomMessage addCharName(L2Character cha)
    {
        _text = _text.replace("{" + mark + "}", cha.getName());
        mark++;
        return this;
    }

     
    public String toString()
    {
        return _text;
    }
}
Уж сколько лет то можно держать такой бред, лучше выпилить подобное и написать с 0.
 
Код:
package l2s.extensions;

import java.sql.ResultSet;

import l2s.database.FiltredPreparedStatement;
import l2s.database.L2DatabaseFactory;
import l2s.database.ThreadConnection;
import l2s.database.utils.DbUtils;
import l2s.game.instancemanager.ServerVariables;
import l2s.game.model.L2ObjectsStorage;
import l2s.game.tables.FakePlayersTable;

public class Stat
{
    private static long _insertItemCounter = 0;
    private static long _deleteItemCounter = 0;
    private static long _updateItemCounter = 0;
    private static long _lazyUpdateItem = 0;
    private static long _updatePlayerBase = 0;

    private static long _taxSum;

    private static long _taxLastUpdate;
    private static long _rouletteSum;
    private static long _rouletteLastUpdate;
    private static long _adenaSum;

    public static void init()
    {
        _taxSum = ServerVariables.getLong("taxsum", 0);
        _rouletteSum = ServerVariables.getLong("rouletteSum", 0);

        ThreadConnection con = null;
        FiltredPreparedStatement statement = null;
        ResultSet rset = null;
        try
        {
            con = L2DatabaseFactory.getInstance().getConnection();
            statement = con.prepareStatement("SELECT (SELECT SUM(count) FROM items WHERE item_id=57) + (SELECT SUM(treasury) FROM castle) AS `count`");
            rset = statement.executeQuery();
            if(rset.next())
                _adenaSum = rset.getLong("count");
        }
        catch(Exception e)
        {
            System.out.println("Unable to load extended RRD stats");
            e.printStackTrace();
        }
        finally
        {
            DbUtils.closeQuietly(con, statement, rset);
        }
    }

    public static void increaseInsertItemCount()
    {
        _insertItemCounter += 1;
    }

    public static long getInsertItemCount()
    {
        return _insertItemCounter;
    }

    public static void increaseDeleteItemCount()
    {
        _deleteItemCounter += 1;
    }

    public static long getDeleteItemCount()
    {
        return _deleteItemCounter;
    }

    public static void increaseUpdateItemCount()
    {
        _updateItemCounter += 1;
    }

    public static long getUpdateItemCount()
    {
        return _updateItemCounter;
    }

    public static void increaseLazyUpdateItem()
    {
        _lazyUpdateItem += 1;
    }

    public static long getLazyUpdateItem()
    {
        return _lazyUpdateItem;
    }

    public static void increaseUpdatePlayerBase()
    {
        _updatePlayerBase += 1;
    }

    public static long getUpdatePlayerBase()
    {
        return _updatePlayerBase;
    }

    public static void addTax(long sum)
    {
        _taxSum += sum;
        if(System.currentTimeMillis() - _taxLastUpdate < 10000)
            return;
        _taxLastUpdate = System.currentTimeMillis();
        ServerVariables.set("taxsum", _taxSum);
    }

    public static void addRoulette(long sum)
    {
        _rouletteSum += sum;
        if(System.currentTimeMillis() - _rouletteLastUpdate < 10000)
            return;
        _rouletteLastUpdate = System.currentTimeMillis();
        ServerVariables.set("rouletteSum", _rouletteSum);
    }

    public static long getTaxSum()
    {
        return _taxSum;
    }

    public static long getRouletteSum()
    {
        return _rouletteSum;
    }

    public static void addAdena(long sum)
    {
        _adenaSum += sum;
    }

    public static long getAdena()
    {
        return _adenaSum;
    }

    public static int getOnline()
    {
        return L2ObjectsStorage.getAllPlayersCount();
    }

    public static int getOnline(boolean includeFake)
    {
        return getOnline() + (includeFake ? FakePlayersTable.getFakePlayersCount() : 0);
    }
}
Код:
package l2s.extensions;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

import l2s.database.FiltredStatement;
import l2s.database.L2DatabaseFactory;
import l2s.database.ThreadConnection;
import l2s.database.utils.DbUtils;
import l2s.game.model.actor.L2Player;

public class Bonus
{
    private L2Player _owner = null;

    public double RATE_XP = 1;
    public double RATE_SP = 1;
    public double RATE_QUESTS_REWARD = 1;
    public double RATE_QUESTS_DROP = 1;
    public double RATE_DROP_ADENA = 1;
    public double RATE_DROP_ITEMS = 1;
    public double RATE_DROP_SPOIL = 1;

    public Bonus(final L2Player player)
    {
        if(player == null || player.getNetConnection() == null)
            return;

        _owner = player;
        restore();

        if(player.getNetConnection() == null)
            return;

        final double bonus = player.getNetConnection().getBonus();
        if(player.hasPremiumAccount())
            player.startBonusTask(player.getNetConnection().getBonusExpire() * 1000);

        RATE_XP *= bonus;
        RATE_SP *= bonus;
        RATE_DROP_ADENA *= bonus;
        RATE_DROP_ITEMS *= bonus;
        RATE_DROP_SPOIL *= bonus;
        RATE_QUESTS_REWARD *= bonus;
        RATE_QUESTS_DROP *= bonus;
    }

    private void restore()
    {
        ThreadConnection con = null;
        FiltredStatement statement = null;
        ResultSet rset = null;
        try
        {
            con = L2DatabaseFactory.getInstance().getConnection();
            statement = con.createStatement();
            rset = statement.executeQuery("SELECT bonus_name, bonus_value FROM bonus WHERE login='" + _owner.getAccountName() + "' AND (bonus_expire_time='-1' OR bonus_expire_time > " + System.currentTimeMillis() / 1000 + ")");
            while (rset.next())
            {
                final String bonus_name = rset.getString("bonus_name");
                final double bonus_value = rset.getDouble("bonus_value");
                final Class<?> cls = getClass();
                try
                {
                    final Field fld = cls.getField(bonus_name);
                    try
                    {
                        fld.setDouble(this, bonus_value);
                    }
                    catch(final IllegalArgumentException e)
                    {
                        e.printStackTrace();
                    }
                    catch(final IllegalAccessException e)
                    {
                        e.printStackTrace();
                    }
                }
                catch(final SecurityException e)
                {
                    e.printStackTrace();
                }
                catch(final NoSuchFieldException e)
                {
                    e.printStackTrace();
                }
            }
        }
        catch(final SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            DbUtils.closeQuietly(con, statement, rset);
        }
    }
}
 
Обратите внимание, что данный пользователь заблокирован! Не совершайте с ним никаких сделок! Перейдите в его профиль, чтобы узнать причину блокировки.
над будет заняться изучением и сесть попилить)
 
Код:
package l2s.extensions.scripts;

import l2s.game.model.L2Object;
import l2s.game.model.actor.L2Player;

public final class Events
{
    public static boolean onAction(final L2Player player, final L2Object obj, final boolean shift)
    {
        if(shift && player.getVarB("noShift"))
            return false;

        final Iterable<EventScript> scripts = Scripts.getInstance().getEventScripts(ScriptEventType.ON_ACTION);
        for(final EventScript script : scripts)
            if(script.notifyAction(player, obj, shift))
                return true;

        return false;
    }
}
Код:
package l2s.extensions.scripts;

import l2s.game.event.L2EventType;
import l2s.game.model.L2Object;
import l2s.game.model.L2Zone;
import l2s.game.model.actor.L2Character;
import l2s.game.model.actor.L2Player;
import l2s.game.network.serverpackets.SystemMessage;

public class EventScript extends Functions
{
    private final String _name;

    public EventScript()
    {
        _name = getClass().getSimpleName();
    }

    public final void addEventId(final ScriptEventType eventType)
    {
        Scripts.getInstance().addScriptEvent(eventType, this);
    }

    public final void addEventId(final ScriptEventType... types)
    {
        for(final ScriptEventType e : types)
            Scripts.getInstance().addScriptEvent(e, this);
    }

    public final void removeEventId(final ScriptEventType eventType)
    {
        Scripts.getInstance().removeScriptEvent(eventType, this);
    }

    public final void removeEventId(final ScriptEventType... types)
    {
        for(final ScriptEventType e : types)
            Scripts.getInstance().removeScriptEvent(e, this);
    }

    public final void notifyOnDie(final L2Character self, final L2Character killer)
    {
        onDie(self, killer);
    }

    public final void notifyOnEscape(final L2Player player)
    {
        onEscape(player);
    }

    public final void notifyEnterWorld(final L2Player player)
    {
        onEnterWorld(player);
    }

    public final void notifyLevelIncreased(final L2Player player)
    {
        onLevelIncreased(player);
    }

    public final void notifySpawned(final L2Player player)
    {
        onSpawn(player);
    }

    public final void notifyRevive(final L2Player player)
    {
        onRevive(player);
    }

    public final boolean notifyPartyLeaveTry(final L2Player player)
    {
        return onPartyLeave(player);
    }

    public final SystemMessage notifyPartyInviteTry(final L2Player inviter, final L2Player target)
    {
        return onPartyInvite(inviter, target);
    }

    public final boolean notifyAction(final L2Player player, final L2Object target, final boolean shift)
    {
        return onAction(player, target, shift);
    }

    public final boolean notifyIsInEventCheck(final L2Player player, final L2EventType type)
    {
        return isInEvent(player, type);
    }

    public final void notifyDisconnect(final L2Player player)
    {
        onDisconnect(player);
    }

    public final void notifyOnAttack(final L2Character victim, final L2Character attacker)
    {
        onAttack(victim, attacker);
    }

    public final void notifyEnterZone(final L2Player player, final L2Zone zone)
    {
        onEnterZone(player, zone);
    }

    public final void notifyExitZone(final L2Player player, final L2Zone zone)
    {
        onExitZone(player, zone);
    }

    protected void onDie(final L2Character self, final L2Character killer)
    {}

    protected void onEscape(final L2Player player)
    {}

    protected void onLevelIncreased(final L2Player player)
    {}

    protected void onEnterWorld(final L2Player player)
    {}

    protected void onSpawn(final L2Player player)
    {}

    protected void onRevive(final L2Player player)
    {}

    protected boolean onPartyLeave(final L2Player player)
    {
        return true;
    }

    protected SystemMessage onPartyInvite(final L2Player inviter, final L2Player target)
    {
        return null;
    }

    protected boolean onAction(final L2Player player, final L2Object target, final boolean shift)
    {
        return false;
    }

    protected boolean isInEvent(final L2Player player, final L2EventType type)
    {
        return false;
    }

    protected void onDisconnect(final L2Player player)
    {}

    protected void onAttack(final L2Character victim, final L2Character attacker)
    {}

    @Deprecated
    protected void onEnterZone(final L2Player player, final L2Zone zone)
    {}

    @Deprecated
    protected void onExitZone(final L2Player player, final L2Zone zone)
    {}

    public String getName()
    {
        return _name;
    }
}
У меня вот тут вопрос, а слушатели придуманы для лохов?
Код:
package l2s.extensions.scripts;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l2s.Config;
import l2s.commons.list.GArray;
import l2s.commons.text.Strings;
import l2s.extensions.multilang.CustomMessage;
import l2s.game.L2GameThreadPools;
import l2s.game.cache.Msg;
import l2s.game.instancemanager.ServerVariables;
import l2s.game.model.L2Object;
import l2s.game.model.L2ObjectsStorage;
import l2s.game.model.L2Spawn;
import l2s.game.model.L2World;
import l2s.game.model.actor.L2Character;
import l2s.game.model.actor.L2Playable;
import l2s.game.model.actor.L2Player;
import l2s.game.model.actor.L2Summon;
import l2s.game.model.instances.L2ItemInstance;
import l2s.game.model.instances.L2NpcInstance;
import l2s.game.model.items.Inventory;
import l2s.game.network.clientpackets.Say2C;
import l2s.game.network.serverpackets.ExShowTrace;
import l2s.game.network.serverpackets.NpcHtmlMessage;
import l2s.game.network.serverpackets.NpcSay;
import l2s.game.network.serverpackets.SystemMessage;
import l2s.game.tables.ItemTable;
import l2s.game.tables.MapRegionTable;
import l2s.game.tables.NpcTable;
import l2s.game.templates.L2NpcTemplate;
import l2s.util.Location;
import l2s.util.Rnd;

public class Functions
{
    protected static final Logger _log = Logger.getLogger(Functions.class.getName());

    public Long self, npc;

    public static final Object[] EMPTY_ARG = new Object[0];

    public L2Object getSelf()
    {
        return L2ObjectsStorage.get(self);
    }
   
    public static void sendDebugMessage(L2Player player, String message)
    {
        if(!player.isGM())
            return;
        player.sendMessage(message);
    }
    public L2Player getSelfPlayer()
    {
        return L2ObjectsStorage.getAsPlayer(self);
    }

    public L2NpcInstance getNpc()
    {
        return L2ObjectsStorage.getAsNpc(npc);
    }

    public static ScheduledFuture<?> executeTask(final L2Object object, final String sClass, final String sMethod, final Object[] args, final HashMap<String, Object> variables, final long delay)
    {
        return L2GameThreadPools.getInstance().scheduleGeneral(new Runnable()
        {
             
            public void run()
            {
                if(object != null)
                    object.callScripts(sClass, sMethod, args, variables);
            }
        }, delay);
    }

    public static ScheduledFuture<?> executeTask(final String sClass, final String sMethod, final Object[] args, final HashMap<String, Object> variables, final long delay)
    {
        return L2GameThreadPools.getInstance().scheduleGeneral(new Runnable()
        {
             
            public void run()
            {
                callScripts(sClass, sMethod, args, variables);
            }
        }, delay);
    }

    public static ScheduledFuture<?> executeTask(final L2Object object, final String sClass, final String sMethod, final Object[] args, final long delay)
    {
        return executeTask(object, sClass, sMethod, args, null, delay);
    }

    public static ScheduledFuture<?> executeTask(final String sClass, final String sMethod, final Object[] args, final long delay)
    {
        return executeTask(sClass, sMethod, args, null, delay);
    }

    public static Object callScripts(final String _class, final String method, final Object[] args)
    {
        return callScripts(_class, method, args, null);
    }

    public static Object callScripts(final String _class, final String method, final Object[] args, final HashMap<String, Object> variables)
    {
        if(Scripts.loading)
            return null;

        final Script scriptClass = Scripts.getInstance().getClasses().get(_class);
        if(scriptClass == null)
            return null;

        ScriptObject o;
        try
        {
            o = scriptClass.newInstance();
        }
        catch(final Exception e)
        {
            _log.log(Level.WARNING, "Error in callScripts class=" + _class + "/method=" + method, e);
            return null;
        }

        if(variables != null)
            for(final Entry<String, Object> obj : variables.entrySet())
                try
                {
                    o.setProperty(obj.getKey(), obj.getValue());
                }
                catch(final Exception e)
                {}

        return o.invokeMethod(method, args);
    }

    public static void show(String text, final L2Player self)
    {
        if(text == null || self == null)
            return;
        NpcHtmlMessage msg;
        if(self.getLastNpc() != null)
            msg = new NpcHtmlMessage(self, self.getLastNpc());
        else
            msg = new NpcHtmlMessage(5);

        if(text.endsWith(".html-ru") || text.endsWith(".htm-ru"))
            text = text.substring(0, text.length() - 3);

        if(text.endsWith(".html") || text.endsWith(".htm"))
            msg.setFile(text);
        else
            msg.setHtml(Strings.bbParse(text));
        self.sendPacket(msg);
    }

    public static void show(final CustomMessage message, final L2Player self)
    {
        show(message.toString(), self);
    }

    public static void sendMessage(final String text, final L2Player self)
    {
        self.sendMessage(text);
    }

    public static void sendMessage(final CustomMessage message, final L2Player self)
    {
        self.sendMessage(message);
    }

    public static void npcSayInRange(final L2NpcInstance npc, final String text, final int range)
    {
        npcSayInRange(npc, Say2C.LOCAL, text, range);
    }

    public static void npcSayInRange(final L2NpcInstance npc, final int messageType, final String text, final int range)
    {
        if(npc == null)
            return;
        final NpcSay cs = new NpcSay(npc, messageType, text);
        for(final L2Player player : L2World.getAroundPlayers(npc, range, 200))
            if(player != null)
                player.sendPacket(cs);
    }

    public static void npcSay(final L2NpcInstance npc, final String text)
    {
        npcSayInRange(npc, text, 1500);
    }

    public static void npcSayToAll(final L2NpcInstance npc, final String text)
    {
        if(npc == null)
            return;
        final NpcSay cs = new NpcSay(npc, 1, text);
        if(Config.GLOBAL_CHAT < 81)
        {
            for(final L2Player player : L2ObjectsStorage.getAllPlayersForIterate())
                if(player != null)
                    player.sendPacket(cs);
        }
        else
            for(final L2Player player : L2World.getAroundPlayers(npc))
                if(player != null)
                    player.sendPacket(cs);
    }

    public static void npcSayToPlayer(final L2NpcInstance npc, final String text, final L2Player player)
    {
        if(npc == null)
            return;
        final NpcSay cs = new NpcSay(npc, 0, text);

        player.sendPacket(cs);
    }

    public static void npcSayToRandomPlayerInRange(final L2NpcInstance npc, final String text, final int range)
    {
        if(npc == null)
            return;
        final NpcSay cs = new NpcSay(npc, 0, text);
        GArray<L2Player> players = npc.getAroundPlayers(range);
        if(players.isEmpty())
            return;
        final L2Player player = players.get(Rnd.get(players.size()));
        if(text.contains("%randomPlayer%"))
            text.replace("%randomPlayer%", player.getName());
        player.sendPacket(cs);
    }

    public static void npcShout(final L2NpcInstance npc, final String text)
    {
        if(npc == null)
            return;
        final NpcSay cs = new NpcSay(npc, 1, text);
        for(final L2Player player : L2World.getAroundPlayers(npc))
            if(player != null)
                player.sendPacket(cs);
    }

    public static void npcShout(final L2NpcInstance npc, final int range, final String text)
    {
        if(npc == null)
            return;
        final NpcSay cs = new NpcSay(npc, 1, text);
        for(final L2Player player : L2World.getAroundPlayers(npc, range, 1500))
            if(player != null)
                player.sendPacket(cs);
    }

    public static void npcSayInRangeCustomMessage(final L2NpcInstance npc, final int range, final String address)
    {
        if(npc == null)
            return;
        for(final L2Player player : L2World.getAroundPlayers(npc, range, 200))
            if(player != null && !player.isBlockAll())
                player.sendPacket(new NpcSay(npc, 0, new CustomMessage(address, player).toString()));
    }

    public static void npcSayInRangeCustomMessage(final L2NpcInstance npc, final int range, final String address, final Object... replacements)
    {
        if(npc == null)
            return;
        for(final L2Player player : L2World.getAroundPlayers(npc, range, 200))
            if(player != null && !player.isBlockAll())
                player.sendPacket(new NpcSay(npc, 0, new CustomMessage(address, player, replacements).toString()));
    }

    public static void npcSayCustomMessage(final L2NpcInstance npc, final String address)
    {
        npcSayInRangeCustomMessage(npc, 1500, address);
    }

    public static void npcSayCustomMessage(final L2NpcInstance npc, final String address, final Object... replacements)
    {
        npcSayInRangeCustomMessage(npc, 1500, address, replacements);
    }

    public static void npcShoutCustomMessage(final L2NpcInstance npc, final String address, final Object... replacements)
    {
        if(npc == null)
            return;

        if(Config.SHOUT_CHAT_MODE == 1)
        {
            for(final L2Player player : L2World.getAroundPlayers(npc, 10000, 1500))
                if(player != null && !player.isBlockAll())
                    player.sendPacket(new NpcSay(npc, 1, new CustomMessage(address, player, replacements).toString()));
        }
        else
        {
            final int mapregion = MapRegionTable.getInstance().getMapRegion(npc.getX(), npc.getY());
            for(final L2Player player : L2ObjectsStorage.getAllPlayersForIterate())
                if(player != null && MapRegionTable.getInstance().getMapRegion(player.getX(), player.getY()) == mapregion && !player.isBlockAll())
                    player.sendPacket(new NpcSay(npc, 1, new CustomMessage(address, player, replacements).toString()));
        }
    }

    public static void addItem(final L2Playable playable, final int item_id, final long count)
    {
        if(playable == null || count < 1)
            return;

        L2Playable player;
        if(playable.isSummon())
            player = playable.getPlayer();
        else
            player = playable;

        final L2ItemInstance item = ItemTable.getInstance().createItem(item_id, player.getObjectId(), 0, "Scripts.addItem");
        if(item.isStackable())
        {
            item.setCount(count);
            player.getInventory().addItem(item);
        }
        else
        {
            player.getInventory().addItem(item);
            for(int i = 1; i < count; i++)
                player.getInventory().addItem(ItemTable.getInstance().createItem(item_id, player.getObjectId(), 0, "Scripts.addItem"));
        }

        player.sendPacket(SystemMessage.obtainItems(item));
    }

    public static long getItemCount(final L2Playable playable, final int item_id)
    {
        long count = 0;
        L2Playable player;
        if(playable != null && playable.isSummon())
            player = playable.getPlayer();
        else
            player = playable;
        final Inventory inv = player.getInventory();
        if(inv == null)
            return 0;
        final L2ItemInstance[] items = inv.getItems();
        for(final L2ItemInstance item : items)
            if(item.getItemId() == item_id)
                count += item.getCount();
        return count;
    }

    public static long removeItem(final L2Playable playable, final int item_id, long count)
    {
        if(playable == null || count < 1)
            return 0;

        L2Playable player;
        if(playable.isSummon())
            player = playable.getPlayer();
        else
            player = playable;
        final Inventory inv = player.getInventory();
        if(inv == null)
            return 0;
        long removed = count;
        final L2ItemInstance[] items = inv.getItems();
        for(final L2ItemInstance item : items)
            if(item.getItemId() == item_id && count > 0)
            {
                final long item_count = item.getCount();
                final long rem = count <= item_count ? count : item_count;
                player.getInventory().destroyItemByItemId(item_id, rem, true);
                count -= rem;
            }
        removed -= count;
        if(removed > 0)
            player.sendPacket(SystemMessage.removeItems(item_id, removed));
        return removed;
    }

    public static boolean ride(final L2Player player, final int pet)
    {
        if(player.isMounted())
            player.setMount(0, 0);

        if(player.getPet() != null)
        {
            player.sendPacket(Msg.YOU_ALREADY_HAVE_A_PET);
            return false;
        }

        player.setMount(pet, 0);
        return true;
    }

    public static void unRide(final L2Player player)
    {
        if(player.isMounted())
            player.setMount(0, 0);
    }

    public static void unSummonPet(final L2Player player)
    {
        final L2Summon pet = player.getPet();
        if(pet == null)
            return;
        pet.unSummon();
    }

    public static L2NpcInstance spawn(final Location loc, final int npcId)
    {
        return spawn(loc, npcId, 0);
    }

    public static L2NpcInstance spawn(final Location loc, final int npcId, final long refId)
    {
        try
        {
            final L2NpcInstance npc = NpcTable.getTemplate(npcId).getNewInstance();
            npc.setReflection(refId);
            npc.setSpawnedLoc(loc.correctGeoZ());
            npc.onSpawn();
            npc.spawnMe(npc.getSpawnedLoc());
            return npc;
        }
        catch(final Exception e)
        {
            _log.log(Level.WARNING, "Could not spawn Npc " + npcId, e);
        }
        return null;
    }

    public static void spawnNPCs(final int npcId, final int[][] locations, final GArray<L2Spawn> list)
    {
        final L2NpcTemplate template = NpcTable.getTemplate(npcId);
        if(template == null)
        {
            System.out.println("WARNING! events.Helper.SpawnNPCs template is null for npc: " + npcId);
            Thread.dumpStack();
            return;
        }
        for(final int[] location : locations)
            try
            {
                final L2Spawn sp = new L2Spawn(template);
                sp.setLoc(new Location(location));
                sp.setAmount(1);
                sp.setRespawnDelay(0);
                sp.init();
                if(list != null)
                    list.add(sp);
            }
            catch(final ClassNotFoundException e)
            {
                _log.log(Level.WARNING, "Could not spawn Npc " + npcId, e);
            }
    }

    public static void deSpawnNPCs(final GArray<L2Spawn> list)
    {
        for(final L2Spawn sp : list)
        {
            sp.stopRespawn();
            if(sp.getLastSpawn() != null)
                sp.getLastSpawn().deleteMe();
        }
        list.clear();
    }

    public static boolean isActive(final String name)
    {
        return ServerVariables.getString(name, "off").equalsIgnoreCase("on");
    }

    public static boolean setActive(final String name, final boolean active)
    {
        if(active == isActive(name))
            return false;
        if(active)
            ServerVariables.set(name, "on");
        else
            ServerVariables.unset(name);
        return true;
    }

    public static boolean SimpleCheckDrop(final L2Character mob, final L2Character killer)
    {
        return mob != null && mob.isMonster() && !mob.isRaid() && killer != null && killer.getPlayer() != null && killer.getLevel() - mob.getLevel() < 10;
    }

    public static void removeItemByObjId(final L2Playable playable, final int item_obj_id, final int count)
    {
        if(playable == null || count < 1)
            return;

        L2Playable player;
        if(playable.isSummon())
            player = playable.getPlayer();
        else
            player = playable;
        final Inventory inv = player.getInventory();
        if(inv == null)
            return;
        final L2ItemInstance[] items = inv.getItems();
        for(final L2ItemInstance item : items)
        {
            if(item.getObjectId() != item_obj_id || count <= 0)
                continue;
            final long item_count = item.getCount();
            final int item_id = item.getItemId();
            final long removed = count > item_count ? item_count : count;
            player.getInventory().destroyItem(item, removed, true);

            if(item_id == 57)
                player.sendPacket(new SystemMessage(SystemMessage.S1_ADENA_DISAPPEARED).addNumber(removed));
            else if(removed > 1)
                player.sendPacket(new SystemMessage(SystemMessage.S2_S1_HAS_DISAPPEARED).addItemName(item_id).addNumber(removed));
            else
                player.sendPacket(new SystemMessage(SystemMessage.S1_HAS_DISAPPEARED).addItemName(item_id));
        }
    }

    public static String htmlButton(final String value, final String action, final int width)
    {
        return Strings.htmlButton(value, action, width);
    }

    public static String htmlButton(final String value, final String action, final int width, final int height)
    {
        return Strings.htmlButton(value, action, width, height);
    }

    public static ExShowTrace Points2Trace(final GArray<int[]> points, final int step, final boolean auto_compleate, final boolean maxz)
    {
        final ExShowTrace result = new ExShowTrace();

        int[] prev = null;
        int[] first = null;
        for(final int[] p : points)
        {
            if(first == null)
                first = p;
            if(prev != null)
                result.addLine(prev[0], prev[1], maxz ? prev[3] : prev[2], p[0], p[1], maxz ? p[3] : p[2], step, 60000);
            prev = p;
        }

        if(prev == null || first == null)
            return result;
        if(auto_compleate)
            result.addLine(prev[0], prev[1], maxz ? prev[3] : prev[2], first[0], first[1], maxz ? first[3] : first[2], step, 60000);
        return result;
    }
}
Мои бедные глаза
Код:
package l2s.extensions.scripts;

public interface ScriptFile
{
    public void onLoad();

    public void onReload();

    public void onShutdown();
}
 
l2s\log - сюда не заходим, ещё видим какой отличный логер реализован.
Видим использование javolution.
 
Обратите внимание, что данный пользователь заблокирован! Не совершайте с ним никаких сделок! Перейдите в его профиль, чтобы узнать причину блокировки.
кик погляди на сервис академмии...... (как у аверии, типа)
там реально вырви глаз)
 
Обратите внимание, что данный пользователь заблокирован! Не совершайте с ним никаких сделок! Перейдите в его профиль, чтобы узнать причину блокировки.
Так это не его а чужой
я про то, что он даже прикрутить не смог его нормально.
такая херня, что даже при не созданной академии в клане, можно инвайтить, так еще и очки зачислят после сдачи профы
 
Ох всеми любимый GArray, один сделал другие сплагиатили
Код:
package l2s.commons.list;

import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;

import l2s.commons.list.procedure.INgObjectProcedure;
import l2s.commons.list.procedure.INgVoidProcedure;
import l2s.game.L2GameThreadPools;


public class GArray<E> implements Collection<E>, RandomAccess
{
    @SuppressWarnings("rawtypes")
    private static final GArray EMPTY_COLLECTION = new EmptyGArray();

    protected transient E[] elementData;
    protected transient int modCount = 0;
    protected int size;

    @SuppressWarnings("unchecked")
    public GArray(int initialCapacity)
    {
        if(initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
        elementData = (E[]) new Object[initialCapacity];
    }

    public GArray()
    {
        this(10);
    }

    public int getCapacity()
    {
        return elementData.length;
    }

    public void ensureCapacity(int minCapacity)
    {
        modCount++;
        int oldCapacity = elementData.length;
        if(minCapacity > oldCapacity)
        {
            int newCapacity = oldCapacity * 3 / 2 + 1;
            if(newCapacity < minCapacity)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }

    public boolean forEach(final INgObjectProcedure<E> procedure)
    {
        for(int i = size; i-- > 0;)
            if(!procedure.execute(elementData[i]))
                return false;
        return true;
    }

    public void forEach(final INgVoidProcedure<E> procedure)
    {
        for(int i = size; i-- > 0;)
            procedure.execute(elementData[i]);
    }

    public void forEachThread(final INgVoidProcedure<E> procedure)
    {
        L2GameThreadPools.getInstance().executeGeneral(new Runnable()
        {
        
            public final void run()
            {
                forEach(procedure);
            }
        });
    }


    public int size()
    {
        return size;
    }


    public boolean isEmpty()
    {
        return size == 0;
    }

    public E[] toNativeArray()
    {
        return Arrays.copyOf(elementData, size);
    }


    public Object[] toArray()
    {
        return Arrays.copyOf(elementData, size);
    }


    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a)
    {
        if(a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if(a.length > size)
            a[size] = null;
        return a;
    }

    public final <T> T[] toArray(final T[] array, final int offset)
    {
        System.arraycopy(elementData, 0, array, offset, size);
        return array;
    }

    /**
    * Returns the value at the specified position in this collection.
    */
    public E get(int index)
    {
        RangeCheck(index);
        return getUnsafe(index);
    }

    public final E getUnsafe(final int index)
    {
        return elementData[index];
    }

    /**
    * Returns the first value of this collection.
    */
    public E getFirst()
    {
        return get(0);
    }

    /**
    * Returns the last value of this collection.
    */
    public E getLast()
    {
        return get(size - 1);
    }


    public boolean add(E value)
    {
        ensureCapacity(size + 1);
        addLastUnsafe(value);
        return true;
    }

    public final void addLastUnsafe(final E value)
    {
        elementData[size++] = value;
    }

    /**
    * Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
    *
    * @param index
    *            index at which the specified element is to be inserted
    * @param element
    *            element to be inserted
    * @throws IndexOutOfBoundsException
    *             {@inheritDoc}
    */
    public void add(int index, E element)
    {
        if(index > size || index < 0)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);

        ensureCapacity(size + 1); // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = element;
        size++;
    }


    public boolean remove(Object o)
    {
        if(o == null)
        {
            for(int index = 0; index < size; index++)
                if(elementData[index] == null)
                {
                    fastRemove(index);
                    return true;
                }
        }
        else
            for(int index = 0; index < size; index++)
                if(o.equals(elementData[index]))
                {
                    fastRemove(index);
                    return true;
                }
        return false;
    }

    /*
    * Private remove method that skips bounds checking and does not
    * return the value removed.
    */
    private void fastRemove(int index)
    {
        modCount++;
        int numMoved = size - index - 1;
        if(numMoved > 0)
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        elementData[--size] = null; // Let gc do its work
    }

    public E remove(int index)
    {
        RangeCheck(index);

        modCount++;
        E oldValue = getUnsafe(index);

        int numMoved = size - index - 1;
        if(numMoved > 0)
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        elementData[--size] = null; // Let gc do its work

        return oldValue;
    }

    public final void removeUnsafeVoid(final int index)
    {
        if(index < --size)
            System.arraycopy(elementData, index + 1, elementData, index, size - index);
        elementData[size] = null;
    }

    public final void removeVoid(final int index)
    {
        if(index >= size || index < 0)
            throw new IndexOutOfBoundsException();

        removeUnsafeVoid(index);
    }

    public E removeFirst()
    {
        return size > 0 ? remove(0) : null;
    }

    public E removeLast()
    {
        if(size > 0)
        {
            modCount++;
            size--;
            E old = elementData[size];
            elementData[size] = null;
            return old;
        }
        return null;
    }

    public E set(int index, E element)
    {
        RangeCheck(index);
        E oldValue = elementData[index];
        elementData[index] = element;
        return oldValue;
    }

    public final void setUnsafeVoid(final int index, final E value)
    {
        elementData[index] = value;
    }

    public int indexOf(Object o)
    {
        if(o == null)
        {
            for(int i = 0; i < size; i++)
                if(elementData[i] == null)
                    return i;
        }
        else
            for(int i = 0; i < size; i++)
                if(o.equals(elementData[i]))
                    return i;
        return -1;
    }


    public boolean contains(Object o)
    {
        if(o == null)
        {
            for(int i = 0; i < size; i++)
                if(elementData[i] == null)
                    return true;
        }
        else
            for(int i = 0; i < size; i++)
                if(o.equals(elementData[i]))
                    return true;
        return false;
    }


    public boolean addAll(Collection<? extends E> c)
    {
        if(c == null)
            return false;
        boolean modified = false;
        Iterator<? extends E> e = c.iterator();
        while (e.hasNext())
            if(add(e.next()))
                modified = true;
        return modified;
    }


    public boolean removeAll(Collection<?> c)
    {
        boolean modified = false;
        for(int i = 0; i < size; i++)
            if(c.contains(elementData[i]))
            {
                modCount++;
                elementData[i] = elementData[size - 1];
                elementData[--size] = null;
                modified = true;
            }
        return modified;
    }


    public boolean retainAll(Collection<?> c)
    {
        boolean modified = false;
        for(int i = 0; i < size; i++)
            if(!c.contains(elementData[i]))
            {
                modCount++;
                elementData[i] = elementData[size - 1];
                elementData[--size] = null;
                modified = true;
            }
        return modified;
    }


    public boolean containsAll(Collection<?> c)
    {
        for(int i = 0; i < size; i++)
            if(!contains(elementData[i]))
                return false;
        return true;
    }

    private void RangeCheck(int index)
    {
        if(index >= size || index < 0)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    }


    @SuppressWarnings("unchecked")
    public void clear()
    {
        modCount++;
        int oldSize = size;
        size = 0;
        if(oldSize > 1000)
            elementData = (E[]) new Object[10];
        else
            for(int i = 0; i < oldSize; i++)
                elementData[i] = null;
        size = 0;
    }

    /**
    * Осторожно, при таком очищении в массиве могут оставаться ссылки на обьекты,
    * удерживающие эти обьекты в памяти!
    */
    public void clearSize()
    {
        modCount++;
        size = 0;
    }


    public Iterator<E> iterator()
    {
        return new Itr();
    }

    private final class Itr implements Iterator<E>
    {
        int cursor = 0;

    
        public final boolean hasNext()
        {
            return cursor < size();
        }

    
        public final E next()
        {
            try
            {
                return elementData[cursor++];
            }
            catch(IndexOutOfBoundsException e)
            {
                throw new NoSuchElementException();
            }
        }

    
        public final void remove()
        {
            try
            {
                fastRemove(--cursor);
            }
            catch(IndexOutOfBoundsException e)
            {
                throw new ConcurrentModificationException();
            }
        }
    }


    public String toString()
    {
        StringBuffer bufer = new StringBuffer();
        for(int i = 0; i < size; i++)
        {
            if(i != 0)
                bufer.append(", ");
            bufer.append(elementData[i]);
        }
        return "<" + bufer + ">";
    }

    @SuppressWarnings({ "unchecked" })
    public static final <E> GArray<E> emptyCollection()
    {
        return EMPTY_COLLECTION;
    }
}
Код:
package l2s.commons.list;

import java.util.Collection;
import java.util.Iterator;

import l2s.commons.list.procedure.INgObjectProcedure;
import l2s.commons.list.procedure.INgVoidProcedure;
import l2s.commons.util.CollectionUtils;


public class EmptyGArray<E> extends GArray<E>
{

    public final Iterator<E> iterator()
    {
        return CollectionUtils.emptyIterator();
    }

    private static final Object[] EMPTY_ARRAY = new Object[0];


    public int size()
    {
        return 0;
    }


    public boolean contains(final Object obj)
    {
        return false;
    }


    public E get(final int index)
    {
        return null;
    }


    public boolean isEmpty()
    {
        return true;
    }


    public Object[] toArray()
    {
        return EMPTY_ARRAY;
    }

    @SuppressWarnings("unchecked")

    public <T> T[] toArray(T[] a)
    {
        return (T[]) EMPTY_ARRAY;
    }


    public boolean add(final E e)
    {
        return false;
    }


    public boolean remove(final Object o)
    {
        return false;
    }


    public boolean containsAll(final Collection<?> c)
    {
        return false;
    }


    public boolean addAll(final Collection<? extends E> c)
    {
        return false;
    }


    public boolean removeAll(final Collection<?> c)
    {
        return false;
    }


    public boolean retainAll(final Collection<?> c)
    {
        return false;
    }


    public void clear()
    {}


    public final boolean forEach(final INgObjectProcedure<E> procedure)
    {
        return true;
    }


    public final void forEach(final INgVoidProcedure<E> procedure)
    {}


    public final void forEachThread(final INgVoidProcedure<E> procedure)
    {}
}
Код:
package l2s.commons.list;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class GCArray<E> implements Collection<E>
{
    private transient E[] elementData;
    private int size;

    @SuppressWarnings("unchecked")
    public GCArray(int initialCapacity)
    {
        super();
        if(initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
        this.elementData = (E[]) new Object[initialCapacity];
    }

    public GCArray()
    {
        this(10);
    }

    public void ensureCapacity(int minCapacity)
    {
        int oldCapacity = elementData.length;
        if(minCapacity > oldCapacity)
        {
            int newCapacity = oldCapacity * 3 / 2 + 1;
            if(newCapacity < minCapacity)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }


    public int size()
    {
        return size;
    }


    public boolean isEmpty()
    {
        return size == 0;
    }

    public E[] toNativeArray()
    {
        return Arrays.copyOf(elementData, size);
    }


    public Object[] toArray()
    {
        return Arrays.copyOf(elementData, size);
    }


    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a)
    {
        if(a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if(a.length > size)
            a[size] = null;
        return a;
    }

    public E get(int index)
    {
        RangeCheck(index);
        return elementData[index];
    }


    public boolean add(E e)
    {
        ensureCapacity(size + 1);
        elementData[size++] = e;
        return true;
    }


    public boolean remove(Object o)
    {
        if(o == null)
        {
            for(int index = 0; index < size; index++)
                if(elementData[index] == null)
                {
                    fastRemove(index);
                    return true;
                }
        }
        else
            for(int index = 0; index < size; index++)
                if(o.equals(elementData[index]))
                {
                    fastRemove(index);
                    return true;
                }
        return false;
    }

    private void fastRemove(int index)
    {
        elementData[index] = elementData[size - 1];
        elementData[--size] = null; // Let gc do its work
    }

    public E remove(int index)
    {
        RangeCheck(index);
        E old = elementData[index];
        elementData[index] = elementData[size - 1];
        elementData[--size] = null;
        return old;
    }

    public E set(int index, E element)
    {
        RangeCheck(index);
        E oldValue = elementData[index];
        elementData[index] = element;
        return oldValue;
    }

    public int indexOf(Object o)
    {
        if(o == null)
        {
            for(int i = 0; i < size; i++)
                if(elementData[i] == null)
                    return i;
        }
        else
            for(int i = 0; i < size; i++)
                if(o.equals(elementData[i]))
                    return i;
        return -1;
    }


    public boolean contains(Object o)
    {
        if(o == null)
        {
            for(int i = 0; i < size; i++)
                if(elementData[i] == null)
                    return true;
        }
        else
            for(int i = 0; i < size; i++)
                if(o.equals(elementData[i]))
                    return true;
        return false;
    }


    public boolean addAll(Collection<? extends E> c)
    {
        boolean modified = false;
        Iterator<? extends E> e = c.iterator();
        while (e.hasNext())
            if(add(e.next()))
                modified = true;
        return modified;
    }


    public boolean removeAll(Collection<?> c)
    {
        boolean modified = false;
        for(int i = 0; i < size; i++)
            if(c.contains(elementData[i]))
            {
                elementData[i] = elementData[size - 1];
                elementData[--size] = null;
                modified = true;
            }
        return modified;
    }


    public boolean retainAll(Collection<?> c)
    {
        boolean modified = false;
        for(int i = 0; i < size; i++)
            if(!c.contains(elementData[i]))
            {
                elementData[i] = elementData[size - 1];
                elementData[--size] = null;
                modified = true;
            }
        return modified;
    }


    public boolean containsAll(Collection<?> c)
    {
        for(int i = 0; i < size; i++)
            if(!contains(elementData[i]))
                return false;
        return true;
    }

    private void RangeCheck(int index)
    {
        if(index >= size)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    }


    @SuppressWarnings("unchecked")
    public void clear()
    {
        int oldSize = size;
        size = 0;
        if(oldSize > 1000)
            elementData = (E[]) new Object[10];
        else
            for(int i = 0; i < oldSize; i++)
                elementData[i] = null;
        size = 0;
    }

    /**
    * Осторожно, при таком очищении в массиве могут оставаться ссылки на обьекты,
    * удерживающие эти обьекты в памяти!
    */
    public void clearSize()
    {
        size = 0;
    }


    public Iterator<E> iterator()
    {
        return new Itr();
    }

    private class Itr implements Iterator<E>
    {
        E[] data = toNativeArray();
        int size = data.length;
        int cursor = 0;

    
        public boolean hasNext()
        {
            return cursor != size;
        }

    
        public E next()
        {
            try
            {
                return data[cursor++];
            }
            catch(IndexOutOfBoundsException e)
            {
                throw new NoSuchElementException();
            }
        }

        /**
        * НЕ РАБОТАЕТ!
        */
    
        public void remove()
        {
            throw new IllegalStateException();
        }
    }
}
 
Кик, а ты в пхп случайно не шаришь? без сарказма. мне нужен норм чел, чтобы сказал где у меня говно код)
 
А можно чутка разжевать как этот говнокод влияет на игровой процесс? ну с академией все понятно...
 
Изначально это повлияет на стабильность и работу самой сборки, а после перетечет в игровой процесс, потому что могут творится некие чудеса, и аптайм самого сервера будет не очень хорошим. Плюс зачем серверу выполнять кучу ненужных задач и грузить излишне память, когда можно сделать компактнее, а что-то действительно убрать вовсе. Но так как Расторгуев большой поклонник конфигов и модов, то у этого человека всегда на первом месте был,есть и будет лишний хлам с костылями, который будет систематически отражаться на работе сервера.
 
То есть по сути, на игровой процесс в целом никак не влияет?)
 
То есть по сути, на игровой процесс в целом никак не влияет?)
Скажу проще, смотря что через это гавно реализовано. Я не смотрел эти исходники, сужу по пакетам которые выложил кик на обозрение.
Т.е. на малом онлайне, тот самый гавно код простит еще. Если говорить про крупный, хотя бы 400 человек (+/-), вот тогда использование этого чуда недопустимо.
Очень хороший пример - это сборка от grind team
 
Ну, суть то сего дела мне понятна так. Либо человек бежит из точки "а" в точку "б", либо он скачет на одной ноге еще через десять точек, напевая песенки и жонглируя. Результат и там и там один - попадание из точки "а" в точку "б".
Но. Конечный пользователь, игрок, процесса перехода не видит. Он, грубо говоря, делает запрос серверу - "надо чтоб человек оказался из точки "а" в точке "б" ", и через мгновение видит как человек, бывший в точке "а", оказался в точке "б". Как он это сделал, пользователю по сути пофиг.

Если без аллегорий, на сколько я понял, говнокод выльется в лишние затраты ресурсов железа?
 
Обратите внимание, что данный пользователь заблокирован! Не совершайте с ним никаких сделок! Перейдите в его профиль, чтобы узнать причину блокировки.
в гринде не круче есть подобная тема ,(там куда веселее все)
PS ты же тоже некст колупал там же тоже такое бред насунут , причем еще основателем Блудом

PS дополню сейчас делают 90% по....й как но лижбы что то типо работало
 
Последнее редактирование:
Хорошо если только затраты железа. Железу придется покрывать лишние задачи которые использует ядро, и возможные утечки памяти.
И всё это только цветочки. А ягодки пойдут, когда по непонятным причинам произойдет краш сервера или частично.
Могу привести в пример того же гринда и его эвент двиг, что после 2-х дневной работы сервера при онлайне в 300+ , могут не завершатся эвенты или не запускаться вообще. Поможет только рестарт сервера. Плюс ко всему заваленный лог ошибками, которые вызваны не то чтобы провоцирующими действиями игрока, а скорее кривым кодом. Хотя Java такая штука, что можно сделать косяк в кодинге в 1 пакете, но этот пакет может потащить за собой что нибудь еще.
Поэтому вопрос оптимизации, и не только оптимизации, он очень важен.
 
Ну вот я для себя вывел 3 типа говнокода:
- ultra optimization, т.е. низкая производительность, утечки;
- кодим в одну строчку, т.е. отсутствие или непродуманность отступов, неинформативные/дезинформирующие названия и т.п;
- убил ножом с другого конца карты, т.е. взятые данные "с потолка" (ясное дело, если придумывать эти данные и потом их тестировать и балансировать для работы с другими данными, то данный пунктик отпадает), логические ошибки.