@Override public synchronized void start() { try { if (!isRunning) { server.start().get(); if (port == 0) { // Replace the specified port number with the primary port number. // Server#activePort doesn't return the first added port, so we need to find that. final Optional<ServerPort> port = server.activePorts().values().stream() .filter(p -> p.protocols().contains(protocol)) .filter(p -> address == null || Arrays.equals(address.getAddress(), p.localAddress().getAddress().getAddress())) .findFirst(); assert port.isPresent() : "the primary port doest not exist."; this.port = port.get().localAddress().getPort(); } isRunning = true; } } catch (Exception cause) { throw new WebServerException("Failed to start " + ArmeriaWebServer.class.getSimpleName(), Exceptions.peel(cause)); } }
@BeforeClass public static void beforeClass() { server = ServerFactory.of(0); server.start().join(); client = HttpClient.of("http://127.0.0.1:" + server.activePort().get().localAddress().getPort()); }
/** * Stops the {@link Server} asynchronously. * * @return the {@link CompletableFuture} that will complete when the {@link Server} is stopped. */ public CompletableFuture<Void> stop() { final Server server = this.server.getAndSet(null); if (server == null || server.activePorts().isEmpty()) { return CompletableFuture.completedFuture(null); } return server.stop(); }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("config", config()) .add("activePorts", activePorts()) .add("state", startStop) .toString(); }
@Override public void serviceAdded(ServiceConfig cfg) { if (armeriaServer != null) { if (armeriaServer != cfg.server()) { throw new IllegalStateException("cannot be added to more than one server"); } else { return; } } armeriaServer = cfg.server(); armeriaServer.addListener(configurator); if (hostname == null) { hostname = armeriaServer.defaultHostname(); } }
private static boolean isStopped(@Nullable Server server) { return server == null || server.activePorts().isEmpty(); }
/** * Returns the {@link MeterRegistry} that collects various stats. */ public MeterRegistry meterRegistry() { return config().meterRegistry(); }
@Override public synchronized void stop() { try { if (isRunning) { server.stop().get(); isRunning = false; } } catch (Exception cause) { throw new WebServerException("Failed to stop " + ArmeriaWebServer.class.getSimpleName(), Exceptions.peel(cause)); } }
/** * Starts the {@link Server} configured by {@link #configure(ServerBuilder)}. * If the {@link Server} has been started up already, the existing {@link Server} is returned. * Note that this operation blocks until the {@link Server} finished the start-up. * * @return the started {@link Server} */ public Server start() { final Server oldServer = server.get(); if (!isStopped(oldServer)) { return oldServer; } final ServerBuilder sb = new ServerBuilder(); try { configure(sb); } catch (Exception e) { throw new IllegalStateException("failed to configure a Server", e); } final Server server = sb.build(); server.start().join(); this.server.set(server); return server; }
public static void main(String[] args) throws Exception { final SamlServiceProvider ssp = samlServiceProvider(); final Server server = new ServerBuilder() .https(8443) // You can add this certificate to your trust store in order to make your web browser happy. .tls(new File(ClassLoader.getSystemResource("localhost.crt").toURI()), new File(ClassLoader.getSystemResource("localhost.key").toURI())) // Decorate you service with SAML decorator. .annotatedService("/", new MyService(), ssp.newSamlDecorator()) // Add SAML service to your server which handles a SAML response and a metadata request. .service(ssp.newSamlService()) .build(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { server.stop().join(); logger.info("Server has been stopped."); })); server.start().join(); logger.info("Server has been started."); } }
@Override public void serverStarted(Server server) throws Exception { // Ensure that the following work will be done once. if (completed.compareAndSet(false, true)) { builder.setSchemeAndPortIfAbsent(server.activePort().get()); assert builder.scheme() != null; config = new SamlPortConfig(builder.scheme(), builder.port()); future.complete(config); } } }
@Before public void startServers() { servers = new ArrayList<>(); for (Endpoint endpoint : sampleEndpoints) { final Server server = new ServerBuilder().http(endpoint.port()) .service("/", new EchoService()) .build(); final ServerListener listener = new ZooKeeperUpdatingListenerBuilder( instance().connectString().get(), zNode) .sessionTimeoutMillis(sessionTimeoutMillis) .endpoint(endpoint) .build(); server.addListener(listener); server.start().join(); servers.add(server); } }
@Override public void serverStarted(Server server) throws Exception { if (endpoint == null) { assert server.activePort().isPresent(); endpoint = Endpoint.of(server.defaultHostname(), server.activePort().get() .localAddress().getPort()); } client.start(); final String key = endpoint.host() + '_' + endpoint.port(); final byte[] value = nodeValueCodec.encode(endpoint); client.create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL) .forPath(zNodePath + '/' + key, value); }
@Override public void serviceAdded(ServiceConfig cfg) throws Exception { if (server != null) { if (server != cfg.server()) { throw new IllegalStateException("cannot be added to more than one server"); } else { return; } } server = cfg.server(); // Auto-detect the primary port number and its session protocol after the server started. server.addListener(portConfigHolder); }
@Test public void addressesAndPorts_localhost() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { final HttpGet request = new HttpGet(server().uri("/jsp/addrs_and_ports.jsp")); request.setHeader("Host", "localhost:1111"); try (CloseableHttpResponse res = hc.execute(request)) { assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK"); assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue()) .startsWith("text/html"); final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity())) .replaceAll(""); assertThat(actualContent).matches( "<html><body>" + "<p>RemoteAddr: 127\\.0\\.0\\.1</p>" + "<p>RemoteHost: 127\\.0\\.0\\.1</p>" + "<p>RemotePort: [1-9][0-9]+</p>" + "<p>LocalAddr: (?!null)[^<]+</p>" + "<p>LocalName: " + server().server().defaultHostname() + "</p>" + "<p>LocalPort: " + server().httpPort() + "</p>" + "<p>ServerName: localhost</p>" + "<p>ServerPort: 1111</p>" + "</body></html>"); } } }
server.addListener(rejectingListener); server.config().defaultVirtualHost(), localAddress().getHostString(), path(),
private boolean hasSessionProtocol(SessionProtocol protocol) { final Server server = this.server.get(); return server != null && server.activePorts().values().stream() .anyMatch(port -> port.hasProtocol(protocol)); }
@Override public void serviceAdded(ServiceConfig cfg) { if (maxInboundMessageSizeBytes == NO_MAX_INBOUND_MESSAGE_SIZE) { maxInboundMessageSizeBytes = (int) Math.min(cfg.server().config().defaultMaxRequestLength(), Integer.MAX_VALUE); } }
@After public void stopServers() { if (servers != null) { servers.forEach(s -> s.stop().join()); } }
s.start().join(); return s;