001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.osgi;
016    
017    import com.liferay.portal.kernel.bean.ClassLoaderBeanHandler;
018    import com.liferay.portal.kernel.util.ProxyUtil;
019    
020    import java.lang.reflect.Field;
021    import java.lang.reflect.InvocationHandler;
022    
023    import org.springframework.aop.TargetSource;
024    import org.springframework.aop.framework.AdvisedSupport;
025    
026    /**
027     * @author Raymond Augé
028     */
029    public class ServiceWrapperUtil {
030    
031            public static AdvisedSupport getAdvisedSupport(Object serviceProxy)
032                    throws Exception {
033    
034                    InvocationHandler invocationHandler = ProxyUtil.getInvocationHandler(
035                            serviceProxy);
036    
037                    Class<?> invocationHandlerClass = invocationHandler.getClass();
038    
039                    Field advisedSupportField = invocationHandlerClass.getDeclaredField(
040                            "_advisedSupport");
041    
042                    advisedSupportField.setAccessible(true);
043    
044                    return (AdvisedSupport)advisedSupportField.get(invocationHandler);
045            }
046    
047            public static Object getTarget(AdvisedSupport advisedSupport)
048                    throws Exception {
049    
050                    TargetSource targetSource = advisedSupport.getTargetSource();
051    
052                    Object previousService = targetSource.getTarget();
053    
054                    if (!ProxyUtil.isProxyClass(previousService.getClass())) {
055                            return previousService;
056                    }
057    
058                    InvocationHandler invocationHandler = ProxyUtil.getInvocationHandler(
059                            previousService);
060    
061                    if (invocationHandler instanceof ClassLoaderBeanHandler) {
062                            ClassLoaderBeanHandler classLoaderBeanHandler =
063                                    (ClassLoaderBeanHandler)invocationHandler;
064    
065                            previousService = classLoaderBeanHandler.getBean();
066                    }
067    
068                    return previousService;
069            }
070    
071    }