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



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

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


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




ANTICHAT ™ © 2001- Antichat Kft.