HOME FORUMS MEMBERS RECENT POSTS LOG IN  
× Авторизация
Имя пользователя:
Пароль:
Нет аккаунта? Регистрация
Баннер 1   Баннер 2
НОВЫЕ ТОРГОВАЯ НОВОСТИ ЧАТ
loading...
Скрыть
Вернуться   ANTICHAT > ПРОГРАММИРОВАНИЕ > Общие вопросы программирования
   
Ответ
 
Опции темы Поиск в этой теме Опции просмотра

  #1  
Старый 17.08.2015, 12:53
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

Решил посмотреть топ сурс, специально для этого раздела с этой шары [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 _connections = new ConcurrentHashMap();

    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 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();
    }
}
Цитата:
Сообщение от Спойлер  


Код:


[CODE]
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

Цитата:
Сообщение от Спойлер  

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 tablesList = new ArrayList();

            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 tablesList = new ArrayList();

            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.*
 
Ответить с цитированием

  #2  
Старый 17.08.2015, 13:00
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

Цитата:
Сообщение от Спойлер  


Код:


[CODE]
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 map = new HashMap();

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

Цитата:
Сообщение от Спойлер  


Код:


Код:
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.
 
Ответить с цитированием

  #3  
Старый 17.08.2015, 13:02
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

Цитата:
Сообщение от Спойлер  


Код:


[CODE]
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

Цитата:
Сообщение от Спойлер  


Код:


Код:
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);
        }
    }
}
 
Ответить с цитированием

  #4  
Старый 17.08.2015, 13:03
mwmkr
Постоянный
Регистрация: 16.08.2015
Сообщений: 573
С нами: 5653763

Репутация: 0


По умолчанию

над будет заняться изучением и сесть попилить)
 
Ответить с цитированием

  #5  
Старый 17.08.2015, 13:06
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

Цитата:
Сообщение от Спойлер  


Код:


Код:
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 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 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 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 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 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  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  0)
            {
                final long item_count = item.getCount();
                final long rem = count  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 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 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()  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 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();
}
 
Ответить с цитированием

  #6  
Старый 17.08.2015, 13:11
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

l2s\log - сюда не заходим, ещё видим какой [S]отличный[/S] логер реализован.

Видим использование javolution.
 
Ответить с цитированием

  #7  
Старый 17.08.2015, 13:13
mwmkr
Постоянный
Регистрация: 16.08.2015
Сообщений: 573
С нами: 5653763

Репутация: 0


По умолчанию

кик погляди на сервис академмии...... (как у аверии, типа)

там реально вырви глаз)
 
Ответить с цитированием

  #8  
Старый 17.08.2015, 13:15
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

Цитата:
Сообщение от mwmkr  

кик погляди на сервис академмии...... (как у аверии, типа)
там реально вырви глаз)
Так это не его а чужой
 
Ответить с цитированием

  #9  
Старый 17.08.2015, 13:16
mwmkr
Постоянный
Регистрация: 16.08.2015
Сообщений: 573
С нами: 5653763

Репутация: 0


По умолчанию

Цитата:
Сообщение от kick  

Так это не его а чужой
я про то, что он даже прикрутить не смог его нормально.

такая херня, что даже при не созданной академии в клане, можно инвайтить, так еще и очки зачислят после сдачи профы
 
Ответить с цитированием

  #10  
Старый 17.08.2015, 13:28
kick
Флудер
Регистрация: 20.01.2015
Сообщений: 7,201
С нами: 5952720

Репутация: 6527


По умолчанию

Ох всеми любимый 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 implements Collection, 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  oldCapacity)
        {
            int newCapacity = oldCapacity * 3 / 2 + 1;
            if(newCapacity  procedure)
    {
        for(int i = size; i-- > 0;)
            if(!procedure.execute(elementData[i]))
                return false;
        return true;
    }

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

    public void forEachThread(final INgVoidProcedure 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[] toArray(T[] a)
    {
        if(a.length  size)
            a[size] = null;
        return a;
    }

    public final  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)
            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 || index  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  c)
    {
        if(c == null)
            return false;
        boolean modified = false;
        Iterator 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  c)
    {
        boolean modified = false;
        for(int i = 0; i  c)
    {
        for(int i = 0; i = size || index  1000)
            elementData = (E[]) new Object[10];
        else
            for(int i = 0; i  iterator()
    {
        return new Itr();
    }

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

    
        public final boolean hasNext()
        {
            return cursor ";
    }

    @SuppressWarnings({ "unchecked" })
    public static final  GArray 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 extends GArray
{

    public final Iterator 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[] 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 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 procedure)
    {
        return true;
    }

    public final void forEach(final INgVoidProcedure procedure)
    {}

    public final void forEachThread(final INgVoidProcedure procedure)
    {}
}
Цитата:
Сообщение от Спойлер  


Код:


Код:
package l2s.commons.list;

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

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

    @SuppressWarnings("unchecked")
    public GCArray(int initialCapacity)
    {
        super();
        if(initialCapacity  oldCapacity)
        {
            int newCapacity = oldCapacity * 3 / 2 + 1;
            if(newCapacity  T[] toArray(T[] a)
    {
        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  c)
    {
        boolean modified = false;
        Iterator 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  c)
    {
        boolean modified = false;
        for(int i = 0; i  c)
    {
        for(int i = 0; i = 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  iterator()
    {
        return new Itr();
    }

    private class Itr implements Iterator
    {
        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();
        }
    }
}
 
Ответить с цитированием
Ответ



Предыдущая тема Следующая тема

Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT ™ © 2001- Antichat Kft.