Search in sources :

Example 36 with SQLException

use of java.sql.SQLException in project Openfire by igniterealtime.

the class DbRuleManager method addRule.

public boolean addRule(Rule rule, Integer order) {
    Connection con = null;
    PreparedStatement pstmt = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(INSERT_RULE);
        if (order == null) {
            order = getLastOrderId() + 1;
            pstmt.setInt(1, order);
        } else {
            pstmt.setInt(1, order);
        }
        rule.setOrder(order);
        pstmt.setString(2, rule.getPackeType().toString());
        pstmt.setString(3, rule.getDestination());
        pstmt.setString(4, rule.getSource());
        pstmt.setString(5, rule.getClass().getName());
        if (rule.isDisabled()) {
            pstmt.setBoolean(6, Boolean.TRUE);
        } else {
            pstmt.setBoolean(6, Boolean.FALSE);
        }
        if (rule.doLog()) {
            pstmt.setBoolean(7, Boolean.TRUE);
        } else {
            pstmt.setBoolean(7, Boolean.FALSE);
        }
        pstmt.setString(8, rule.getDescription());
        pstmt.setString(9, rule.getSourceType().toString());
        pstmt.setString(10, rule.getDestType().toString());
        pstmt.execute();
        rules.clear();
    } catch (SQLException sqle) {
        Log.error(sqle.getMessage(), sqle);
        return false;
    } finally {
        DbConnectionManager.closeConnection(pstmt, con);
        updateCluster();
    }
    return true;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 37 with SQLException

use of java.sql.SQLException in project Core by iConomy.

the class iConomy method onEnable.

public void onEnable() {
    final long startTime = System.nanoTime();
    final long endTime;
    try {
        // Localize locale to prevent issues.
        Locale.setDefault(Locale.US);
        // Server & Terminal Support
        Server = getServer();
        if (getServer().getServerName().equalsIgnoreCase("craftbukkit")) {
            TerminalSupport = ((CraftServer) getServer()).getReader().getTerminal().isANSISupported();
        }
        // Get general plugin information
        info = getDescription();
        // Plugin directory setup
        directory = getDataFolder();
        if (!directory.exists())
            directory.mkdir();
        // Extract Files
        Common.extract("Config.yml", "Template.yml");
        // Setup Configuration
        Constants.load(new File(directory, "Config.yml"));
        // Setup Template
        Template = new Template(directory.getPath(), "Template.yml");
        // Upgrade Template to 6.0.9b
        LinkedHashMap<String, String> nodes = new LinkedHashMap<String, String>();
        nodes.put("top.opening", "<green>-----[ <white>Wealthiest Accounts <green>]-----");
        nodes.put("top.item", "<gray>+i. <green>+name <gray>- <white>+amount");
        try {
            Template.update(nodes);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        // Check Drivers if needed
        Type type = Database.getType(Constants.Nodes.DatabaseType.toString());
        if (!(type.equals(Type.InventoryDB) || type.equals(Type.MiniDB))) {
            Drivers driver = null;
            switch(type) {
                case H2DB:
                    driver = Constants.Drivers.H2;
                    break;
                case MySQL:
                    driver = Constants.Drivers.MySQL;
                    break;
                case SQLite:
                    driver = Constants.Drivers.SQLite;
                    break;
                case Postgre:
                    driver = Constants.Drivers.Postgre;
                    break;
            }
            if (driver != null)
                if (!(new File("lib", driver.getFilename()).exists())) {
                    System.out.println("[iConomy] Downloading " + driver.getFilename() + "...");
                    wget.fetch(driver.getUrl(), driver.getFilename());
                    System.out.println("[iConomy] Finished Downloading.");
                }
        }
        // Setup Commands
        Commands.add("/money +name", new Money(this));
        Commands.setPermission("money", "iConomy.holdings");
        Commands.setPermission("money+", "iConomy.holdings.others");
        Commands.setHelp("money", new String[] { "", "Check your balance." });
        Commands.setHelp("money+", new String[] { " [name]", "Check others balance." });
        Commands.add("/money -h|?|help +command", new Help(this));
        Commands.setPermission("help", "iConomy.help");
        Commands.setHelp("help", new String[] { " (command)", "For Help & Information." });
        Commands.add("/money -t|top", new Top(this));
        Commands.setPermission("top", "iConomy.top");
        Commands.setHelp("top", new String[] { "", "View top economical accounts." });
        Commands.add("/money -p|pay +name +amount:empty", new Payment(this));
        Commands.setPermission("pay", "iConomy.payment");
        Commands.setHelp("pay", new String[] { " [name] [amount]", "Send money to others." });
        Commands.add("/money -c|create +name", new Create(this));
        Commands.setPermission("create", "iConomy.accounts.create");
        Commands.setHelp("create", new String[] { " [name]", "Create an account." });
        Commands.add("/money -r|remove +name", new Remove(this));
        Commands.setPermission("remove", "iConomy.accounts.remove");
        Commands.setHelp("remove", new String[] { " [name]", "Remove an account." });
        Commands.add("/money -g|give +name +amount:empty", new Give(this));
        Commands.setPermission("give", "iConomy.accounts.give");
        Commands.setHelp("give", new String[] { " [name] [amount]", "Give money." });
        Commands.add("/money -t|take +name +amount:empty", new Take(this));
        Commands.setPermission("take", "iConomy.accounts.take");
        Commands.setHelp("take", new String[] { " [name] [amount]", "Take money." });
        Commands.add("/money -s|set +name +amount:empty", new Set(this));
        Commands.setPermission("set", "iConomy.accounts.set");
        Commands.setHelp("set", new String[] { " [name] [amount]", "Set account balance." });
        Commands.add("/money -u|status +name +status:empty", new Status(this));
        Commands.setPermission("status", "iConomy.accounts.status");
        Commands.setPermission("status+", "iConomy.accounts.status.set");
        Commands.setHelp("status", new String[] { " [name] (status)", "Check/Set account status." });
        Commands.add("/money -x|purge", new Purge(this));
        Commands.setPermission("purge", "iConomy.accounts.purge");
        Commands.setHelp("purge", new String[] { "", "Purge all accounts with initial holdings." });
        Commands.add("/money -e|empty", new Empty(this));
        Commands.setPermission("empty", "iConomy.accounts.empty");
        Commands.setHelp("empty", new String[] { "", "Empty database of accounts." });
        // Setup Database.
        try {
            Database = new Database(Constants.Nodes.DatabaseType.toString(), Constants.Nodes.DatabaseUrl.toString(), Constants.Nodes.DatabaseUsername.toString(), Constants.Nodes.DatabasePassword.toString());
            // If it doesn't exist, Create one.
            if (Database.isSQL()) {
                if (!Database.tableExists(Constants.Nodes.DatabaseTable.toString())) {
                    String SQL = Common.resourceToString("SQL/Core/Create-Table-" + Database.getType().toString().toLowerCase() + ".sql");
                    SQL = String.format(SQL, Constants.Nodes.DatabaseTable.getValue());
                    try {
                        QueryRunner run = new QueryRunner();
                        Connection c = iConomy.Database.getConnection();
                        try {
                            run.update(c, SQL);
                        } catch (SQLException ex) {
                            System.out.println("[iConomy] Error creating database: " + ex);
                        } finally {
                            DbUtils.close(c);
                        }
                    } catch (SQLException ex) {
                        System.out.println("[iConomy] Database Error: " + ex);
                    }
                }
            } else {
                this.onConversion();
            }
        } catch (MissingDriver ex) {
            System.out.println(ex.getMessage());
        }
        getServer().getPluginManager().registerEvents(new players(), this);
    } finally {
        endTime = System.nanoTime();
    }
    // Setup Interest
    if (Constants.Nodes.Interest.getBoolean()) {
        Thrun.init(new Runnable() {

            public void run() {
                long time = Constants.Nodes.InterestTime.getLong() * 1000L;
                Interest = new Timer();
                Interest.scheduleAtFixedRate(new Interest(getDataFolder().getPath()), time, time);
            }
        });
    }
    if (Constants.Nodes.Purging.getBoolean()) {
        Thrun.init(new Runnable() {

            public void run() {
                Queried.purgeDatabase();
                System.out.println("[" + info.getName() + " - " + Constants.Nodes.CodeName.toString() + "] Purged accounts with default balance.");
            }
        });
    }
    final long duration = endTime - startTime;
    // Finish
    System.out.println("[" + info.getName() + " - " + Constants.Nodes.CodeName.toString() + "] Enabled (" + Common.readableProfile(duration) + ")");
}
Also used : ResultSet(java.sql.ResultSet) Drivers(com.iCo6.Constants.Drivers) SQLException(java.sql.SQLException) Template(com.iCo6.util.Template) LinkedHashMap(java.util.LinkedHashMap) Interest(com.iCo6.system.Interest) Database(com.iCo6.IO.Database) com.iCo6.listeners.players(com.iCo6.listeners.players) Connection(java.sql.Connection) IOException(java.io.IOException) QueryRunner(com.iCo6.util.org.apache.commons.dbutils.QueryRunner) Type(com.iCo6.IO.Database.Type) Timer(java.util.Timer) MissingDriver(com.iCo6.IO.exceptions.MissingDriver) File(java.io.File) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile)

Example 38 with SQLException

use of java.sql.SQLException in project Core by iConomy.

the class iConomy method onConversion.

public boolean onConversion() {
    if (!Constants.Nodes.Convert.getBoolean())
        return false;
    Thrun.init(new Runnable() {

        public void run() {
            String from = Constants.Nodes.ConvertFrom.toString();
            String table = Constants.Nodes.ConvertTable.toString();
            String username = Constants.Nodes.ConvertUsername.toString();
            String password = Constants.Nodes.ConvertPassword.toString();
            String url = Constants.Nodes.ConvertURL.toString();
            if (!Common.matches(from, "h2", "h2db", "h2sql", "mysql", "mysqldb"))
                return;
            String driver = "", dsn = "";
            if (Common.matches(from, "sqlite", "h2", "h2sql", "h2db")) {
                driver = "org.h2.Driver";
                dsn = "jdbc:h2:" + directory + File.separator + table + ";AUTO_RECONNECT=TRUE";
                username = "sa";
                password = "sa";
            } else if (Common.matches(from, "mysql", "mysqldb")) {
                driver = "com.mysql.jdbc.Driver";
                dsn = url + "/" + table;
            }
            if (!DbUtils.loadDriver(driver)) {
                System.out.println("Please make sure the " + from + " driver library jar exists.");
                return;
            }
            Connection old = null;
            try {
                old = (username.isEmpty() && password.isEmpty()) ? DriverManager.getConnection(url) : DriverManager.getConnection(url, username, password);
            } catch (SQLException ex) {
                System.out.println(ex);
                return;
            }
            QueryRunner run = new QueryRunner();
            try {
                try {
                    run.query(old, "SELECT * FROM " + table, new ResultSetHandler() {

                        public Object handle(ResultSet rs) throws SQLException {
                            Account current = null;
                            Boolean next = rs.next();
                            if (next)
                                if (iConomy.Accounts.exists(rs.getString("username")))
                                    current = iConomy.Accounts.get(rs.getString("username"));
                                else
                                    iConomy.Accounts.create(rs.getString("username"), rs.getDouble("balance"));
                            if (current != null)
                                current.getHoldings().setBalance(rs.getDouble("balance"));
                            if (next)
                                if (iConomy.Accounts.exists(rs.getString("username")))
                                    if (rs.getBoolean("hidden"))
                                        iConomy.Accounts.get(rs.getString("username")).setStatus(1);
                            return true;
                        }
                    });
                } catch (SQLException ex) {
                    System.out.println("[iConomy] Error issueing SQL query: " + ex);
                } finally {
                    DbUtils.close(old);
                }
            } catch (SQLException ex) {
                System.out.println("[iConomy] Database Error: " + ex);
            }
            System.out.println("[iConomy] Conversion complete. Please update your configuration, change convert to false!");
        }
    });
    return false;
}
Also used : Account(com.iCo6.system.Account) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ResultSetHandler(com.iCo6.util.org.apache.commons.dbutils.ResultSetHandler) QueryRunner(com.iCo6.util.org.apache.commons.dbutils.QueryRunner)

Example 39 with SQLException

use of java.sql.SQLException in project Core by iConomy.

the class BeanProcessor method callSetter.

/**
     * Calls the setter method on the target object for the given property.
     * If no setter method exists for the property, this method does nothing.
     * @param target The object to set the property on.
     * @param prop The property to set.
     * @param value The value to pass into the setter.
     * @throws SQLException if an error occurs setting the property.
     */
private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException {
    Method setter = prop.getWriteMethod();
    if (setter == null) {
        return;
    }
    Class<?>[] params = setter.getParameterTypes();
    try {
        // convert types for some popular ones
        if (value != null) {
            if (value instanceof java.util.Date) {
                if (params[0].getName().equals("java.sql.Date")) {
                    value = new java.sql.Date(((java.util.Date) value).getTime());
                } else if (params[0].getName().equals("java.sql.Time")) {
                    value = new java.sql.Time(((java.util.Date) value).getTime());
                } else if (params[0].getName().equals("java.sql.Timestamp")) {
                    value = new java.sql.Timestamp(((java.util.Date) value).getTime());
                }
            }
        }
        // Don't call setter if the value object isn't the right type 
        if (this.isCompatibleType(value, params[0])) {
            setter.invoke(target, new Object[] { value });
        } else {
            throw new SQLException("Cannot set " + prop.getName() + ": incompatible types.");
        }
    } catch (IllegalArgumentException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());
    } catch (IllegalAccessException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());
    } catch (InvocationTargetException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());
    }
}
Also used : SQLException(java.sql.SQLException) Timestamp(java.sql.Timestamp) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 40 with SQLException

use of java.sql.SQLException in project Core by iConomy.

the class QueryRunner method fillStatement.

/**
     * Fill the <code>PreparedStatement</code> replacement parameters with 
     * the given objects.
     * @param stmt PreparedStatement to fill
     * @param params Query replacement parameters; <code>null</code> is a valid
     * value to pass in.
     * @throws SQLException if a database access error occurs
     */
public void fillStatement(PreparedStatement stmt, Object... params) throws SQLException {
    if (params == null) {
        return;
    }
    ParameterMetaData pmd = null;
    if (!pmdKnownBroken) {
        pmd = stmt.getParameterMetaData();
        if (pmd.getParameterCount() < params.length) {
            throw new SQLException("Too many parameters: expected " + pmd.getParameterCount() + ", was given " + params.length);
        }
    }
    for (int i = 0; i < params.length; i++) {
        if (params[i] != null) {
            stmt.setObject(i + 1, params[i]);
        } else {
            // VARCHAR works with many drivers regardless
            // of the actual column type.  Oddly, NULL and 
            // OTHER don't work with Oracle's drivers.
            int sqlType = Types.VARCHAR;
            if (!pmdKnownBroken) {
                try {
                    sqlType = pmd.getParameterType(i + 1);
                } catch (SQLException e) {
                    pmdKnownBroken = true;
                }
            }
            stmt.setNull(i + 1, sqlType);
        }
    }
}
Also used : SQLException(java.sql.SQLException) ParameterMetaData(java.sql.ParameterMetaData)

Aggregations

SQLException (java.sql.SQLException)17708 PreparedStatement (java.sql.PreparedStatement)7646 ResultSet (java.sql.ResultSet)6472 Connection (java.sql.Connection)6226 Statement (java.sql.Statement)3089 ArrayList (java.util.ArrayList)2495 Test (org.junit.Test)1525 IOException (java.io.IOException)1220 List (java.util.List)760 HashMap (java.util.HashMap)633 CallableStatement (java.sql.CallableStatement)506 Map (java.util.Map)471 Properties (java.util.Properties)426 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)387 Timestamp (java.sql.Timestamp)363 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)328 DatabaseMetaData (java.sql.DatabaseMetaData)326 ResultSetMetaData (java.sql.ResultSetMetaData)301 DataSource (javax.sql.DataSource)295 File (java.io.File)280