Getting Started on Undertow Server

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.
 
Undertow source code is available in github. It can either downloaded and configure the server manually. Other easy option would be directly embedded into the project using the maven dependency as below. Undertow recent version can be checked in github releases page.
 <dependency>
        <groupId>io.undertow</groupId>
        <artifactId>undertow-core</artifactId>
        <version>${undertow.version}</version>
 </dependency>
 <dependency>
        <groupId>io.undertow</groupId>
        <artifactId>undertow-servlet</artifactId>
        <version>${undertow.version}</version>
 </dependency>
 <dependency>
        <groupId>io.undertow</groupId>
        <artifactId>undertow-websockets-jsr</artifactId>
        <version>${undertow.version}</version>
 </dependency
 
It has three components
 
  1. undertow-core: Undertow core, which provides support for non blocking handlers and web sockets
  2. undertow-servlet: Support for Servlet 3.1
  3. undertow-websockets-jsr: for the Java API for Websockets (JSR-356) standard
 
Bootstrapping Undertow
 
Undertow can be started using io.undertow.Undertow builder API. It doesn't have any global container it just assemble the handlers and start the server. Undertow applications has to manage the lifecycle of handlers and resource utitlized by the handlers.
 
public class HelloWorldServer {

    public static void main(final String[] args) {
        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/html");
                        StringBuilder output = new StringBuilder("<h1>Checking Status Undertow</h1>");
                        output.append("<h3 style='color:green'>I am up and running at port 8080!!!</h3>");
                        exchange.getResponseSender().send(output.toString());
                    }
                }).build();
        server.start();
    }
}
 
Undertow server can be instantiated with builder having hostname, port number and handler details. In the HttpHandler, using HttpServerExchange parameter to get the response object. In this case, we are sending status of the server in html format in the response sender.
 
Undertow bootstrap within milliseconds (log for reference) whereas other microservice frameworks takes seconds to start.
 
Mar 12, 2019 3:38:10 AM org.xnio.Xnio <clinit>
INFO: XNIO version 3.3.8.Final
Mar 12, 2019 3:38:10 AM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.3.8.Final
 
Architecture Overview
 
An undertow server is basically composed of three things like XNIO Worker Instance, one or more connectors and handler chain to handle the incoming requests.  XNIO Worker is based on the Jboss XNIO project which is simplified low-level I/O layer built on top java nio library. Connectors are tied to XNIO worker with listeners for HTTP/1.1, HTTPS, AJP will generally do all IO operations. After connection, XNIO invokes the HttpOpenListener which creates the server connection(HttpServerConnection) to hold the state associated with the connection. Then, it invokes HttpReadListener which is responsible for parsing the request, they will create HttpServerExchange object populated with request data and then hand it to handler chain.
 
Root handler chain will be invoked by the connector where built in handlers are available and also custom handler can be created and added.
 
File Server
 
Undertow is shipped with many built in handlers like access log handlers, allowed methods, request dumping handler and so on. Resource handler is for listing and finding the files as ftp server. Now we will add the base path for the directory listing using resource manager and it can be handled for exception like file not found.
 
 HttpHandler handle404Example = new HttpHandler() {
  @Override
  public void handleRequest(HttpServerExchange exchange) throws Exception {
   exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
   exchange.getResponseSender().send("File Not Found");
  }
 };


 ResourceHandler resourceHandler = new ResourceHandler(
                 new PathResourceManager(Paths.get(System.getProperty("user.home")), 100), handle404Example)
                 .setDirectoryListingEnabled(true);
 RequestDumpingHandler requestDumpingHandler = new RequestDumpingHandler(resourceHandler);
 Undertow server = Undertow.builder()
                 .addHttpListener(8080, "localhost")
                 .setHandler(path(Handlers.path()
                 .addPrefixPath("/", requestDumpingHandler)))
                 .build();
 server.start();
 
Now resourceHandler will list all the files from user home directory, if we try to hit the url with non existing files like http://localhost:8080/test, it will invoke the handle404Example which shows the content like "File not found".

Rest API
 
We can create rest api for retrieving and presisting the users with routing handler. Routing handler will invoke the handlers based on the api url and methods. In our case, we will route GET method of /users path to retrieve the users and POST method of /users path to save the data. Below example, will have class member holding all the "users", so post is adding and get is retrieving it from the users.
 
   RoutingHandler routes = new RoutingHandler().get("/users", new HttpHandler() {
           public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
                 httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                 httpServerExchange.getResponseSender().send(users.toString());
            }
    })
       .post("/users", new RequestDumpingHandler(new HttpHandler() {
            public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
                 FormParserFactory.Builder builder = FormParserFactory.builder();

                 final FormDataParser formDataParser = builder.build().createParser(httpServerExchange);

                if (formDataParser != null) {
                     FormData formData = formDataParser.parseBlocking();
                     Integer id = Integer.parseInt(formData.get("id").peek().getValue());
                     User user1 = new User(id, formData.get("name").peek().getValue());
                     formDataParser.close();
                     users.add(user1);
                     httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                     httpServerExchange.getResponseSender().send("added successfully");
               }

       }
   }));


  Undertow undertow = Undertow.builder()
                     .addHttpListener(8080, "localhost")
                     .setHandler(routes).build();
 
 undertow.start();
 
For invoking the POST request, send the data as x-www-form-url-encoded through postman(chrome browser app) with keys as id and name. Likewise the GET request,  http://localhost:8080/users will retrieve the data.

There are more working examples provided as part of undertow project. clone the project and inside the project there is a folder examples. Once the project is build, move to target folder and execute the jar, which shows all the  examples as below.

  $ java -jar undertow-examples.jar
     Welcome to the Undertow Examples
     Please select an example:
     a) Basic Authentication
     b) Chat
     c) File Serving
     d) HTTP2
     e) Hello World
     f) JSR Web Sockets
     g) ModCluster Proxy Server
     h) Reverse Proxy
     i) Server Sent Events
     j) Servlet
    k) Session Handling
    l) Web Socket Extensions
   m) Web Sockets
 
choose the one and execute to see how that works.

Reference:
 
 

Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More



ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More


RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More


Cache using Hazelcast InMemory Data Grid

  • hazelcast cache key-value

Hazelcast is an open source In-Memory Data Grid (IMDG). It provides elastically scalable distributed In-Memory computing, widely recognized as the fastest and most scalable approach to application performance.&nbsp;Hazelcast makes distributed computing simple by offering distributed implementations of many developer-friendly interfaces from Java such as Map, Queue, ExecutorService, Lock and JCache.

Read More


RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More


Thymeleaf - Text display, Iteration and Conditionals

  • thymeleaf template-engine web-programming java

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.

Read More


GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More


Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More


Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Appserver.io – The First Multithreaded Application Server for PHP written in PHP

  • appserver application-server php

What if you could reliably run PHP without Nginx or Apache, but also without relying on its internal server? What if you could do async operations in PHP with true multi threading, fully taking advantage of multi core processors without hacks or a jungle of callbacks? What if you had drag and drop installation support for your PHAR packaged web apps in an environment identical to its production counterpart? Welcome to appserver.io – the worlds first open source application server for PHP.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


Univention Corporate Server - An open source identity management system

  • ucs identity-management-system

Univention Corporate Server is an open source identity management system, an IT infrastructure and device management solution and an extensible platform with a store-like App Center that includes tested third party applications and further UCS components: This is what Univention combines in their main product Univention Corporate Server, a Debian GNU/Linux based enterprise distribution. This article provides you the overview of Univention Corporate Server, its feature and installation.

Read More


Solr vs Elastic Search

  • full-text-search search-engine lucene solr elastic-search

Solr and Elastic Search are built on top of Lucene. Both are open source and both have extra features which makes programmer life easy. This article explains the difference and the best situation to choose between them.

Read More


PrestaShop - A feature rich Open Source eCommerce solution

PrestaShop is an Open Source eCommerce Solution. It comes complete with over 310 features that have been carefully developed to assist business owners in increasing sales with virtually little effort. It is being used in more than 150,000 online stores.

Read More