Firstly, create a folder for application and build an appropriate project structure:
Next, configure your pom.xml file. We will need the following dependencies: datakernel-http,
datakernel-boot and some logger (Note: we don’t need to specify eventloop, because it already
is a transitive dependency of both datakernel-boot and datakernel-http modules).
So your pom.xml should look like following:
Now lets create simple hello world launcher.
In example above we see how to create simple launcher and execute it.
Don’t mind getModules right now, we will come back to it later.
Firstly we create our launcher. You can override these methods:
onStart will be executed first.
run is your application main method, all logic must be in it.
finally onStop method is executed.
Next we launching our launcher, by passing args and EagerSingletonMode constant, which is passed to Guice.
Now let’s move to something more complex, we will build echo http server from scratch.
In code above you can see, that getModules is used to provide Modules with dependencies.
What is going on:
ServiceGraphModule will start components of your application in the right order.
ConfigModule will provide Config to your components.
SimpleModule will provide AsyncHttpServer and since it needs Eventloop and AsyncServlet as dependencies we providing them too.
run method just awaits shutdown of application(Keyboard Interruption, for example).
main method launches our application.
Setting up simple HTTP server is a common task, so Datakernel provides you with few predefined launchers to make your life easier.
Let’s take a look how simple it would be if we use HttpServerLauncher:
When you are using predefined launchers you need to override these methods:
getBusinessLogicModules to specify actual logic of application.
getOverrideModules if you want to override default modules.
In example above we are overriding default port with our own and providing servlet that will handle each connection.
That’s it. Lets test our code.
The next will be http servers:
If you now try to connect to localhost port 25565 using your browser or curl you will see “Hello from HTTP server” string