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

import org.activemq.io.WireFormat;
import org.activemq.transport.TransportServerChannel;
import org.activemq.transport.TransportServerChannelFactory;

import javax.jms.JMSException;
import javax.net.ServerSocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;

/**
 * An implementation of TransportServerChannelFactory which uses a ServerSocketFactory
 * to create ServerSocket instances
 *
 * @version $Revision: 1.1.1.1 $
 */
public class SfTransportServerChannelFactory implements TransportServerChannelFactory {

    protected static final int BACKLOG = 500;

    private ServerSocketFactory serverSocketFactory;

    public SfTransportServerChannelFactory(ServerSocketFactory socketFactory) {
        this.serverSocketFactory = socketFactory;
    }

    /**
     * Bind a ServerChannel to an address
     *
     * @param wireFormat
     * @param bindAddress
     * @return the TransportChannel bound to the remote node
     * @throws JMSException
     */
    public TransportServerChannel create(WireFormat wireFormat, URI bindAddress) throws JMSException {
        ServerSocket serverSocket = null;
        try {
            serverSocket = createServerSocket(bindAddress);
        }
        catch (IOException e) {
            JMSException jmsEx = new JMSException("Creation of ServerSocket failed: " + e);
            jmsEx.setLinkedException(e);
            throw jmsEx;
        }
        return new TcpTransportServerChannel(wireFormat, serverSocket);
    }

    protected ServerSocket createServerSocket(URI bind) throws IOException {
        String host = bind.getHost();
        host = (host == null || host.length() == 0) ? "localhost" : host;

        InetAddress addr = InetAddress.getByName(host);
        if (addr.equals(InetAddress.getLocalHost())) {
            return serverSocketFactory.createServerSocket(bind.getPort(), BACKLOG);
        }
        else {
            return serverSocketFactory.createServerSocket(bind.getPort(), BACKLOG, addr);
        }
    }

}