io.undertow.Undertow Java Examples

The following examples show how to use io.undertow.Undertow. 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 Project: wildfly-samples   Author: arun-gupta   File: AnnotatedWebSocketServer.java    License: MIT License 7 votes vote down vote up
public AnnotatedWebSocketServer() throws IOException {
    final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader());
    final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap());

    WebSocketDeploymentInfo websocket = new WebSocketDeploymentInfo()
            .addEndpoint(MyAnnotatedEndpoint.class)
            .setWorker(xnioWorker);

    DeploymentInfo deploymentInfo = deployment()
            .setClassLoader(MyAnnotatedEndpoint.class.getClassLoader())
            .setContextPath("/myapp")
            .setDeploymentName("websockets")
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, websocket);

    manager = defaultContainer().addDeployment(deploymentInfo);
    manager.deploy();
}
 
Example #2
Source Project: e-commerce-microservice   Author: xebialabs   File: WebConfigurerTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testCustomizeServletContainer() {
    env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
    assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
    assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    if (container.getDocumentRoot() != null) {
        assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
    }

    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
 
Example #3
Source Project: Jax-RS-Performance-Comparison   Author: smallnest   File: Main.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        String host = "0.0.0.0";
        int port = 8080;
        if (args.length > 0) {
            host = args[0];
        }
        if (args.length > 1) {
            port = Integer.parseInt(args[1]);
        }

        Undertow.Builder builder = Undertow.builder().addHttpListener(port, host);
        server = new UndertowJaxrsServer().start(builder);
        server.deploy(MyApplication.class, "/");

//        DeploymentInfo di = server.undertowDeployment(MyApplication.class);
//        di.setContextPath("/rest");
//        di.setDeploymentName("rest");
//        server.deploy(di);

    }
 
Example #4
Source Project: light-rest-4j   Author: networknt   File: ResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");
        TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
        HttpHandler handler = Handlers.routing()
                .add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #5
Source Project: quarkus-http   Author: quarkusio   File: DefaultServer.java    License: Apache License 2.0 6 votes vote down vote up
private static void runInternal(final RunNotifier notifier) {
    if (openssl && OPENSSL_FAILURE != null) {
        throw new RuntimeException(OPENSSL_FAILURE);
    }
    if (first) {
        first = false;
        undertow = Undertow.builder()
                .setHandler(rootHandler)
                .addHttpListener(getHostPort(DEFAULT), getHostAddress(DEFAULT))
                .build();
        undertow.start();
        notifier.addListener(new RunListener() {
            @Override
            public void testRunFinished(Result result) throws Exception {
                super.testRunFinished(result);
                undertow.stop();
                clientGroup.shutdownGracefully();
            }
        });
    }
}
 
Example #6
Source Project: quarkus-http   Author: quarkusio   File: DefaultServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Start the SSL server using the default settings.
     * <p/>
     * The default settings initialise a server with a key for 'localhost' and a trust store containing the certificate of a
     * single client, the client authentication mode is set to 'REQUESTED' to optionally allow progression to CLIENT-CERT
     * authentication.
     */
    public static void startSSLServer() throws IOException {
        getClientSSLContext();
        sslUndertow = Undertow.builder()
                .setWorker(undertow.getWorker())
                .setHandler(rootHandler)
                .addListener(new Undertow.ListenerBuilder().setType(Undertow.ListenerType.HTTPS)
                        .setPort(getHostSSLPort(DEFAULT))
                        .setHost(getHostAddress())
                        .setKeyStore(SERVER_KEY_STORE)
                        .setKeyStorePassword(STORE_PASSWORD)
                        .setTrustStore(SERVER_TRUST_STORE)
                        .setTrustStorePassword(STORE_PASSWORD)).build();
        sslUndertow.start();

//        startSSLServer(serverContext, OptionMap.create(Options.SSL_CLIENT_AUTH_MODE, SslClientAuthMode.REQUESTED, Options.SSL_ENABLED_PROTOCOLS, Sequence.of("TLSv1.2")));
    }
 
Example #7
Source Project: StubbornJava   Author: StubbornJava   File: HelloWorldServer.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
    int port = 8080;
    /*
     *  "localhost" will ONLY listen on local host.
     *  If you want the server reachable from the outside you need to set "0.0.0.0"
     */
    String host = "localhost";

    /*
     * This web server has a single handler with no routing.
     * ALL urls are handled by the helloWorldHandler.
     */
    Undertow server = Undertow.builder()
        // Add the helloWorldHandler as a method reference.
        .addHttpListener(port, host, HelloWorldServer::helloWorldHandler)
        .build();
    logger.debug("starting on http://" + host + ":" + port);
    server.start();
}
 
Example #8
Source Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");

        HttpHandler handler = getPetStoreHandler();
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        SwaggerHandler swaggerHandler = new SwaggerHandler();
        swaggerHandler.setNext(handler);
        handler = swaggerHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #9
Source Project: wildfly-samples   Author: arun-gupta   File: SimpleServletServer.java    License: MIT License 6 votes vote down vote up
public SimpleServletServer() {
    DeploymentInfo deploymentInfo = deployment()
            .setClassLoader(SimpleServletServer.class.getClassLoader())
            .setContextPath("/helloworld")
            .setDeploymentName("helloworld.war")
            .addServlets(
                    Servlets.servlet("MyServlet", MyServlet.class)
                        .addInitParam("message", "Hello World")
                        .addMapping("/MyServlet"),
                    Servlets.servlet("MyAnotherServlet", MyAnotherServlet.class)
                        .addMapping("/MyAnotherServlet")
            );

    DeploymentManager manager = defaultContainer().addDeployment(deploymentInfo);
    manager.deploy ();
    try {
        server = Undertow.builder()
                .addListener(8080, "localhost")
                .setHandler(manager.start())
                .build();
    } catch (ServletException ex) {
        Logger.getLogger(SimpleServletServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #10
Source Project: light-4j   Author: networknt   File: DerefMiddlewareHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() {
    if(server == null) {
        logger.info("starting server");
        HttpHandler handler = getTestHandler();
        DerefMiddlewareHandler derefHandler = new DerefMiddlewareHandler();
        derefHandler.setNext(handler);
        handler = derefHandler;

        server = Undertow.builder()
                .addHttpListener(8887, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }

    if(oauth == null) {
        logger.info("starting oauth mock server");
        oauth = Undertow.builder()
                .addHttpListener(6753, "localhost")
                .setHandler(getOAuthHandler())
                .build();
        oauth.start();
    }

}
 
Example #11
Source Project: hawkular-apm   Author: hawkular   File: AbstractBaseHttpITest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() {
    server = Undertow.builder()
            .addHttpListener(8180, "localhost")
            .setHandler(path().addPrefixPath("sayHello", new HttpHandler() {
                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    if (!exchange.getRequestHeaders().contains("test-fault")) {
                        if (!exchange.getRequestHeaders().contains("test-no-data")) {
                            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                            exchange.getResponseSender().send(HELLO_WORLD);
                        }
                    } else {
                        exchange.setResponseCode(401);
                    }
                }
            })).build();

    server.start();
}
 
Example #12
Source Project: brave   Author: openzipkin   File: HttpServerBenchmarks.java    License: Apache License 2.0 6 votes vote down vote up
protected int initServer() throws Exception {
  DeploymentInfo servletBuilder = Servlets.deployment()
    .setClassLoader(getClass().getClassLoader())
    .setContextPath("/")
    .setDeploymentName("test.war");

  init(servletBuilder);

  DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
  manager.deploy();
  server = Undertow.builder()
    .addHttpListener(0, "127.0.0.1")
    .setHandler(manager.start()).build();
  server.start();
  return ((InetSocketAddress) server.getListenerInfo().get(0).getAddress()).getPort();
}
 
Example #13
Source Project: light-rest-4j   Author: networknt   File: JwtVerifyHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() {
    if(server == null) {
        logger.info("starting server");
        HttpHandler handler = getTestHandler();
        JwtVerifyHandler jwtVerifyHandler = new JwtVerifyHandler();
        jwtVerifyHandler.setNext(handler);
        SwaggerHandler swaggerHandler = new SwaggerHandler();
        swaggerHandler.setNext(jwtVerifyHandler);
        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(swaggerHandler)
                .build();
        server.start();
    }
}
 
Example #14
Source Project: oxygen   Author: justlive1   File: UndertowWebServer.java    License: Apache License 2.0 6 votes vote down vote up
@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 #15
Source Project: leafserver   Author: Yaccc   File: IndexController.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    Undertow server = Undertow.builder()
            .addHttpListener(9999, "localhost").setHandler(new PathHandler() {
                {
                    addExactPath("/id", exchange -> {
                        Map<String, Deque<String>> pathParameters = exchange.getQueryParameters();
                        Result result = sequenceCore.nextValue(pathParameters.get("app").getFirst(), pathParameters.get("key").getFirst());
                        exchange.getResponseSender().send(JSON.toJSONString(result));
                    });
                }

            })
            .build();
    server.start();
}
 
Example #16
Source Project: StubbornJava   Author: StubbornJava   File: UndertowUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 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 #17
Source Project: jweb-cms   Author: chifei   File: UndertowApp.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void start() {
    super.configure();
    container = new UndertowHttpContainer(this);
    container.getApplicationHandler().onStartup(container);

    UndertowOptions undertowOptions = options("undertow", UndertowOptions.class);
    this.undertow = Undertow.builder()
        .addHttpListener(undertowOptions.port, undertowOptions.host)
        .setServerOption(io.undertow.UndertowOptions.MAX_ENTITY_SIZE, undertowOptions.maxEntitySize)
        .setServerOption(io.undertow.UndertowOptions.MULTIPART_MAX_ENTITY_SIZE, undertowOptions.maxEntitySize)
        .setHandler(path()
            .addPrefixPath("/", new UndertowIOHandler(this, container)))
        .build();
    logger.info("server started, host={}, port={}", undertowOptions.host, undertowOptions.port);
    Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
    this.undertow.start();
}
 
Example #18
Source Project: light-4j   Author: networknt   File: ServerBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public Undertow build() {
    HttpHandler handler = HandlerBuilder.build();

    SanitizerHandler sanitizerHandler = new SanitizerHandler(configName);
    sanitizerHandler.setNext(handler);
    handler = sanitizerHandler;

    BodyHandler bodyHandler = new BodyHandler();
    bodyHandler.setNext(handler);
    handler = bodyHandler;

    instance = null;

    return Undertow.builder()
            .addHttpListener(8080, "localhost")
            .setHandler(handler)
            .build();
}
 
Example #19
Source Project: skywalking   Author: apache   File: Application.java    License: Apache License 2.0 6 votes vote down vote up
private static void undertow() {
    Undertow server = Undertow.builder().addHttpListener(8080, "0.0.0.0").setHandler(exchange -> {
        if (CASE_URL.equals(exchange.getRequestPath())) {
            exchange.dispatch(() -> {
                try {
                    visit("http://localhost:8081/undertow-routing-scenario/case/undertow?send=httpHandler");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseSender().send("Success");
    }).build();
    Runtime.getRuntime().addShutdownHook(new Thread(server::stop));
    server.start();
}
 
Example #20
Source Project: divolte-collector   Author: divolte   File: MappingTestServer.java    License: Apache License 2.0 5 votes vote down vote up
public MappingTestServer(final String schemaFilename, final String mappingFilename, final int port, final String host) throws IOException {
    final Schema schema = loadSchema(schemaFilename);
    final ValidatedConfiguration vc = new ValidatedConfiguration(ConfigFactory::load);
    mapper = new DslRecordMapper(vc, mappingFilename, schema, Optional.ofNullable(lookupServiceFromConfig(vc)));

    final HttpHandler handler = new AllowedMethodsHandler(this::handleEvent, Methods.POST);
    final HttpHandler rootHandler = new ProxyAdjacentPeerAddressHandler(handler);
    undertow = Undertow.builder()
            .addHttpListener(port, host)
            .setHandler(rootHandler)
            .build();
}
 
Example #21
Source Project: StubbornJava   Author: StubbornJava   File: SimpleServer.java    License: MIT License 5 votes vote down vote up
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 #22
Source Project: tutorials   Author: eugenp   File: FileServer.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
      .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100))
        .setDirectoryListingEnabled(true))
      .build();
    server.start();
}
 
Example #23
Source Project: spring-reactive-sample   Author: hantsy   File: Application.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Bean
public Undertow undertowServer(ApplicationContext context) {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();  // (2)

    // Undertow
    UndertowHttpHandlerAdapter undertowAdapter = new UndertowHttpHandlerAdapter(handler);
    Undertow server = Undertow.builder()
        .addHttpListener(port, "localhost")
        .setHandler(undertowAdapter)
        .build();

    return server;
}
 
Example #24
Source Project: quarkus-http   Author: quarkusio   File: ProgramaticAutobahnServer.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {

        try {

            final ServletContainer container = ServletContainer.Factory.newInstance();
            DeploymentInfo builder = new DeploymentInfo()
                    .setClassLoader(ProgramaticAutobahnServer.class.getClassLoader())
                    .setContextPath("/")
                    .setClassIntrospecter(TestClassIntrospector.INSTANCE)
                    .setDeploymentName("servletContext.war")
                    .addFilter(new FilterInfo("filter", JsrWebSocketFilter.class))
                    .addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST)

                    .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                            new WebSocketDeploymentInfo()
                                    .setDispatchToWorkerThread(true)
                                    .addEndpoint(new ServerEndpointConfigImpl(ProgramaticAutobahnEndpoint.class, "/"))
                    );

            DeploymentManager manager = container.addDeployment(builder);
            manager.deploy();


            Undertow.builder().addHttpListener(port, "localhost")
                    .setHandler(manager.start())
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
Example #25
Source Project: quarkus-http   Author: quarkusio   File: AnnotatedAutobahnServer.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {


        try {
            final ServletContainer container = ServletContainer.Factory.newInstance();

            DeploymentInfo builder = new DeploymentInfo()
                    .setClassLoader(AnnotatedAutobahnServer.class.getClassLoader())
                    .setContextPath("/")
                    .setClassIntrospecter(TestClassIntrospector.INSTANCE)
                    .setDeploymentName("servletContext.war")
                    .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                            new WebSocketDeploymentInfo()
                                    .addEndpoint(AutobahnAnnotatedEndpoint.class)
                                    .setDispatchToWorkerThread(true)
                    )
                    .addFilter(new FilterInfo("filter", JsrWebSocketFilter.class))
                    .addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST);

            DeploymentManager manager = container.addDeployment(builder);
            manager.deploy();

            Undertow.builder().addHttpListener(port, "localhost")
                    .setHandler(manager.start())
                    .build();

        } catch (Exception e) {
            log.error("failed to start server", e);
        }
    }
 
Example #26
Source Project: wildfly-samples   Author: arun-gupta   File: AnnotatedWebSocketServer.java    License: MIT License 5 votes vote down vote up
public void start() throws ServletException {
    server = Undertow.builder()
            .addListener(8080, "localhost")
            .setHandler(manager.start())
            .build();
    server.start();
}
 
Example #27
Source Project: jbang   Author: jbangdev   File: undertow.java    License: MIT License 5 votes vote down vote up
public static void main(String args[]) {
  var server = Undertow.builder().addHttpListener(8080, "localhost").setHandler((exchange) -> {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
    exchange.getResponseSender().send("Hello World");
  }).build();

  server.start();
}
 
Example #28
Source Project: tutorials   Author: eugenp   File: SocketServer.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
            .setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> {
                channel.getReceiveSetter().set(getListener());
                channel.resumeReceives();
            })).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(),
                    SocketServer.class.getPackage())).addWelcomeFiles("index.html")))
            .build();

    server.start();
}
 
Example #29
Source Project: greycat   Author: datathings   File: DebugVisualizerServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String urltoConnect = "ws://localhost:5678";
        final String serverUrl = "0.0.0.0";
        final int serverPort = 8080;

        Undertow server = Undertow.builder()
                .addHttpListener(serverPort,serverUrl)
                .setHandler(
                        Handlers.path(
                                Handlers.resource(
                                        new PathResourceManager(Paths.get("plugins/visualizer/src/main/resources").toAbsolutePath(),0)
                                )
                        )
                )
                .build();


        server.start();

        StringBuilder goToBuilder = new StringBuilder();
        goToBuilder.append("http://")
                .append(serverUrl)
                .append(":")
                .append(serverPort)
                .append("?q=")
                .append(urltoConnect);
        System.out.println("Go to: " + goToBuilder);


        System.out.println();

    }
 
Example #30
Source Project: spring-reactive-sample   Author: hantsy   File: Application.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);  // (1)
    Undertow server = context.getBean(Undertow.class);
    server.start();
    System.out.println("Press ENTER to exit.");
    System.in.read();
}