Java Code Examples for org.eclipse.jetty.server.ServerConnector#getLocalPort()

The following examples show how to use org.eclipse.jetty.server.ServerConnector#getLocalPort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectionDroppedTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startProxy() throws Exception {
  GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
  proxy = new Server();
  proxyConnector = new ServerConnector(proxy);
  proxy.addConnector(proxyConnector);

  /* start Knox with WebsocketAdapter to test */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  proxy.setHandler(context);

  // Start Server
  proxy.start();

  String host = proxyConnector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = proxyConnector.getLocalPort();
  proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
 
Example 2
Source File: ErrorCases.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void startHttpsServer() throws Exception {
    skipIfHeadlessEnvironment();
    server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(ErrorCases.class.getResource("keystore").getPath());
    sslContextFactory.setKeyStorePassword("activeeon");

    HttpConfiguration httpConfig = new HttpConfiguration();
    HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server,
                                                       new ConnectionFactory[] { new SslConnectionFactory(sslContextFactory,
                                                                                                          HttpVersion.HTTP_1_1.asString()),
                                                                                 new HttpConnectionFactory(httpsConfig) });

    server.addConnector(sslConnector);
    server.start();
    serverUrl = "https://localhost:" + sslConnector.getLocalPort() + "/rest";
}
 
Example 3
Source File: MessageFailureTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startProxy() throws Exception {
  GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
  proxy = new Server();
  proxyConnector = new ServerConnector(proxy);
  proxy.addConnector(proxyConnector);

  /* start Knox with WebsocketAdapter to test */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  proxy.setHandler(context);

  // Start Server
  proxy.start();

  String host = proxyConnector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = proxyConnector.getLocalPort();
  proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
 
Example 4
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Open the main listener for the server
 * @throws Exception exception opening listener
 */
void openListeners() throws Exception {
  LOG.debug("opening listeners: {}", listeners);
  for (ServerConnector listener : listeners) {
    if (listener.getLocalPort() != -1 && listener.getLocalPort() != -2) {
      // This listener is either started externally or has been bound or was
      // closed
      continue;
    }
    int port = listener.getPort();
    if (portRanges != null && port != 0) {
      bindForPortRange(listener, port);
    } else {
      bindForSinglePort(listener, port);
    }
  }
}
 
Example 5
Source File: ProxyInboundClientTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  server = new Server();
  ServerConnector connector = new ServerConnector(server);
  server.addConnector(connector);

  Handler handler = new WebsocketEchoHandler();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(handler);
  server.setHandler(context);

  server.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/",host,port));
}
 
Example 6
Source File: WebsocketBackendUrlTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  WebsocketEchoTestBase.setUpBeforeClass();

  backendServer = new Server();
  ServerConnector connector = new ServerConnector(backendServer);
  backendServer.addConnector(connector);

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
  backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/testpart/", host, port));
  WebsocketEchoTestBase.setupGatewayConfig(backendServerUri.toString());
}
 
Example 7
Source File: HttpServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Get the address that corresponds to a particular connector.
 *
 * @return the corresponding address for the connector, or null if there's no
 *         such connector or the connector is not bounded.
 */
public InetSocketAddress getConnectorAddress(int index) {
  Preconditions.checkArgument(index >= 0);

  if (index > webServer.getConnectors().length) {
    return null;
  }

  ServerConnector c = (ServerConnector)webServer.getConnectors()[index];
  if (c.getLocalPort() == -1 || c.getLocalPort() == -2) {
    // -1 if the connector has not been opened
    // -2 if it has been closed
    return null;
  }

  return new InetSocketAddress(c.getHost(), c.getLocalPort());
}
 
Example 8
Source File: UsefulApplicationUrlsTableFormatter.java    From verify-service-provider with MIT License 6 votes vote down vote up
private static List<ApplicationUrlsGenerator> extractTableRowForDefaultServer(Environment environment, ServerConnector connector) {
    String protocol = connector.getDefaultProtocol();
    int port = connector.getLocalPort();

    if ("admin".equals(connector.getName())) {
        String adminContextPath = environment.getAdminContext().getContextPath();

        return ImmutableList.of(
            new ApplicationUrlsGenerator(ADMIN_URL_TYPE, isHttps(protocol), port, adminContextPath),
            new ApplicationUrlsGenerator(HEALTHCHECK_URL_TYPE, isHttps(protocol), port, adminContextPath)
        );
    }

    return ImmutableList.of(
        new ApplicationUrlsGenerator(APPLICATION_URL_TYPE, isHttps(protocol), port, environment.getApplicationContext().getContextPath())
    );
}
 
Example 9
Source File: DownloadRemoteIndexTaskTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Before
public void initialize()
    throws Exception
{
    Path cfgFile = Paths.get("target/appserver-base/conf/archiva.xml");
    if (Files.exists(cfgFile)) {
        Files.delete(cfgFile);
    }
    try {
        repositoryRegistry.removeRepository( "test-repo-re" );
    } catch (Exception e) {
        // Ignore
    }
    server = new Server( );
    serverConnector = new ServerConnector( server, new HttpConnectionFactory());
    server.addConnector( serverConnector );
    createContext( server, Paths.get( "src/test/" ) );
    this.server.start();
    this.port = serverConnector.getLocalPort();
    log.info( "start server on port {}", this.port );
}
 
Example 10
Source File: HttpServer.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private RpcMetadataResponse createRpcServerMetadata(ServerConnector connector) throws
    UnknownHostException {
  String host = connector.getHost();
  if (null == host) {
    // "null" means binding to all interfaces, we need to pick one so the client gets a real
    // address and not "0.0.0.0" or similar.
    host = InetAddress.getLocalHost().getHostName();
  }

  final int port = connector.getLocalPort();

  return new RpcMetadataResponse(
      String.format(Locale.ROOT, "%s:%d", host, port));
}
 
Example 11
Source File: WebsocketEchoTestBase.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Start Gateway Server.
 * @throws Exception exception on server start
 */
private static void startGatewayServer() throws Exception {
  gatewayServer = new Server();
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));

  /* Setup websocket handler */
  setupGatewayConfig(backendServerUri.toString());

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 12
Source File: WebsocketMultipleConnectionTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private static void startGatewayServer() throws Exception {
  /* use default Max threads */
  gatewayServer = new Server(new QueuedThreadPool(254));
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));

  /* Setup websocket handler */
  setupGatewayConfig(backendServerUri.toString());

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 13
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Get the address that corresponds to a particular connector.
 *
 * @return the corresponding address for the connector, or null if there's no
 *         such connector or the connector is not bounded or was closed.
 */
public InetSocketAddress getConnectorAddress(int index) {
  Preconditions.checkArgument(index >= 0);
  if (index > webServer.getConnectors().length)
    return null;

  ServerConnector c = (ServerConnector)webServer.getConnectors()[index];
  if (c.getLocalPort() == -1 || c.getLocalPort() == -2) {
    // The connector is not bounded or was closed
    return null;
  }

  return new InetSocketAddress(c.getHost(), c.getLocalPort());
}
 
Example 14
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the socket the WebSocket server is listening on.
 */
public SocketAddress getWebSocketAddress() {
  if (httpServer == null) {
    return null;
  } else {
    ServerConnector c = (ServerConnector)httpServer.getConnectors()[0];
    return new InetSocketAddress(c.getHost(), c.getLocalPort());
  }
}
 
Example 15
Source File: ConsulServiceListener.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
@Override
public void serverStarted(final Server server) {

  String applicationScheme = null;
  int applicationPort = -1;
  int adminPort = -1;

  for (Connector connector : server.getConnectors()) {
    @SuppressWarnings("resource")
    final ServerConnector serverConnector = (ServerConnector) connector;
    if (APPLICATION_NAME.equals(connector.getName())) {
      applicationPort = serverConnector.getLocalPort();
      applicationScheme = getScheme(connector.getProtocols());
    } else if (ADMIN_NAME.equals(connector.getName())) {
      adminPort = serverConnector.getLocalPort();
    } else {
      applicationPort = serverConnector.getLocalPort();
      applicationScheme = getScheme(connector.getProtocols());
      adminPort = applicationPort;
    }
  }

  LOGGER.debug(
      "applicationScheme: {}, applicationPort: {}, adminPort: {}",
      applicationScheme,
      applicationPort,
      adminPort);

  register(applicationScheme, applicationPort, adminPort);
}
 
Example 16
Source File: HttpServer2.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Get the address that corresponds to a particular connector.
 *
 * @param index index of the connector
 * @return the corresponding address for the connector, or null if there's no
 *         such connector or the connector is not bounded or was closed.
 */
public InetSocketAddress getConnectorAddress(int index) {
  Preconditions.checkArgument(index >= 0);
  if (index > webServer.getConnectors().length) {
    return null;
  }

  ServerConnector c = (ServerConnector)webServer.getConnectors()[index];
  if (c.getLocalPort() == -1 || c.getLocalPort() == -2) {
    // The connector is not bounded or was closed
    return null;
  }

  return new InetSocketAddress(c.getHost(), c.getLocalPort());
}
 
Example 17
Source File: HostedRepositoryIntegrationTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
private URI toServerURI(ServerConnector connector) throws URISyntaxException {
    String host = connector.getHost();
    if (host == null) {
        host = DEFAULT_HOST;
    }
    int port = connector.getLocalPort();
    return new URI(String.format("http://%s:%d",
                                 host,
                                 port));
}
 
Example 18
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());

    ServerConnector connector = new ServerConnector(server);

    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example 19
Source File: DownloadArtifactsTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Override

    @Before
    public void startServer()
        throws Exception
    {
        super.startServer();

        // repo handler

        this.repoServer = new Server(  );
        ServerConnector repoServerConnector = new ServerConnector( this.repoServer, new HttpConnectionFactory());
        this.repoServer.addConnector( repoServerConnector );

        ServletHolder shRepo = new ServletHolder( RepoServlet.class );
        ServletContextHandler contextRepo = new ServletContextHandler();

        contextRepo.setContextPath( "/" );
        contextRepo.addServlet( shRepo, "/*" );

        repoServer.setHandler( contextRepo );

        repoServer.start();
        this.repoServerPort = repoServerConnector.getLocalPort();

        //redirect handler

        this.redirectServer = new Server( );
        ServerConnector redirectServerConnector = new ServerConnector( this.redirectServer, new HttpConnectionFactory());
        this.redirectServer.addConnector( redirectServerConnector );

        ServletHolder shRedirect = new ServletHolder( RedirectServlet.class );
        ServletContextHandler contextRedirect = new ServletContextHandler();
        contextRedirect.setAttribute( "redirectToPort", Integer.toString( this.repoServerPort ) );

        contextRedirect.setContextPath( "/" );
        contextRedirect.addServlet( shRedirect, "/*" );

        redirectServer.setHandler( contextRedirect );
        redirectServer.start();
        this.redirectPort = redirectServerConnector.getLocalPort();
        log.info( "redirect server port {}", redirectPort );

    }
 
Example 20
Source File: HMaster.java    From hbase with Apache License 2.0 4 votes vote down vote up
private int putUpJettyServer() throws IOException {
  if (!conf.getBoolean("hbase.master.infoserver.redirect", true)) {
    return -1;
  }
  final int infoPort = conf.getInt("hbase.master.info.port.orig",
    HConstants.DEFAULT_MASTER_INFOPORT);
  // -1 is for disabling info server, so no redirecting
  if (infoPort < 0 || infoServer == null) {
    return -1;
  }
  if(infoPort == infoServer.getPort()) {
    return infoPort;
  }
  final String addr = conf.get("hbase.master.info.bindAddress", "0.0.0.0");
  if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) {
    String msg =
        "Failed to start redirecting jetty server. Address " + addr
            + " does not belong to this host. Correct configuration parameter: "
            + "hbase.master.info.bindAddress";
    LOG.error(msg);
    throw new IOException(msg);
  }

  // TODO I'm pretty sure we could just add another binding to the InfoServer run by
  // the RegionServer and have it run the RedirectServlet instead of standing up
  // a second entire stack here.
  masterJettyServer = new Server();
  final ServerConnector connector = new ServerConnector(masterJettyServer);
  connector.setHost(addr);
  connector.setPort(infoPort);
  masterJettyServer.addConnector(connector);
  masterJettyServer.setStopAtShutdown(true);

  final String redirectHostname =
      StringUtils.isBlank(useThisHostnameInstead) ? null : useThisHostnameInstead;

  final RedirectServlet redirect = new RedirectServlet(infoServer, redirectHostname);
  final WebAppContext context = new WebAppContext(null, "/", null, null, null, null, WebAppContext.NO_SESSIONS);
  context.addServlet(new ServletHolder(redirect), "/*");
  context.setServer(masterJettyServer);

  try {
    masterJettyServer.start();
  } catch (Exception e) {
    throw new IOException("Failed to start redirecting jetty server", e);
  }
  return connector.getLocalPort();
}