public static void testTtansaction_1() { for (User user : getSession().findAll(User.class)) { getSession().delete(User.class, user.getId()); } Transaction transaction = getSession().getTransaction(); transaction.begin(); User user = new User(); try { user.setId(1231234); getSession().insert(user); user = getSession().find(User.class, "1231234"); System.out.println("1:" + user); user.setName("123"); getSession().update(user); } catch (Exception e) { e.printStackTrace(); } finally { transaction.end(); } user = getSession().find(User.class, "1231234"); System.out.println("2" + user); System.out.println("=========="); transaction = getSession().getTransaction(); transaction.begin(); user = new User(); try { user.setId(1231234567); getSession().insert(user); user = getSession().find(User.class, "1231234567"); System.out.println("1:" + user); user.setName("123"); getSession().update(user); transaction.submit(); } finally { transaction.end(); } user = getSession().find(User.class, "1231234567"); System.out.println("2" + user); System.out.println("=========="); transaction = getSession().getTransaction(); transaction.begin(); user = new User(); try { user.setId(12312345); getSession().insert(user); user = getSession().find(User.class, "12312345"); System.out.println("1:" + user); user.setName("123"); getSession().update(user); transaction.submit(); } finally { transaction.end(); } user = getSession().find(User.class, "12312345"); System.out.println("2" + user); }
@Test(groups = "dev") public void autoWrapTest() throws EventDeliveryException { ctx.put(MongoSink.AUTO_WRAP, Boolean.toString(true)); ctx.put(MongoSink.DB_NAME, "test_wrap"); MongoSink sink = new MongoSink(); Configurables.configure(sink, ctx); sink.setChannel(channel); sink.start(); Transaction tx = channel.getTransaction(); tx.begin(); String msg = "2012/10/26 11:23:08 [error] 7289#0: *6430831 open() \"/usr/local/nginx/html/50x.html\" failed (2: No such file or directory), client: 10.160.105.161, server: sg15.redatoms.com, request: \"POST /mojo/ajax/embed HTTP/1.0\", upstream: \"fastcgi://unix:/tmp/php-fpm.sock:\", host: \"sg15.redatoms.com\", referrer: \"http://sg15.redatoms.com/mojo/mobile/package\""; Event e = EventBuilder.withBody(msg.getBytes()); channel.put(e); tx.commit(); tx.close(); sink.process(); sink.stop(); DB db = mongo.getDB("test_wrap"); DBCollection collection = db.getCollection("test_log"); DBCursor cursor = collection.find(new BasicDBObject(MongoSink.DEFAULT_WRAP_FIELD, msg)); assertTrue(cursor.hasNext()); DBObject dbObject = cursor.next(); assertNotNull(dbObject); assertEquals(dbObject.get(MongoSink.DEFAULT_WRAP_FIELD), msg); mongo.dropDatabase("test_wrap"); }
@Test(groups = "dev") public void sinkSingleModelTest() throws EventDeliveryException { ctx.put(MongoSink.MODEL, MongoSink.CollectionModel.single.name()); MongoSink sink = new MongoSink(); Configurables.configure(sink, ctx); sink.setChannel(channel); sink.start(); Transaction tx = channel.getTransaction(); tx.begin(); JSONObject msg = new JSONObject(); msg.put("name", "test"); msg.put("age", 11); msg.put("birthday", new Date().getTime()); Event e = EventBuilder.withBody(msg.toJSONString().getBytes()); channel.put(e); tx.commit(); tx.close(); sink.process(); sink.stop(); DB db = mongo.getDB("test_events"); DBCollection collection = db.getCollection("test_log"); DBCursor cursor = collection.find(new BasicDBObject(msg)); assertTrue(cursor.hasNext()); DBObject dbObject = cursor.next(); assertNotNull(dbObject); assertEquals(dbObject.get("name"), msg.get("name")); assertEquals(dbObject.get("age"), msg.get("age")); assertEquals(dbObject.get("birthday"), msg.get("birthday")); }
@Test(groups = "dev") public void timestampExistingFieldTest() throws EventDeliveryException, ParseException { ctx.put(MongoSink.MODEL, MongoSink.CollectionModel.dynamic.name()); String tsField = "createdOn"; ctx.put(MongoSink.TIMESTAMP_FIELD, tsField); MongoSink sink = new MongoSink(); Configurables.configure(sink, ctx); sink.setChannel(channel); sink.start(); JSONObject msg = new JSONObject(); msg.put("age", 11); msg.put("birthday", new Date().getTime()); String dateText = "2013-02-19T14:20:53+08:00"; msg.put(tsField, dateText); Transaction tx; for (int i = 0; i < 10; i++) { tx = channel.getTransaction(); tx.begin(); msg.put("name", "test" + i); JSONObject header = new JSONObject(); header.put(MongoSink.COLLECTION, "my_events"); header.put(MongoSink.DB_NAME, "dynamic_db"); Event e = EventBuilder.withBody(msg.toJSONString().getBytes(), header); channel.put(e); tx.commit(); tx.close(); } sink.process(); sink.stop(); msg.put(tsField, MongoSink.dateTimeFormatter.parseDateTime(dateText).toDate()); for (int i = 0; i < 10; i++) { msg.put("name", "test" + i); System.out.println("i = " + i); DB db = mongo.getDB("dynamic_db"); DBCollection collection = db.getCollection("my_events"); DBCursor cursor = collection.find(new BasicDBObject(msg)); assertTrue(cursor.hasNext()); DBObject dbObject = cursor.next(); assertNotNull(dbObject); assertEquals(dbObject.get("name"), msg.get("name")); assertEquals(dbObject.get("age"), msg.get("age")); assertEquals(dbObject.get("birthday"), msg.get("birthday")); assertTrue(dbObject.get(tsField) instanceof Date); System.out.println("ts = " + dbObject.get(tsField)); } }
@Test(groups = "dev") public void sinkDynamicDbTest() throws EventDeliveryException { ctx.put(MongoSink.MODEL, MongoSink.CollectionModel.dynamic.name()); MongoSink sink = new MongoSink(); Configurables.configure(sink, ctx); sink.setChannel(channel); sink.start(); JSONObject msg = new JSONObject(); msg.put("age", 11); msg.put("birthday", new Date().getTime()); Transaction tx; for (int i = 0; i < 10; i++) { tx = channel.getTransaction(); tx.begin(); msg.put("name", "test" + i); JSONObject header = new JSONObject(); header.put(MongoSink.COLLECTION, "my_events"); header.put(MongoSink.DB_NAME, "dynamic_db"); Event e = EventBuilder.withBody(msg.toJSONString().getBytes(), header); channel.put(e); tx.commit(); tx.close(); } sink.process(); sink.stop(); for (int i = 0; i < 10; i++) { msg.put("name", "test" + i); System.out.println("i = " + i); DB db = mongo.getDB("dynamic_db"); DBCollection collection = db.getCollection("my_events"); DBCursor cursor = collection.find(new BasicDBObject(msg)); assertTrue(cursor.hasNext()); DBObject dbObject = cursor.next(); assertNotNull(dbObject); assertEquals(dbObject.get("name"), msg.get("name")); assertEquals(dbObject.get("age"), msg.get("age")); assertEquals(dbObject.get("birthday"), msg.get("birthday")); } }
public int deleteByPK(int idControlHoras) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); transaction.begin(); Query q = session.createQuery("delete from ControlHoras where idControlHoras = :id"); q.setInteger("id", idControlHoras); int rows = q.executeUpdate(); transaction.commit(); return rows; } catch (Exception e) { System.out.println("Error borrando control de horas..."); e.printStackTrace(); transaction.rollback(); return 0; } finally { session.close(); } }
private ModelAndView startTransaction( Repository repository, HttpServletRequest request, HttpServletResponse response) throws IOException, ClientHTTPException, ServerHTTPException { ProtocolUtil.logRequestParameters(request); Map<String, Object> model = new HashMap<String, Object>(); IsolationLevel isolationLevel = null; final String isolationLevelString = request.getParameter(Protocol.ISOLATION_LEVEL_PARAM_NAME); if (isolationLevelString != null) { final IRI level = SimpleValueFactory.getInstance().createIRI(isolationLevelString); // FIXME this needs to be adapted to accommodate custom isolation levels // from third party stores. for (IsolationLevel standardLevel : IsolationLevels.values()) { if (standardLevel.getURI().equals(level)) { isolationLevel = standardLevel; break; } } } try { Transaction txn = new Transaction(repository); txn.begin(isolationLevel); UUID txnId = txn.getID(); ActiveTransactionRegistry.INSTANCE.register(txn); model.put(SimpleResponseView.SC_KEY, SC_CREATED); final StringBuffer txnURL = request.getRequestURL(); txnURL.append("/" + txnId.toString()); Map<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put("Location", txnURL.toString()); model.put(SimpleResponseView.CUSTOM_HEADERS_KEY, customHeaders); return new ModelAndView(SimpleResponseView.getInstance(), model); } catch (RepositoryException | InterruptedException | ExecutionException e) { throw new ServerHTTPException("Transaction start error: " + e.getMessage(), e); } }
private Status parseEvents() throws EventDeliveryException { Status status = Status.READY; Channel channel = getChannel(); Transaction tx = null; Map<String, List<DBObject>> eventMap = new HashMap<String, List<DBObject>>(); try { tx = channel.getTransaction(); tx.begin(); for (int i = 0; i < batchSize; i++) { Event event = channel.take(); if (event == null) { status = Status.BACKOFF; break; } else { processEvent(eventMap, event); } } if (!eventMap.isEmpty()) { saveEvents(eventMap); } tx.commit(); } catch (Exception e) { logger.error("can't process events, drop it!", e); if (tx != null) { tx.commit(); // commit to drop bad event, otherwise it will enter dead loop. } throw new EventDeliveryException(e); } finally { if (tx != null) { tx.close(); } } return status; }
@Test public void testIssue508And513() throws Exception { HazelcastClient client = getHazelcastClient(); IMap<String, HashSet<byte[]>> callEventsMap = client.getMap("CALL_EVENTS"); IMap<String, Long> metaDataMap = client.getMap("CALL_META_DATA"); IMap<String, byte[]> callStartMap = client.getMap("CALL_START_EVENTS"); MultiMap<String, String> calls = client.getMultiMap("CALLS"); calls.lock("1"); calls.unlock("1"); byte[] bytes = new byte[10]; HashSet<byte[]> hashSet = new HashSet<byte[]>(); hashSet.add(bytes); String callId = "1"; callEventsMap.put(callId, hashSet); callStartMap.put(callId, bytes); metaDataMap.put(callId, 10L); Transaction txn = client.getTransaction(); txn.begin(); try { // remove the data callEventsMap.remove(callId); // remove meta data metaDataMap.remove(callId); // remove call start callStartMap.remove(callId); calls.put(callId, callId); txn.commit(); } catch (Exception e) { fail(); } assertNull(callEventsMap.get(callId)); assertNull(metaDataMap.get(callId)); assertNull(callStartMap.get(callId)); assertEquals(0, callEventsMap.size()); assertEquals(0, metaDataMap.size()); assertEquals(0, callStartMap.size()); }
/** * Look up and return the ClassInfo for an integer handle. This is used when decoding an <code> * Object</code> from a <code>com.persistit.Value</code> to associate the encoded integer handle * value with the corresponding class. * * @param handle The handle * @return The associated ClassInfo, or <i>null</i> if there is none. */ public ClassInfo lookupByHandle(final int handle) { final AtomicReferenceArray<ClassInfoEntry> hashTable = _hashTable; ClassInfoEntry cie = hashTable.get(handle % hashTable.length()); while (cie != null) { if (cie._classInfo.getHandle() == handle) return cie._classInfo; cie = cie._next; } _cacheMisses.incrementAndGet(); synchronized (this) { _sessionId.assign(); Exchange ex = null; try { ex = getExchange(); final Transaction txn = ex.getTransaction(); txn.begin(); try { ex.clear().append(BY_HANDLE).append(handle).fetch(); txn.commit(); } catch (final Exception e) { _persistit.getLogBase().exception.log(e); throw new ConversionException(e); } finally { txn.end(); } final Value value = ex.getValue(); if (value.isDefined()) { value.setStreamMode(true); final int storedId = value.getInt(); final String storedName = value.getString(); final long storedSuid = value.getLong(); if (storedId != handle) { throw new IllegalStateException( "ClassInfo stored for handle=" + handle + " has invalid stored handle=" + storedId); } final Class<?> cl = Class.forName(storedName, false, Thread.currentThread().getContextClassLoader()); long suid = 0; final ObjectStreamClass osc = ObjectStreamClass.lookupAny(cl); if (osc != null) suid = osc.getSerialVersionUID(); if (storedSuid != suid) { throw new ConversionException( "Class " + cl.getName() + " persistent SUID=" + storedSuid + " does not match current class SUID=" + suid); } final ClassInfo ci = new ClassInfo(cl, suid, handle, osc); hashClassInfo(ci); return ci; } else { final ClassInfo ci = new ClassInfo(null, 0, handle, null); hashClassInfo(ci); return ci; } } catch (final ClassNotFoundException cnfe) { throw new ConversionException(cnfe); } catch (final PersistitException pe) { throw new ConversionException(pe); } finally { if (ex != null) releaseExchange(ex); } } }
/** * Look up and return the ClassInfo for a class. This is used when encoding an <code>Object</code> * into a <code>com.persistit.Value</code>. * * @param clazz The <code>Class</code> * @return The ClassInfo for the specified Class. */ public ClassInfo lookupByClass(final Class<?> clazz) { final AtomicReferenceArray<ClassInfoEntry> hashTable = _hashTable; ObjectStreamClass osc = null; long suid = 0; final int nh = clazz.getName().hashCode() & 0x7FFFFFFF; ClassInfoEntry cie = hashTable.get(nh % hashTable.length()); while (cie != null) { if (clazz.equals(cie._classInfo.getDescribedClass())) { return cie._classInfo; } if (cie._classInfo.getDescribedClass() != null && cie._classInfo.getName().equals(clazz.getName())) { if (osc == null) { osc = ObjectStreamClass.lookupAny(clazz); if (osc != null) { suid = osc.getSerialVersionUID(); } } if (suid == cie._classInfo.getSUID()) { return cie._classInfo; } } cie = cie._next; } if (osc == null) { osc = ObjectStreamClass.lookupAny(clazz); } if (osc != null) { suid = osc.getSerialVersionUID(); } _cacheMisses.incrementAndGet(); /** * To update the tree, this class uses a unique SessionId and results in using a unique * Transaction context unrelated to the application context. Therefore if an application does * this: * * <pre> * <code> * txn.begin(); * value.put(new SomeClass()); * txn.rollback(); * txn.end(); * </code> * </pre> * * the class SomeClass will be registered even though the enclosing transaction rolled back. * This is important because other concurrent threads may have started using the handle for * SomeClass. Therefore this class ensures that a non-nested transaction to insert the new * ClassInfo into the system volume has committed before adding the handle to the hash table. */ synchronized (this) { final SessionId saveSessionId = _persistit.getSessionId(); Exchange ex = null; try { _persistit.setSessionId(_sessionId); ex = getExchange(); final Transaction txn = ex.getTransaction(); final ClassInfo ci; final int handle; txn.begin(); ex.clear().append(BY_NAME).append(clazz.getName()).append(suid).fetch(); final Value value = ex.getValue(); try { if (value.isDefined()) { value.setStreamMode(true); handle = value.getInt(); final String storedName = value.getString(); final long storedSuid = value.getLong(); if (storedSuid != suid || !clazz.getName().equals(storedName)) { throw new ConversionException( "Class " + clazz.getName() + " persistent SUID=" + storedSuid + " does not match current class SUID=" + suid); } ci = new ClassInfo(clazz, suid, handle, osc); } else { // // Store a new ClassInfo record // ex.clear().append(NEXT_ID).fetch(); handle = Math.max(_testIdFloor, value.isDefined() ? value.getInt() : HANDLE_BASE) + 1; value.clear().put(handle); ex.store(); value.clear(); value.setStreamMode(true); value.put(handle); value.put(clazz.getName()); value.put(suid); ex.clear().append(BY_NAME).append(clazz.getName()).append(suid).store(); ex.clear().append(BY_HANDLE).append(handle).store(); ci = new ClassInfo(clazz, suid, handle, osc); } txn.commit(); hashClassInfo(ci); return ci; } finally { txn.end(); } } catch (final PersistitException pe) { throw new ConversionException(pe); } finally { if (ex != null) { releaseExchange(ex); } _persistit.setSessionId(saveSessionId); } } }
public Transaction begainTransaction() { Session currentSession = this.sessionFactory.openSession(); Transaction tran = currentSession.beginTransaction(); tran.begin(); return tran; }
// system test-driver public static void test(Connection connection) { Transaction txn = new Transaction(); if (connection != null) { try { String businessKey = UUID.nextID(); BusinessEntity business = new BusinessEntity(); business.setBusinessKey(businessKey); business.setAuthorizedName("sviens"); business.setOperator("WebServiceRegistry.com"); String serviceKey = UUID.nextID(); BusinessService service = new BusinessService(); service.setBusinessKey(businessKey); service.setServiceKey(serviceKey); // begin a new transaction txn.begin(connection); String authorizedUserID = "sviens"; // insert a new BusinessEntity BusinessEntityTable.insert(business, authorizedUserID, connection); // insert a new BusinessService BusinessServiceTable.insert(service, connection); // insert another new BusinessService service.setServiceKey(UUID.nextID()); BusinessServiceTable.insert(service, connection); // insert one more new BusinessService service.setServiceKey(UUID.nextID()); BusinessServiceTable.insert(service, connection); // select a BusinessService object service = BusinessServiceTable.select(serviceKey, connection); // delete a BusinessService object BusinessServiceTable.delete(serviceKey, connection); // select a BusinessService object service = BusinessServiceTable.select(serviceKey, connection); // select a Collection BusinessService objects by BusinessKey BusinessServiceTable.selectByBusinessKey(businessKey, connection); // delete a Collection BusinessService objects by BusinessKey BusinessServiceTable.deleteByBusinessKey(businessKey, connection); // select a Collection BusinessService objects by BusinessKey BusinessServiceTable.selectByBusinessKey(businessKey, connection); // commit the transaction txn.commit(); } catch (Exception ex) { ex.printStackTrace(); try { txn.rollback(); } catch (java.sql.SQLException sqlex) { sqlex.printStackTrace(); } } } }