/** 
 * 
 * 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.codehaus.activemq.transport.tcp;

import org.codehaus.activemq.ActiveMQConnection;
import org.codehaus.activemq.ActiveMQConnectionFactory;
import org.codehaus.activemq.test.TestSupport;

import javax.jms.Connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import java.io.IOException;
import java.net.Socket;

/**
 * @version $Revision: 1.4 $
 */
public class ExceptionListenerTest extends TestSupport implements ExceptionListener {
    protected Connection connection;
    protected JMSException exception;

    public void testFailingConnection() throws Exception {
        breakTransport();

        synchronized (this) {
            if (exception == null) {
                wait(3000L);
            }
        }
        assertTrue("Should have been notified of an exception", exception != null);

    }

    public synchronized void onException(JMSException e) {
        System.out.println("Caught exception: " + e);

        exception = e;
        notifyAll();
    }

    protected void breakTransport() throws IOException, JMSException {
        // now lets make the socket fail
        TcpTransportChannel transport = (TcpTransportChannel) ((ActiveMQConnection) connection).getTransportChannel();
        Socket socket = transport.getSocket();
        socket.close();
    }


    protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
        factory.setUseEmbeddedBroker(true);
        factory.setBrokerURL("tcp://localhost:62345");
        return factory;
    }

    protected void setUp() throws Exception {
        super.setUp();
        connection = createConnection();
        connection.setExceptionListener(this);
        System.out.println("Created connection: " + connection);

    }

    protected void tearDown() throws Exception {
        if (connection != null) {
            try {
                connection.close();
            }
            catch (JMSException e) {
                System.out.println("Failed to close connection: " + e);
                e.printStackTrace();
            }

        }
        super.tearDown();
    }
}
