use of java.sql.Savepoint in project adempiere by adempiere.
the class Migrate method cleanupCustomizations.
/**
* re-apply customizations
*/
private void cleanupCustomizations() {
// only continue if we have required tables
if (!m_source.isObjectExists("AD_ChangeLog", m_source.getTables()))
return;
if (!m_source.isObjectExists("AD_Table", m_source.getTables()))
return;
if (!m_source.isObjectExists("AD_Column", m_source.getTables()))
return;
if (!m_source.isObjectExists("AD_Reference", m_source.getTables()))
return;
// reset DB objects
resetDBObjects(null);
m_objectType = s_logger.localizeMessage("customization");
m_objectTypes = s_logger.localizeMessage("customizations");
m_counterUpd = new Integer(0);
m_totalUpd = new Integer(0);
s_logger.log(Level.CONFIG, "");
s_logger.log(Level.CONFIG, "cleanupCustomizations", new Object[] { m_objectTypes, m_direction });
String vendor = m_target.getVendor();
String catalog = m_target.getCatalog();
String schema = m_target.getSchema();
// remember savepoint for rollback
Savepoint sp = m_target.setSavepoint("reapply customizations");
// load customizations
Statement stmtLoadCustomizations = m_target.setStatement();
ResultSet rsLoadCustomizations = m_target.executeQuery(stmtLoadCustomizations, s_dbEngine.sqlAD_getCustomizationChangeLogs(vendor, catalog, schema));
while (m_target.getResultSetNext(rsLoadCustomizations)) {
String tableName = m_target.getResultSetString(rsLoadCustomizations, "TABLENAME");
int recordID = m_target.getResultSetInt(rsLoadCustomizations, "RECORDID");
String columnName = m_target.getResultSetString(rsLoadCustomizations, "COLUMNNAME");
String newValue = m_target.getResultSetString(rsLoadCustomizations, "NEWVALUE");
String displayType = m_target.getResultSetString(rsLoadCustomizations, "DISPLAYTYPE");
// null
if (newValue == null || newValue.length() == 0 || newValue.equalsIgnoreCase("NULL")) {
newValue = null;
} else // boolean
if (displayType.equalsIgnoreCase("YES-NO")) {
if (newValue.equalsIgnoreCase("true"))
newValue = "Y";
else
newValue = "N";
}
// get data type
int dataType = 0;
DBObject table = m_source.getObjectByName(tableName, m_source.getTables());
String checkVendor = m_source.getVendor();
// target
if (table == null) {
table = m_target.getObjectByName(tableName, m_target.getTables());
checkVendor = m_target.getVendor();
// ignored
if (table != null && table.getCustomizationLevel() == s_parameters.CUSTOMNONE)
table = null;
}
if (table != null) {
HashMap<Integer, DBObjectDefinition> columns = table.getContents();
for (Iterator<Integer> it = columns.keySet().iterator(); it.hasNext(); ) {
int key = it.next();
DBObject_Table_Column column = (DBObject_Table_Column) columns.get(key);
if (column.getName().equalsIgnoreCase(columnName)) {
dataType = s_dbEngine.getDataTypeID(checkVendor, column.getType());
break;
}
}
}
// (if we do not, it means the table or column no longer exists)
if (dataType != 0) {
// column name as array
ArrayList<String> columnNames = new ArrayList<String>();
columnNames.add(columnName);
// where condition as array
ArrayList<String> whereColumnNames = new ArrayList<String>();
String whereColumnName = new StringBuffer(tableName).append("_ID").toString();
if (tableName.equalsIgnoreCase("AD_Ref_Table"))
whereColumnName = "AD_Reference_ID";
whereColumnNames.add(whereColumnName);
// customize record in database
PreparedStatementWrapper stmtReapplyCustomization = m_target.setPreparedStatement(s_dbEngine.sql_updatePreparedStatement(vendor, catalog, schema, tableName, columnNames, whereColumnNames));
// set value depending on data type
if (dataType >= s_dbEngine.DATETYPE_START && dataType <= s_dbEngine.TIMESTAMPTYPE_END) {
// dates and times
if (newValue != null)
m_target.setPreparedStatementTimestamp(stmtReapplyCustomization, 1, java.sql.Timestamp.valueOf(newValue));
else
m_target.setPreparedStatementNull(stmtReapplyCustomization, 1, java.sql.Types.TIMESTAMP);
} else if (dataType < s_dbEngine.CHARTYPE_START) {
// numbers
if (newValue != null)
m_target.setPreparedStatementBigDecimal(stmtReapplyCustomization, 1, new BigDecimal(newValue));
else
m_target.setPreparedStatementNull(stmtReapplyCustomization, 1, java.sql.Types.NUMERIC);
} else {
// treat everything else as String
if (newValue != null)
m_target.setPreparedStatementString(stmtReapplyCustomization, 1, newValue);
else
m_target.setPreparedStatementNull(stmtReapplyCustomization, 1, java.sql.Types.VARCHAR);
}
// set WHERE clause to record to customize
m_target.setPreparedStatementInt(stmtReapplyCustomization, 2, recordID);
// execute the update
Integer sqlResult = m_target.executeUpdate(stmtReapplyCustomization, false);
if (sqlResult != null) {
logUpdateDetail(sqlResult, null);
m_counterUpd = new Integer(m_counterUpd.intValue() + 1);
}
// release prepared statement
m_target.releasePreparedStatement(stmtReapplyCustomization);
}
// increment total counter
// counts all active change logs marked as customizations
// also those for which the target table no longer exists
m_totalUpd = new Integer(m_totalUpd.intValue() + 1);
}
// release customization result set
m_target.releaseResultSet(rsLoadCustomizations);
m_target.releaseStatement(stmtLoadCustomizations);
// release savepoint
m_target.releaseSavepoint(sp);
logResults();
}
use of java.sql.Savepoint in project adempiere by adempiere.
the class Migrate method dropClient.
/**
* remove client entries from all tables
*
* @param clientID
* client to remove
*/
private boolean dropClient(int clientID) {
boolean result = false;
// Do not drop system client AD-Client_ID=0
if (clientID == s_parameters.SYSTEMCLIENTID)
return result;
// list of none-AD tables in which system client data is to be preserved
// (for example C_UOM, C_Region)
// use UPPERCASE table tames
ArrayList<String> tablesToPreserve = new ArrayList<String>();
Collections.addAll(tablesToPreserve, "C_UOM", "C_UOM_CONVERSION", "C_REGION");
String clientName = m_target.getSystemClients().get(clientID);
s_logger.log(Level.FINE, "dropClient", new Object[] { m_objectType, clientName, m_direction });
// iterate through all tables
Savepoint sp = m_target.setSavepoint(clientName);
Vector<String> v = new Vector<String>(m_targetMap.keySet());
java.util.Collections.sort(v);
for (Iterator<String> it = v.iterator(); it.hasNext(); ) {
String key = it.next();
DBObject obj = m_targetMap.get(key);
// but only use those where an AD_Client_ID field exists.
HashMap<Integer, DBObjectDefinition> columns = obj.getContents();
for (Iterator<Integer> it2 = columns.keySet().iterator(); it2.hasNext(); ) {
int key2 = it2.next();
DBObject_Table_Column col = (DBObject_Table_Column) columns.get(key2);
if (col.getName().equalsIgnoreCase("AD_Client_ID")) {
String vendor = m_target.getVendor();
String catalog = m_target.getCatalog();
String schema = m_target.getSchema();
String table = col.getTable();
String whereClause = new StringBuffer("AD_Client_ID = ").append(clientID).toString();
Statement stmt = m_target.setStatement();
String sqlCommand = s_dbEngine.sql_deleteByCondition(vendor, catalog, schema, table, whereClause);
Integer sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
if (sqlResult != null) {
logDropDetail(sqlResult, null);
result = true;
}
m_target.releaseStatement(stmt);
}
}
}
m_target.releaseSavepoint(sp);
return result;
}
use of java.sql.Savepoint in project adempiere by adempiere.
the class PO method save.
// is_new
/*
* Classes which override save() method:
* org.compiere.process.DocActionTemplate
* org.compiere.model.MClient
* org.compiere.model.MClientInfo
* org.compiere.model.MSystem
*/
/**************************************************************************
* Update Value or create new record.
* To reload call load() - not updated
* @return true if saved
*/
public boolean save() {
CLogger.resetLast();
// save locally as load resets
boolean newRecord = is_new();
if (!newRecord && !is_Changed()) {
log.fine("Nothing changed - " + p_info.getTableName());
return true;
}
// Organization Check
if (getAD_Org_ID() == 0 && (get_AccessLevel() == ACCESSLEVEL_ORG || (get_AccessLevel() == ACCESSLEVEL_CLIENTORG && MClientShare.isOrgLevelOnly(getAD_Client_ID(), get_Table_ID())))) {
log.saveError("FillMandatory", Msg.getElement(getCtx(), "AD_Org_ID"));
return false;
}
// Should be Org 0
if (getAD_Org_ID() != 0) {
boolean reset = get_AccessLevel() == ACCESSLEVEL_SYSTEM;
if (!reset && MClientShare.isClientLevelOnly(getAD_Client_ID(), get_Table_ID())) {
reset = get_AccessLevel() == ACCESSLEVEL_CLIENT || get_AccessLevel() == ACCESSLEVEL_SYSTEMCLIENT || get_AccessLevel() == ACCESSLEVEL_ALL || get_AccessLevel() == ACCESSLEVEL_CLIENTORG;
}
if (reset) {
log.warning("Set Org to 0");
setAD_Org_ID(0);
}
}
Trx localTrx = null;
Trx trx = null;
Savepoint savepoint = null;
if (m_trxName == null) {
m_trxName = Trx.createTrxName("POSave");
localTrx = Trx.get(m_trxName, true);
} else {
trx = Trx.get(m_trxName, false);
if (trx == null) {
// Using a trx that was previously closed or never opened
// Creating and starting the transaction right here, but please note
// that this is not a good practice
trx = Trx.get(m_trxName, true);
log.severe("Transaction closed or never opened (" + m_trxName + ") => starting now --> " + toString());
}
}
// Before Save
try {
// If not a localTrx we need to set a savepoint for rollback
if (localTrx == null)
savepoint = trx.setSavepoint(null);
if (!beforeSave(newRecord)) {
log.warning("beforeSave failed - " + toString());
if (localTrx != null) {
localTrx.rollback();
localTrx.close();
m_trxName = null;
} else {
trx.rollback(savepoint);
savepoint = null;
}
return false;
}
} catch (Exception e) {
log.log(Level.WARNING, "beforeSave - " + toString(), e);
log.saveError("Error", e, false);
if (localTrx != null) {
localTrx.rollback();
localTrx.close();
m_trxName = null;
} else if (savepoint != null) {
try {
trx.rollback(savepoint);
} catch (SQLException e1) {
}
savepoint = null;
}
return false;
}
try {
// Call ModelValidators TYPE_NEW/TYPE_CHANGE
String errorMsg = ModelValidationEngine.get().fireModelChange(this, newRecord ? ModelValidator.TYPE_NEW : ModelValidator.TYPE_CHANGE);
if (errorMsg != null) {
log.warning("Validation failed - " + errorMsg);
log.saveError("Error", errorMsg);
if (localTrx != null) {
localTrx.rollback();
m_trxName = null;
} else {
trx.rollback(savepoint);
}
return false;
}
// Save
if (newRecord) {
boolean b = saveNew();
if (b) {
if (localTrx != null)
return localTrx.commit();
else
return b;
} else {
if (localTrx != null)
localTrx.rollback();
else
trx.rollback(savepoint);
return b;
}
} else {
boolean b = saveUpdate();
if (b) {
if (localTrx != null)
return localTrx.commit();
else
return b;
} else {
if (localTrx != null)
localTrx.rollback();
else
trx.rollback(savepoint);
return b;
}
}
} catch (SQLException e) {
log.log(Level.WARNING, "afterSave - " + toString(), e);
if (localTrx != null) {
localTrx.rollback();
} else if (savepoint != null) {
try {
trx.rollback(savepoint);
} catch (SQLException e1) {
}
savepoint = null;
}
return false;
} finally {
if (localTrx != null) {
localTrx.close();
m_trxName = null;
} else {
if (savepoint != null) {
try {
trx.releaseSavepoint(savepoint);
} catch (SQLException e) {
e.printStackTrace();
}
}
savepoint = null;
trx = null;
}
}
}
use of java.sql.Savepoint in project adempiere by adempiere.
the class MWFActivity method run.
// getApproval
/**************************************************************************
* Execute Work.
* Called from MWFProcess.startNext
* Feedback to Process via setWFState -> checkActivities
*/
public void run() {
log.info("Node=" + getNode());
m_newValue = null;
//m_trx = Trx.get(, true);
Trx trx = null;
boolean localTrx = false;
if (get_TrxName() == null) {
this.set_TrxName(Trx.createTrxName("WFA"));
localTrx = true;
}
trx = Trx.get(get_TrxName(), true);
Savepoint savepoint = null;
//
try {
if (!localTrx)
savepoint = trx.setSavepoint(null);
if (!m_state.isValidAction(StateEngine.ACTION_Start)) {
setTextMsg("State=" + getWFState() + " - cannot start");
addTextMsg(new Exception(""));
setWFState(StateEngine.STATE_Terminated);
return;
}
//
setWFState(StateEngine.STATE_Running);
if (getNode().get_ID() == 0) {
setTextMsg("Node not found - AD_WF_Node_ID=" + getAD_WF_Node_ID());
setWFState(StateEngine.STATE_Aborted);
return;
}
// Do Work
/**** Trx Start ****/
boolean done = performWork(Trx.get(get_TrxName(), false));
// Reason: if the commit fails the document should be put in Invalid state
if (localTrx) {
try {
trx.commit(true);
} catch (Exception e) {
// If we have a DocStatus, change it to Invalid, and throw the exception to the next level
if (m_docStatus != null)
m_docStatus = DocAction.STATUS_Invalid;
throw e;
}
}
setWFState(done ? StateEngine.STATE_Completed : StateEngine.STATE_Suspended);
} catch (Exception e) {
log.log(Level.WARNING, "" + getNode(), e);
/**** Trx Rollback ****/
if (localTrx) {
trx.rollback();
} else if (savepoint != null) {
try {
trx.rollback(savepoint);
} catch (SQLException e1) {
}
}
//
if (e.getCause() != null)
log.log(Level.WARNING, "Cause", e.getCause());
String processMsg = e.getLocalizedMessage();
if (processMsg == null || processMsg.length() == 0)
processMsg = e.getMessage();
setTextMsg(processMsg);
addTextMsg(e);
// unlocks
setWFState(StateEngine.STATE_Terminated);
// Set Document Status
if (m_po != null && m_po instanceof DocAction && m_docStatus != null) {
m_po.load(get_TrxName());
DocAction doc = (DocAction) m_po;
doc.setDocStatus(m_docStatus);
m_po.saveEx();
}
} finally {
if (localTrx && trx != null) {
trx.close();
}
}
}
Aggregations