001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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 */
017package org.apache.activemq.transport;
018
019import java.net.InetAddress;
020import java.net.URI;
021
022import org.apache.activemq.util.InetAddressUtil;
023import org.eclipse.jetty.server.Connector;
024import org.eclipse.jetty.server.Server;
025
026abstract public class WebTransportServerSupport extends TransportServerSupport {
027
028    protected URI bindAddress;
029    protected Server server;
030    protected Connector connector;
031    protected SocketConnectorFactory socketConnectorFactory;
032    protected String host;
033
034    public WebTransportServerSupport(URI location) {
035        super(location);
036    }
037
038    private <T> void setConnectorProperty(String name, Class<T> type, T value) throws Exception {
039        connector.getClass().getMethod("set" + name, type).invoke(connector, value);
040    }
041
042    protected void createServer() {
043        server = new Server();
044        try {
045            server.getClass().getMethod("setStopTimeout", Long.TYPE).invoke(server, 500l);
046        } catch (Throwable t) {
047            //ignore, jetty 8.
048        }
049    }
050    public URI bind() throws Exception {
051
052        URI bind = getBindLocation();
053
054        String bindHost = bind.getHost();
055        bindHost = (bindHost == null || bindHost.length() == 0) ? "localhost" : bindHost;
056        InetAddress addr = InetAddress.getByName(bindHost);
057        host = addr.getCanonicalHostName();
058
059        setConnectorProperty("Host", String.class, host);
060        setConnectorProperty("Port", Integer.TYPE, bindAddress.getPort());
061        server.addConnector(connector);
062        if (addr.isAnyLocalAddress()) {
063            host = InetAddressUtil.getLocalHostName();
064        }
065
066        URI boundUri = new URI(bind.getScheme(), bind.getUserInfo(), host, bindAddress.getPort(), bind.getPath(), bind.getQuery(), bind.getFragment());
067        setConnectURI(boundUri);
068        return boundUri;
069    }
070}