List of usage examples for java.sql BatchUpdateException getNextException
public SQLException getNextException()
SQLException
object by setNextException(SQLException ex). From source file:wiki.link.LinkResource.java
public static void insertAll(List<Link> links, DbConnector dbc) { BatchPreparedStatementSetter bpss = new BatchPreparedStatementSetter() { @Override/*from ww w. j av a2 s. c om*/ public void setValues(PreparedStatement preparedStatement, int i) throws SQLException { preparedStatement.setLong(1, links.get(i).from); preparedStatement.setLong(2, links.get(i).to); } @Override public int getBatchSize() { return links.size(); } }; try { dbc.jdbcTemplate.batchUpdate("INSERT INTO links(fromPage, toPage) values(?, ?)", bpss); } catch (BadSqlGrammarException e) { e.printStackTrace(); BatchUpdateException bue = (BatchUpdateException) e.getCause(); System.out.println(bue.getNextException()); System.exit(1); } }
From source file:com.chaosinmotion.securechat.server.commands.DropMessages.java
public static void processRequest(UserInfo userinfo, JSONObject requestParams) throws ClassNotFoundException, SQLException, IOException { ArrayList<Message> messages = new ArrayList<Message>(); JSONArray a = requestParams.getJSONArray("messages"); int i, len = a.length(); for (i = 0; i < len; ++i) { JSONObject item = a.getJSONObject(i); Message msg = new Message(); msg.message = item.getInt("messageid"); msg.checksum = item.getString("checksum"); messages.add(msg);//from w w w. ja v a2 s. c o m } /* * Iterate through the messages, deleting each. We only delete a * message if message belongs to the user and the checksum matches. * This assumes it's our message and it was read with someone who * can read the message. * * (Thus, the weird query) */ Connection c = null; PreparedStatement ps = null; ResultSet rs = null; try { int count = 0; c = Database.get(); ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN " + " (SELECT Messages.messageid " + " FROM Messages, Devices " + " WHERE Messages.messageid = ? " + " AND Messages.checksum = ? " + " AND Devices.deviceid = Messages.deviceid " + " AND Devices.userid = ?)"); for (Message msg : messages) { /* * Get the device ID for this device. Verify it belongs to the * user specified */ ps.setInt(1, msg.message); ps.setString(2, msg.checksum); ps.setInt(3, userinfo.getUserID()); ps.addBatch(); ++count; if (count > 10240) { ps.executeBatch(); } } if (count > 0) { ps.executeBatch(); } } catch (BatchUpdateException batch) { throw batch.getNextException(); } finally { if (rs != null) rs.close(); if (ps != null) ps.close(); if (c != null) c.close(); } }
From source file:org.pvalsecc.jdbc.JdbcUtilities.java
public static <T> void runInsertQuery(String description, String sqlStatement, Connection conn, Iterator<T> items, int batchSize, InsertTask<T> task) throws SQLException { PreparedStatement stmt = null; try {//from w w w. j a v a2 s.com long beginTime = System.currentTimeMillis(); // It's property closed in the finally! //noinspection JDBCResourceOpenedButNotSafelyClosed stmt = conn.prepareStatement(sqlStatement); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Executing SQL : " + sqlStatement + " (" + description + ")"); } int idx = 0; int cpt = 0; while (items.hasNext()) { T item = items.next(); if (task.marshall(stmt, item)) { stmt.addBatch(); if (++idx >= batchSize) { stmt.executeBatch(); idx = 0; } ++cpt; } } if (idx > 0) { stmt.executeBatch(); // do not forget the last one as usual... } if (TIMING_LOGGER.isDebugEnabled()) { TIMING_LOGGER.debug("Time " + description + " (" + cpt + " records): " + UnitUtilities.toElapsedTime(System.currentTimeMillis() - beginTime)); } } catch (BatchUpdateException ex) { LOGGER.error(ex.getNextException()); throw ex; } finally { safeClose(stmt); } }
From source file:module.entities.NameFinder.DB.java
public static void insertDemocracitConsultationMinister(TreeMap<Integer, String> consultationCountersign, TreeMap<Integer, String> consultationCounterrole) throws SQLException { try {//from w w w .j ava 2 s . com String sql = "INSERT INTO consultations_ner " + "(id,countersigned_name, countersigned_position) VALUES " + "(?,?,?)"; PreparedStatement prepStatement = connection.prepareStatement(sql); for (int consId : consultationCountersign.keySet()) { prepStatement.setInt(1, consId); prepStatement.setString(2, consultationCountersign.get(consId)); if (consultationCounterrole.get(consId) != null) { prepStatement.setString(3, consultationCounterrole.get(consId)); } else { prepStatement.setString(3, ""); } prepStatement.addBatch(); } prepStatement.executeBatch(); prepStatement.close(); } catch (BatchUpdateException ex) { // ex.printStackTrace(); System.out.println(ex.getNextException()); } }
From source file:biblivre3.cataloging.bibliographic.IndexDAO.java
public final boolean insert(IndexTable table, List<IndexDTO> indexList) { if (indexList == null && indexList.isEmpty()) { return false; }/*from w ww. j a va 2 s.com*/ Connection con = null; try { con = getDataSource().getConnection(); StringBuilder sql = new StringBuilder(); sql.append(" INSERT INTO ").append(table.getTableName()); sql.append(" (index_word, record_serial) "); sql.append(" VALUES (?, ?);"); PreparedStatement pst = con.prepareStatement(sql.toString()); for (IndexDTO index : indexList) { pst.setString(1, StringUtils.substring(index.getWord(), 0, 511)); pst.setInt(2, index.getRecordSerial()); pst.addBatch(); } pst.executeBatch(); } catch (BatchUpdateException bue) { log.error(bue.getNextException(), bue); throw new ExceptionUser("ERROR_BIBLIO_DAO_EXCEPTION"); } catch (Exception e) { log.error(e.getMessage(), e); throw new ExceptionUser("ERROR_BIBLIO_DAO_EXCEPTION"); } finally { closeConnection(con); } return true; }
From source file:com.excilys.ebi.spring.dbunit.DbUnitDatabasePopulator.java
@Override public void populate(Connection connection) throws SQLException { LOGGER.debug("populating"); StopWatch sw = new StopWatch("DbUnitDatabasePopulator"); DatabaseOperation operation = phase.getOperation(dataSetConfiguration); try {// w w w .j a v a 2s . co m IDataSet dataSet = decorateDataSetIfNeeded(dataSetConfiguration.getDataSet(), dataSetConfiguration.getDecorators()); String schema = dataSetConfiguration.getSchema(); DatabaseConnection databaseConnection = getDatabaseConnection(connection, schema, dataSetConfiguration); sw.start("populating"); operation.execute(databaseConnection, dataSet); sw.stop(); LOGGER.debug(sw.prettyPrint()); } catch (BatchUpdateException e) { LOGGER.error("BatchUpdateException while loading dataset", e); LOGGER.error("Caused by : ", e.getNextException()); throw e; } catch (DatabaseUnitException e) { throw new DbUnitException(e); } catch (IOException e) { throw new DbUnitException(e); } }
From source file:org.fao.geonet.MetadataResourceDatabaseMigration.java
@Override public void update(Connection connection) throws SQLException { Log.debug(Geonet.DB, "MetadataResourceDatabaseMigration"); try (PreparedStatement update = connection.prepareStatement("UPDATE metadata SET data=? WHERE id=?")) { try (Statement statement = connection.createStatement(); ResultSet resultSet = statement .executeQuery("SELECT data,id,uuid FROM metadata WHERE isharvested = 'n'")) { int numInBatch = 0; final SettingManager settingManager = applicationContext.getBean(SettingManager.class); while (resultSet.next()) { final Element xml = Xml.loadString(resultSet.getString(1), false); final int id = resultSet.getInt(2); final String uuid = resultSet.getString(3); boolean changed = updateMetadataResourcesLink(xml, uuid, settingManager); if (changed) { String updatedData = Xml.getString(xml); update.setString(1, updatedData); update.setInt(2, id); update.addBatch();// w w w. j a v a 2 s. c o m numInBatch++; if (numInBatch > 200) { update.executeBatch(); numInBatch = 0; } } } update.executeBatch(); } catch (java.sql.BatchUpdateException e) { System.out.println("Error occurred while updating resource links:"); e.printStackTrace(); SQLException next = e.getNextException(); while (next != null) { System.err.println("Next error: "); next.printStackTrace(); next = e.getNextException(); } throw new RuntimeException(e); } catch (Exception e) { throw new Error(e); } } }
From source file:hoot.services.db.DbUtils.java
public static void deleteOSMRecordByName(Connection conn, String mapName) throws Exception { try {//w ww. j av a 2 s . c om Configuration configuration = getConfiguration(); QMaps maps = QMaps.maps; List<Long> mapIds = new SQLQuery(conn, configuration).from(maps) .where(maps.displayName.equalsIgnoreCase(mapName)).list(maps.id); if (mapIds.size() > 0) { Long mapId = mapIds.get(0); deleteMapRelatedTablesByMapId(mapId); conn.setAutoCommit(false); ListSubQuery<Long> res = new SQLSubQuery().from(maps) .where(maps.displayName.equalsIgnoreCase(mapName)).list(maps.id); new SQLDeleteClause(conn, configuration, maps).where(maps.displayName.eq(mapName)).execute(); QReviewItems reviewItems = QReviewItems.reviewItems; new SQLDeleteClause(conn, configuration, reviewItems).where(reviewItems.mapId.in(res)).execute(); QElementIdMappings elementIdMappings = QElementIdMappings.elementIdMappings; new SQLDeleteClause(conn, configuration, elementIdMappings).where(elementIdMappings.mapId.in(res)) .execute(); QReviewMap reviewMap = QReviewMap.reviewMap; new SQLDeleteClause(conn, configuration, reviewMap).where(reviewMap.mapId.in(res)).execute(); conn.commit(); } } catch (Exception e) { String msg = "Error deleting OSM record. "; if (e.getCause() instanceof BatchUpdateException) { BatchUpdateException batchException = (BatchUpdateException) e.getCause(); msg += " " + batchException.getNextException().getMessage(); } throw new Exception(msg); } }
From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java
/** * Returns the cause of a trigger exception (BatchupdateException). * /*w w w .j a va2 s .com*/ * Hibernate and JDBC will wrap the exception thrown by the trigger in another exception (the * java.sql.BatchUpdateException) and this exception is sometimes wrapped again. Also the * java.sql.BatchUpdateException stores the underlying trigger exception in the nextException and * not in the cause property. * * @param t * exception. * @return the underlying trigger message. */ public static String getExceptionMessage(Throwable t) { if (t.getCause() instanceof BatchUpdateException && ((BatchUpdateException) t.getCause()).getNextException() != null) { final BatchUpdateException bue = (BatchUpdateException) t.getCause(); return bue.getNextException().getMessage(); } return t.getMessage(); }
From source file:org.apache.marmotta.kiwi.reasoner.test.persistence.JustificationPersistenceTest.java
/** * Test 1: create some triples through a repository connection (some inferred, some base), load a program, and * store justifications for the inferred triples based on rules and base triples. Test the different listing * functions./*from w w w . j a v a 2 s.c o m*/ * */ @Test public void testStoreJustifications() throws Exception { KiWiValueFactory v = (KiWiValueFactory) repository.getValueFactory(); URI ctxb = v.createURI("http://localhost/context/default"); URI ctxi = v.createURI("http://localhost/context/inferred"); URI s1 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI s2 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI s3 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI p1 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI p2 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI o1 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI o2 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); URI o3 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8)); // first, load a sample program (it does not really matter what it actually contains, since we are not really // running the reasoner) KWRLProgramParserBase parser = new KWRLProgramParser(v, this.getClass().getResourceAsStream("test-001.kwrl")); Program p = parser.parseProgram(); p.setName("test-001"); KiWiReasoningConnection connection = rpersistence.getConnection(); try { // should not throw an exception and the program should have a database ID afterwards connection.storeProgram(p); connection.commit(); } finally { connection.close(); } // then get a connection to the repository and create a number of triples, some inferred and some base RepositoryConnection con = repository.getConnection(); try { con.add(s1, p1, o1); con.add(s2, p1, o2); con.add(s3, p1, o3); con.add(s1, p2, o1, ctxi); con.add(s2, p2, o2, ctxi); con.add(s3, p2, o3, ctxi); con.commit(); } finally { con.close(); } connection = rpersistence.getConnection(); try { // retrieve the persisted triples and put them into two sets to build justifications List<Statement> baseTriples = asList( connection.listTriples(null, null, null, v.convert(ctxb), false, true)); List<Statement> infTriples = asList( connection.listTriples(null, null, null, v.convert(ctxi), true, true)); Assert.assertEquals("number of base triples was not 3", 3, baseTriples.size()); Assert.assertEquals("number of inferred triples was not 3", 3, infTriples.size()); // we manually update the "inferred" flag for all inferred triples, since this is not possible through the // repository API PreparedStatement updateInferred = connection.getJDBCConnection() .prepareStatement("UPDATE triples SET inferred = true WHERE id = ?"); for (Statement stmt : infTriples) { KiWiTriple triple = (KiWiTriple) stmt; updateInferred.setLong(1, triple.getId()); updateInferred.addBatch(); } updateInferred.executeBatch(); updateInferred.close(); // now we create some justifications for the inferred triples and store them Set<Justification> justifications = new HashSet<Justification>(); Justification j1 = new Justification(); j1.getSupportingRules().add(p.getRules().get(0)); j1.getSupportingRules().add(p.getRules().get(1)); j1.getSupportingTriples().add((KiWiTriple) baseTriples.get(0)); j1.getSupportingTriples().add((KiWiTriple) baseTriples.get(1)); j1.setTriple((KiWiTriple) infTriples.get(0)); justifications.add(j1); Justification j2 = new Justification(); j2.getSupportingRules().add(p.getRules().get(1)); j2.getSupportingTriples().add((KiWiTriple) baseTriples.get(1)); j2.getSupportingTriples().add((KiWiTriple) baseTriples.get(2)); j2.setTriple((KiWiTriple) infTriples.get(1)); justifications.add(j2); connection.storeJustifications(justifications); connection.commit(); // we should now have two justifications in the database PreparedStatement listJustifications = connection.getJDBCConnection() .prepareStatement("SELECT count(*) AS count FROM reasoner_justifications"); ResultSet resultListJustifications = listJustifications.executeQuery(); Assert.assertTrue(resultListJustifications.next()); Assert.assertEquals(2, resultListJustifications.getInt("count")); resultListJustifications.close(); connection.commit(); PreparedStatement listSupportingTriples = connection.getJDBCConnection() .prepareStatement("SELECT count(*) AS count FROM reasoner_just_supp_triples"); ResultSet resultListSupportingTriples = listSupportingTriples.executeQuery(); Assert.assertTrue(resultListSupportingTriples.next()); Assert.assertEquals(4, resultListSupportingTriples.getInt("count")); resultListSupportingTriples.close(); connection.commit(); PreparedStatement listSupportingRules = connection.getJDBCConnection() .prepareStatement("SELECT count(*) AS count FROM reasoner_just_supp_rules"); ResultSet resultListSupportingRules = listSupportingRules.executeQuery(); Assert.assertTrue(resultListSupportingRules.next()); Assert.assertEquals(3, resultListSupportingRules.getInt("count")); resultListSupportingRules.close(); connection.commit(); // *** check listing justifications by base triple (supporting triple) // there should now be two justifications based on triple baseTriples.get(1)) List<Justification> supported1 = asList( connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(1))); Assert.assertEquals("number of justifications is wrong", 2, supported1.size()); Assert.assertThat("justifications differ", supported1, hasItems(j1, j2)); // only j1 should be supported by triple baseTriples.get(0)) List<Justification> supported2 = asList( connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(0))); Assert.assertEquals("number of justifications is wrong", 1, supported2.size()); Assert.assertThat("justifications differ", supported2, allOf(hasItem(j1), not(hasItem(j2)))); // only j2 should be supported by triple baseTriples.get(2)) List<Justification> supported3 = asList( connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(2))); Assert.assertEquals("number of justifications is wrong", 1, supported3.size()); Assert.assertThat("justifications differ", supported3, allOf(hasItem(j2), not(hasItem(j1)))); // *** check listing justificatoins by supporting rule // there should now be two justifications based on triple p.getRules().get(1) List<Justification> supported4 = asList(connection.listJustificationsBySupporting(p.getRules().get(1))); Assert.assertEquals("number of justifications is wrong", 2, supported4.size()); Assert.assertThat("justifications differ", supported4, hasItems(j1, j2)); // only j1 should be supported by triple p.getRules().get(0) List<Justification> supported5 = asList(connection.listJustificationsBySupporting(p.getRules().get(0))); Assert.assertEquals("number of justifications is wrong", 1, supported5.size()); Assert.assertThat("justifications differ", supported5, allOf(hasItem(j1), not(hasItem(j2)))); // *** check listing justifications by supported (inferred) triple // there should now be one justification supporting infTriples.get(0) List<Justification> supported6 = asList( connection.listJustificationsForTriple((KiWiTriple) infTriples.get(0))); Assert.assertEquals("number of justifications is wrong", 1, supported6.size()); Assert.assertThat("justifications differ", supported6, allOf(hasItem(j1), not(hasItem(j2)))); // there should now be one justification supporting infTriples.get(1) List<Justification> supported7 = asList( connection.listJustificationsForTriple((KiWiTriple) infTriples.get(1))); Assert.assertEquals("number of justifications is wrong", 1, supported7.size()); Assert.assertThat("justifications differ", supported7, allOf(hasItem(j2), not(hasItem(j1)))); // there should now be no justification supporting infTriples.get(2) List<Justification> supported8 = asList( connection.listJustificationsForTriple((KiWiTriple) infTriples.get(2))); Assert.assertEquals("number of justifications is wrong", 0, supported8.size()); // *** check listing unsupported triples List<KiWiTriple> unsupported = asList(connection.listUnsupportedTriples()); Assert.assertEquals("number of unsupported triples is wrong", 1, unsupported.size()); Assert.assertThat("unsupported triples differ", unsupported, hasItem((KiWiTriple) infTriples.get(2))); // now we delete justification 2; as a consequence, // - there should be only once justification left // - there should be two unsupported triples connection.deleteJustifications(Collections.singleton(j2)); // we should now have one justifications in the database resultListJustifications = listJustifications.executeQuery(); Assert.assertTrue(resultListJustifications.next()); Assert.assertEquals(1, resultListJustifications.getInt("count")); resultListJustifications.close(); connection.commit(); resultListSupportingTriples = listSupportingTriples.executeQuery(); Assert.assertTrue(resultListSupportingTriples.next()); Assert.assertEquals(2, resultListSupportingTriples.getInt("count")); resultListSupportingTriples.close(); connection.commit(); resultListSupportingRules = listSupportingRules.executeQuery(); Assert.assertTrue(resultListSupportingRules.next()); Assert.assertEquals(2, resultListSupportingRules.getInt("count")); resultListSupportingRules.close(); connection.commit(); List<KiWiTriple> unsupported2 = asList(connection.listUnsupportedTriples()); Assert.assertEquals("number of unsupported triples is wrong", 2, unsupported2.size()); Assert.assertThat("unsupported triples differ", unsupported2, hasItem((KiWiTriple) infTriples.get(1))); } catch (BatchUpdateException ex) { if (ex.getNextException() != null) { ex.printStackTrace(); throw ex.getNextException(); } else { throw ex; } } finally { connection.close(); } }