Java Code Examples for io.undertow.Undertow#Builder
The following examples show how to use
io.undertow.Undertow#Builder .
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: UndertowWebServer.java From oxygen with Apache License 2.0 | 6 votes |
@Override public void listen(int port) { this.port = port; this.contextPath = WebConfigKeys.SERVER_CONTEXT_PATH.getValue(); undertowConf = ConfigFactory.load(UndertowConf.class); DeploymentManager manager = deployment(); manager.deploy(); Undertow.Builder builder = Undertow.builder(); configServer(builder); try { undertow = builder.setHandler(configHttp(manager.start())).build(); } catch (ServletException e) { throw Exceptions.wrap(e); } undertow.start(); }
Example 2
Source File: UndertowUtil.java From StubbornJava with MIT License | 6 votes |
/** * This is currently intended to be used in unit tests but may * be appropriate in other situations as well. It's not worth building * out a test module at this time so it lives here. * * This helper will spin up the http handler on a random available port. * The full host and port will be passed to the hostConsumer and the server * will be shut down after the consumer completes. * * @param builder * @param handler * @param hostConusmer */ public static void useLocalServer(Undertow.Builder builder, HttpHandler handler, Consumer<String> hostConusmer) { Undertow undertow = null; try { // Starts server on a random open port undertow = builder.addHttpListener(0, "127.0.0.1", handler).build(); undertow.start(); ListenerInfo listenerInfo = undertow.getListenerInfo().get(0); InetSocketAddress addr = (InetSocketAddress) listenerInfo.getAddress(); String host = "http://localhost:" + addr.getPort(); hostConusmer.accept(host); } finally { if (undertow != null) { undertow.stop(); } } }
Example 3
Source File: UndertowHttpServer.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Start the server. */ @Override public void start() { Undertow.Builder builder = Undertow.builder() .setHandler(new UndertowHttpHandler(httpServerProcessor)); if (ssl) { try { builder.addHttpsListener(serverPort, "0.0.0.0", SSLContext.getDefault()); } catch (NoSuchAlgorithmException e) { if (LOGGER.isLoggable(SEVERE)) { LOGGER.log(WARNING, "Unable to match SSL algorithm", e); } } } else { builder.addHttpListener(serverPort, "0.0.0.0"); } undertow = builder.build(); undertow.start(); }
Example 4
Source File: UndertowServer.java From openshift-ping with Apache License 2.0 | 6 votes |
public synchronized boolean start(JChannel channel) throws Exception { boolean started = false; if (server == null) { try { Undertow.Builder builder = Undertow.builder(); builder.addHttpListener(port, "0.0.0.0"); builder.setHandler(new Handler(this)); server = builder.build(); server.start(); started = true; } catch (Exception e) { server = null; throw e; } } addChannel(channel); return started; }
Example 5
Source File: UndertowSettings.java From pippo with Apache License 2.0 | 6 votes |
/** * * @param builder - undertow builder * method adds undertow options to builder * undertow.server.* would be added to serverOptions * undertow.socket.* would be added to socketOptions * undertow.worker.* would be added to workerOptions */ public void addUndertowOptions(Undertow.Builder builder) { List<String> propertyNames = pippoSettings.getSettingNames(PREFIX); String prefix; for (String propertyName: propertyNames) { prefix = null; if (propertyName.startsWith(UNDERTOW_SERVER_PREFIX)) { prefix = UNDERTOW_SERVER_PREFIX; } else if (propertyName.startsWith(UNDERTOW_SOCKET_PREFIX)) { prefix = UNDERTOW_SOCKET_PREFIX; } else if (propertyName.startsWith(UNDERTOW_WORKER_PREFIX)) { prefix = UNDERTOW_WORKER_PREFIX; } if (prefix != null) { addUndertowOption(builder, propertyName, prefix); } } }
Example 6
Source File: ServerFactory.java From seed with Mozilla Public License 2.0 | 6 votes |
Undertow createServer(HttpHandler httpHandler, SSLProvider sslProvider) { PathHandler path = Handlers .path(Handlers.redirect(serverConfig.getContextPath())) .addPrefixPath(serverConfig.getContextPath(), httpHandler); Undertow.Builder builder = Undertow.builder().setWorker(xnioWorker); if (!serverConfig.isHttp() && !serverConfig.isHttps()) { throw SeedException.createNew(UndertowErrorCode.NO_LISTENER_CONFIGURED); } else { if (serverConfig.isHttp()) { builder = configureHttp(builder); } if (serverConfig.isHttps()) { builder = configureHttps(builder, sslProvider); if (serverConfig.isHttp2()) { LOGGER.info("HTTP/2 support is enabled"); builder.setServerOption(UndertowOptions.ENABLE_HTTP2, serverConfig.isHttp2()); } } } return builder.setHandler(path).build(); }
Example 7
Source File: UndertowHTTPServerEngine.java From cxf with Apache License 2.0 | 5 votes |
private Undertow createServer(URL url, UndertowHTTPHandler undertowHTTPHandler) throws Exception { Undertow.Builder result = Undertow.builder(); result.setServerOption(UndertowOptions.IDLE_TIMEOUT, getMaxIdleTime()); if (this.shouldEnableHttp2(undertowHTTPHandler.getBus())) { result.setServerOption(UndertowOptions.ENABLE_HTTP2, Boolean.TRUE); } if (tlsServerParameters != null) { if (this.sslContext == null) { this.sslContext = createSSLContext(); } result = result.addHttpsListener(getPort(), getHost(), this.sslContext); } else { result = result.addHttpListener(getPort(), getHost()); } path = Handlers.path(new NotFoundHandler()); if (url.getPath().length() == 0) { result = result.setHandler(Handlers.trace(undertowHTTPHandler)); } else { if (undertowHTTPHandler.isContextMatchExact()) { path.addExactPath(url.getPath(), undertowHTTPHandler); } else { path.addPrefixPath(url.getPath(), undertowHTTPHandler); } result = result.setHandler(wrapHandler(new HttpContinueReadHandler(path))); } result = decorateUndertowSocketConnection(result); result = disableSSLv3(result); result = configureThreads(result); return result.build(); }
Example 8
Source File: SimpleServer.java From StubbornJava with MIT License | 5 votes |
public static SimpleServer simpleServer(HttpHandler handler) { Undertow.Builder undertow = Undertow.builder() /* * This setting is needed if you want to allow '=' as a value in a cookie. * If you base64 encode any cookie values you probably want it on. */ .setServerOption(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, true) // Needed to set request time in access logs .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true) .addHttpListener(DEFAULT_PORT, DEFAULT_HOST, handler) ; return new SimpleServer(undertow); }
Example 9
Source File: UndertowSettings.java From pippo with Apache License 2.0 | 5 votes |
private <T> void addUndertowOption(Undertow.Builder builder, Option<T> option, T value, String prefix) { switch (prefix) { case UNDERTOW_SERVER_PREFIX: builder.setServerOption(option, value); break; case UNDERTOW_SOCKET_PREFIX: builder.setSocketOption(option, value); break; case UNDERTOW_WORKER_PREFIX: builder.setWorkerOption(option, value); break; default: break; } }
Example 10
Source File: RoutingServer.java From StubbornJava with MIT License | 5 votes |
public static void main(String[] args) { /* * You caught us! We changed our mind and decided to add a small abstraction. * Notice however we have zero intention of hiding Undertow. We have embraced * Undertow as our web server and will allow it to be leaked out. This is a conscious * design decision to improve developer productivity. */ SimpleServer server = SimpleServer.simpleServer(ROUTES); // See we have access to it here! Undertow.Builder undertow = server.getUndertow(); server.start(); }
Example 11
Source File: UndertowWebServer.java From oxygen with Apache License 2.0 | 5 votes |
private void configServer(Undertow.Builder builder) { builder.addHttpListener(this.port, undertowConf.getHost()) .setWorkerThreads(undertowConf.getWorkerThreads()).setIoThreads(undertowConf.getIoThreads()) .setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, undertowConf.isAllowUnescapedCharactersInUrl()) .setServerOption(UndertowOptions.ENABLE_HTTP2, undertowConf.isHttp2enabled()); }
Example 12
Source File: ServerFactory.java From seed with Mozilla Public License 2.0 | 4 votes |
private Undertow.Builder configureHttp(Undertow.Builder builder) { LOGGER.info("Undertow listening for HTTP on {}:{}", serverConfig.getHost(), serverConfig.getPort()); return builder.addHttpListener(serverConfig.getPort(), serverConfig.getHost()); }
Example 13
Source File: UndertowAdapter.java From enkan with Eclipse Public License 1.0 | 4 votes |
private void setOptions(Undertow.Builder builder, OptionMap options) { if (options.containsKey("ioThreads")) builder.setIoThreads(options.getInt("ioThreads")); if (options.containsKey("workerThreads")) builder.setWorkerThreads(options.getInt("workerThreads")); if (options.containsKey("bufferSize")) builder.setBufferSize(options.getInt("bufferSize")); if (options.containsKey("directBuffers")) builder.setDirectBuffers(options.getBoolean("directBuffers")); }
Example 14
Source File: UndertowAdapter.java From enkan with Eclipse Public License 1.0 | 4 votes |
public Undertow runUndertow(WebApplication application, OptionMap options) { Undertow.Builder builder = Undertow.builder(); builder.setHandler(new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HttpRequest request = new DefaultHttpRequest(); request.setRequestMethod(exchange.getRequestMethod().toString()); request.setUri(exchange.getRequestURI()); request.setProtocol(exchange.getProtocol().toString()); request.setQueryString(exchange.getQueryString()); request.setCharacterEncoding(exchange.getRequestCharset()); request.setBody(new ChannelInputStream(exchange.getRequestChannel())); request.setContentLength(exchange.getRequestContentLength()); request.setRemoteAddr(exchange.getSourceAddress() .getAddress() .getHostAddress()); request.setScheme(exchange.getRequestScheme()); request.setServerName(exchange.getHostName()); request.setServerPort(exchange.getHostPort()); Headers headers = Headers.empty(); exchange.getRequestHeaders().forEach(e -> { String headerName = e.getHeaderName().toString(); e.forEach(v -> headers.put(headerName, v)); }); request.setHeaders(headers); try { HttpResponse response = application.handle(request); exchange.setStatusCode(response.getStatus()); setResponseHeaders(response.getHeaders(), exchange); exchange.startBlocking(); setBody(exchange.getResponseSender(), response.getBody()); } catch (ServiceUnavailableException ex) { exchange.setStatusCode(503); } finally { exchange.endExchange(); } } }); setOptions(builder, options); if (options.getBoolean("http?", true)) { builder.addHttpListener(options.getInt("port", 80), options.getString("host", "0.0.0.0")); } if (options.getBoolean("ssl?", false)) { builder.addHttpsListener(options.getInt("sslPort", 443), options.getString("host", "0.0.0.0"), createSslContext(options)); } Undertow undertow = builder.build(); undertow.start(); return undertow; }
Example 15
Source File: Server.java From light-4j with Apache License 2.0 | 4 votes |
static private boolean bind(HttpHandler handler, int port) { ServerConfig serverConfig = getServerConfig(); try { Undertow.Builder builder = Undertow.builder(); if (serverConfig.enableHttps) { port = port < 0 ? serverConfig.getHttpsPort() : port; sslContext = createSSLContext(); builder.addHttpsListener(port, serverConfig.getIp(), sslContext); } else if (serverConfig.enableHttp) { port = port < 0 ? serverConfig.getHttpPort() : port; builder.addHttpListener(port, serverConfig.getIp()); } else { throw new RuntimeException( "Unable to start the server as both http and https are disabled in server.yml"); } if (serverConfig.enableHttp2) { builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true); } if (serverConfig.isEnableTwoWayTls()) { builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, SslClientAuthMode.REQUIRED); } // set and validate server options serverOptionInit(); server = builder.setBufferSize(serverConfig.getBufferSize()).setIoThreads(serverConfig.getIoThreads()) // above seems slightly faster in some configurations .setSocketOption(Options.BACKLOG, serverConfig.getBacklog()) .setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false) // don't send a keep-alive header for // HTTP/1.1 requests, as it is not required .setServerOption(UndertowOptions.ALWAYS_SET_DATE, serverConfig.isAlwaysSetDate()) .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, false) .setServerOption(UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, serverConfig.isAllowUnescapedCharactersInUrl()) // This is to overcome a bug in JDK 11.0.1, 11.0.2. For more info https://issues.jboss.org/browse/UNDERTOW-1422 .setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of("TLSv1.2")) .setHandler(Handlers.header(handler, Headers.SERVER_STRING, serverConfig.getServerString())).setWorkerThreads(serverConfig.getWorkerThreads()).build(); server.start(); System.out.println("HOST IP " + System.getenv(STATUS_HOST_IP)); } catch (Exception e) { if (!serverConfig.dynamicPort || usedPorts.size() >= (serverConfig.maxPort - serverConfig.minPort)) { String triedPortsMessage = serverConfig.dynamicPort ? serverConfig.minPort + " to " + (serverConfig.maxPort) : port + ""; String errMessage = "No ports available to bind to. Tried: " + triedPortsMessage; System.out.println(errMessage); logger.error(errMessage); throw new RuntimeException(errMessage, e); } System.out.println("Failed to bind to port " + port + ". Trying " + ++port); if (logger.isInfoEnabled()) logger.info("Failed to bind to port " + port + ". Trying " + ++port); return false; } // application level service registry. only be used without docker container. if (serverConfig.enableRegistry) { // assuming that registry is defined in service.json, otherwise won't start the server. serviceUrls = new ArrayList<>(); serviceUrls.add(register(serverConfig.getServiceId(), port)); // check if any serviceIds from startup hook that need to be registered. if(serviceIds.size() > 0) { for(String id: serviceIds) { serviceUrls.add(register(id, port)); } } // start heart beat if registry is enabled SwitcherUtil.setSwitcherValue(Constants.REGISTRY_HEARTBEAT_SWITCHER, true); if (logger.isInfoEnabled()) logger.info("Registry heart beat switcher is on"); } if (serverConfig.enableHttp) { System.out.println("Http Server started on ip:" + serverConfig.getIp() + " Port:" + port); if (logger.isInfoEnabled()) logger.info("Http Server started on ip:" + serverConfig.getIp() + " Port:" + port); } else { System.out.println("Http port disabled."); if (logger.isInfoEnabled()) logger.info("Http port disabled."); } if (serverConfig.enableHttps) { System.out.println("Https Server started on ip:" + serverConfig.getIp() + " Port:" + port); if (logger.isInfoEnabled()) logger.info("Https Server started on ip:" + serverConfig.getIp() + " Port:" + port); } else { System.out.println("Https port disabled."); if (logger.isInfoEnabled()) logger.info("Https port disabled."); } return true; }
Example 16
Source File: SimpleServer.java From StubbornJava with MIT License | 4 votes |
public Undertow.Builder getUndertow() { return undertowBuilder; }
Example 17
Source File: SimpleServer.java From StubbornJava with MIT License | 4 votes |
private SimpleServer(Undertow.Builder undertow) { this.undertowBuilder = undertow; }
Example 18
Source File: SimpleServer.java From StubbornJava with MIT License | 4 votes |
public Undertow.Builder getUndertow() { return undertowBuilder; }
Example 19
Source File: UndertowRpcServer.java From aion with MIT License | 4 votes |
@Override public void start() { try { Undertow.Builder undertowBuilder = Undertow.builder(); if (sslEnabled) undertowBuilder.addHttpsListener(port, hostName, sslContext()); else undertowBuilder.addHttpListener(port, hostName); int effectiveIoThreadCount; if (getIoPoolSize().isPresent()) { LOG.info( "<rpc-server - setting io thread count manually not recommended. recommended io thread pool size: {}>", Math.max(Runtime.getRuntime().availableProcessors(), 2)); undertowBuilder.setIoThreads(getIoPoolSize().get()); effectiveIoThreadCount = getIoPoolSize().get(); } else { /** this number comes from {@link io.undertow.Undertow.Builder#Builder()} */ effectiveIoThreadCount = Math.max(Runtime.getRuntime().availableProcessors(), 2); } /** * used to "remember" Undertow worker-thread count, since no getter exposed in {@link * Undertow}. */ int effectiveWorkerThreadCount; if (getWorkerPoolSize().isPresent()) { LOG.info( "<rpc-server - setting worker thread count manually not recommended. recommended worker thread pool size: {}>", Math.max(Runtime.getRuntime().availableProcessors(), 2) * 8); undertowBuilder.setWorkerThreads(getWorkerPoolSize().get()); effectiveWorkerThreadCount = getWorkerPoolSize().get(); } else { /** this number comes from {@link io.undertow.Undertow.Builder#Builder()} */ effectiveWorkerThreadCount = Math.max(Runtime.getRuntime().availableProcessors(), 2) * 8; } StuckThreadDetectorConfiguration stuckThreadDetector = new StuckThreadDetectorConfiguration(false, STUCK_THREAD_TIMEOUT_SECONDS); if (stuckThreadDetectorEnabled) { stuckThreadDetector = new StuckThreadDetectorConfiguration(true, STUCK_THREAD_TIMEOUT_SECONDS); } RequestLimitingConfiguration requestLimiting = new RequestLimitingConfiguration(false, -1, 1); boolean isQueueBounded = getRequestQueueSize().isPresent() && getRequestQueueSize().get() > 0; if (isQueueBounded) { requestLimiting = new RequestLimitingConfiguration( true, effectiveWorkerThreadCount, getRequestQueueSize().get()); } AionUndertowRpcHandler rpcHandler = new AionUndertowRpcHandler(corsEnabled, CORS_HEADERS, rpcProcessor); undertowBuilder.setHandler( new AionUndertowRootHandler(rpcHandler, requestLimiting, stuckThreadDetector)); server = undertowBuilder.build(); server.start(); LOG.info( "<rpc-server - (UNDERTOW) started on {}://{}:{}>", sslEnabled ? "https" : "http", hostName, port); LOG.debug("----------------------------------------"); LOG.debug("UNDERTOW RPC Server Started with Options"); LOG.debug("----------------------------------------"); LOG.debug( "SSL: {}", sslEnabled ? "Enabled; Certificate = " + sslCertCanonicalPath : "Not Enabled"); LOG.debug( "CORS: {}", corsEnabled ? "Enabled; Allowed Origins = \"" + corsOrigin + "\"" : "Not Enabled"); LOG.debug("Worker Thread Count: {}", effectiveWorkerThreadCount); LOG.debug("I/O Thread Count: {}", effectiveIoThreadCount); LOG.debug( "Request Queue Size: {}", isQueueBounded ? getRequestQueueSize().get() : "Unbounded"); LOG.debug("----------------------------------------"); } catch (Exception e) { LOG.error("<rpc-server - failed bind on {}:{}>", hostName, port); LOG.error("<rpc-server - " + e.getMessage() + ">"); System.exit(SystemExitCodes.INITIALIZATION_ERROR); } }
Example 20
Source File: UndertowLogbackAccessInstaller.java From logback-access-spring-boot-starter with Apache License 2.0 | 2 votes |
/** * Enables recording the request start time. * * @param builder the Undertow builder. */ private void enableRecordingRequestStartTime(Undertow.Builder builder) { builder.setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true); }