Java Code Examples for io.undertow.Undertow#start()

The following examples show how to use io.undertow.Undertow#start() . 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: UndertowUtil.java    From StubbornJava with 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 2
Source File: Application.java    From skywalking with 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 3
Source File: UndertowUtil.java    From StubbornJava with 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 4
Source File: IndexController.java    From leafserver with 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 5
Source File: UndertowStartFilter.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(ApplicationExchange application, LauncherFilterChain filterChain) {

    int port = application.getServerPort();

    ClassLoader classLoader = new LaunchedURLClassLoader(application.getClassPathUrls(), deduceParentClassLoader());

    DeploymentInfo servletBuilder = Servlets.deployment()
                   .setClassLoader(classLoader)
                   .setContextPath(application.getContextPath())
                   .setDeploymentName(application.getApplication().getPath());

    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
 
    manager.deploy();

    Undertow server = null;
    try {
        server = Undertow.builder()
                .addHttpListener(port, "localhost")
                .setHandler(manager.start()).build();
        server.start();
    } catch (ServletException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 6
Source File: SymjaServer.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public static void main(final String[] args) {
	ToggleFeature.COMPILE = false;
	Config.FUZZY_PARSER = true;
	Config.UNPROTECT_ALLOWED = false;
	Config.USE_MANIPULATE_JS = true;
	Config.JAS_NO_THREADS = false;
	// Config.THREAD_FACTORY = com.google.appengine.api.ThreadManager.currentRequestThreadFactory();
	Config.MATHML_TRIG_LOWERCASE = false;
	Config.MAX_AST_SIZE = ((int) Short.MAX_VALUE) * 8;
	Config.MAX_OUTPUT_SIZE = Short.MAX_VALUE;
	Config.MAX_BIT_LENGTH = ((int) Short.MAX_VALUE) * 8;
	Config.MAX_INPUT_LEAVES = 100L;
	Config.MAX_MATRIX_DIMENSION_SIZE = 100;
	EvalEngine.get().setPackageMode(true);
	F.initSymbols(null, null, false);// new SymbolObserver(), false);
	FuzzyParserFactory.initialize();

	final APIHandler apiHandler = new APIHandler();

	PathHandler path = new PathHandler()
			.addPrefixPath("/",
					resource(new ClassPathResourceManager(SymjaServer.class.getClassLoader(),
							SymjaServer.class.getPackage())).addWelcomeFiles("index.html"))
			.addExactPath("/api", apiHandler);

	Undertow server = Undertow.builder().//
			addHttpListener(8080, "localhost").//
			setHandler(path).//
			build();
	server.start();
	System.out.println("started");
}
 
Example 7
Source File: SimpleServer.java    From StubbornJava with MIT License 5 votes vote down vote up
public Undertow start() {
    Undertow undertow = undertowBuilder.build();
    undertow.start();
    /*
     *  Undertow logs this on debug but we generally set 3rd party
     *  default logger levels to info so we log it here. If it wasn't using the
     *  io.undertow context we could turn on just that logger but no big deal.
     */
    undertow.getListenerInfo()
            .stream()
            .forEach(listenerInfo -> logger.info(listenerInfo.toString()));
    return undertow;
}
 
Example 8
Source File: WebServer.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
public static void startServer(int port, boolean enableCors) throws Exception {
    final DeploymentInfo deployment = Servlets.deployment().setClassLoader(WebServer.class.getClassLoader());
    deployment.setContextPath("");
    deployment.setDeploymentName("membrane");
    deployment.addInitParameter("contextConfigLocation", "classpath:context/application-context.xml");
    deployment.setResourceManager(new FileResourceManager(new File("."), 0));
    deployment.addListener(Servlets.listener(ContextLoaderListener.class));
    deployment.addListener(Servlets.listener(RequestContextListener.class));
    deployment.addServlet(Servlets.servlet("dispatcher", DispatcherServlet.class).addMapping("/*")
            .addInitParam("contextConfigLocation", "classpath:context/dispatcher-servlet.xml"));
    deployment.addFilter(Servlets.filter(CharacterEncodingFilter.class).addInitParam("forceEncoding", "true")
            .addInitParam("encoding", "UTF-8"));

    final DeploymentManager manager = Servlets.defaultContainer().addDeployment(deployment);
    manager.deploy();

    final HttpHandler handler;
    if (enableCors) {
        CorsHandlers corsHandlers = new CorsHandlers();
        handler = corsHandlers.allowOrigin(manager.start());
    } else {
        handler = manager.start();
    }

    final Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0").setHandler(handler).build();
    server.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // graceful shutdown of everything
            server.stop();
            try {
                manager.stop();
            } catch (ServletException e) {
            }
            manager.undeploy();
        }
    });
}
 
Example 9
Source File: Main.java    From zooadmin with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DeploymentInfo servletBuilder = Servlets.deployment()
            .setContextPath("/")
            .setClassLoader(Main.class.getClassLoader())
            .setDeploymentName("zooadmin.war")
            ;
    Integer port= PropUtil.getInt("port");
    String host=PropUtil.getString("host");
    String resource=PropUtil.getString("resource");
    FilterInfo jfinalFilter=new FilterInfo("jfinal",JFinalFilter.class);
    jfinalFilter.addInitParam("configClass","com.baicai.core.Config");
    servletBuilder.addFilter(jfinalFilter);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.REQUEST);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.FORWARD);
    servletBuilder.setResourceManager(new FileResourceManager(new File(resource), 1024));


    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect("/"))
           .addPrefixPath("/", manager.start());
    Undertow server = Undertow.builder()
            .addHttpListener(port, host)
            .setHandler(path)
            .build();
    // start server
    server.start();
    log.info("http://"+host+":"+port);
}
 
Example 10
Source File: Application.java    From spring-reactive-sample with 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();
}
 
Example 11
Source File: DebugVisualizerServer.java    From greycat with 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 12
Source File: Server.java    From greycat with Apache License 2.0 5 votes vote down vote up
public Server() {
    Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0",
            Handlers.path()
                    .addPrefixPath("rpc", this)
                    .addPrefixPath("/", new ResourceHandler(new ClassPathResourceManager(Server.class.getClassLoader(), "static")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false))
    ).build();
    server.start();
    System.out.println("Server running at : 9077");
}
 
Example 13
Source File: SecureServer.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    final Map<String, char[]> users = new HashMap<>(2);
    users.put("root", "password".toCharArray());
    users.put("admin", "password".toCharArray());

    final IdentityManager idm = new CustomIdentityManager(users);

    Undertow server = Undertow.builder()
      .addHttpListener(8080, "localhost")
      .setHandler(addSecurity(SecureServer::setExchange, idm)).build();

    server.start();
}
 
Example 14
Source File: FileHandlerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws URISyntaxException {
    Path rootPath = Paths.get(FileHandlerTestCase.class.getResource("page.html").toURI()).getParent().getParent();
    HttpHandler root = new CanonicalPathHandler()
            .setNext(new PathHandler()
                    .addPrefixPath("/path", new ResourceHandler(new PathResourceManager(rootPath, 1))
                            // 1 byte = force transfer
                            .setDirectoryListingEnabled(true)));
    Undertow undertow = Undertow.builder()
            .addHttpListener(8888, "localhost")
            .setHandler(root)
            .build();
    undertow.start();
}
 
Example 15
Source File: Server.java    From griffin with Apache License 2.0 5 votes vote down vote up
/**
    * Creates and starts the server to serve the contents of OUTPUT_DIRECTORY on port
9090.
    */
   protected void startPreview() {
       ResourceHandler resourceHandler = resource(new PathResourceManager(Paths.get(OUTPUT_DIRECTORY), 100, true, true))
               .setDirectoryListingEnabled(false);
       FileErrorPageHandler errorHandler = new FileErrorPageHandler(Paths.get(OUTPUT_DIRECTORY).resolve("404.html"), StatusCodes.NOT_FOUND);
       errorHandler.setNext(resourceHandler);
       GracefulShutdownHandler shutdown = Handlers.gracefulShutdown(errorHandler);
       Undertow server = Undertow.builder().addHttpListener(port, "localhost")
               .setHandler(shutdown)
               .build();
       server.start();
   }
 
Example 16
Source File: Http2Server.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    String version = System.getProperty("java.version");
    System.out.println("Java version " + version);
    if(version.charAt(0) == '1' && Integer.parseInt(version.charAt(2) + "") < 8 ) {
        System.out.println("This example requires Java 1.8 or later");
        System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's");
        System.out.println("See section 9.2.2 of the HTTP2 specification for details");
        System.exit(1);
    }
    String bindAddress = System.getProperty("bind.address", "localhost");
    SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore"));
    Undertow server = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8080, bindAddress)
            .addHttpsListener(8443, bindAddress, sslContext)
            .setHandler(new SessionAttachmentHandler(new LearningPushHandler(100, -1, Handlers.header(predicate(secure(), resource(new PathResourceManager(Paths.get(System.getProperty("example.directory", System.getProperty("user.home"))), 100))
                    .setDirectoryListingEnabled(true), new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath());
                    exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                }
            }), "x-undertow-transport", ExchangeAttributes.transportProtocol())), new InMemorySessionManager("test"), new SessionCookieConfig())).build();

    server.start();

    SSLContext clientSslContext = createSSLContext(loadKeyStore("client.keystore"), loadKeyStore("client.truststore"));
    LoadBalancingProxyClient proxy = new LoadBalancingProxyClient()
            .addHost(new URI("https://localhost:8443"), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, clientSslContext), UndertowOptionMap.create(UndertowOptions.ENABLE_HTTP2, true))
            .setConnectionsPerThread(20);

    Undertow reverseProxy = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8081, bindAddress)
            .addHttpsListener(8444, bindAddress, sslContext)
            .setHandler(ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime( 30000).build())
            .build();
    reverseProxy.start();

}
 
Example 17
Source File: ServletServer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {
    try {

        DeploymentInfo servletBuilder = deployment()
                .setClassLoader(ServletServer.class.getClassLoader())
                .setContextPath(MYAPP)
                .setDeploymentName("test.war")
                .addServlets(
                        servlet("MessageServlet", MessageServlet.class)
                                .addInitParam("message", "Hello World")
                                .addMapping("/*"),
                        servlet("MyServlet", MessageServlet.class)
                                .addInitParam("message", "MyServlet")
                                .addMapping("/myservlet"));

        DeploymentManager manager = defaultContainer().addDeployment(servletBuilder);
        manager.deploy();

        HttpHandler servletHandler = manager.start();
        PathHandler path = Handlers.path(Handlers.redirect(MYAPP))
                .addPrefixPath(MYAPP, servletHandler);
        Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(path)
                .build();
        server.start();
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source File: FileServer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(final 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 19
Source File: UnderTowBench.java    From Voovan with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {
    String tmp="OK";
    Undertow server = Undertow.builder()
            .addHttpListener(8080, "localhost")
            .setHandler(new HttpHandler() {
                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                    exchange.getResponseHeaders().put(Headers.SERVER, "Voovan-WebServer/v4.0.0");
                    exchange.getResponseSender().send(tmp);
                }
            }).build();
    server.start();
}
 
Example 20
Source File: VisualizerServer.java    From greycat with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    if(args.length == 2) {
        try {
            serverPort = Integer.parseInt(args[0]);
        } catch (NumberFormatException ex) {
            System.err.println(ex.getMessage());
            printHelp();
            System.exit(2);
        }
        urltoConnect = args[1];
    } else if(args.length != 0) {
        printHelp();
        return;
    }


    Undertow server = Undertow.builder()
            .addHttpListener(serverPort,serverUrl)
            .setHandler(
                    Handlers.path(
                            Handlers.resource(new ClassPathResourceManager(VisualizerServer.class.getClassLoader()))
                    )
            )
            .build();


    server.start();

    StringBuilder goToBuilder = new StringBuilder();
    goToBuilder.append("http://")
            .append(serverUrl)
            .append(":")
            .append(serverPort);
    if(urltoConnect != null) {
        goToBuilder.append("?q=")
                .append(urltoConnect);
    }

    System.out.println("Go to: " + goToBuilder);

}