/** test batch loading. */ @SuppressWarnings("unchecked") @Test public void testBatchLoading2() { System.out.println("Batch-test 2"); PersistenceManager pm = null; Object oid = null; try { pm = TestTools.openPM(); pm.currentTransaction().begin(); DBArrayList<Object> dbv = new DBArrayList<Object>(); for (int i = 0; i < 120; i++) { dbv.add(new PersistentDummyImpl()); } pm.makePersistent(dbv); oid = pm.getObjectId(dbv); pm.currentTransaction().commit(); pm.close(); pm = null; pm = TestTools.openPM(); pm.currentTransaction().begin(); dbv = (DBArrayList<Object>) pm.getObjectById(oid); dbv.setBatchSize(110); for (Object o : dbv) { o.getClass(); } pm.currentTransaction().commit(); } finally { if (pm != null) { pm.close(); } } }
/** * Test serialisation. * * <p>If a transaction has only new objects (no modified objects) and if the new objects have * other persistent capable objects referenced (but no have called makePersistent() on them) and * if we are not in the first transaction in a session, then we get the following NPE. See issue * #57. */ @Test public void testSerialization() { TestTools.defineSchema(ProjectPC.class, CoordinatePC.class); PersistenceManager pm = TestTools.openPM(); pm.currentTransaction().begin(); CoordinatePC x = new CoordinatePC(); pm.makePersistent(x); pm.currentTransaction().commit(); pm.currentTransaction().begin(); ProjectPC s = new ProjectPC(new ProjectPC(null)); pm.makePersistent(s); Object oid = pm.getObjectId(s); pm.currentTransaction().commit(); TestTools.closePM(); pm = TestTools.openPM(); pm.currentTransaction().begin(); ProjectPC s2 = (ProjectPC) pm.getObjectById(oid); assertNotNull(s2); pm.currentTransaction().commit(); pm.close(); }
@BeforeClass public static void setUp() { TestTools.createDb(DB_NAME); TestTools.defineSchema(DB_NAME, JB0.class); TestTools.defineSchema(DB_NAME, JB1.class); TestTools.defineSchema(DB_NAME, JB2.class); TestTools.defineSchema(DB_NAME, JB3.class); TestTools.defineSchema(DB_NAME, JB4.class); PersistenceManager pm = TestTools.openPM(); pm.currentTransaction().begin(); for (int i = 1; i <= COUNT; i++) { JB0 jb; jb = new JB4(4, 4, i, 4, 4); pm.makePersistent(jb); jb = new JB3(3, 3, i, 3); pm.makePersistent(jb); jb = new JB2(2, 2, i); pm.makePersistent(jb); jb = new JB1(1, 2); pm.makePersistent(jb); jb = new JB0(0); pm.makePersistent(jb); } pm.currentTransaction().commit(); TestTools.closePM(pm); }
private void endBuffer(ZipEntry ze) { if (ze == null) { return; } if (store != null) { store.close(); // 終了処理は別スレッドで実行中 String digest = store.getDigest(); logPersister.addDigest(addDigests, digest); store = null; } else if (charsetDecoder != null) { charBuffer.flip(); charBuffer.array(); String accessLogJson = new String(charBuffer.array(), charBuffer.position(), charBuffer.limit()); charsetDecoder = null; charBuffer = null; AccessLog accessLog = AccessLog.fromJson(accessLogJson); if (accessLog == null) { return; } logPersister.addDigest(refDigests, accessLog.getRequestHeaderDigest()); logPersister.addDigest(refDigests, accessLog.getRequestBodyDigest()); logPersister.addDigest(refDigests, accessLog.getResponseHeaderDigest()); logPersister.addDigest(refDigests, accessLog.getResponseBodyDigest()); accessLog.setId(null); accessLog.setPersist(true); PersistenceManager pm = JdoUtil.getPersistenceManager(); logPersister.executeInsert(pm, accessLog); if (pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } } }
public static int addAndGet(String name, int delta) { PersistenceManager pm = PMF.get().getPersistenceManager(); NamedCounter counter = null; try { // Detach the persisted objects after changes are commited since we // access members after the transaction is commited. Without this // setting, the counter members could be wiped after the transaction // is // closed. pm.setDetachAllOnCommit(true); pm.currentTransaction().begin(); try { counter = pm.getObjectById(NamedCounter.class, KeyFactory.keyToString(getKeyForName(name))); counter.add(delta); } catch (JDOObjectNotFoundException e) { counter = new NamedCounter(name); // Only need this make persistent call here, since any counter // already retrieved using JDO will be marked as persistent once // we increment the counter; JDO will automatically write it to // the Datastore on commit. counter.add(delta); pm.makePersistent(counter); } pm.currentTransaction().commit(); } finally { if (pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } } return counter.getCount(); }
public void testMultipleDetachCopyAndFetchPlanModification() { try { Properties multiProps = new Properties(); multiProps.setProperty("datanucleus.Multithreaded", "true"); pmf = TestHelper.getPMF(1, multiProps); int THREAD_SIZE = 1000; Thread[] threads = new Thread[THREAD_SIZE]; Runnable[] runner = new Runnable[THREAD_SIZE]; PersistenceManager pm = pmf.getPersistenceManager(); pm.currentTransaction().begin(); Employee woody = new Employee( 1, "Woody", "Woodpecker", "*****@*****.**", 13, "serial 1", new Integer(10)); Manager bart = new Manager(2, "Bart", "Simpson", "*****@*****.**", 2, "serial 2"); woody.setManager(bart); pm.makePersistent(woody); pm.currentTransaction().commit(); pm.currentTransaction().begin(); try { for (int i = 0; i < THREAD_SIZE; i++) { if (i % 2 == 0) { runner[i] = new MultithreadDetachRunner(pm, woody); } else { runner[i] = new MultithreadFetchPlanRunner(pm); } threads[i] = new Thread(runner[i]); threads[i].start(); } for (int i = 0; i < THREAD_SIZE; i++) { threads[i].join(); Exception e = null; if (runner[i] instanceof MultithreadDetachRunner) { e = ((MultithreadDetachRunner) runner[i]).getException(); } else if (runner[i] instanceof MultithreadFetchPlanRunner) { e = ((MultithreadFetchPlanRunner) runner[i]).getException(); } if (e != null) { LOG.error("Exception during test", e); fail("Exception thrown during test : " + e); } } } catch (Exception e) { fail(e.getMessage()); } finally { if (pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } pm.close(); } } finally { CompanyHelper.clearCompanyData(pmf); } }
/** * Tests extent across transaction boundaries. The problem here is that extents are pos-indices, * which are COWed. So during a commit, object may get rewritten, changing the index, meaning that * the positions in the extents are wrong. * * <p>In this test we simply check that commits do not affect the extent if the index is not * modified. */ @Test public void testExtentAcrossCommit() { int N = 10000; PersistenceManager pm = TestTools.openPM(); // pm.setIgnoreCache(false); pm.currentTransaction().begin(); for (int i = 0; i < N; i++) { TestClass tc = new TestClass(); tc.setInt(i); pm.makePersistent(tc); } pm.currentTransaction().commit(); pm.currentTransaction().begin(); // modify all --> create empty space in the beginning of the DB for (TestClass tc : pm.getExtent(TestClass.class)) { tc.setLong(12); } pm.currentTransaction().commit(); pm.currentTransaction().begin(); // start iterating Iterator<TestClass> it = pm.getExtent(TestClass.class).iterator(); int n = 0; while (n < N / 2 && it.hasNext()) { n++; it.next(); } // commit, this should invalidate the first extent pm.currentTransaction().commit(); pm.currentTransaction().begin(); try { it.hasNext(); fail(); } catch (JDOUserException e) { // good } try { it.next(); fail(); } catch (JDOUserException e) { // good } pm.currentTransaction().commit(); TestTools.closePM(); }
// TODO非同期 public void executeDelete(PersistenceManager pm, Collection<Long> accessLogsIds) { pm.currentTransaction().begin(); for (Long id : accessLogsIds) { AccessLog accessLog = pm.getObjectById(AccessLog.class, id); StoreManager.unref(accessLog.getRequestHeaderDigest()); StoreManager.unref(accessLog.getRequestBodyDigest()); StoreManager.unref(accessLog.getResponseHeaderDigest()); StoreManager.unref(accessLog.getResponseBodyDigest()); pm.deletePersistent(accessLog); } pm.currentTransaction().commit(); }
/** Test changing the state */ public void testMultipleNonTransitionWrite() { try { Properties multiProps = new Properties(); multiProps.setProperty("datanucleus.Multithreaded", "true"); pmf = TestHelper.getPMF(1, multiProps); int THREAD_SIZE = 1000; Thread[] threads = new Thread[THREAD_SIZE]; PersistenceManager pm = pmf.getPersistenceManager(); pm.currentTransaction().begin(); final Employee woody = new Employee( 1, "Woody", "Woodpecker", "*****@*****.**", 13, "serial 1", new Integer(10)); Manager bart = new Manager(2, "Bart", "Simpson", "*****@*****.**", 2, "serial 2"); final Manager boss = new Manager(3, "Boss", "WakesUp", "*****@*****.**", 4, "serial 3"); woody.setManager(bart); pm.makePersistent(woody); pm.currentTransaction().commit(); pm.currentTransaction().setNontransactionalWrite(true); try { for (int i = 0; i < THREAD_SIZE; i++) { threads[i] = new Thread( new Runnable() { public void run() { woody.setLastName("name"); woody.setManager(boss); } }); } for (int i = 0; i < THREAD_SIZE; i++) { threads[i].start(); } for (int i = 0; i < THREAD_SIZE; i++) { try { threads[i].join(); } catch (InterruptedException e) { fail(e.getMessage()); } } } finally { if (pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } pm.close(); } } finally { CompanyHelper.clearCompanyData(pmf); } }
private void populate() { PersistenceManager pm = TestTools.openPM(); pm.currentTransaction().begin(); for (int i = 0; i < N; i++) { ComplexHolder1 h = new ComplexHolder1(); h.setId(YEARS_MIN + i / YEARS); pm.makePersistent(h); ComplexHolder2 h2 = new ComplexHolder2(); h2.setId(YEARS_MIN + i / YEARS); pm.makePersistent(h2); } pm.currentTransaction().commit(); TestTools.closePM(); }
/** Used only internally by the cleaner daemon (run()). */ private long remove(Long threshold) throws DAOException { PersistenceManager deleteManager = getManager(); if (deleteManager == null) { return 0; } Transaction tx = deleteManager.currentTransaction(); AlarmDAOFilter filter = AlarmJDOUtils.getDeleteBeforeFilter(threshold); try { tx.begin(); long removed = AlarmJDOUtils.delete(deleteManager, filter); tx.commit(); logger.debug("successfully removed {} entries", removed); return removed; } catch (Exception t) { String message = "remove: " + filter + ": " + t.getLocalizedMessage(); throw new DAOException(message, t); } finally { try { rollbackIfActive(tx); } finally { deleteManager.close(); } } }
@Override public long remove(Collection<LogEntry> selected) { if (selected.isEmpty()) { return 0; } PersistenceManager deleteManager = getManager(); if (deleteManager == null) { return 0; } Transaction tx = deleteManager.currentTransaction(); AlarmDAOFilter filter = AlarmJDOUtils.getIdFilter(selected); try { tx.begin(); long removed = AlarmJDOUtils.delete(deleteManager, filter); tx.commit(); logger.debug("successfully removed {} entries", removed); return removed; } catch (JDOException t) { logJDOException("update", filter, t); return 0; } finally { try { rollbackIfActive(tx); } finally { deleteManager.close(); } } }
@Override public Collection<LogEntry> get(AlarmDAOFilter filter) { PersistenceManager readManager = getManager(); if (readManager == null) { return Collections.emptyList(); } Transaction tx = readManager.currentTransaction(); try { tx.begin(); Collection<LogEntry> result = AlarmJDOUtils.execute(readManager, filter); logger.debug("got collection {}", result); Collection<LogEntry> detached = readManager.detachCopyAll(result); logger.debug("got detatched collection {}", detached); tx.commit(); logger.debug("successfully executed get for filter {}", filter); return detached; } catch (JDOException t) { logJDOException("update", filter, t); return Collections.emptyList(); } finally { try { rollbackIfActive(tx); } finally { readManager.close(); } } }
public void testMbrTouches() throws SQLException, ParseException { if (!runTestsForDatastore()) { return; } PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Point point = (Point) wktReader.read("POINT(75 75)"); Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrTouches(:point, geom)"); List list = (List) query.execute(point); assertEquals( "Wrong number of geometries which are touched by a given point returned", 2, list.size()); assertTrue( "Polygon 1 should be in the list of geometries which are touched by a given point", list.contains(getSamplePolygon(1))); assertTrue( "Polygon 2 should be in the list of geometries which are touched by a given point", list.contains(getSamplePolygon(2))); } finally { tx.commit(); } }
public void testMbrEqual() throws SQLException, ParseException { if (!runTestsForDatastore()) { return; } PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Polygon polygon = (Polygon) wktReader.read( "POLYGON((25 25,75 25,75 75,25 75,25 25),(45 45,55 45,55 55,45 55,45 45))"); Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrEqual(geom, :polygon)"); List list = (List) query.execute(polygon); assertEquals( "Wrong number of geometries which are equal to a given polygon returned", 1, list.size()); assertTrue( "Polygon 1 should be in the list of geometries which are equal to a given polygon", list.contains(getSamplePolygon(1))); } finally { tx.commit(); } }
private User getUser(String login, String password) { PersistenceManager manager = null; Transaction transaction = null; List<User> users = null; try { manager = PMF.newInstance().getPersistenceManager(); transaction = manager.currentTransaction(); transaction.begin(); Query query = manager.newQuery(User.class); users = (List<User>) query.execute(); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } } finally { manager.close(); } if (users != null && !users.isEmpty()) { for (User u : users) { System.out.println(u.getLogin() + " : " + u.getPassword()); if (login.equals(u.getLogin()) && password.equals(u.getPassword())) { System.out.println(u.getLogin() + " : " + u.getPassword()); return u; } } } return null; }
@Before public void before() { TestTools.createDb(); TestTools.defineSchema(TestClass.class); pm = TestTools.openPM(); pm.currentTransaction().begin(); }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); String gameId = req.getParameter("gameId"); String mode = req.getParameter("mode"); resp.getWriter().println("ship post mode " + mode + ":"); resp.getWriter().println(String.format("gameId: %s", gameId)); resp.getWriter().println(String.format("name: %s", req.getParameter("name"))); resp.getWriter().println(String.format("race: %s", req.getParameter("race"))); resp.getWriter().println(String.format("type: %s", req.getParameter("type"))); resp.getWriter().println(String.format("description: %s", req.getParameter("description"))); if (gameId != null && gameId.length() > 0) { PersistenceManager pm = DB.getManager(); boolean isNew = false; Ship ship = shipDao.getShipByGameId(pm, gameId); if (ship == null) { ship = new Ship( req.getParameter("gameId"), req.getParameter("name"), req.getParameter("type"), req.getParameter("race"), getShipImgs(req).get("shipIcon")); isNew = true; } else { // Update if ("file".equals(mode)) { HashMap<String, Blob> shipImgs = getShipImgs(req); ship.setIcon(shipImgs.get("shipIcon")); ship.setImg256(shipImgs.get("ship256")); } if ("data".equals(mode)) { ship.setDescription(req.getParameter("description")); ship.setBasePrice(req.getParameter("basePrice")); ship.setMass(req.getParameter("mass")); ship.setVolume(req.getParameter("volume")); ship.setCapacity(req.getParameter("capacity")); ship.setInertiaModifier(req.getParameter("inertiaModifier")); } } pm.currentTransaction().begin(); pm.makePersistent(ship); pm.currentTransaction().commit(); resp.getWriter().println(isNew ? "Created" : "Updated"); } }
// Retrieve the user from the database if it already exist or // create a new account if it is the first loggin public static UserProfile findUserProfile(UserProfile user) { PersistenceManager pm = PMFactory.getTxnPm(); Transaction tx = null; UserProfile oneResult = null, detached = null; String uniqueId = user.getUniqueId(); Query q = pm.newQuery(UserProfile.class, "uniqueId == :uniqueId"); q.setUnique(true); // perform the query and creation under transactional control, // to prevent another process from creating an acct with the same id. try { for (int i = 0; i < NUM_RETRIES; i++) { tx = pm.currentTransaction(); tx.begin(); oneResult = (UserProfile) q.execute(uniqueId); if (oneResult != null) { log.info("User uniqueId already exists: " + uniqueId); detached = pm.detachCopy(oneResult); } else { log.info("UserProfile " + uniqueId + " does not exist, creating..."); // Create friends from Google+ // user.setKarma(new Karma()); pm.makePersistent(user); detached = pm.detachCopy(user); } try { tx.commit(); break; } catch (JDOCanRetryException e1) { if (i == (NUM_RETRIES - 1)) { throw e1; } } } // end for } catch (JDOUserException e) { log.info("JDOUserException: UserProfile table is empty"); // Create friends from Google+ pm.makePersistent(user); detached = pm.detachCopy(user); try { tx.commit(); } catch (JDOCanRetryException e1) { } } catch (Exception e) { e.printStackTrace(); } finally { if (tx.isActive()) { tx.rollback(); } pm.close(); q.closeAll(); } return detached; }
@Test public void testThatPrintingDoesntThrowExceptions() { pm.currentTransaction().commit(); pm.currentTransaction().begin(); ZooClassDef def = getDef(TestClass.class); QueryParser qp = new QueryParser("(_int > 1 && _int < 52) || _int > 50", def, null, null); QueryTreeNode qtn = qp.parseQuery(); assertNotNull(qtn.print()); }
/** @return List of Public Places */ @SuppressWarnings("unchecked") public List<Place> getPlacesPublic(Account account, String createdorder) { PersistenceManager pm = PMUtils.getPersistenceManager(); try { // prepare query Query q = pm.newQuery(Place.class); q.setOrdering("type desc, createdOrder desc"); q.setRange(0, account != null ? account.getFetchRows() : 20); q.declareImports("import com.hotf.server.model.Location.Type"); List<Place> list; if (createdorder != null && createdorder.length() > 0) { // execute with filter q.declareParameters("String p_createdOrder"); q.setFilter("type != null && type != 'START' && createdOrder >= p_createdOrder"); String n = createdorder.toUpperCase(); log.info("Getting more public places from the Datastore"); list = (List<Place>) q.execute(n); } else { // execute without filter q.setFilter("type != null && type != 'START'"); log.info("Getting public places from the Datastore"); list = (List<Place>) q.execute(); } return list; } catch (RuntimeException t) { log.severe(t.getMessage()); // roll-back transactions and re-throw if (pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } throw t; } }
/** This used to fail because deserialized DbCollection were marked dirty. */ @SuppressWarnings("unchecked") @Test public void testSerialization() { PersistenceManager pm = TestTools.openPM(); pm.currentTransaction().begin(); DBHashMap<TestClass, TestClass> h1 = new DBHashMap<TestClass, TestClass>(); DBHashMap<TestClass, TestClass> h2 = new DBHashMap<TestClass, TestClass>(); TestClass k = new TestClass(); h2.put(k, new TestClass()); DBArrayList<TestClass> l1 = new DBArrayList<TestClass>(); DBArrayList<TestClass> l2 = new DBArrayList<TestClass>(); l2.add(new TestClass()); pm.makePersistent(h1); pm.makePersistent(h2); pm.makePersistent(k); pm.makePersistent(l1); pm.makePersistent(l2); Object oid1 = pm.getObjectId(h1); Object oid2 = pm.getObjectId(h2); Object oidk = pm.getObjectId(k); Object oid3 = pm.getObjectId(l1); Object oid4 = pm.getObjectId(l2); pm.currentTransaction().commit(); TestTools.closePM(); pm = TestTools.openPM(); pm.currentTransaction().begin(); h1 = (DBHashMap<TestClass, TestClass>) pm.getObjectById(oid1); assertEquals(false, JDOHelper.isDirty(h1)); h2 = (DBHashMap<TestClass, TestClass>) pm.getObjectById(oid2); assertEquals(false, JDOHelper.isDirty(h2)); k = (TestClass) pm.getObjectById(oidk); assertEquals(false, JDOHelper.isDirty(k)); assertEquals(false, JDOHelper.isDirty(h2.get(k))); l1 = (DBArrayList<TestClass>) pm.getObjectById(oid3); assertEquals(false, JDOHelper.isDirty(l1)); l2 = (DBArrayList<TestClass>) pm.getObjectById(oid4); assertEquals(false, JDOHelper.isDirty(l2)); assertEquals(false, JDOHelper.isDirty(l2.get(0))); pm.currentTransaction().commit(); pm.close(); }
/** Test import of ZooDB 0.3 xml files. */ @Test public void testImport0_3() { String path = Test_014_XmlImportExport.class.getResource("XmlComplexTest.xml").getPath(); // import to DB TestTools.defineSchema(TestSerializer.class, TestSuper.class, DBLargeVector.class); ZooXmlImport.main(new String[] {TestTools.getDbName(), path}); // check target PersistenceManager pm2 = TestTools.openPM(); pm2.currentTransaction().begin(); // Check for content in target Extent<TestSerializer> ext = pm2.getExtent(TestSerializer.class); TestSerializer ts2 = ext.iterator().next(); ts2.check(false); pm2.currentTransaction().rollback(); TestTools.closePM(); }
private void doJobs() { PersistenceManager pm = JdoUtil.getPersistenceManager(); while (true) { Object req = null; synchronized (requestQueue) { if (requestQueue.size() == 0) { break; } req = requestQueue.remove(0); } try { pm = doJob(pm, req); } finally { if (pm != null && pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } } } }
@SuppressWarnings({"unchecked"}) private void browserAuth(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm) throws IOException { OpenIdUser openIdUser = (OpenIdUser) req.getAttribute(OpenIdUser.ATTR_NAME); if (openIdUser == null) { setResponse(resp, 403, "OpenID authorization required"); return; } String email = getEmail(openIdUser); String openidUrl = getOpenidUrl(resp, openIdUser, email); if (openidUrl == null) return; long id = Long.parseLong(req.getRequestURI().substring("/browser-auth/".length())); Date date = new Date(); DbUser dbUser = findUser(pm, openidUrl, email); if (dbUser == null) { dbUser = createAndStoreUser(pm, openidUrl, email); } SqlCloudSession session = persistenceHelper.createSqlCloudSession(id, date, dbUser.createKeyObject(), email); Transaction tx = pm.currentTransaction(); tx.begin(); try { pm.makePersistent(session); tx.commit(); } finally { if (tx.isActive()) tx.rollback(); } resp.setStatus(200); resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); writer.println( "<title>" + getCloudName() + "</title>" + "<table border=0 cellpadding=10><tr>" + "<td bgcolor='#b9b9fe' valign='top'>" + "<img src='http://findbugs.sourceforge.net/umdFindbugs.png' alt='FindBugs'>" + "</td>" + "<td valign='top'>" + "<h1>You are now signed into " + getCloudName() + "</h1>" + "<p style='font-size: large'>" + "Return to the FindBugs application window to continue.</p>" + "<p>Signed in as <strong>" + escapeHtml(email) + "</strong><br>" + "<span style='font-size:x-small; font-style: italic'>(" + escapeHtml(openidUrl) + ")</span></p>"); }
public static void reset(String name) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { pm.currentTransaction().begin(); try { NamedCounter counter = pm.getObjectById(NamedCounter.class, KeyFactory.keyToString(getKeyForName(name))); pm.deletePersistent(counter); } catch (JDOObjectNotFoundException e) { // Object isn't there, so ignore it. return; } pm.currentTransaction().commit(); } finally { if (pm.currentTransaction().isActive()) { pm.currentTransaction().rollback(); } } }
private void checkResults(String queryFilter, int nRes) { pm.currentTransaction().commit(); pm.currentTransaction().begin(); Query q = pm.newQuery(TestClass.class, queryFilter); Collection<?> c = (Collection<?>) q.execute(); int n = 0; for (Object o : c) { assertNotNull(o); n++; } assertEquals(nRes, n); }
@Test public void testCallBack() { PersistenceManager pm = TestTools.openPM(); pm.currentTransaction().begin(); TestPreStore ps = new TestPreStore(); TestPostLoad pl = new TestPostLoad(); TestPreClear pc = new TestPreClear(); TestPreDelete pd = new TestPreDelete(); pm.makePersistent(ps); pm.makePersistent(pl); pm.makePersistent(pc); pm.makePersistent(pd); assertFalse(TestPreStore.storeCalled); assertFalse(TestPostLoad.loadCalled); assertFalse(TestPreClear.clearCalled); assertFalse(TestPreDelete.deleteCalled); pm.currentTransaction().commit(); assertTrue(TestPreStore.storeCalled); assertTrue(TestPreClear.clearCalled); assertFalse(TestPostLoad.loadCalled); assertFalse(TestPreDelete.deleteCalled); pm.currentTransaction().begin(); pl.getI(); assertTrue(TestPostLoad.loadCalled); pm.deletePersistent(pd); assertFalse(TestPreDelete.deleteCalled); pm.currentTransaction().commit(); assertTrue(TestPreDelete.deleteCalled); TestTools.closePM(); }
private DbUser createAndStoreUser(PersistenceManager pm, String openidUrl, String email) { DbUser dbUser = persistenceHelper.createDbUser(openidUrl, email); Transaction tx = pm.currentTransaction(); tx.begin(); try { pm.makePersistent(dbUser); tx.commit(); } finally { if (tx.isActive()) tx.rollback(); } return dbUser; }
private void begin() { lock.lock(); try { if (isActive()) throw new IllegalStateException("Transaction is already active!"); lockIfWrite(); persistenceManager = persistenceManagerFactory.getPersistenceManager(); jdoTransaction = persistenceManager.currentTransaction(); jdoTransaction.begin(); listenerRegistry.onBegin(); } finally { lock.unlock(); } }