/* Copyright 2004, 2005, 2006, 2007 Acegi Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.acegisecurity.acls.objectidentity;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.acegisecurity.acls.IdentityUnavailableException;
import org.acegisecurity.acls.objectidentity.ObjectIdentity;
import org.acegisecurity.acls.objectidentity.ObjectIdentityImpl;
import org.acegisecurity.acls.objectidentity.ObjectIdentityRetrievalStrategy;
import org.springframework.util.Assert;

/**
 * Basic implementation of {@link ObjectIdentityRetrievalStrategy} that is aware
 * of proxying technologies.
 * 
 * @author Simon van der Sluis
 * @version $Id: ObjectIdentityRetrievalStrategyImpl.java,v 1.1 2007/02/23
 *          01:55:25 simonv Exp $
 */
public class ProxyAwareObjectIdentityRetrievalStrategy implements
	ObjectIdentityRetrievalStrategy {

    /**
     * As per {@link ObjectIdentityRetrievalStrategy#getObjectIdentity(Object)}
     * but if the object is a proxy ensures that the {@link ObjectIdentity}
     * generated contains the real class of the object not the class of the
     * proxy.
     * @param object The {@link Object} to create an {@link ObjectIdentity} for
     * @return The {@link ObjectIdentity} to represent object
     */
    public ObjectIdentity getObjectIdentity(Object object) {
	Assert.notNull(object);
	Class clazz = object.getClass();
	
	// check if it's a cglib proxy
	if (net.sf.cglib.proxy.Proxy.isProxyClass(clazz)) {
	    clazz = clazz.getSuperclass();
	}
	
	// check if it's cglib enhanced
	else if (net.sf.cglib.proxy.Enhancer.isEnhanced(clazz)) {
	    clazz = clazz.getSuperclass();
	}

	// check if it's a jdk proxy
	if (java.lang.reflect.Proxy.isProxyClass(clazz)) {
	    // TODO Figure out if / how to make this work
	    throw new IllegalArgumentException("JDK proxies not yet supported");
	}
	
	// now create the ObjectIdentity
	Object result = null;
	try {
	    Method method = clazz.getMethod("getId", new Class[] {});
	    result = method.invoke(object, new Object[] {});
	} catch (Exception e) {
	    throw new IdentityUnavailableException(
		    "Could not extract identity from object " + object, e);
	}

	Assert.isInstanceOf(Serializable.class, result,
		"Getter must provide a return value of type Serializable");
	Serializable id = (Serializable) result;

	return new ObjectIdentityImpl(clazz, id);

    }

}
