001 /**
002 *
003 * Copyright 2004 Protique Ltd
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 **/
018 package org.activemq.transport.tcp;
019
020 import org.activemq.io.WireFormat;
021 import org.activemq.transport.TransportServerChannel;
022 import org.activemq.transport.TransportServerChannelFactory;
023
024 import javax.jms.JMSException;
025 import javax.net.ServerSocketFactory;
026 import java.io.IOException;
027 import java.net.InetAddress;
028 import java.net.ServerSocket;
029 import java.net.URI;
030
031 /**
032 * An implementation of TransportServerChannelFactory which uses a ServerSocketFactory
033 * to create ServerSocket instances
034 *
035 * @version $Revision: 1.1.1.1 $
036 */
037 public class SfTransportServerChannelFactory implements TransportServerChannelFactory {
038
039 protected static final int BACKLOG = 500;
040
041 private ServerSocketFactory serverSocketFactory;
042
043 public SfTransportServerChannelFactory(ServerSocketFactory socketFactory) {
044 this.serverSocketFactory = socketFactory;
045 }
046
047 /**
048 * Bind a ServerChannel to an address
049 *
050 * @param wireFormat
051 * @param bindAddress
052 * @return the TransportChannel bound to the remote node
053 * @throws JMSException
054 */
055 public TransportServerChannel create(WireFormat wireFormat, URI bindAddress) throws JMSException {
056 ServerSocket serverSocket = null;
057 try {
058 serverSocket = createServerSocket(bindAddress);
059 }
060 catch (IOException e) {
061 JMSException jmsEx = new JMSException("Creation of ServerSocket failed: " + e);
062 jmsEx.setLinkedException(e);
063 throw jmsEx;
064 }
065 return new TcpTransportServerChannel(wireFormat, serverSocket);
066 }
067
068 protected ServerSocket createServerSocket(URI bind) throws IOException {
069 String host = bind.getHost();
070 host = (host == null || host.length() == 0) ? "localhost" : host;
071
072 InetAddress addr = InetAddress.getByName(host);
073 if (addr.equals(InetAddress.getLocalHost())) {
074 return serverSocketFactory.createServerSocket(bind.getPort(), BACKLOG);
075 }
076 else {
077 return serverSocketFactory.createServerSocket(bind.getPort(), BACKLOG, addr);
078 }
079 }
080
081 }