Example usage for java.net InetSocketAddress getPort

List of usage examples for java.net InetSocketAddress getPort

Introduction

In this page you can find the example usage for java.net InetSocketAddress getPort.

Prototype

public final int getPort() 

Source Link

Document

Gets the port number.

Usage

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testAPop() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*w  w w  . j  av  a 2s .co  m*/
    try {
        TestApopCmdHandler handler = new TestApopCmdHandler();
        server = createServer(createProtocol(handler), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        String welcomeMessage = client.getReplyString();

        // check for valid syntax that include all info needed for APOP
        assertThat(welcomeMessage.trim()).matches(Pattern.compile("\\+OK \\<-?\\d+\\.\\d+@.+\\> .+"));

        assertThat(client.sendCommand("APOP invalid invalid")).isEqualTo(POP3Reply.ERROR);

        handler.add("valid", new MockMailbox("id"));
        assertThat(client.sendCommand("APOP valid valid")).isEqualTo(POP3Reply.OK);

        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.hadoop.hdfs.server.hightidenode.HighTideNode.java

private void initialize(Configuration conf) throws IOException, SAXException, InterruptedException,
        HighTideConfigurationException, ClassNotFoundException, ParserConfigurationException {
    this.conf = conf;
    InetSocketAddress socAddr = HighTideNode.getAddress(conf);
    int handlerCount = conf.getInt("fs.hightidenodenode.handler.count", 10);

    // read in the configuration
    configMgr = new ConfigManager(conf);
    configMgr.reloadConfigsIfNecessary();
    configMgr.startReload();/*from www .ja v a 2  s .com*/

    // create Metrics object
    myMetrics = new HighTideNodeMetrics(conf, this);

    // create rpc server
    this.server = RPC.getServer(this, socAddr.getAddress().getHostAddress(), socAddr.getPort(), handlerCount,
            false, conf);

    // The rpc-server port can be ephemeral... ensure we have the correct info
    this.serverAddress = this.server.getListenerAddress();
    LOG.info("HighTideNode up at: " + this.serverAddress);

    initialized = true;
    running = true;
    this.server.start(); // start RPC server

    this.fileFixer = new FileFixer(conf);
    this.fileFixerThread = new Daemon(this.fileFixer);
    fileFixer.setPolicyInfo(configMgr.getAllPolicies());
    this.fileFixerThread.start();

    // start the deamon thread to resync if needed
    this.triggerThread = new Daemon(new TriggerMonitor());
    this.triggerThread.start();
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build// www . j  a v  a2 s .  c o  m
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

From source file:org.apache.hadoop.ha.DummyHAService.java

private InetSocketAddress startAndGetRPCServerAddress(InetSocketAddress serverAddress) {
    Configuration conf = new Configuration();

    try {/*from www . ja va2s.c o m*/
        RPC.setProtocolEngine(conf, HAServiceProtocolPB.class, ProtobufRpcEngine.class);
        HAServiceProtocolServerSideTranslatorPB haServiceProtocolXlator = new HAServiceProtocolServerSideTranslatorPB(
                new MockHAProtocolImpl());
        BlockingService haPbService = HAServiceProtocolService
                .newReflectiveBlockingService(haServiceProtocolXlator);

        Server server = new RPC.Builder(conf).setProtocol(HAServiceProtocolPB.class).setInstance(haPbService)
                .setBindAddress(serverAddress.getHostName()).setPort(serverAddress.getPort()).build();
        server.start();
        return NetUtils.getConnectAddress(server);
    } catch (IOException e) {
        return null;
    }
}

From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

/**
 * @param config/*  ww w  .j a v  a2 s  .  c om*/
 *          initial configuration
 */
@SuppressWarnings("deprecation")
public MiniAccumuloClusterImpl(MiniAccumuloConfigImpl config) throws IOException {

    this.config = config.initialize();

    mkdirs(config.getConfDir());
    mkdirs(config.getLogDir());
    mkdirs(config.getLibDir());
    mkdirs(config.getLibExtDir());

    if (!config.useExistingInstance()) {
        if (!config.useExistingZooKeepers())
            mkdirs(config.getZooKeeperDir());
        mkdirs(config.getAccumuloDir());
    }

    if (config.useMiniDFS()) {
        File nn = new File(config.getAccumuloDir(), "nn");
        mkdirs(nn);
        File dn = new File(config.getAccumuloDir(), "dn");
        mkdirs(dn);
        File dfs = new File(config.getAccumuloDir(), "dfs");
        mkdirs(dfs);
        Configuration conf = new Configuration();
        conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, nn.getAbsolutePath());
        conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, dn.getAbsolutePath());
        conf.set(DFSConfigKeys.DFS_REPLICATION_KEY, "1");
        conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
        conf.set("dfs.support.append", "true");
        conf.set("dfs.datanode.synconclose", "true");
        conf.set("dfs.datanode.data.dir.perm", MiniDFSUtil.computeDatanodeDirectoryPermission());
        String oldTestBuildData = System.setProperty("test.build.data", dfs.getAbsolutePath());
        miniDFS = new MiniDFSCluster.Builder(conf).build();
        if (oldTestBuildData == null)
            System.clearProperty("test.build.data");
        else
            System.setProperty("test.build.data", oldTestBuildData);
        miniDFS.waitClusterUp();
        InetSocketAddress dfsAddress = miniDFS.getNameNode().getNameNodeAddress();
        dfsUri = "hdfs://" + dfsAddress.getHostName() + ":" + dfsAddress.getPort();
        File coreFile = new File(config.getConfDir(), "core-site.xml");
        writeConfig(coreFile, Collections.singletonMap("fs.default.name", dfsUri).entrySet());
        File hdfsFile = new File(config.getConfDir(), "hdfs-site.xml");
        writeConfig(hdfsFile, conf);

        Map<String, String> siteConfig = config.getSiteConfig();
        siteConfig.put(Property.INSTANCE_DFS_URI.getKey(), dfsUri);
        siteConfig.put(Property.INSTANCE_DFS_DIR.getKey(), "/accumulo");
        config.setSiteConfig(siteConfig);
    } else if (config.useExistingInstance()) {
        dfsUri = config.getHadoopConfiguration().get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY);
    } else {
        dfsUri = "file:///";
    }

    File clientConfFile = config.getClientConfFile();
    // Write only the properties that correspond to ClientConfiguration properties
    writeConfigProperties(clientConfFile,
            Maps.filterEntries(config.getSiteConfig(),
                    v -> org.apache.accumulo.core.client.ClientConfiguration.ClientProperty
                            .getPropertyByKey(v.getKey()) != null));

    Map<String, String> clientProps = config.getClientProps();
    clientProps.put(ClientProperty.INSTANCE_ZOOKEEPERS.getKey(), config.getZooKeepers());
    clientProps.put(ClientProperty.INSTANCE_NAME.getKey(), config.getInstanceName());
    if (!clientProps.containsKey(ClientProperty.AUTH_TYPE.getKey())) {
        clientProps.put(ClientProperty.AUTH_TYPE.getKey(), "password");
        clientProps.put(ClientProperty.AUTH_PRINCIPAL.getKey(), config.getRootUserName());
        clientProps.put(ClientProperty.AUTH_TOKEN.getKey(), config.getRootPassword());
    }

    File clientPropsFile = config.getClientPropsFile();
    writeConfigProperties(clientPropsFile, clientProps);

    File siteFile = new File(config.getConfDir(), "accumulo.properties");
    writeConfigProperties(siteFile, config.getSiteConfig());
    siteConfig = new SiteConfiguration(siteFile);

    if (!config.useExistingInstance() && !config.useExistingZooKeepers()) {
        zooCfgFile = new File(config.getConfDir(), "zoo.cfg");
        FileWriter fileWriter = new FileWriter(zooCfgFile);

        // zookeeper uses Properties to read its config, so use that to write in order to properly
        // escape things like Windows paths
        Properties zooCfg = new Properties();
        zooCfg.setProperty("tickTime", "2000");
        zooCfg.setProperty("initLimit", "10");
        zooCfg.setProperty("syncLimit", "5");
        zooCfg.setProperty("clientPortAddress", "127.0.0.1");
        zooCfg.setProperty("clientPort", config.getZooKeeperPort() + "");
        zooCfg.setProperty("maxClientCnxns", "1000");
        zooCfg.setProperty("dataDir", config.getZooKeeperDir().getAbsolutePath());
        zooCfg.store(fileWriter, null);

        fileWriter.close();
    }
    clusterControl = new MiniAccumuloClusterControl(this);
}

From source file:org.sonatype.nexus.apachehttpclient.NexusSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    checkNotNull(host);/* w w  w. j av  a2  s .  c  o  m*/
    checkNotNull(remoteAddress);
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException e) {
        Closeables.close(sock, true);
        throw e;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:my.adam.smo.client.HTTPClient.java

@Override
public RpcChannel connect(final InetSocketAddress sa) {
    RpcChannel rpcChannel = new RpcChannel() {
        private Channel c = bootstrap.connect(sa).awaitUninterruptibly().getChannel();

        @Override// w w  w .  j  a v  a  2 s  .c  om
        public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request,
                Message responsePrototype, RpcCallback<Message> done) {
            StopWatch stopWatch = new StopWatch("callMethod");
            stopWatch.start();

            long id = seqNum.addAndGet(1);

            logger.trace("calling method: " + method.getFullName());

            HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                    "http://" + sa.getHostName() + ":" + sa.getPort());
            httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
            httpRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
            httpRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE,
                    HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);

            RPCommunication.Request protoRequest = RPCommunication.Request.newBuilder()
                    .setServiceName(method.getService().getFullName()).setMethodName(method.getName())
                    .setMethodArgument(request.toByteString()).setRequestId(id).build();

            logger.trace("request built: " + request.toString());

            if (enableSymmetricEncryption) {
                protoRequest = getEncryptedRequest(protoRequest);
                logger.trace("symmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            if (enableAsymmetricEncryption) {
                protoRequest = getAsymEncryptedRequest(protoRequest);
                logger.trace("asymmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            byte[] arr = protoRequest.toByteArray();

            ChannelBuffer s = Base64.encode(ChannelBuffers.copiedBuffer(arr), Base64Dialect.STANDARD);

            httpRequest.setContent(s);

            httpRequest.addHeader(HttpHeaders.Names.CONTENT_LENGTH, s.readableBytes());

            httpRequest.setChunked(false);

            callbackMap.put(id, done);
            descriptorProtoMap.put(id, responsePrototype);

            c.write(httpRequest);
            logger.trace("request sent: " + protoRequest.toString());

            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
        }
    };
    logger.trace("connected to address: " + sa.toString());
    return rpcChannel;
}

From source file:org.apache.hadoop.hdfs.DomainSocketFactory.java

/**
 * Create a DomainSocket./*from   ww  w.j a v a2s . c om*/
 * 
 * @param addr        The address of the DataNode
 * @param stream      The DFSInputStream the socket will be created for.
 *
 * @return            null if the socket could not be created; the
 *                    socket otherwise.  If there was an error while
 *                    creating the socket, we will add the socket path
 *                    to our list of failed domain socket paths.
 */
DomainSocket create(InetSocketAddress addr, DFSInputStream stream) {
    // If there is no domain socket path configured, we can't use domain
    // sockets.
    if (conf.domainSocketPath.isEmpty())
        return null;
    // If we can't do anything with the domain socket, don't create it.
    if (!conf.domainSocketDataTraffic && (!conf.shortCircuitLocalReads || conf.useLegacyBlockReaderLocal)) {
        return null;
    }
    // UNIX domain sockets can only be used to talk to local peers
    if (!DFSClient.isLocalAddress(addr))
        return null;
    // If the DomainSocket code is not loaded, we can't create
    // DomainSocket objects.
    if (DomainSocket.getLoadingFailureReason() != null)
        return null;
    String escapedPath = DomainSocket.getEffectivePath(conf.domainSocketPath, addr.getPort());
    PathStatus info = pathInfo.getIfPresent(escapedPath);
    if (info == PathStatus.UNUSABLE) {
        // We tried to connect to this domain socket before, and it was totally
        // unusable.
        return null;
    }
    if ((!conf.domainSocketDataTraffic)
            && ((info == PathStatus.SHORT_CIRCUIT_DISABLED) || stream.shortCircuitForbidden())) {
        // If we don't want to pass data over domain sockets, and we don't want
        // to pass file descriptors over them either, we have no use for domain
        // sockets.
        return null;
    }
    boolean success = false;
    DomainSocket sock = null;
    try {
        sock = DomainSocket.connect(escapedPath);
        sock.setAttribute(DomainSocket.RECEIVE_TIMEOUT, conf.socketTimeout);
        success = true;
    } catch (IOException e) {
        LOG.warn("error creating DomainSocket", e);
        // fall through
    } finally {
        if (!success) {
            if (sock != null) {
                IOUtils.closeQuietly(sock);
            }
            pathInfo.put(escapedPath, PathStatus.UNUSABLE);
            sock = null;
        }
    }
    return sock;
}

From source file:org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java

private ListenerEndpoint startEndpoint(InetSocketAddress inetSocketAddress,
        ListeningIOReactor defaultListeningIOReactor, String endPointName) throws Exception {
    ListenerEndpoint endpoint = defaultListeningIOReactor.listen(inetSocketAddress);
    try {/*w  w w .j av  a2s.c  o  m*/
        endpoint.waitFor();
        InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
        if (!address.isUnresolved()) {
            log.info((endPointName != null ? "Pass-through " + endPointName : " Pass-through Http ")
                    + " Listener started on " + address.getHostName() + ":" + address.getPort());
        } else {
            log.info((endPointName != null ? "Pass-through " + endPointName : " Pass-through Http ")
                    + " Listener started on " + address);
        }
    } catch (Exception e) {
        throw new Exception("Endpoint does not start for port " + inetSocketAddress.getPort()
                + "May be IO Reactor not started or endpoint binding exception ", e);

    }
    return endpoint;
}

From source file:org.red5.server.undertow.UndertowLoader.java

/**
 * Initialization./*ww  w .ja  v a2 s. com*/
 */
public void start() {
    log.info("Loading undertow context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // scan the sub directories to determine our context paths
    buildContextPathList(webappFolder);
    try {
        // create our servlet container
        container = ServletContainer.Factory.newInstance();
        // create a root path handler
        final PathHandler rootHandler = new PathHandler();
        // create one server and use it everywhere
        Undertow.Builder builder = Undertow.builder();
        // loop through connectors adding listeners to the builder
        for (UndertowConnector undertowConnector : connectors) {
            InetSocketAddress addr = undertowConnector.getSocketAddress();
            builder.addListener(addr.getPort(), addr.getHostName(),
                    (undertowConnector.isSecure() ? ListenerType.HTTPS : ListenerType.HTTP));
        }
        log.trace("Classloader for undertow: {} TCL: {}", Undertow.class.getClassLoader(), originalClassLoader);
        // create references for later lookup
        LoaderBase.setApplicationLoader(new UndertowApplicationLoader(container, applicationContext));
        // loop the other contexts
        for (String contextPath : contextPaths) {
            // create a class loader for the context
            ClassLoader classLoader = buildWebClassLoader(originalClassLoader, webappFolder, contextPath);
            // create deployment info
            DeploymentInfo info = deployment().setClassLoader(classLoader)
                    .setContextPath(contextPath.equalsIgnoreCase("/ROOT") ? "/" : contextPath)
                    .setDefaultEncoding("UTF-8").setDeploymentName(contextPath.substring(1) + ".war")
                    .setUrlEncoding("UTF-8");
            // parse the web.xml and configure the context
            parseWebXml(webappFolder, contextPath, info);
            if (log.isDebugEnabled()) {
                log.debug("Deployment info - name: {} servlets: {} filters: {}", new Object[] {
                        info.getDisplayName(), info.getServlets().size(), info.getFilters().size() });
            }
            // add the new deployment to the servlet container
            DeploymentManager manager = container.addDeployment(info);
            // set a reference to the manager and deploy the context
            LoaderBase.setRed5ApplicationContext(contextPath, new UndertowApplicationContext(manager));
            // deploy
            manager.deploy();
            // add path
            rootHandler.addPrefixPath(info.getContextPath(), manager.start());
            // get deployment
            Deployment deployment = manager.getDeployment();
            // get servlet context
            final ServletContext servletContext = deployment.getServletContext();
            log.debug("Context initialized: {}", servletContext.getContextPath());
            try {
                log.debug("Context: {}", servletContext);
                final ClassLoader webClassLoader = info.getClassLoader();
                log.debug("Webapp classloader: {}", webClassLoader);
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                // set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);
                // create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(webClassLoader);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        // web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            // set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                            appctx.start();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class", e);
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
        // Dump deployments list
        if (log.isDebugEnabled()) {
            for (String deployment : container.listDeployments()) {
                log.debug("Container deployment: {}", deployment);
            }
        }
        // if everything is ok at this point then call the rtmpt and rtmps beans so they will init
        //         if (applicationContext.containsBean("rtmpt.server")) {
        //            log.debug("Initializing RTMPT");
        //            applicationContext.getBean("rtmpt.server");
        //            log.debug("Finished initializing RTMPT");
        //         } else {
        //            log.info("Dedicated RTMPT server configuration was not specified");
        //         }
        //         if (applicationContext.containsBean("rtmps.server")) {
        //            log.debug("Initializing RTMPS");
        //            applicationContext.getBean("rtmps.server");
        //            log.debug("Finished initializing RTMPS");
        //         } else {
        //            log.debug("Dedicated RTMPS server configuration was not specified");
        //         }
        // add a root handler
        builder.setHandler(rootHandler);
        // build the server instance
        server = builder.build();
        log.info("Starting Undertow");
        server.start();
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading undertow, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading undertow", e);
        }
    } finally {
        registerJMX();
    }
    log.debug("Undertow init exit");
}