/*
* Delegate.java
*
*/
package cli_fmw.delegate;
import cli_fmw.delegate.cache.SecondaryCacheManager;
import framework.beans.EntityDetails;
import framework.beans.EntityFacade;
import framework.beans.FacadeBean;
import cli_fmw.delegate.cache.ExtraDataManager;
import cli_fmw.main.ClipsException;
import cli_fmw.login.UserInfoAbstract;
import cli_fmw.main.AccessException;
import framework.audit.AuditDetails;
import framework.beans.ModificationInfo;
import framework.beans.security.BeanRights;
import framework.security.MagicValues;
import java.util.LinkedList;
import java.util.List;
import javax.swing.event.EventListenerList;
/**
* Делегат
*
* @param <BEANFACADE>
* @param <DETAILSTYPE>
* @author Axe Ilshat
*/
abstract public class DelegateLine2<BEANFACADE extends EntityFacade,
DETAILSTYPE extends EntityDetails>
extends DelegateStateful {
private EventListenerList listeners = new EventListenerList();
private SharedFacadeBean bean = new SharedFacadeBean(getBeanName());
private BeanRights beanRights;
protected List<AuditDetails> auditDetailsList = new LinkedList<AuditDetails>();
private ExtraDataManager edm;
private SecondaryCacheManager ecm;
private int initializedID;
private DETAILSTYPE details, detailsOriginal;
private String understandableName = "";
/**
* SHARED BEAN
*/
private class SharedFacadeBean extends SharedBean<BEANFACADE> {
public SharedFacadeBean(String beanClassName) {
super(beanClassName);
}
@Override
protected void initBean(BEANFACADE bean) throws ClipsException {
try {
beanRights = bean.initByID(initializedID, UserInfoAbstract.get().getSessionId());
understandableName = bean.getEntityName();
/*System.out.println("Initialized bean " + getBeanName() + "\n"
+ beanRights.toString()); */
} catch (Exception ex) {
throw new ClipsException("Элемент ("+ DelegateLine2.this.getClass().getSimpleName()
+") с ID = " + initializedID + " отсутствует в базе",ex);
}
}
}
public DelegateLine2(AuditListener al) {
this(0, al);
}
public DelegateLine2(int initializedID, AuditListener al) {
this.initializedID = initializedID;
if(initializedID == 0) {
setDetails(getNewDetails());
}
boolean initNew = (initializedID == 0);
edm = new ExtraDataManager(bean, this, initNew);
ecm = new SecondaryCacheManager(initNew);
addAuditListener(al);
}
public DelegateLine2(DETAILSTYPE d, AuditListener al) {
this.initializedID = d.getId();
setDetails(d);
boolean initNew = (initializedID == 0);
edm = new ExtraDataManager(bean, this, initNew);
ecm = new SecondaryCacheManager(initNew);
addAuditListener(al);
}
final public ExtraDataManager getEDM() {
return edm;
}
final public SecondaryCacheManager getSCM() {
return ecm;
}
final public int getID() {
return initializedID;
}
@Override
final public boolean isNewlyCreated() {
return initializedID == 0;
}
abstract protected DETAILSTYPE getNewDetails();
final public DETAILSTYPE getDetails() throws ClipsException {
checkAccess();
if (details == null) {
load();
}
return details;
}
/**
* Check magic values
* @throws cli_fmw.main.AccessException
*/
private void checkAccess() throws AccessException{
if (this.initializedID == MagicValues.ACCESS_DENIED_ID){
throw AccessException.EX;
}
}
@SuppressWarnings("unchecked")
private void setDetails(DETAILSTYPE details) {
this.details = details;
detailsOriginal = (DETAILSTYPE) details.clone();
}
@SuppressWarnings("unchecked")
final protected DETAILSTYPE getDetailsOriginal() throws ClipsException {
return (DETAILSTYPE) detailsOriginal.clone();
}
final protected BEANFACADE getBean() throws ClipsException {
return bean.get();
}
final public void clearBean() {
bean.clear();
}
@SuppressWarnings("unchecked")
protected void load() throws ClipsException {
if (details != null) {
throw new RuntimeException("DelegateLine.load called once again");
}
try {
details = (DETAILSTYPE) getBean().getDetails();
} catch (Exception ex) {
try {
clearBean();
details = (DETAILSTYPE) getBean().getDetails();
} catch (Exception ex1) {
String str = "Не удалось загрузить объект \'" + understandableName + "\'";
/*try {
str += " (" + this.toString() + ")";
} catch (Exception ex2) {
ex2.printStackTrace();
}*/
throw new ClipsException(str, ex1);
}
}
detailsOriginal = (DETAILSTYPE) details.clone();
initializedID = details.getId();
}
/**
* перегружает делегат (только детали!)
*/
public void reload() throws ClipsException {
details = null;
load();
}
final public boolean hasRight(int aBeanCommandId) throws ClipsException {
getBean();
return beanRights.isCommandAccessible(aBeanCommandId);
}
@Override
final public boolean canCreate() throws ClipsException {
return hasRight(FacadeBean.COMMAND_CREATE);
}
@Override
final public boolean canModify() throws ClipsException {
return hasRight(FacadeBean.COMMAND_MODIFY);
}
@Override
final public boolean canRead() throws ClipsException {
return hasRight(FacadeBean.COMMAND_READ);
}
@Override
final public boolean canRemove() throws ClipsException {
return hasRight(FacadeBean.COMMAND_REMOVE);
}
protected void afterRemove() {
}
final public void remove() throws ClipsException {
if (! UserInfoAbstract.get().isSuperUser()){
if (!canRemove()){
throw new ClipsException("У вас нет прав для удаления объекта " + understandableName);
}
}
int auditcount = auditDetailsList.size();
try {
ModificationInfo remove = getBean().remove();
afterRemove();
auditDetailsList.addAll(remove.getAudit());
} catch (Exception ex) {
try {
clearBean();
ModificationInfo audit = getBean().remove();
auditDetailsList.addAll(audit.getAudit());
afterRemove();
} catch (Exception ex1) {
clearBean();
throw new ClipsException("Не удалось удалить объект \'" + understandableName + "\' (" + this.toString() + ")", ex1);
}
}
if(auditcount != auditDetailsList.size()) {
fireAuditEvent();
}
}
@Override
@SuppressWarnings({"unchecked"})
public void save1() throws ClipsException {
int auditcount = auditDetailsList.size();
try {
ecm.sinchronizePrimaryCache();
if (isNewlyCreated() || (details != null && !details.equals(detailsOriginal))) {
ModificationInfo modificationInfo = getBean().update(details);
if (isNewlyCreated()) {
details.setId(modificationInfo.getId());
initializedID = modificationInfo.getId();
}
detailsOriginal = (DETAILSTYPE) details.clone();
auditDetailsList.addAll(modificationInfo.getAudit());
}
} catch (Exception ex) {
clearBean();
throw new ClipsException("Не удалось сохранить объект \'"+ understandableName +"\' (" + this.toString()+")", ex);
}
edm.saveExtraCache();
fireContentStateEvent();
if(auditcount != auditDetailsList.size()) {
fireAuditEvent();
}
}
abstract protected String getBeanName();
@Override
public boolean isDirty() {
if (isNewlyCreated()) {
return true;
}
if (details != null && !details.equals(detailsOriginal)) {
return true;
}
return edm.isDirty();
}
@Override
@SuppressWarnings("unchecked")
public void restore() {
details = (DETAILSTYPE) detailsOriginal.clone();
edm.restore();
ecm.restore();
fireContentStateEvent();
}
@Override
public String toStringSimple() {
return understandableName;
}
public void addAuditListener(AuditListener l) {
listeners.add(AuditListener.class, l);
}
public void removeAuditListener(AuditListener l) {
listeners.remove(AuditListener.class, l);
}
protected void fireAuditEvent() {
for(AuditDetails ad: auditDetailsList) {
System.out.println("Received to sign:" + ad.value);
}
// AuditFrame dlg = AuditFrame.getDialog();
// dlg.showMe(auditDetailsList);
AuditList list = new AuditList(auditDetailsList);
boolean fire = false;
for(Object o: listeners.getListeners(AuditListener.class)) {
if (o == null) {
continue;
}
AuditListener l = (AuditListener) o;
l.needDSA(list);
fire = true;
}
auditDetailsList.clear();
// if (!fire){
// throw new RuntimeException("Нет слушателя для событий аудита у делегата " + this.getClass().getName());
// }
}
public AuditListener getAuditListener(){
AuditListener[] listeners1 = listeners.getListeners(AuditListener.class);
if (listeners1.length == 1){
return listeners1[0];
}else if(listeners1.length > 1){
//throw new RuntimeException("Несколько слушателей для событий аудита у делегата " + this.getClass().getName());
return null;
}else{
/*Exception ex = new Exception("Нет слушателя для событий аудита у делегата " + this.getClass().getName());
ex.printStackTrace();*/
return null;
}
}
}