/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * 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.activemq;

import org.activemq.broker.BrokerContainerFactory;
import org.activemq.util.JMSExceptionHelper;

import javax.jms.JMSException;
import java.lang.reflect.Method;

/**
 * Helper methods to avoid a runtime dependency on Spring unless its
 * used to configure the ActiveMQ broker via the XML configuration
 *
 * @version $Revision: 1.1.1.1 $
 */
public class XmlConfigHelper {
    private static final Class[] ARGUMENT_TYPES = {String.class};
    public static final String SPRING_CLASS_NAME = "org.activemq.spring.SpringBrokerContainerFactory";

    /**
     * Creates an instance of the broker factory which uses the Spring XML configuration file
     * mechanism.
     */
    public static BrokerContainerFactory createBrokerContainerFactory(String xmlConfig) throws JMSException {
        try {
            Class factoryClass = getSpringFactoryClass();
            Method method = factoryClass.getMethod("newFactory", ARGUMENT_TYPES);
            if (method == null) {
                throw new JMSException("Could not find newFactory() method - classpath strangeness occurred");
            }
            return (BrokerContainerFactory) method.invoke(null, new Object[]{xmlConfig});
        }
        catch (JMSException e) {
            throw e;
        }
        catch (ClassNotFoundException e) {
            throw JMSExceptionHelper.newJMSException("Could not configure broker using XML configuration file as Spring factory class could not be loaded. Maybe you need the Spring.jar on your classpath? Reason: " + e, e);
        }
        catch (Exception e) {
            throw JMSExceptionHelper.newJMSException("Could not configure broker using XML configuration file as attempt to use Spring factory failed. Reason: " + e, e);
        }
    }

    private static Class getSpringFactoryClass() throws ClassNotFoundException {
        Class answer = null;
        try {
            answer = Thread.currentThread().getContextClassLoader().loadClass(SPRING_CLASS_NAME);
        }
        catch (ClassNotFoundException e) {
            answer = XmlConfigHelper.class.getClassLoader().loadClass(SPRING_CLASS_NAME);
        }
        return answer;
    }
}
