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 freelance developer and also does corporate training. He can be reached at nagappan08@gmail.com

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


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


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


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


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


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


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


MailHog - Web and API based SMTP testing

  • smtp-testing testing-tool smtp test automation email-server email

Most of the projects will have a requirement of sending and receiving mails. We have mentioned about GreenMail - Email Test Framework, in our previous article about API based SMTP testing. In this article, we discuss about MailHog - Web and API based SMTP testing. You send out a mail from your code and you can check it via web visually and also via API. Those who do API testing can check via API. Developers may want to visually verify the format of the mail. MailHog is a best bet for SMTP testing.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More


Ngnix - High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy

  • load-balancer proxy-server web-server

Nginx is a High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy server. It can also be used as mail proxy server and a generic TCP/UDP proxy server. Nginx claims to be more efficient and faster in the Web space compared to the other web servers. This can be evident with the architecture which is based on asynchronous event-driven approach. The event driven architecture enables to scale to hundreds / thousands of concurrent connections.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


An introduction to web cache proxy server - nuster

  • web-cache proxy-server load-balancer

Nuster is a simple yet powerful web caching proxy server based on HAProxy. It is 100% compatible with HAProxy, and takes full advantage of the ACL functionality of HAProxy to provide fine-grained caching policy based on the content of request, response or server status. This article gives an overview of nuster - web cache proxy server, its installation and few examples of how to use it.

Read More


mkcert - No config certificate authority tool

  • certificate ssl security cert go go-lang

Mkcert is go-lang project, which is super easy tool to setup certificate authority without any configuration. Using certificates are inevitable these days, data should be transferred in a secure communication channel. Buying a certificate is expensive and mostly companies buy certificates only for production systems. In Dev setup, if we use self-signed certificate then there will be trust errors. mkcert automatically creates and installs a local CA in the system root store, and generates locally-trusted certificates.

Read More


Web based commenting system. Embed directly in to your site

  • comment free commenting-system

Comments are very important for a blog or website to get feedback from their users. Comments could be threaded where users could be discuss and post reply to the comment. Here we going discuss about the most popular and widely used free commenting system. You need to embed their javascript code in your every page and it will take care the rest of the task.

Read More


Holistic usage guide for OpenSSL

  • openssl security certificate tools

OpenSSL is a general purpose cryptographty toolkit that provides an open source implementation of Transport Layer Security(TLS) and Secure Socket Layer(SSL) protocols. It is written in C,assembly and Perl language but wrappers are available in all languages. This article explains about OpenSSL commands.

Read More


Restrict Solr Admin Access

  • solr searchengine tips

Solr is a search engine built on top of Lucene. It supports REST interface and has lot of built-in capabilities. Solr package has Admin UI interface which has support to perform query and even delete the contents of the index. If you are using Solr in production then you may need to restrict access. I saw couple of questions in the group related to this topic. Thought to write an article explaining few tips to restrict the user access to Solr admin UI.

Read More