List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:com.hs.mail.imap.user.DefaultUserManager.java
public int updateUser(final User user) { return (Integer) getTransactionTemplate().execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { return DaoFactory.getUserDao().updateUser(user); } catch (DataAccessException ex) { status.setRollbackOnly(); throw ex; }/*www. j a v a 2 s . c o m*/ } }); }
From source file:org.jasig.schedassist.impl.DefaultAvailableScheduleReflectionServiceImpl.java
/** * First attempts to obtain the semaphore for the specified {@link IScheduleOwner}. * If successful, then retrieve's the owner's current {@link AvailableSchedule} and * passes it to {@link CalendarDao#reflectAvailableSchedule(IScheduleOwner, AvailableSchedule)}. * // w w w . j a v a 2 s .c om * @param owner * @return true if able to execute the operation, false if failed to obtain the lock */ protected boolean processScheduleOwner(final IScheduleOwner owner) { // add owner to lock table addOwnerToLockTableIfNotPresent(owner); boolean result = this.transactionTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { // obtain "lock" for owner if (lock(owner)) { // reflect schedule AvailableSchedule schedule = availableScheduleDao.retrieve(owner); calendarDataDao.reflectAvailableSchedule(owner, schedule); return true; } else { return false; } } }); return result; }
From source file:com.javaetmoi.core.persistence.hibernate.TestLazyLoadingUtil.java
/** * Verify the {@link LazyInitializationException} is thrown when accessing entity relations * outside a transaction, an Hibernate {@link PersistentCollection} in this test. *///from w w w . j a v a2 s . c o m @Test(expected = LazyInitializationException.class) public void lazyInitializationExceptionOnPersistentCollection() { // Load each entity in a transaction Employee dbJames = transactionTemplate.execute(new TransactionCallback<Employee>() { public Employee doInTransaction(TransactionStatus status) { Employee employee = (Employee) sessionFactory.getCurrentSession().get(Employee.class, 1); return employee; } }); // At this step, transaction and session are closed dbJames.getProjects().contains(android); }
From source file:org.apache.camel.processor.aggregate.jdbc.OptimisticLockingJdbcAggregationRepository.java
@Override public Exchange add(CamelContext camelContext, String key, Exchange exchange) { return getTransactionTemplate().execute(new TransactionCallback<Exchange>() { @Override/* w w w.ja v a 2s. c o m*/ public Exchange doInTransaction(TransactionStatus status) { Exchange result = get(camelContext, key); try { log.debug(String.format("Adding exchange with key: [%s]", key)); byte[] marshalledExchange = getCodec().marshallExchange(camelContext, exchange, true); boolean present = getJdbcTemplate().queryForObject( String.format("SELECT COUNT(*) FROM %1$s WHERE %2$s=?", getRepositoryName(), ID_KEY), new Object[] { key }, new int[] { Types.VARCHAR }, Integer.class) != 0; if (present) { long version = exchange.getProperty(VERSION_EXCHANGE_PROPERTY, Long.class); log.debug(String.format("Updating record with key: [%s] and version: [%s].", key, version)); int affectedRows = getJdbcTemplate().update( String.format("UPDATE %1$s SET %2$s=?, %3$s=? WHERE %4$s=? AND %3$s=?", getRepositoryName(), EXCHANGE_KEY, VERSION_KEY, ID_KEY), new Object[] { new SqlLobValue(marshalledExchange, getLobHandler()), version + 1, key, version }, new int[] { Types.BLOB, Types.BIGINT, Types.VARCHAR, Types.BIGINT }); if (affectedRows < 1) { throw new RuntimeException(String.format( "Error updating record with key: [%s] and version: [%s]. Stale version...", key, version)); } } else { log.debug(String.format("Inserting record with key: [%s].", key)); getJdbcTemplate().update( String.format("INSERT INTO %1$s (%2$s, %3$s, %4$s) VALUES (?, ?, ?)", getRepositoryName(), ID_KEY, EXCHANGE_KEY, VERSION_KEY), new Object[] { key, new SqlLobValue(marshalledExchange, getLobHandler()), 1L }, new int[] { Types.VARCHAR, Types.BLOB, Types.BIGINT }); } } catch (Exception e) { throw new RuntimeException(String.format("Error adding to repository [%s] with key [%s].", getRepositoryName(), key), e); } return result; } }); }
From source file:ch.tatool.app.service.impl.ModuleServiceImpl.java
/** * Load a module given its info object/*from ww w. j a v a 2 s . c o m*/ */ public Module loadModule(Module.Info info) { final ModuleInfoImpl moduleInfoImpl = (ModuleInfoImpl) info; // load the module from the database ModuleImpl module = (ModuleImpl) moduleInfoImpl.getAccount().getTransactionTemplate() .execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ModuleDAO moduleDAO = moduleInfoImpl.getAccount().getModuleDAO(); ModuleImpl module = moduleDAO.loadModule(moduleInfoImpl); return module; } }); initializeModule(module); // initialize exporters for module // TODO: String "SpringXmlElementConfig" is defined in ch.tatool.core.module.initializer.SpringExecutorInitializer Map<String, DataExporter> exporters = getModuleExportersFromXML( module.getBinaryModuleProperty("SpringXmlElementConfig")); module.setModuleExporters(exporters); return module; }
From source file:org.pentaho.custom.authentication.provider.userroledao.hibernate.UserRoleDaoTransactionDecorator.java
@SuppressWarnings("unchecked") public List<IUser> getUsers() throws UncategorizedUserRoleDaoException { return (List<IUser>) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { return userRoleDao.getUsers(); }// www . j a v a 2 s . com }); }
From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java
public <K, T extends Persistable<K>> int count(final Class<T> type) { Integer p_count = _executeTx("countAll", type, new TransactionCallback<Integer>() { public Integer doInTransaction(final TransactionStatus status) { return getDao(type).count(); }//from ww w .ja va 2 s. c om }); return p_count.intValue(); }
From source file:org.cleverbus.test.AbstractDbTest.java
protected Message[] createAndSaveMessages(final int messageCount, final ExternalSystemExtEnum sourceSystem, final ServiceExtEnum service, final String operationName, final String payload) { TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager); return tx.execute(new TransactionCallback<Message[]>() { @Override//from w w w . ja v a 2 s . c om public Message[] doInTransaction(TransactionStatus status) { Message[] messages = new Message[messageCount]; for (int i = 0; i < messages.length; i++) { messages[i] = createMessage(sourceSystem, service, operationName, payload); messages[i].setMsgTimestamp(DateTime.now().plusSeconds(i * 5).toDate()); em.persist(messages[i]); } em.flush(); return messages; } }); }
From source file:org.ambraproject.struts2.TransactionInterceptor.java
public String intercept(final ActionInvocation actionInvocation) throws Exception { final Action action = (Action) actionInvocation.getAction(); final ActionProxy actionProxy = actionInvocation.getProxy(); final String methodName = actionProxy.getMethod(); if (getAnnotation(action.getClass(), methodName, ManualTransactionManagement.class) != null) { //Method is annotated tellling us not to manage a transaction for it log.debug(//from www. j av a 2 s. c o m "Not managing transaction for " + action.getClass().getSimpleName() + "." + methodName + "()"); return actionInvocation.invoke(); } if (log.isDebugEnabled()) { log.debug("Intercepted " + action.getClass().getSimpleName() + "." + methodName + "()"); } final Transactional transactionalAnnotation = getAnnotation(action.getClass(), methodName, Transactional.class); TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); if (transactionalAnnotation != null) { txTemplate.setReadOnly(transactionalAnnotation.readOnly()); txTemplate.setTimeout(transactionalAnnotation.timeout()); txTemplate.setIsolationLevel(transactionalAnnotation.isolation().value()); txTemplate.setPropagationBehavior(transactionalAnnotation.propagation().value()); } CallbackResult callbackResult = (CallbackResult) txTemplate.execute(new TransactionCallback() { public CallbackResult doInTransaction(TransactionStatus transactionStatus) { CallbackResult result = new CallbackResult(); try { String actionResult = actionInvocation.invoke(); result.setResult(actionResult); //Rollback for Action responses indicating failure for (String response : new String[] { Action.ERROR, Action.INPUT, Action.LOGIN }) { if (response.equalsIgnoreCase(actionResult) && !transactionStatus.isRollbackOnly()) { log.debug("Rolling back action " + action.getClass().getSimpleName() + " due to result: " + actionResult); transactionStatus.setRollbackOnly(); break; } } } catch (Exception e) { /* * Callback does not throw exception. We need to pass Exception object in the return * parameter so we can throw it in the calling method. */ boolean noRollback = false; if (transactionalAnnotation != null && transactionalAnnotation.noRollbackFor() != null) { for (Class<? extends Throwable> exception : transactionalAnnotation.noRollbackFor()) { if (exception.isInstance(e)) { noRollback = true; break; } } } if (!noRollback && transactionalAnnotation != null && transactionalAnnotation.rollbackFor() != null) { for (Class<? extends Throwable> exception : transactionalAnnotation.rollbackFor()) { if (exception.isInstance(e)) { log.debug("Caught exception, rolling back action invocation " + action.getClass().getSimpleName()); transactionStatus.setRollbackOnly(); break; } } } result.setException(e); } return result; } }); if (callbackResult.getException() != null) throw callbackResult.getException(); return callbackResult.getResult(); }
From source file:com.mothsoft.alexis.engine.retrieval.RssRetrievalTaskImpl.java
private List<RssFeed> findFeedsToProcess() { try {/*w w w . java 2 s. co m*/ return this.transactionTemplate.execute(new TransactionCallback<List<RssFeed>>() { public List<RssFeed> doInTransaction(TransactionStatus status) { return RssRetrievalTaskImpl.this.rssFeedDao .listRssFeedsWithRetrievalDateMoreThanXMinutesAgo(30); } }); } catch (final Exception e) { logger.error("Listing sources for retrieval failed: " + e, e); return Collections.emptyList(); } }