List of usage examples for org.springframework.jdbc.datasource DataSourceTransactionManager DataSourceTransactionManager
public DataSourceTransactionManager(DataSource dataSource)
From source file:org.foxbpm.rest.service.api.model.ModelsResouce.java
@Post public String deploy(Representation entity) { FileOutputStream fileOutputStream = null; final Map<String, InputStream> resourceMap = new HashMap<String, InputStream>(); InputStream is = null;//from www .j av a 2 s .c om try { File file = File.createTempFile(System.currentTimeMillis() + "flowres", ".zip"); fileOutputStream = new FileOutputStream(file); DiskFileItemFactory factory = new DiskFileItemFactory(); RestletFileUpload upload = new RestletFileUpload(factory); List<FileItem> items = null; try { items = upload.parseRepresentation(entity); } catch (FileUploadException e) { throw new FoxBPMException("??"); } FileItem fileItem = items.get(0); fileItem.write(file); String sysTemp = System.getProperty("java.io.tmpdir"); final File targetDir = new File(sysTemp + File.separator + "ModelsTempFile"); targetDir.mkdirs(); FileUtil.unZip(file.getPath(), targetDir.getPath()); PlatformTransactionManager transactionManager = new DataSourceTransactionManager( DBUtils.getDataSource()); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService(); for (File tmpFile : targetDir.listFiles()) { if (tmpFile.isDirectory()) { DeploymentBuilder deploymentBuilder = modelService.createDeployment(); String fileName = tmpFile.getName(); if (fileName.indexOf(SEP) == -1) { throw new FoxBPMException("??"); } //???? insert-processExpens-1? insert??processExpens?key,1? String operation = fileName.substring(0, fileName.indexOf(SEP)); String processKey = fileName.substring(fileName.indexOf(SEP) + 1, fileName.lastIndexOf(SEP)); int version = Integer.parseInt(fileName.substring(fileName.lastIndexOf(SEP) + 1)); File[] files = tmpFile.listFiles(); for (File t : files) { InputStream input = new FileInputStream(t); //map? resourceMap.put(t.getName(), input); deploymentBuilder.addInputStream(t.getName(), input, version); } if (PREFIX_ADD.equals(operation)) { deploymentBuilder.deploy(); } else if (PREFIX_UPDATE.equals(operation)) { ProcessDefinition processDefinition = null; processDefinition = modelService.getProcessDefinition(processKey, version); if (processDefinition != null) { String deploymentId = processDefinition.getDeploymentId(); deploymentBuilder.updateDeploymentId(deploymentId); } deploymentBuilder.deploy(); } else if (PREFIX_DELETE.equals(operation)) { ProcessDefinition processDefinitionNew = modelService .getProcessDefinition(processKey, version); if (processDefinitionNew != null) { String deploymentId = processDefinitionNew.getDeploymentId(); modelService.deleteDeployment(deploymentId); } else { log.warn("??key:" + processKey + "version:" + version + "??"); } } else if ("NotModify".equals(operation)) { log.debug(processKey + "????"); } else { throw new FoxBPMException("??" + operation); } } } } catch (Exception ex) { if (ex instanceof FoxBPMException) { throw (FoxBPMException) ex; } else { throw new FoxBPMException("?", ex); } } } }); setStatus(Status.SUCCESS_CREATED); } catch (Exception e) { if (e instanceof FoxBPMException) { throw (FoxBPMException) e; } throw new FoxBPMException(e.getMessage(), e); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { log.error("?", e); } } for (String name : resourceMap.keySet()) { InputStream isTmp = resourceMap.get(name); if (isTmp != null) { try { isTmp.close(); } catch (IOException e) { log.error("?", e); } } } if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; }
From source file:org.jamwiki.db.DatabaseConnection.java
/** * Static method that will configure a DataSource based on the Environment setup. */// ww w .ja v a 2s .c o m private synchronized static void configDataSource() throws SQLException { if (dataSource != null) { closeConnectionPool(); // DataSource has already been created so remove it } String url = Environment.getValue(Environment.PROP_DB_URL); DataSource targetDataSource = null; if (url.startsWith("jdbc:")) { try { // Use an internal "LocalDataSource" configured from the Environment targetDataSource = new LocalDataSource(); } catch (ClassNotFoundException e) { logger.error("Failure while configuring local data source", e); throw new SQLException("Failure while configuring local data source: " + e.toString()); } } else { try { // Use a container DataSource obtained via JNDI lookup // TODO: Should try prefix java:comp/env/ if not already part of the JNDI name? Context ctx = new InitialContext(); targetDataSource = (DataSource) ctx.lookup(url); } catch (NamingException e) { logger.error("Failure while configuring JNDI data source with URL: " + url, e); throw new SQLException( "Unable to configure JNDI data source with URL " + url + ": " + e.toString()); } } dataSource = new LazyConnectionDataSourceProxy(targetDataSource); transactionManager = new DataSourceTransactionManager(targetDataSource); }
From source file:org.lexevs.dao.database.utility.DefaultDatabaseUtility.java
/** * Do execute script.//from w ww . ja v a2 s. c om * * @param scriptResource the script resource */ private void doExecuteScript(final String scriptResource) { if (scriptResource == null) { return; } TransactionTemplate transactionTemplate = new TransactionTemplate( new DataSourceTransactionManager(getDataSource())); transactionTemplate.execute(new TransactionCallback() { @SuppressWarnings("unchecked") public Object doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = getJdbcTemplate(); String[] scripts; try { scripts = StringUtils.delimitedListToStringArray( stripComments(IOUtils.readLines(new StringReader(scriptResource))), ";"); } catch (IOException e) { throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); } for (int i = 0; i < scripts.length; i++) { String script = scripts[i].trim(); if (StringUtils.hasText(script)) { try { jdbcTemplate.execute(script); } catch (DataAccessException e) { throw e; } } } return null; } }); }
From source file:org.opoo.oqs.spring.transaction.SpringJdbcTransaction.java
public SpringJdbcTransaction(DataSource ds) { transactionManager = new DataSourceTransactionManager(ds); }
From source file:org.pentaho.aggdes.ui.exec.impl.JdbcTemplateSqlExecutor.java
public void execute(final String[] sql, final ExecutorCallback callback) throws DataAccessException { Exception exceptionDuringExecute = null; DatabaseMeta dbMeta = connectionModel.getDatabaseMeta(); String url = null;// w ww. j a v a2 s . com try { url = dbMeta.getURL(); } catch (KettleDatabaseException e) { throw new DataAccessException("DatabaseMeta problem", e) { private static final long serialVersionUID = -3457360074729938909L; }; } // create the datasource DataSource ds = new SingleConnectionDataSource(dbMeta.getDriverClass(), url, dbMeta.getUsername(), dbMeta.getPassword(), false); // create the jdbc template final JdbcTemplate jt = new JdbcTemplate(ds); // create the transaction manager DataSourceTransactionManager tsMan = new DataSourceTransactionManager(ds); // create the transaction template TransactionTemplate txTemplate = new TransactionTemplate(tsMan); // set behavior txTemplate.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW); final String noCommentSql[] = removeCommentsAndSemicolons(connectionModel.getSchema(), sql); try { // run the code in a transaction txTemplate.execute(new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult(TransactionStatus status) { jt.batchUpdate(noCommentSql); } }); } catch (DataAccessException e) { if (logger.isErrorEnabled()) { logger.error("data access exception", e); } exceptionDuringExecute = e; } callback.executionComplete(exceptionDuringExecute); }
From source file:org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer.java
@Autowired(required = false) public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.transactionManager = new DataSourceTransactionManager(dataSource); }
From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanUnexpectedRollbackTests.java
@Test @Ignore //FIXME//from w ww. jav a 2 s . c o m public void testTransactionException() throws Exception { final SkipWriterStub<String> writer = new SkipWriterStub<String>(); FaultTolerantStepFactoryBean<String, String> factory = new FaultTolerantStepFactoryBean<String, String>(); factory.setItemWriter(writer); @SuppressWarnings("serial") DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource) { private boolean failed = false; @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException { if (writer.getWritten().isEmpty() || failed || !isExistingTransaction(status.getTransaction())) { super.doCommit(status); return; } failed = true; status.setRollbackOnly(); super.doRollback(status); throw new UnexpectedRollbackException("Planned"); } }; factory.setBeanName("stepName"); factory.setTransactionManager(transactionManager); factory.setCommitInterval(2); ItemReader<String> reader = new ListItemReader<String>(Arrays.asList("1", "2")); factory.setItemReader(reader); JobRepositoryFactoryBean repositoryFactory = new JobRepositoryFactoryBean(); repositoryFactory.setDataSource(dataSource); repositoryFactory.setTransactionManager(transactionManager); repositoryFactory.afterPropertiesSet(); JobRepository repository = repositoryFactory.getObject(); factory.setJobRepository(repository); JobExecution jobExecution = repository.createJobExecution("job", new JobParameters()); StepExecution stepExecution = jobExecution.createStepExecution(factory.getName()); repository.add(stepExecution); Step step = factory.getObject(); step.execute(stepExecution); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); assertEquals("[]", writer.getCommitted().toString()); }
From source file:org.springframework.batch.test.DataSourceInitializer.java
private void doExecuteScript(final Resource scriptResource) { if (scriptResource == null || !scriptResource.exists()) return;//from ww w. ja v a 2 s. c om TransactionTemplate transactionTemplate = new TransactionTemplate( new DataSourceTransactionManager(dataSource)); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String[] scripts; try { scripts = StringUtils.delimitedListToStringArray( stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";"); } catch (IOException e) { throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); } for (int i = 0; i < scripts.length; i++) { String script = scripts[i].trim(); if (StringUtils.hasText(script)) { try { jdbcTemplate.execute(script); } catch (DataAccessException e) { if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { logger.debug("DROP script failed (ignoring): " + script); } else { throw e; } } } } return null; } }); }
From source file:org.springframework.boot.autoconfigure.batch.BasicBatchConfigurer.java
protected PlatformTransactionManager createTransactionManager() { if (this.entityManagerFactory != null) { return new JpaTransactionManager(this.entityManagerFactory); }//from w ww . j a va 2 s. c o m return new DataSourceTransactionManager(this.dataSource); }
From source file:org.springframework.cloud.task.configuration.DefaultTaskConfigurer.java
@Override public PlatformTransactionManager getTransactionManager() { if (this.transactionManager == null) { if (isDataSourceAvailable()) { try { Class.forName("javax.persistence.EntityManager"); if (this.context != null && this.context.getBeanNamesForType(EntityManager.class).length > 0) { logger.debug("EntityManager was found, using JpaTransactionManager"); this.transactionManager = new JpaTransactionManager(); }/* ww w .j a v a 2s . co m*/ } catch (ClassNotFoundException ignore) { logger.debug("No EntityManager was found, using DataSourceTransactionManager"); } finally { if (this.transactionManager == null) { this.transactionManager = new DataSourceTransactionManager(this.dataSource); } } } else { logger.debug("No DataSource was found, using ResourcelessTransactionManager"); this.transactionManager = new ResourcelessTransactionManager(); } } return this.transactionManager; }