/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: JOnASENCInterceptor.java 21594 2011-08-08 12:29:10Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.ejb.easybeans;

import javax.naming.Context;
import org.ow2.easybeans.api.EasyBeansInvocationContext;
import org.ow2.easybeans.api.naming.NamingInterceptor;
import org.ow2.easybeans.naming.interceptors.AbsENCInterceptor;
import org.ow2.jonas.naming.JNamingManager;

/**
 * Interceptor used when EasyBeans is integrated in JOnAS.<br>
 * As the java: namespace is managed by JOnAS, EasyBeans needs to call JOnAS
 * objects to set java: context.
 * @author Florent Benoit
 */
public class JOnASENCInterceptor extends AbsENCInterceptor implements NamingInterceptor {

    /**
     * Naming Manager of JOnAS.
     */
    private JNamingManager namingManager = null;

    /**
     * Default constructor. <br>
     * Gets a reference on the JOnAS naming manager .
     */
    public JOnASENCInterceptor() {
        if (namingManager == null) {
            namingManager = EasyBeansService.getNamingManager();
        }
    }

    /**
     * Sets JOnAS ENC context.
     * @param invocationContext context with useful attributes on the current
     *        invocation.
     * @return result of the next invocation (to chain interceptors).
     * @throws Exception needs for signature of interceptor.
     */
    @Override
    public Object intercept(final EasyBeansInvocationContext invocationContext) throws Exception {
        Context oldContext = (Context) namingManager.setComponentContext(invocationContext.getFactory().getJavaContext());
        try {
            return invocationContext.proceed();
        } finally {
            namingManager.resetComponentContext(oldContext);
        }
    }
}
