List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:org.kuali.rice.kew.test.TestUtilities.java
public static void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String edenSchemaName, final List<String> dontClear) { LOG.info("Clearing tables for schema " + edenSchemaName); if (dataSource == null) { Assert.fail("Null data source given"); }/*from www . ja v a 2 s. c om*/ if (edenSchemaName == null || edenSchemaName.equals("")) { Assert.fail("Empty eden schema name given"); } new TransactionTemplate(transactionManager).execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { verifyTestEnvironment(dataSource); JdbcTemplate template = new JdbcTemplate(dataSource); return template.execute(new StatementCallback() { public Object doInStatement(Statement statement) throws SQLException { List<String> reEnableConstraints = new ArrayList<String>(); ResultSet resultSet = statement.getConnection().getMetaData().getTables(null, edenSchemaName, null, new String[] { "TABLE" }); while (resultSet.next()) { String tableName = resultSet.getString("TABLE_NAME"); if (tableName.startsWith("EN_") && !dontClear.contains(tableName)) { ResultSet keyResultSet = statement.getConnection().getMetaData() .getExportedKeys(null, edenSchemaName, tableName); while (keyResultSet.next()) { String fkName = keyResultSet.getString("FK_NAME"); String fkTableName = keyResultSet.getString("FKTABLE_NAME"); statement.addBatch( "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName); reEnableConstraints .add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName); } keyResultSet.close(); statement.addBatch("DELETE FROM " + tableName); } } for (String constraint : reEnableConstraints) { statement.addBatch(constraint); } statement.executeBatch(); resultSet.close(); return null; } }); } }); LOG.info("Tables successfully cleared for schema " + edenSchemaName); }
From source file:org.kuali.rice.kns.web.struts.action.KualiRequestProcessor.java
/** * Hook into action perform to handle errors in the error map and catch * exceptions./* ww w. j a va2 s . co m*/ * * <p> * A transaction is started prior to the execution of the action. This * allows for the action code to execute efficiently without the need for * using PROPAGATION_SUPPORTS in the transaction definitions. The * PROPAGATION_SUPPORTS propagation type does not work well with JTA. */ @Override protected ActionForward processActionPerform(final HttpServletRequest request, final HttpServletResponse response, final Action action, final ActionForm form, final ActionMapping mapping) throws IOException, ServletException { try { TransactionTemplate template = new TransactionTemplate(getTransactionManager()); ActionForward forward = null; try { forward = (ActionForward) template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { ActionForward actionForward = null; try { actionForward = action.execute(mapping, form, request, response); } catch (Exception e) { if (e.getMessage() != null && e.getMessage().equals(KRADConstants.KRAD_INITIATED_DOCUMENT_VIEW_NAME)) { ConfigurationService kualiConfigurationService = CoreApiServiceLocator .getKualiConfigurationService(); StringBuffer sb = new StringBuffer(); sb.append(kualiConfigurationService .getPropertyValueAsString(KRADConstants.KRAD_URL_KEY)); sb.append(kualiConfigurationService .getPropertyValueAsString(KRADConstants.KRAD_INITIATED_DOCUMENT_URL_KEY)); return new ActionForward(KRADConstants.KRAD_INITIATED_DOCUMENT_VIEW_NAME, sb.toString(), true); } // the doInTransaction method has no means for // throwing exceptions, so we will wrap the // exception in // a RuntimeException and re-throw. The one caveat // here is that this will always result in // the // transaction being rolled back (since // WrappedRuntimeException is a runtime exception). throw new WrappedRuntimeException(e); } if (status.isRollbackOnly()) { // this means that the struts action execution // caused the transaction to rollback, we want to // go ahead // and trigger the rollback by throwing an exception // here but then return the action forward // from this method throw new WrappedActionForwardRuntimeException(actionForward); } return actionForward; } }); } catch (WrappedActionForwardRuntimeException e) { forward = e.getActionForward(); } publishMessages(request); saveMessages(request); saveAuditErrors(request); if (form instanceof PojoForm) { if (((PojoForm) form).getEditableProperties() == null || ((PojoForm) form).getEditableProperties().isEmpty()) { EditablePropertiesHistoryHolder holder = (EditablePropertiesHistoryHolder) GlobalVariables .getUserSession().getObjectMap() .get(KRADConstants.EDITABLE_PROPERTIES_HISTORY_HOLDER_ATTR_NAME); if (holder == null) { holder = new EditablePropertiesHistoryHolder(); } final String guid = holder .addEditablePropertiesToHistory(((PojoForm) form).getEditableProperties()); ((PojoForm) form).setActionEditablePropertiesGuid(guid); GlobalVariables.getUserSession() .addObject(KRADConstants.EDITABLE_PROPERTIES_HISTORY_HOLDER_ATTR_NAME, holder); } } return forward; } catch (Exception e) { if (e instanceof WrappedRuntimeException) { e = (Exception) e.getCause(); } if (e instanceof ValidationException) { // add a generic error message if there are none if (GlobalVariables.getMessageMap().hasNoErrors()) { GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, RiceKeyConstants.ERROR_CUSTOM, e.getMessage()); } if (form instanceof PojoForm) { if (((PojoForm) form).getEditableProperties() == null || ((PojoForm) form).getEditableProperties().isEmpty()) { EditablePropertiesHistoryHolder holder = (EditablePropertiesHistoryHolder) GlobalVariables .getUserSession().getObjectMap() .get(KRADConstants.EDITABLE_PROPERTIES_HISTORY_HOLDER_ATTR_NAME); if (holder == null) { holder = new EditablePropertiesHistoryHolder(); } final String guid = holder .addEditablePropertiesToHistory(((PojoForm) form).getEditableProperties()); ((PojoForm) form).setActionEditablePropertiesGuid(guid); GlobalVariables.getUserSession() .addObject(KRADConstants.EDITABLE_PROPERTIES_HISTORY_HOLDER_ATTR_NAME, holder); } } // display error messages and return to originating page publishMessages(request); return mapping.findForward(RiceConstants.MAPPING_BASIC); } publishMessages(request); return (processException(request, response, e, form, mapping)); } }
From source file:org.kuali.rice.test.ClearDatabaseLifecycle.java
protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource) { Assert.assertNotNull("DataSource could not be located.", dataSource); try {/*from www . j a va 2s . c o m*/ StopWatch s = new StopWatch(); s.start(); new TransactionTemplate(transactionManager).execute(new TransactionCallback() { public Object doInTransaction(final TransactionStatus status) { verifyTestEnvironment(dataSource); return new JdbcTemplate(dataSource).execute(new StatementCallback() { public Object doInStatement(Statement statement) throws SQLException { String schemaName = statement.getConnection().getMetaData().getUserName().toUpperCase(); LOG.info("Clearing tables for schema " + schemaName); if (StringUtils.isBlank(schemaName)) { Assert.fail("Empty schema name given"); } final List<String> reEnableConstraints = new ArrayList<String>(); DatabaseMetaData metaData = statement.getConnection().getMetaData(); Map<String, List<String[]>> exportedKeys = indexExportedKeys(metaData, schemaName); final ResultSet resultSet = metaData.getTables(null, schemaName, null, new String[] { "TABLE" }); final StringBuilder logStatements = new StringBuilder(); while (resultSet.next()) { String tableName = resultSet.getString("TABLE_NAME"); if (shouldTableBeCleared(tableName)) { if (!isUsingDerby(metaData) && isUsingOracle(metaData)) { List<String[]> exportedKeyNames = exportedKeys.get(tableName); if (exportedKeyNames != null) { for (String[] exportedKeyName : exportedKeyNames) { final String fkName = exportedKeyName[0]; final String fkTableName = exportedKeyName[1]; final String disableConstraint = "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName; logStatements.append("Disabling constraints using statement ->" + disableConstraint + "<-\n"); statement.addBatch(disableConstraint); reEnableConstraints.add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName); } } } else if (isUsingMySQL(metaData)) { statement.addBatch("SET FOREIGN_KEY_CHECKS = 0"); } String deleteStatement = "DELETE FROM " + tableName; logStatements.append( "Clearing contents using statement ->" + deleteStatement + "<-\n"); statement.addBatch(deleteStatement); } } for (final String constraint : reEnableConstraints) { logStatements .append("Enabling constraints using statement ->" + constraint + "<-\n"); statement.addBatch(constraint); } if (isUsingMySQL(metaData)) { statement.addBatch("SET FOREIGN_KEY_CHECKS = 1"); } LOG.info(logStatements); int[] results = statement.executeBatch(); for (int index = 0; index < results.length; index++) { if (results[index] == Statement.EXECUTE_FAILED) { Assert.fail("Execution of database clear statement failed."); } } resultSet.close(); LOG.info("Tables successfully cleared for schema " + schemaName); return null; } }); } }); s.stop(); LOG.info("Time to clear tables: " + DurationFormatUtils.formatDurationHMS(s.getTime())); } catch (Exception e) { LOG.error(e); throw new RuntimeException(e); } }
From source file:org.kuali.rice.test.SQLDataLoader.java
public void runSql() throws Exception { String[] sqlStatements = null; if (statement == null) { String sqlStatementsContent = getContentsAsString(fileLoc); // separator char must be the last non-whitespace char on the line // to avoid splitting in the middle of data that might contain the separator char sqlStatements = sqlStatementsContent.split("(?m)" + getSeperatorChar() + "\\s*$"); } else {/* w w w . j a va2 s .c o m*/ sqlStatements = new String[] { statement }; } final String[] finalSqlStatements = sqlStatements; new TransactionTemplate(TestHarnessServiceLocator.getJtaTransactionManager()) .execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { return new JdbcTemplate(TestHarnessServiceLocator.getDataSource()) .execute(new ConnectionCallback() { public Object doInConnection(Connection connection) throws SQLException { Statement statement = connection.createStatement(); LOG.info("################################"); LOG.info(fileLoc != null ? "#" + fileLoc : "#"); LOG.info("#"); for (String sqlStatement : finalSqlStatements) { if (StringUtils.isNotBlank(sqlStatement)) { LOG.info("# Executing sql statement ->" + sqlStatement + "<-"); statement.execute(sqlStatement); } } LOG.info("#"); LOG.info("#"); LOG.info("################################"); statement.close(); return null; } }); } }); }
From source file:org.lexevs.dao.database.operation.DefaultLexEvsDatabaseOperations.java
protected void doDropCodingSchemeTables(final String codingSchemeUri, final String version, final String prefix) { TransactionTemplate template = new TransactionTemplate(this.getTransactionManager()); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); template.execute(new TransactionCallback() { @Override//from w w w . j av a2 s . c om public Object doInTransaction(TransactionStatus status) { if (!getSystemVariables().isSingleTableMode()) { dropCodingSchemeHistoryTables(codingSchemeUri, version); } doExecuteSql(codingSchemeXmlDdl, new DropSchemaPlatformActor(), prefix); return null; } }); }
From source file:org.lexevs.dao.database.operation.DefaultLexEvsDatabaseOperations.java
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void dropCodingSchemeTablesByPrefix(final String prefix) { TransactionTemplate template = new TransactionTemplate(this.getTransactionManager()); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); template.execute(new TransactionCallback() { @Override//w w w . j a v a 2s . c om public Object doInTransaction(TransactionStatus status) { dropCodingSchemeHistoryTablesByPrefix(prefix); doExecuteSql(codingSchemeXmlDdl, new DropSchemaPlatformActor(), prefix); return null; } }); }
From source file:org.lexevs.dao.database.utility.DefaultDatabaseUtility.java
/** * Do execute script./* w w w . j a v a2s . co m*/ * * @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.ms123.common.workflow.tasks.TaskScriptExecutor.java
@Override public void execute(DelegateExecution execution) { final TaskContext tc = new TaskContext(execution); if (script == null) { return;/* w w w.j av a2s . c o m*/ } tc.setScript(script.getValue(execution).toString()); if (m_ownTransaction) { TransactionTemplate tt = getTransactionService().getTransactionTemplate(true); tt.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus paramTransactionStatus) { _execute(tc, null); return null; } }); } else { _execute(tc, null); } }
From source file:org.ms123.common.workflow.tasks.TaskScriptExecutor.java
public void execute(String namespace, String processDefinitionKey, String pid, String script, final Map addVars, VariableScope variableScope, String hint, DataLayer dataLayer, WorkflowService ws) { if (script == null) { return;/*from w w w . ja v a2s . c o m*/ } final TaskContext tc = new TaskContext(); tc.setTenantId(namespace); tc.setProcessDefinitionKey(processDefinitionKey); tc.setHint(hint); tc.setPid(pid); tc.setScript(script); tc.setExecution(variableScope); m_dataLayer = dataLayer; m_workflowService = ws; if (m_ownTransaction) { TransactionTemplate tt = getTransactionService().getTransactionTemplate(true); tt.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus paramTransactionStatus) { _execute(tc, addVars); return null; } }); } else { _execute(tc, addVars); } }
From source file:org.ms123.common.workflow.TaskScriptExecutor.java
@Override public void execute(DelegateExecution execution) { final TaskContext tc = new TaskContext(); tc.setExecution(execution);// w ww .j a va 2 s . c o m setCategory(tc); if (script == null) { return; } tc.setScript(script.getValue(execution).toString()); if (m_ownTransaction) { TransactionTemplate tt = getTransactionService().getTransactionTemplate(true); tt.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus paramTransactionStatus) { _execute(tc, null); return null; } }); } else { _execute(tc, null); } }