org.eclipse.jetty.server.NetworkConnector Java Examples

The following examples show how to use org.eclipse.jetty.server.NetworkConnector. 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: CodeGenBugTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelloWorldExternalBindingFile() throws Exception {
    Server server = new Server(0);
    try {
        ResourceHandler reshandler = new ResourceHandler();
        reshandler.setResourceBase(getLocation("/wsdl2java_wsdl/"));
        // this is the only handler we're supposed to need, so we don't need to
        // 'add' it.
        server.setHandler(reshandler);
        server.start();
        Thread.sleep(250); //give network connector a little time to spin up
        int port = ((NetworkConnector)server.getConnectors()[0]).getLocalPort();
        env.put(ToolConstants.CFG_WSDLURL, "http://localhost:"
            + port + "/hello_world.wsdl");
        env.put(ToolConstants.CFG_BINDING, "http://localhost:"
            + port + "/remote-hello_world_binding.xsd");
        processor.setContext(env);
        processor.execute();
        reshandler.stop();
    } finally {
        server.stop();
        server.destroy();
    }

}
 
Example #2
Source File: BrooklynRestApiLauncher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static Server startServer(ManagementContext mgmt, ContextHandler context, String summary, InetSocketAddress bindLocation) {
    Server server = new Server(bindLocation);

    initAuth(mgmt, server);

    server.setHandler(context);
    try {
        server.start();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
    log.info("Brooklyn REST server started ("+summary+") on");
    log.info("  http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort()+"/");

    return server;
}
 
Example #3
Source File: JettyWebSocketTestServer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void start() throws Exception {
	this.jettyServer.start();
	this.contextHandler.start();

	Connector[] connectors = jettyServer.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	this.port = connector.getLocalPort();
}
 
Example #4
Source File: JettyServer.java    From jqm with Apache License 2.0 5 votes vote down vote up
int getActualPort()
{
    if (server == null)
    {
        return 0;
    }
    return ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
}
 
Example #5
Source File: MockSnapshotServer.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
public void start() {
    try {
        server.start();
    } catch (Exception e) {
        Log.warn("Exception when trying to start server", e);
    }
    port = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
}
 
Example #6
Source File: GatewayServer.java    From knox with Apache License 2.0 5 votes vote down vote up
public InetSocketAddress[] getAddresses() {
  InetSocketAddress[] addresses = new InetSocketAddress[ jetty.getConnectors().length ];
  for( int i=0, n=addresses.length; i<n; i++ ) {
    NetworkConnector connector = (NetworkConnector)jetty.getConnectors()[ i ];
    String host = connector.getHost();
    if( host == null ) {
      addresses[ i ] = new InetSocketAddress( connector.getLocalPort() );
    } else {
      addresses[ i ] = new InetSocketAddress( host, connector.getLocalPort() );
    }
  }
  return addresses;
}
 
Example #7
Source File: GatewayServer.java    From knox with Apache License 2.0 5 votes vote down vote up
public static GatewayServer startGateway( GatewayConfig config, GatewayServices svcs ) throws Exception {
  log.startingGateway();
  server = new GatewayServer( config );
  synchronized ( server ) {
    //KM[ Commented this out because is causes problems with
    // multiple services instance used in a single test process.
    // I'm not sure what drive including this check though.
    //if (services == null) {
    services = svcs;
    //}
    //KM]
    services.start();
    DeploymentFactory.setGatewayServices(services);
    server.start();

    // Logging for topology <-> port
    Connector[] connectors = server.jetty.getConnectors();
    for (Connector connector : connectors) {
      NetworkConnector networkConnector = (NetworkConnector) connector;
      if (networkConnector != null) {
        for (ConnectionFactory x : networkConnector.getConnectionFactories()) {
          if (x instanceof HttpConnectionFactory) {
            ((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(config.isGatewayServerHeaderEnabled());
          }
        }
        if (networkConnector.getName() == null) {
          log.startedGateway(networkConnector.getLocalPort());
        } else {
          log.startedGateway(networkConnector.getName(), networkConnector.getLocalPort());
        }
      }
    }

    return server;
  }
}
 
Example #8
Source File: BrooklynJacksonSerializerIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
    super.setUp();
    server = BrooklynRestApiLauncher.launcher().managementContext(mgmt).start();
    client = HttpTool.httpClientBuilder().build();

    String serverAddress = "http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort();
    String appUrl = serverAddress + "/v1/applications/" + app.getId();
    entityUrl = URI.create(appUrl + "/entities/" + app.getId());
    configUri = new URIBuilder(entityUrl + "/config/" + TestEntity.CONF_OBJECT.getName())
            .addParameter("raw", "true")
            .build();

}
 
Example #9
Source File: AbstractJettyMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings( "ValueOfIncrementOrDecrementUsed" )
public final Interface[] interfacesServed()
{
    Connector[] connectors = server.getConnectors();
    Interface[] result = new Interface[ connectors.length ];
    int index = 0;
    for( Connector connector : connectors )
    {
        if( connector instanceof NetworkConnector )
        {
            NetworkConnector netConnector = (NetworkConnector) connector;
            String host = configuration().hostName().get();
            if( host == null )
            {
                host = netConnector.getHost();
                if( host == null ) // If serving all interfaces.
                {
                    try
                    {
                        host = InetAddress.getLocalHost().getHostAddress();
                    }
                    catch( UnknownHostException e )
                    {
                        throw new InternalError( "UnknownHost for local interface.", e );
                    }
                }
            }
            result[ index++] = new InterfaceImpl( host, netConnector.getPort(), servedProtocol() );
        }
    }
    return result;
}
 
Example #10
Source File: TestSamzaRestService.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartShouldStartTheMetricsReportersAndServer() throws Exception {
  NetworkConnector connector = Mockito.mock(NetworkConnector.class);
  int testServerPort = 100;
  Mockito.doReturn(testServerPort).when(connector).getPort();
  Mockito.when(server.getConnectors()).thenReturn(new NetworkConnector[]{connector});
  Mockito.doNothing().when(server).start();
  samzaRestService.start();
  Mockito.verify(metricsReporter).start();
  Mockito.verify(metricsReporter).register("SamzaRest", metricsRegistry);
  Mockito.verify(server).start();
}
 
Example #11
Source File: SamzaRestService.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the server asynchronously. To stop the server, see {@link #stop()}.
 *
 * @throws Exception if the server could not be successfully started.
 */
public void start()
    throws Exception {
  metricsReporters.forEach((reporterName, metricsReporter) -> {
    log.info("Registering the metrics reporter : {},  with source :  {}.", reporterName, METRICS_SOURCE);
    metricsReporter.register(METRICS_SOURCE, metricsRegistry);
    log.info("Starting the metrics reporter : {}.", reporterName);
    metricsReporter.start();
  });
  log.info("Starting server on port {}", ((NetworkConnector) server.getConnectors()[0]).getPort());
  server.start();
  log.info("Server is running");
}
 
Example #12
Source File: AbstractJettyServerTestCase.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startJettyServer() throws Exception {

	// Let server pick its own random, available port.
	jettyServer = new Server(0);

	ServletContextHandler handler = new ServletContextHandler();
	handler.setContextPath("/");

	handler.addServlet(new ServletHolder(new EchoServlet()), "/echo");
	handler.addServlet(new ServletHolder(new ParameterServlet()), "/params");
	handler.addServlet(new ServletHolder(new StatusServlet(200)), "/status/ok");
	handler.addServlet(new ServletHolder(new StatusServlet(404)), "/status/notfound");
	handler.addServlet(new ServletHolder(new MethodServlet("DELETE")), "/methods/delete");
	handler.addServlet(new ServletHolder(new MethodServlet("GET")), "/methods/get");
	handler.addServlet(new ServletHolder(new MethodServlet("HEAD")), "/methods/head");
	handler.addServlet(new ServletHolder(new MethodServlet("OPTIONS")), "/methods/options");
	handler.addServlet(new ServletHolder(new PostServlet()), "/methods/post");
	handler.addServlet(new ServletHolder(new MethodServlet("PUT")), "/methods/put");
	handler.addServlet(new ServletHolder(new MethodServlet("PATCH")), "/methods/patch");

	jettyServer.setHandler(handler);
	jettyServer.start();

	Connector[] connectors = jettyServer.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	baseUrl = "http://localhost:" + connector.getLocalPort();
}
 
Example #13
Source File: JettyWebSocketTestServer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
	this.jettyServer.start();

	Connector[] connectors = jettyServer.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	this.port = connector.getLocalPort();
}
 
Example #14
Source File: RequestPartIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startServer() throws Exception {
	// Let server pick its own random, available port.
	server = new Server(0);

	ServletContextHandler handler = new ServletContextHandler();
	handler.setContextPath("/");

	Class<?> config = CommonsMultipartResolverTestConfig.class;
	ServletHolder commonsResolverServlet = new ServletHolder(DispatcherServlet.class);
	commonsResolverServlet.setInitParameter("contextConfigLocation", config.getName());
	commonsResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
	handler.addServlet(commonsResolverServlet, "/commons-resolver/*");

	config = StandardMultipartResolverTestConfig.class;
	ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class);
	standardResolverServlet.setInitParameter("contextConfigLocation", config.getName());
	standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
	standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
	handler.addServlet(standardResolverServlet, "/standard-resolver/*");

	server.setHandler(handler);
	server.start();

	Connector[] connectors = server.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	baseUrl = "http://localhost:" + connector.getLocalPort();
}
 
Example #15
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void logOperationalShutdownMessage()
{
    for (NetworkConnector connector : _portConnectorMap.values())
    {
        logOperationalShutdownMessage(connector.getLocalPort());
    }
}
 
Example #16
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void logOperationalListenMessages()
{
    for (Map.Entry<HttpPort<?>, ServerConnector> portConnector : _portConnectorMap.entrySet())
    {
        HttpPort<?> port = portConnector.getKey();
        NetworkConnector connector = portConnector.getValue();
        logOperationalListenMessages(port, connector.getLocalPort());
    }
}
 
Example #17
Source File: AbstractJettyServerTestCase.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startJettyServer() throws Exception {

	// Let server pick its own random, available port.
	jettyServer = new Server(0);

	ServletContextHandler handler = new ServletContextHandler();
	byte[] bytes = helloWorld.getBytes("utf-8");
	handler.addServlet(new ServletHolder(new GetServlet(bytes, textContentType)), "/get");
	handler.addServlet(new ServletHolder(new GetServlet(new byte[0], textContentType)), "/get/nothing");
	handler.addServlet(new ServletHolder(new GetServlet(bytes, null)), "/get/nocontenttype");
	handler.addServlet(
			new ServletHolder(new PostServlet(helloWorld, "/post/1", bytes, textContentType)),
			"/post");
	handler.addServlet(
			new ServletHolder(new JsonPostServlet("/jsonpost/1", jsonContentType)),
			"/jsonpost");
	handler.addServlet(new ServletHolder(new StatusCodeServlet(204)), "/status/nocontent");
	handler.addServlet(new ServletHolder(new StatusCodeServlet(304)), "/status/notmodified");
	handler.addServlet(new ServletHolder(new ErrorServlet(404)), "/status/notfound");
	handler.addServlet(new ServletHolder(new ErrorServlet(500)), "/status/server");
	handler.addServlet(new ServletHolder(new UriServlet()), "/uri/*");
	handler.addServlet(new ServletHolder(new MultipartServlet()), "/multipart");
	handler.addServlet(new ServletHolder(new FormServlet()), "/form");
	handler.addServlet(new ServletHolder(new DeleteServlet()), "/delete");
	handler.addServlet(
			new ServletHolder(new PutServlet(helloWorld, bytes, textContentType)),
			"/put");

	jettyServer.setHandler(handler);
	jettyServer.start();

	Connector[] connectors = jettyServer.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	port = connector.getLocalPort();
	baseUrl = "http://localhost:" + port;
}
 
Example #18
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public int getBoundPort(final HttpPort httpPort)
{
    NetworkConnector c = _portConnectorMap.get(httpPort);
    if (c != null)
    {
        return c.getLocalPort();
    }
    else
    {
        return -1;
    }
}
 
Example #19
Source File: RequestPartIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@BeforeClass
public static void startServer() throws Exception {
	// Let server pick its own random, available port.
	server = new Server(0);

	ServletContextHandler handler = new ServletContextHandler();
	handler.setContextPath("/");

	Class<?> config = CommonsMultipartResolverTestConfig.class;
	ServletHolder commonsResolverServlet = new ServletHolder(DispatcherServlet.class);
	commonsResolverServlet.setInitParameter("contextConfigLocation", config.getName());
	commonsResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
	handler.addServlet(commonsResolverServlet, "/commons-resolver/*");

	config = StandardMultipartResolverTestConfig.class;
	ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class);
	standardResolverServlet.setInitParameter("contextConfigLocation", config.getName());
	standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
	standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
	handler.addServlet(standardResolverServlet, "/standard-resolver/*");

	server.setHandler(handler);
	server.start();

	Connector[] connectors = server.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	baseUrl = "http://localhost:" + connector.getLocalPort();
}
 
Example #20
Source File: ODataTestServer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private String serverBaseUri(NetworkConnector connector) {
    if (connector == null) {
        return null;
    }

    ContextHandler context = getChildHandlerByClass(ContextHandler.class);

    try {
        String protocol = connector.getDefaultConnectionFactory().getProtocol();
        String scheme = "http";
        if (protocol.startsWith("SSL-") || protocol.equals("SSL"))
            scheme = "https";

        String host = connector.getHost();
        if (context != null && context.getVirtualHosts() != null && context.getVirtualHosts().length > 0)
            host = context.getVirtualHosts()[0];
        if (host == null)
            host = InetAddress.getLocalHost().getHostAddress();

        String path = context == null ? null : context.getContextPath();
        if (path == null) {
            path = FORWARD_SLASH;
        }

        URI uri = new URI(scheme, null, host, connector.getLocalPort(), path, null, null);
        return uri.toString();
    }
    catch(Exception e) {
        LOG.error("Uri error", e);
        return null;
    }
}
 
Example #21
Source File: RequestPartIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@BeforeClass
public static void startServer() throws Exception {
	// Let server pick its own random, available port.
	server = new Server(0);

	ServletContextHandler handler = new ServletContextHandler();
	handler.setContextPath("/");

	Class<?> config = CommonsMultipartResolverTestConfig.class;
	ServletHolder commonsResolverServlet = new ServletHolder(DispatcherServlet.class);
	commonsResolverServlet.setInitParameter("contextConfigLocation", config.getName());
	commonsResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
	handler.addServlet(commonsResolverServlet, "/commons-resolver/*");

	config = StandardMultipartResolverTestConfig.class;
	ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class);
	standardResolverServlet.setInitParameter("contextConfigLocation", config.getName());
	standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
	standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
	handler.addServlet(standardResolverServlet, "/standard-resolver/*");

	server.setHandler(handler);
	server.start();

	Connector[] connectors = server.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	baseUrl = "http://localhost:" + connector.getLocalPort();
}
 
Example #22
Source File: JettyWebSocketTestServer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void start() throws Exception {
	this.jettyServer.start();
	this.contextHandler.start();

	Connector[] connectors = jettyServer.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	this.port = connector.getLocalPort();
}
 
Example #23
Source File: ExampleServerTest.java    From rack-servlet with Apache License 2.0 4 votes vote down vote up
public int getPort() {
  Connector[] connectors = server.getConnectors();
  NetworkConnector connector = (NetworkConnector) connectors[0];
  return connector.getLocalPort();
}
 
Example #24
Source File: ExampleServerTest.java    From rack-servlet with Apache License 2.0 4 votes vote down vote up
public int getPort() {
  Connector[] connectors = server.getConnectors();
  NetworkConnector connector = (NetworkConnector) connectors[0];
  return connector.getLocalPort();
}
 
Example #25
Source File: ExampleServer.java    From rack-servlet with Apache License 2.0 4 votes vote down vote up
public int getPort() {
  Connector[] connectors = server.getConnectors();
  NetworkConnector connector = (NetworkConnector) connectors[0];
  return connector.getLocalPort();
}
 
Example #26
Source File: JettyManager.java    From DataGenerator with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares a Jetty server for communicating with consumers.
 */
public void prepareServer() {
    try {
        server = new Server(0);
        jettyHandler = new AbstractHandler() {
            public void handle(String target, Request req, HttpServletRequest request,
                               HttpServletResponse response) throws IOException, ServletException {
                response.setContentType("text/plain");

                String[] operands = request.getRequestURI().split("/");

                String name = "";
                String command = "";
                String value = "";

                //operands[0] = "", request starts with a "/"

                if (operands.length >= 2) {
                    name = operands[1];
                }

                if (operands.length >= 3) {
                    command = operands[2];
                }

                if (operands.length >= 4) {
                    value = operands[3];
                }

                if (command.equals("report")) { //report a number of lines written
                    response.getWriter().write(makeReport(name, value));
                } else if (command.equals("request") && value.equals("block")) { //request a new block of work
                    response.getWriter().write(requestBlock(name));
                } else if (command.equals("request") && value.equals("name")) { //request a new name to report with
                    response.getWriter().write(requestName());
                } else { //non recognized response
                    response.getWriter().write("exit");
                }

                ((Request) request).setHandled(true);
            }
        };

        server.setHandler(jettyHandler);

        // Select any available port
        server.start();
        Connector[] connectors = server.getConnectors();
        NetworkConnector nc = (NetworkConnector) connectors[0];
        listeningPort = nc.getLocalPort();
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #27
Source File: ReporterFactoryTest.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
private int getPort() {
    return ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
}
 
Example #28
Source File: AbstractServletTest.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
protected int getPort() {
    return ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
}
 
Example #29
Source File: BrooklynRestApiLauncherTestFixture.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** returns base of server, without trailing slash - e.g. <code>http://localhost:8081</code> */
public static String getBaseUriHostAndPost(Server server) {
    return "http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort();
}
 
Example #30
Source File: CampServer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public Integer getPort() {
    if (server==null) return null;
    NetworkConnector networkConnector = (NetworkConnector) server.getConnectors()[0];
    return networkConnector.getLocalPort();
}