package org.hibernate.internal.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.hibernate.HibernateException;
public class Cloneable {
private static final Object[] READER_METHOD_ARGS = new Object[0];
public Object shallowCopy() {
return AccessController.doPrivileged(
new PrivilegedAction() {
@Override
public Object run() {
return copyListeners();
}
}
);
}
public void validate() throws HibernateException {
AccessController.doPrivileged(
new PrivilegedAction() {
@Override
public Object run() {
checkListeners();
return null;
}
}
);
}
private Object copyListeners() {
Object copy = null;
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo( getClass(), Object.class );
internalCheckListeners( beanInfo );
copy = getClass().newInstance();
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for ( PropertyDescriptor pd : pds ) {
try {
pd.getWriteMethod().invoke(
copy,
pd.getReadMethod().invoke( this, READER_METHOD_ARGS )
);
}
catch (Throwable t) {
throw new HibernateException( "Unable copy copy listener [" + pd.getName() + "]" );
}
}
}
catch (Exception t) {
throw new HibernateException( "Unable to copy listeners", t );
}
finally {
if ( beanInfo != null ) {
Introspector.flushFromCaches( getClass() );
}
}
return copy;
}
private void checkListeners() {
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo( getClass(), Object.class );
internalCheckListeners( beanInfo );
}
catch (IntrospectionException t) {
throw new HibernateException( "Unable to validate listener config", t );
}
finally {
if ( beanInfo != null ) {
Introspector.flushFromCaches( getClass() );
}
}
}
private void internalCheckListeners(BeanInfo beanInfo) {
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
try {
for ( PropertyDescriptor pd : pds ) {
final Object listener = pd.getReadMethod().invoke( this, READER_METHOD_ARGS );
if ( listener == null ) {
throw new HibernateException( "Listener [" + pd.getName() + "] was null" );
}
if ( listener.getClass().isArray() ) {
Object[] listenerArray = (Object[]) listener;
for ( Object aListenerArray : listenerArray ) {
if ( aListenerArray == null ) {
throw new HibernateException( "Listener in [" + pd.getName() + "] was null" );
}
}
}
}
}
catch (HibernateException e) {
throw e;
}
catch (Throwable t) {
throw new HibernateException( "Unable to validate listener config" );
}
}
}