List of usage examples for java.sql PreparedStatement addBatch
void addBatch() throws SQLException;
PreparedStatement
object's batch of commands. From source file:org.wso2.carbon.device.mgt.core.dao.impl.AbstractApplicationDAOImpl.java
@Override public List<Integer> removeApplications(List<Application> apps, int tenantId) throws DeviceManagementDAOException { Connection conn = null;// w w w. j a v a2 s . c o m PreparedStatement stmt = null; ResultSet rs = null; List<Integer> applicationIds = new ArrayList<>(); try { conn = this.getConnection(); conn.setAutoCommit(false); stmt = conn.prepareStatement("DELETE DM_APPLICATION WHERE APP_IDENTIFIER = ? AND TENANT_ID = ?", new String[] { "id" }); for (Application app : apps) { stmt.setString(1, app.getApplicationIdentifier()); stmt.setInt(2, tenantId); stmt.addBatch(); } stmt.executeBatch(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationIds.add(rs.getInt(1)); } return applicationIds; } catch (SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException e1) { log.error("Error occurred while roll-backing the transaction", e); } throw new DeviceManagementDAOException("Error occurred while removing bulk application list", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:com.nabla.wapp.server.auth.UserManager.java
public boolean updateRoleDefinition(final Integer roleId, final SelectionDelta delta) throws SQLException { Assert.argumentNotNull(roleId);// w ww. j a v a 2 s. c o m Assert.argumentNotNull(delta); final LockTableGuard lock = new LockTableGuard(conn, LOCK_USER_TABLES); try { final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn); try { if (delta.isRemovals()) Database.executeUpdate(conn, "DELETE FROM role_definition WHERE role_id=? AND child_role_id IN (?);", roleId, delta.getRemovals()); if (delta.isAdditions()) { final PreparedStatement stmt = conn .prepareStatement("INSERT INTO role_definition (role_id, child_role_id) VALUES(?,?);"); try { stmt.clearBatch(); stmt.setInt(1, roleId); for (final Integer childId : delta.getAdditions()) { stmt.setInt(2, childId); stmt.addBatch(); } if (!Database.isBatchCompleted(stmt.executeBatch())) return false; } finally { stmt.close(); } } return guard.setSuccess(updateUserRoleTable()); } finally { guard.close(); } } finally { lock.close(); } }
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.// ww w . j a va2s . c om * */ @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(); } }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationDAOImpl.java
@Override public List<Integer> removeApplications(List<Application> apps, int tenantId) throws DeviceManagementDAOException { Connection conn = null;//from w w w . ja v a 2s . c o m PreparedStatement stmt = null; ResultSet rs = null; List<Integer> applicationIds = new ArrayList<>(); try { conn = this.getConnection(); conn.setAutoCommit(false); stmt = conn.prepareStatement("DELETE DM_APPLICATION WHERE APP_IDENTIFIER = ? AND TENANT_ID = ?", new String[] { "id" }); for (Application app : apps) { stmt.setString(1, app.getApplicationIdentifier()); stmt.setInt(2, tenantId); stmt.addBatch(); } stmt.executeBatch(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationIds.add(rs.getInt(1)); } return applicationIds; } catch (SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException e1) { log.warn("Error occurred while roll-backing the transaction", e); } throw new DeviceManagementDAOException("Error occurred while removing bulk application list", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:edu.ucsb.cs.eager.dao.EagerDependencyMgtDAO.java
private void saveDependencies(Connection conn, ApplicationInfo app) throws SQLException { if (app.getDependencies() == null && app.getEnclosedAPIs() == null) { return;/*from w w w . j a v a 2s . c om*/ } String insertQuery = "INSERT INTO EAGER_API_DEPENDENCY (EAGER_DEPENDENCY_NAME, " + "EAGER_DEPENDENCY_VERSION, EAGER_DEPENDENT_NAME, EAGER_DEPENDENT_VERSION, " + "EAGER_DEPENDENCY_OPERATIONS) VALUES (?,?,?,?,?)"; PreparedStatement psInsert = null; try { psInsert = conn.prepareStatement(insertQuery); if (app.getDependencies() != null) { for (DependencyInfo dependency : app.getDependencies()) { psInsert.setString(1, dependency.getName()); psInsert.setString(2, dependency.getVersion()); psInsert.setString(3, app.getName()); psInsert.setString(4, app.getVersion()); psInsert.setString(5, getOperationsListAsString(dependency)); psInsert.addBatch(); } } if (app.getEnclosedAPIs() != null) { for (APIInfo enclosedAPI : app.getEnclosedAPIs()) { psInsert.setString(1, app.getName()); psInsert.setString(2, app.getVersion()); psInsert.setString(3, enclosedAPI.getName()); psInsert.setString(4, enclosedAPI.getVersion()); psInsert.setString(5, ""); psInsert.addBatch(); } } psInsert.executeBatch(); psInsert.clearBatch(); } finally { APIMgtDBUtil.closeAllConnections(psInsert, null, null); } }
From source file:org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl.AndroidFeatureDAOImpl.java
@Override public boolean addFeatures(List<MobileFeature> mobileFeatures) throws MobileDeviceManagementDAOException { PreparedStatement stmt = null; MobileFeature mobileFeature;/*from ww w . j a v a 2 s . c o m*/ boolean status = false; Connection conn; try { conn = AndroidDAOFactory.getConnection(); stmt = conn.prepareStatement("INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)"); for (int i = 0; i < mobileFeatures.size(); i++) { mobileFeature = mobileFeatures.get(i); stmt.setString(1, mobileFeature.getCode()); stmt.setString(2, mobileFeature.getName()); stmt.setString(3, mobileFeature.getDescription()); stmt.addBatch(); } stmt.executeBatch(); status = true; } catch (SQLException e) { throw new AndroidFeatureManagementDAOException( "Error occurred while adding android features into the metadata repository", e); } finally { MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); } return status; }
From source file:de.indiplex.javapt.JavAPT.java
public void updateSources(boolean downloadSs) throws URISyntaxException, IOException, SQLException { Statement stat = db.getStat(); stat.executeUpdate("DELETE FROM packages;"); debs = new ArrayList<DEB>(); int last = 0; for (String u : sourcesURLs) { String pre = new URL(u).getHost(); File out = new File(dTemp, pre + ".source"); if (downloadSs) { URLConnection con = new URL(u.toString() + "Packages.bz2").openConnection(); File tmpOut = new File(dTemp, pre + ".source.bz2"); System.out.println("Downloading " + con.getURL() + "..."); download(con, tmpOut);/*from w w w .j a v a 2 s.c o m*/ System.out.println("Decompressing..."); CountingFileInputStream fis = new CountingFileInputStream(tmpOut); BZip2CompressorInputStream in = new BZip2CompressorInputStream(fis); Finish = tmpOut.length(); Util.checkFiles(out); OutputStream fout = new FileOutputStream(out); int i = in.read(); while (i != -1) { State = fis.getCount(); fout.write(i); i = in.read(); } fout.close(); in.close(); } BufferedReader br = new BufferedReader(new FileReader(out)); DEB deb = null; ArrayList<String> lines = new ArrayList<String>(); while (br.ready()) { String line = br.readLine(); lines.add(line); } Finish = lines.size(); State = 0; System.out.println("Parsing..."); for (String line : lines) { State++; if (line.startsWith("Package")) { if (deb != null) { debs.add(deb); } deb = new DEB(p(line)); } if (line.startsWith("Depends")) { if (deb == null) { continue; } deb.depends = p(line).trim(); deb.depends = deb.depends.replaceAll("\\({1}[^\\(]*\\)", ""); } if (line.startsWith("Provides")) { if (deb == null) { continue; } deb.provides = p(line); } if (line.startsWith("Filename")) { if (deb == null) { continue; } deb.filename = u + p(line); if (u.equals("http://apt.saurik.com/dists/ios/675.00/main/binary-iphoneos-arm/")) { deb.filename = "http://apt.saurik.com/" + p(line); } if (u.contains("apt.thebigboss")) { deb.filename = deb.filename.replace("dists/stable/main/binary-iphoneos-arm/", ""); } deb.filename = deb.filename.replace("http://", ""); deb.filename = deb.filename.replace("//", "/"); deb.filename = "http://" + deb.filename; } } System.out.println("Updated " + u + "! " + (debs.size() - last) + " packages found"); last = debs.size(); } PreparedStatement pstat = db .getPreparedStatement("INSERT INTO packages (name, depends, provides, filename) VALUES (?,?,?,?);"); for (DEB deb : debs) { pstat.setString(1, deb.packagename); pstat.setString(2, deb.depends); pstat.setString(3, deb.provides); pstat.setString(4, deb.filename); pstat.addBatch(); } db.closePS(); if (isGUI()) { mf.fillPackages(debs); } hashDEB(); }
From source file:netflow.DatabaseProxy.java
private void updateAggregationResults(List<AggregationRecord> records) throws SQLException { if (records.isEmpty()) { log.debug("Nothing to update"); return;/*from w w w . j a v a2 s.c o m*/ } log.debug("updateAggregationResults(): <<<<"); log.debug(records.size() + " to update"); PreparedStatement pstmt = con.prepareStatement(getQuery("aggregation.summary.update")); for (AggregationRecord record : records) { pstmt.setLong(1, record.getInput()); pstmt.setLong(2, record.getOutput()); pstmt.setInt(3, record.getClientId()); pstmt.setDate(4, record.getDate()); pstmt.addBatch(); } final int[] ints = pstmt.executeBatch(); log.debug(ints.length + " records updated"); log.debug("updateAggregationResults(): >>>>"); }
From source file:netflow.DatabaseProxy.java
private void addAggregationResults(List<AggregationRecord> records) throws SQLException { if (records.isEmpty()) { log.debug("Nothing to insert"); return;/*from ww w.j a va2 s . c o m*/ } log.debug("insertAggregationResults(): <<<<"); log.debug(records.size() + " to insert"); PreparedStatement pstmt = con.prepareStatement(getQuery("aggregation.summary.insert")); for (AggregationRecord record : records) { pstmt.setLong(1, record.getInput()); pstmt.setLong(2, record.getOutput()); pstmt.setInt(3, record.getClientId()); pstmt.setDate(4, record.getDate()); pstmt.addBatch(); } final int[] ints = pstmt.executeBatch(); log.debug(ints.length + " records inserted"); log.debug("insertAggregationResults(): >>>>"); }
From source file:org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl.java
@Override public void addDeviceProperties(Map<String, String> propertyMap, int deviceId, int enrolmentId) throws DeviceDetailsMgtDAOException { if (propertyMap.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Property map of device id :" + deviceId + " is empty."); }/*from ww w .ja v a2 s . c o m*/ return; } Connection conn; PreparedStatement stmt = null; try { conn = this.getConnection(); stmt = conn.prepareStatement( "INSERT INTO DM_DEVICE_INFO (DEVICE_ID, KEY_FIELD, VALUE_FIELD, ENROLMENT_ID) " + "VALUES (?, ?, ?, ?)"); for (Map.Entry<String, String> entry : propertyMap.entrySet()) { stmt.setInt(1, deviceId); stmt.setString(2, entry.getKey()); stmt.setString(3, entry.getValue()); stmt.setInt(4, enrolmentId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new DeviceDetailsMgtDAOException("Error occurred while inserting device properties to database.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } }