Search in sources :

Example 91 with BatchUpdateException

use of java.sql.BatchUpdateException in project ignite by apache.

the class JdbcInsertStatementSelfTest method testErrorAmidstBatch.

/**
 * @throws SQLException if failed.
 */
@Test
public void testErrorAmidstBatch() throws SQLException {
    formBatch(1, 2);
    // Duplicate key
    formBatch(3, 1);
    BatchUpdateException reason = (BatchUpdateException) GridTestUtils.assertThrows(log, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            return prepStmt.executeBatch();
        }
    }, BatchUpdateException.class, "Failed to INSERT some keys because they are already in cache");
    // Check update counts in the exception.
    int[] counts = reason.getUpdateCounts();
    assertNotNull(counts);
    assertEquals(1, counts.length);
    assertEquals(2, counts[0]);
}
Also used : Callable(java.util.concurrent.Callable) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test)

Example 92 with BatchUpdateException

use of java.sql.BatchUpdateException in project ignite by apache.

the class JdbcInsertStatementSelfTest method testSingleItemBatchError.

/**
 * @throws SQLException if failed.
 */
@Test
public void testSingleItemBatchError() throws SQLException {
    formBatch(1, 2);
    prepStmt.executeBatch();
    // Duplicate key
    formBatch(1, 2);
    BatchUpdateException reason = (BatchUpdateException) GridTestUtils.assertThrows(log, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            return prepStmt.executeBatch();
        }
    }, BatchUpdateException.class, "Failed to INSERT some keys because they are already in cache");
    // Check update counts in the exception.
    assertTrue(F.isEmpty(reason.getUpdateCounts()));
}
Also used : Callable(java.util.concurrent.Callable) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test)

Example 93 with BatchUpdateException

use of java.sql.BatchUpdateException in project ignite by apache.

the class JdbcStatementBatchingSelfTest method testErrorAmidstBatch.

/**
 * @throws SQLException If failed.
 */
@Test
public void testErrorAmidstBatch() throws SQLException {
    BatchUpdateException reason = (BatchUpdateException) GridTestUtils.assertThrows(log, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            try (Statement stmt = conn.createStatement()) {
                stmt.addBatch("INSERT INTO Person(_key, id, firstName, lastName, age, data) " + "VALUES ('p1', 0, 'J', 'W', 250, RAWTOHEX('W'))");
                stmt.addBatch("UPDATE Person SET id = 3, firstName = 'Mike', lastName = 'Green', " + "age = 40, data = RAWTOHEX('Green') WHERE _key = 'p3'");
                stmt.addBatch("SELECT id FROM Person WHERE _key = 'p1'");
                return stmt.executeBatch();
            }
        }
    }, BatchUpdateException.class, "Given statement type does not match that declared by JDBC driver");
    // Check update counts in the exception.
    int[] counts = reason.getUpdateCounts();
    assertEquals(2, counts.length);
    assertEquals(1, counts[0]);
    assertEquals(0, counts[1]);
}
Also used : Statement(java.sql.Statement) Callable(java.util.concurrent.Callable) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test)

Example 94 with BatchUpdateException

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

the class Interest method run.

@Override
public void run() {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    DecimalFormat DecimalFormat = new DecimalFormat("#.##");
    List<String> players = new ArrayList<String>();
    HashMap<String, Integer> bankPlayers = new HashMap<String, Integer>();
    if (Constants.InterestOnline) {
        Player[] player = iConomy.getBukkitServer().getOnlinePlayers();
        if (Constants.InterestType.equalsIgnoreCase("players") || !Constants.Banking) {
            for (Player p : player) {
                players.add(p.getName());
            }
        } else {
            for (Player p : player) {
                Account account = iConomy.getAccount(p.getName());
                if (account != null) {
                    for (BankAccount baccount : account.getBankAccounts()) {
                        bankPlayers.put(p.getName(), baccount.getBankId());
                    }
                }
            }
        }
    } else {
        conn = iConomy.getiCoDatabase().getConnection();
        try {
            if (Constants.InterestType.equalsIgnoreCase("players") || !Constants.Banking)
                ps = conn.prepareStatement("SELECT * FROM " + Constants.SQLTable);
            else {
                ps = conn.prepareStatement("SELECT account_name,bank_id FROM " + Constants.SQLTable + "_BankRelations group by bank_id");
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                if (Constants.InterestType.equalsIgnoreCase("players") || !Constants.Banking)
                    players.add(rs.getString("username"));
                else {
                    bankPlayers.put(rs.getString("account_name"), rs.getInt("bank_id"));
                }
            }
        } catch (Exception E) {
            System.out.println("[iConomy] Error executing query for interest: " + E.getMessage());
        } finally {
            if (conn != null)
                conn = null;
            if (ps != null)
                ps = null;
            if (rs != null)
                rs = null;
        }
    }
    double cutoff = Constants.InterestCutoff;
    double amount = 0.0;
    boolean percentage = false;
    if (Constants.InterestPercentage != 0.0) {
        percentage = true;
    } else {
        Double min = Constants.InterestMin;
        Double max = Constants.InterestMax;
        try {
            if (min != max)
                amount = Double.valueOf(DecimalFormat.format(Math.random() * (max - min) + (min)));
            else {
                amount = max;
            }
        } catch (NumberFormatException e) {
            System.out.println("[iConomy] Invalid Interest: " + e);
        }
    }
    try {
        conn = iConomy.getiCoDatabase().getConnection();
        conn.setAutoCommit(false);
        if (Constants.InterestType.equalsIgnoreCase("players") || !Constants.Banking) {
            String updateSQL = "UPDATE " + Constants.SQLTable + " SET balance = ? WHERE username = ?";
            ps = conn.prepareStatement(updateSQL);
            for (String name : players) {
                Account account = iConomy.getAccount(name);
                if (account != null) {
                    Holdings holdings = account.getHoldings();
                    if (holdings != null) {
                        double balance = holdings.balance();
                        double original = balance;
                        if (cutoff > 0.0) {
                            if (original >= cutoff) {
                                continue;
                            }
                        } else if (cutoff < 0.0) {
                            if (original <= cutoff) {
                                continue;
                            }
                        }
                        if (percentage) {
                            amount = Math.round((Constants.InterestPercentage * balance) / 100);
                        }
                        ps.setDouble(1, balance + amount);
                        ps.setString(2, name);
                        ps.addBatch();
                        if (Constants.InterestAnn && Constants.InterestOnline) {
                            Messaging.send(iConomy.getBukkitServer().getPlayer(name), Template.parse("interest.announcement", new String[] { "+amount,+money,+interest,+a,+m,+i" }, new Object[] { iConomy.format(amount) }));
                        }
                        if (amount < 0.0)
                            iConomy.getTransactions().insert("[System Interest]", name, 0.0, original, 0.0, 0.0, amount);
                        else {
                            iConomy.getTransactions().insert("[System Interest]", name, 0.0, original, 0.0, amount, 0.0);
                        }
                    }
                }
            }
        } else {
            String updateSQL = "UPDATE " + Constants.SQLTable + "_BankRelations SET holdings = ? WHERE account_name = ? AND bank_id = ?";
            ps = conn.prepareStatement(updateSQL);
            for (String name : bankPlayers.keySet()) {
                Account account = iConomy.getAccount(name);
                if (account != null) {
                    Holdings holdings = account.getBankHoldings(bankPlayers.get(name));
                    if (holdings != null) {
                        double balance = holdings.balance();
                        double original = balance;
                        if (cutoff > 0.0) {
                            if (original >= cutoff) {
                                continue;
                            }
                        } else if (cutoff < 0.0) {
                            if (original <= cutoff) {
                                continue;
                            }
                        }
                        if (percentage) {
                            amount = Math.round((Constants.InterestPercentage * balance) / 100);
                        }
                        ps.setDouble(1, balance + amount);
                        ps.setString(2, name);
                        ps.setInt(3, bankPlayers.get(name));
                        ps.addBatch();
                        if (Constants.InterestAnn && Constants.InterestOnline) {
                            Messaging.send(iConomy.getBukkitServer().getPlayer(name), Template.parse("interest.announcement", new String[] { "+amount,+money,+interest,+a,+m,+i" }, new Object[] { iConomy.format(amount) }));
                        }
                        if (amount < 0.0)
                            iConomy.getTransactions().insert("[System Interest]", name, 0.0, original, 0.0, 0.0, amount);
                        else {
                            iConomy.getTransactions().insert("[System Interest]", name, 0.0, original, 0.0, amount, 0.0);
                        }
                    }
                }
            }
        }
        // Execute the batch.
        ps.executeBatch();
        // Commit
        conn.commit();
        ps.clearBatch();
    } catch (BatchUpdateException e) {
        System.out.println(e);
    } catch (SQLException e) {
        System.out.println(e);
    } finally {
        if (ps != null)
            try {
                ps.close();
            } catch (SQLException ex) {
            }
        if (conn != null)
            iConomy.getiCoDatabase().close(conn);
    }
}
Also used : Player(org.bukkit.entity.Player) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) DecimalFormat(java.text.DecimalFormat) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) BatchUpdateException(java.sql.BatchUpdateException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) BatchUpdateException(java.sql.BatchUpdateException)

Example 95 with BatchUpdateException

use of java.sql.BatchUpdateException in project ambry by linkedin.

the class AccountDaoTest method testAddContainerWithException.

@Test
public void testAddContainerWithException() throws Exception {
    when(mockContainerInsertStatement.executeBatch()).thenThrow(new BatchUpdateException());
    TestUtils.assertException(BatchUpdateException.class, () -> accountDao.updateAccounts(Collections.singletonList(testAccountInfo), 50), null);
}
Also used : BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.Test)

Aggregations

BatchUpdateException (java.sql.BatchUpdateException)103 SQLException (java.sql.SQLException)39 PreparedStatement (java.sql.PreparedStatement)33 Statement (java.sql.Statement)22 ArrayList (java.util.ArrayList)19 Test (org.junit.Test)19 Connection (java.sql.Connection)17 Test (org.testng.annotations.Test)17 BaseTest (util.BaseTest)17 SerializedBatchUpdateException (util.SerializedBatchUpdateException)17 ResultSet (java.sql.ResultSet)13 List (java.util.List)12 CallableStatement (java.sql.CallableStatement)8 HashSet (java.util.HashSet)8 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)7 HashMap (java.util.HashMap)6 Map (java.util.Map)5 CustomChangeException (liquibase.exception.CustomChangeException)5 DatabaseException (liquibase.exception.DatabaseException)5 SetupException (liquibase.exception.SetupException)5