Thursday, April 22, 2010

Refreshing SharedAM viewobjects periodically

SharedAM viewobjects get instantiated once per JVM life cycle.In the mean time , if we have a requirement to have the ViewObjects of the SharedAM reflect the latest changes of Data from underlying Database Tables, we have a programmatic way to do so.

public long lastRefreshedTime;

private void setLastRefreshedTime(long lastRefreshedTime) {
this.lastRefreshedTime = lastRefreshedTime;
}

private long getLastRefreshedTime() {
return lastRefreshedTime;
}


private void refreshSharedAMVOs() {
String[] voNames = this.getViewObjectNames();
for (String voName : voNames) {
ViewObjectImpl vo = (ViewObjectImpl)this.findViewObject(voName);
processDatabaseChangeNotification(vo);
}
}


public void refreshSharedAM() {

long currentTime = System.currentTimeMillis();
long lastRefreshedTime = getLastRefreshedTime();

//hardcoded to 1 day
if ((currentTime - lastRefreshedTime) > 12 * 60 * 60 * 1000) {
synchronized (this) {
refreshSharedAMVOs();
}
setLastRefreshedTime(currentTime);
}
}

private void processDatabaseChangeNotification(ViewObjectImpl vo) {
try {
Row currentRow = vo.getCurrentRow();

if (currentRow == null) {
int rangeStartBeforeQuery = vo.getRangeStart();
vo.executeQuery();
vo.setRangeStart(rangeStartBeforeQuery);
} else {
Key currentRowKey = currentRow.getKey();
int rangePosOfCurrentRow = vo.getRangeIndexOf(currentRow);
int rangeStartBeforeQuery = vo.getRangeStart();
vo.executeQuery();
vo.setRangeStart(rangeStartBeforeQuery);
vo.findAndSetCurrentRowByKey(currentRowKey,
rangePosOfCurrentRow);
}

} catch (Exception e) {
e.printStackTrace();
}
}


No comments: