List of usage examples for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult
TransactionCallbackWithoutResult
From source file:app.web.AbstractCrudController.java
@RequestMapping(value = "/delete") // TODO: , method = RequestMethod.POST) public String delete(@RequestParam final int id) { new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { Db.delete(getTypeClass(), id); }/* ww w.j a va 2s. c om*/ }); return "redirect:."; }
From source file:com.example.test.HibernateBookRepositoryTest.java
private void persistBooks(Supplier<AbstractBook> bookSupplier) throws Exception { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override//from ww w. ja v a 2s . c om protected void doInTransactionWithoutResult(TransactionStatus ts) { Session session = getCurrentSession(); Category softwareDevelopment = new Category(); softwareDevelopment.setName("Software development"); session.persist(softwareDevelopment); Category systemDesign = new Category(); systemDesign.setName("System design"); session.persist(systemDesign); Author martinFowler = new Author(); martinFowler.setFullName("Martin Fowler"); session.persist(martinFowler); AbstractBook poeaa = bookSupplier.get(); poeaa.setIsbn("007-6092019909"); poeaa.setTitle("Patterns of Enterprise Application Architecture"); poeaa.setPublicationDate(Date.from(Instant.parse("2002-11-15T00:00:00.00Z"))); poeaa.setAuthors(asList(martinFowler)); poeaa.setCategories(asList(softwareDevelopment, systemDesign)); session.persist(poeaa); Author gregorHohpe = new Author(); gregorHohpe.setFullName("Gregor Hohpe"); session.persist(gregorHohpe); Author bobbyWoolf = new Author(); bobbyWoolf.setFullName("Bobby Woolf"); session.persist(bobbyWoolf); AbstractBook eip = bookSupplier.get(); eip.setIsbn("978-0321200686"); eip.setTitle("Enterprise Integration Patterns"); eip.setPublicationDate(Date.from(Instant.parse("2003-10-20T00:00:00.00Z"))); eip.setAuthors(asList(gregorHohpe, bobbyWoolf)); eip.setCategories(asList(softwareDevelopment, systemDesign)); session.persist(eip); Category objectOrientedSoftwareDesign = new Category(); objectOrientedSoftwareDesign.setName("Object-Oriented Software Design"); session.persist(objectOrientedSoftwareDesign); Author ericEvans = new Author(); ericEvans.setFullName("Eric Evans"); session.persist(ericEvans); AbstractBook ddd = bookSupplier.get(); ddd.setIsbn("860-1404361814"); ddd.setTitle("Domain-Driven Design: Tackling Complexity in the Heart of Software"); ddd.setPublicationDate(Date.from(Instant.parse("2003-08-01T00:00:00.00Z"))); ddd.setAuthors(asList(ericEvans)); ddd.setCategories(asList(softwareDevelopment, systemDesign, objectOrientedSoftwareDesign)); session.persist(ddd); Category networkingCloudComputing = new Category(); networkingCloudComputing.setName("Networking & Cloud Computing"); session.persist(networkingCloudComputing); Category databasesBigData = new Category(); databasesBigData.setName("Databases & Big Data"); session.persist(databasesBigData); Author pramodSadalage = new Author(); pramodSadalage.setFullName("Pramod J. Sadalage"); session.persist(pramodSadalage); AbstractBook nosql = bookSupplier.get(); nosql.setIsbn("978-0321826626"); nosql.setTitle("NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence"); nosql.setPublicationDate(Date.from(Instant.parse("2012-08-18T00:00:00.00Z"))); nosql.setAuthors(asList(pramodSadalage, martinFowler)); nosql.setCategories(asList(networkingCloudComputing, databasesBigData)); session.persist(nosql); } }); System.out.println("##################################################"); }
From source file:com.mothsoft.alexis.engine.numeric.StockQuoteDataSetImporter.java
private void importStockQuotes(final HttpClientResponse response) { try {// w ww . j a va2 s. c om this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { final DataSetType type = StockQuoteDataSetImporter.this.dataSetTypeDao .findSystemDataSetType(STOCK_QUOTES); BufferedReader reader = null; try { reader = new BufferedReader( new InputStreamReader(response.getInputStream(), response.getCharset())); String line = null; while ((line = reader.readLine()) != null) { final String[] tokens = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); final String symbolName = StringUtils.replace(tokens[0], "\"", ""); final Double price; try { price = Double.valueOf(tokens[2]); } catch (final Exception e) { logger.error("Unable to parse stock price, exception: " + e, e); return; } DataSet dataSet = StockQuoteDataSetImporter.this.dataSetDao.findSystemDataSet(type, symbolName); if (dataSet == null) { dataSet = new DataSet(symbolName, type); StockQuoteDataSetImporter.this.dataSetDao.add(dataSet); } final DataSetPoint point = new DataSetPoint(dataSet, new Date(), price); StockQuoteDataSetImporter.this.dataSetPointDao.add(point); } } catch (IOException e) { logger.warn(e, e); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(reader); } } }); } catch (final Exception e) { response.abort(); logger.warn(e, e); throw new RuntimeException(e); } finally { response.close(); } }
From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java
public <K, T extends Persistable<K>> void remove(final Class<T> type, final T object) { _executeTx("remove", type, object, new TransactionCallbackWithoutResult() { @Override/*from ww w . j a v a2 s . com*/ public void doInTransactionWithoutResult(final TransactionStatus status) { getDao(type).remove(object); } }); }
From source file:com.mothsoft.alexis.engine.textual.TopicDocumentMatcherImpl.java
private void match() { this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override/*from ww w . jav a 2 s. c o m*/ protected void doInTransactionWithoutResult(TransactionStatus txStatus) { try { CurrentUserUtil.setSystemUserAuthentication(); final Map<Long, List<TopicScore>> documentTopicMap = new HashMap<Long, List<TopicScore>>(); final List<Topic> topics = TopicDocumentMatcherImpl.this.topicDao.list(); for (final Topic topic : topics) { mapMatches(topic, documentTopicMap); } saveMatches(documentTopicMap); final long rowsAffected = documentTopicMap.size(); logger.info("Topic<=>Document matching associated " + rowsAffected + " items"); } finally { CurrentUserUtil.clearAuthentication(); } } }); }
From source file:net.cpollet.jixture.fixtures.loaders.SimpleFixtureLoader.java
public void execute(Mode mode, final Executable executable) { getTransactionTemplate(mode).execute(new TransactionCallbackWithoutResult() { @Override//from w ww. j a va2 s . com protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { executable.execute(); unitDaoFactory.getUnitDao().flushAndClear(); } }); }
From source file:com.hmsinc.epicenter.service.ClassificationService.java
@PostConstruct public void init() throws Exception { logger.info("Initializing classifiers.."); new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() { /*/* ww w . jav a 2 s. c o m*/ * (non-Javadoc) * * @see org.springframework.transaction.support.TransactionCallbackWithoutResult#doInTransactionWithoutResult(org.springframework.transaction.TransactionStatus) */ @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // Configure default classifiers final List<Classifier> allClassifiers = analysisRepository.getList(Classifier.class); try { final ClassifierMetadata cm = (ClassifierMetadata) jaxbContext.createUnmarshaller() .unmarshal(configuration.getInputStream()); for (Classifier classifier : cm.getClassifiers()) { try { final ClassificationEngine engine = ClassifierFactory .createClassifier(classifier.getResource()); if (engine != null) { Validate.isTrue(engine.getName().equals(classifier.getName()), "Classifier names must match! (configured: " + classifier.getName() + " actual: " + engine.getName()); boolean isInstalled = false; for (Classifier installed : allClassifiers) { if (installed.getName().equals(engine.getName()) && installed.getVersion().equals(engine.getVersion())) { isInstalled = true; classifier = installed; break; } } classifiers.put(engine.getName(), engine); if (!isInstalled) { // Copy the properties and create // Classification objects classifier.setVersion(engine.getVersion()); classifier.setDescription(engine.getDescription()); logger.info("Installing classifier: {}", classifier.getName()); final SortedSet<Classification> classifications = new TreeSet<Classification>(); for (String category : engine.getCategories()) { if (!category.equalsIgnoreCase("Other")) { classifications.add(new Classification(classifier, category)); } } classifier.setClassifications(classifications); analysisRepository.save(classifier); } } } catch (IOException e) { logger.warn(e.getMessage()); } } // Load the and initialize any unconfigured classifiers.. for (Classifier classifier : allClassifiers) { if (classifier.isEnabled() && !classifiers.containsKey(classifier.getName())) { try { final ClassificationEngine engine = ClassifierFactory .createClassifier(classifier.getResource()); if (engine != null) { classifiers.put(engine.getName(), engine); } } catch (IOException e) { logger.warn(e.getMessage()); } } } // Configure DataTypes final List<DataType> dataTypes = cm.getDataTypes(); // Hydrate the PatientClasses because the XML descriptor // will only reference the name // Also remove any targets with unconfigured classifiers. for (DataType dataType : dataTypes) { logger.debug("Data type: " + dataType.toString()); final List<ClassificationTarget> unconfigured = new ArrayList<ClassificationTarget>(); for (ClassificationTarget ct : dataType.getTargets()) { if (ct.getClassifier() == null || ct.getClassifier().getId() == null && !classifiers.containsKey(ct.getClassifier().getName())) { logger.debug("Skipping unconfigured classification target"); unconfigured.add(ct); } else { final PatientClass pc = attributeRepository .getPatientClassByName(ct.getPatientClass().getName()); Validate.notNull(pc, "Unknown patient class: " + ct.getPatientClass().toString()); ct.setPatientClass(pc); if (classifiers.containsKey(ct.getClassifier().getName())) { ct.setClassifier( analysisRepository.getClassifierByName(ct.getClassifier().getName())); } } } dataType.getTargets().removeAll(unconfigured); } upgradeTasks.validateAttributes(dataTypes, DataType.class, analysisRepository); } catch (JAXBException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }); }
From source file:com.alibaba.otter.manager.biz.config.canal.impl.CanalServiceImpl.java
/** * /*from w w w .j a va 2 s. c om*/ */ public void modify(final Canal canal) { Assert.assertNotNull(canal); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { CanalDO canalDo = modelToDo(canal); if (canalDao.checkUnique(canalDo)) { canalDao.update(canalDo); } else { String exceptionCause = "exist the same repeat canal in the database."; logger.warn("WARN ## " + exceptionCause); throw new RepeatConfigureException(exceptionCause); } } catch (RepeatConfigureException rce) { throw rce; } catch (Exception e) { logger.error("ERROR ## modify canal(" + canal.getId() + ") has an exception!"); throw new ManagerException(e); } } }); }
From source file:ch.tatool.app.service.impl.ModuleServiceImpl.java
/** * Creates a new module data object.//from ww w.j av a 2 s .c o m * * @param account the account to create a module for * @param properties the properties to use for the module. These will overwrite properties set in the * configuration * @param configuration module configuration, such as the element tree and session scheduler */ public Module createModule(UserAccount account, Map<String, String> moduleProperties, Map<String, byte[]> binaryModuleProperties, Map<String, DataExporter> moduleExporters) { final UserAccountImpl accountImpl = (UserAccountImpl) account; // add the properties and save the object final ModuleImpl module = new ModuleImpl(); module.setAccount(accountImpl); module.setAccountId(accountImpl.getId()); if (moduleProperties != null) { module.setModuleProperties(moduleProperties); } if (binaryModuleProperties != null) { module.setBinaryModuleProperties(binaryModuleProperties); } if (moduleExporters != null) { module.setModuleExporters(moduleExporters); } // set the module name String moduleName = moduleProperties.get(Module.PROPERTY_MODULE_NAME); if (moduleName == null) { logger.warn("No module name defined."); moduleName = "Module " + System.currentTimeMillis(); module.getModuleProperties().put(Module.PROPERTY_MODULE_NAME, moduleName); } module.setName(moduleName); // save the module accountImpl.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult(TransactionStatus status) { // save the module object accountImpl.getModuleDAO().saveModule(module); } }); // initialize initializeModule(module); return module; }
From source file:org.jasig.jpa.BaseJpaDao.java
protected final <T> CriteriaQuery<T> createCriteriaQuery(Function<CriteriaBuilder, CriteriaQuery<T>> builder) { final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory(); final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder(); final CriteriaQuery<T> criteriaQuery = builder.apply(criteriaBuilder); //Do in TX so the EM gets closed correctly transactionOperations.execute(new TransactionCallbackWithoutResult() { @Override/*from www . java2 s. c om*/ protected void doInTransactionWithoutResult(TransactionStatus status) { entityManager.createQuery(criteriaQuery); //pre-compile critera query to avoid race conditions when setting aliases } }); return criteriaQuery; }