Table of contents
1.
Introduction
2.
Embedding an Akka Http server in your application
2.1.
Logging configuration
3.
Embedding a Netty server in your application
3.1.
Logging configuration
4.
Frequently Asked Questions
4.1.
What is the use of the Play framework?
4.2.
Is Play Framework MVC?
4.3.
Which server is used as an embedded play server? 
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Scala developers-Embedding Play

Author Nagendra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Scala developer is an expert in developing, building, and maintaining Scala-based applications. Additionally, they perform software analysis, write code per app specifications, and work with the software development team to validate application designs.

This article explains the details of Embedding Play in Scala developers along with the details of Embedding an Akka Http server and Embedding a Netty server in your application.

Without further ado, let's get started.

Play Image

Embedding an Akka Http server in your application

You can embed a Play server within your own existing application, even though Play apps are most frequently utilised as their own containers. The Twirl template compiler and the Play routes compiler can be used in conjunction with this, but they are not required. An application with just a few straightforward routes is a typical use case. You must meet the following requirement in order to utilise Akka HTTP Server embedded:

Code:

libraryDependencies ++= Seq(
  akkaHttpServer
)
You can also try this code with Online Java Compiler
Run Code

 

The factory methods of the AkkaHttpServer object can be used to launch a Play Akka HTTP server. You might choose to utilise the String Interpolating Routing DSL in conjunction with the fromRouterWithComponents method if all you need to do is supply a few simple routes:

Code:

import play.api.mvc._
import play.api.routing.sird._
import play.core.server.AkkaHttpServer

val server = AkkaHttpServer.fromRouterWithComponents() { components =>
  import Results._
  import components.{ defaultActionBuilder => Action }
  {
    case GET(p"/hello/$to") =>
      Action {
        Ok(s"Hello $to")
      }
  }
}
You can also try this code with Online Java Compiler
Run Code


By default, a server in prod mode will be started on port 9000. A ServerConfig can be used to configure the server.

Code:

import play.api.mvc._
import play.api.routing.sird._
import play.core.server.AkkaHttpServer
import play.core.server._


val server = AkkaHttpServer.fromRouterWithComponents(
  ServerConfig(
    port = Some(19000),
    address = "127.0.0.1"
  )
) { components =>
  import Results._
  import components.{ defaultActionBuilder => Action }
  {
    case GET(p"/hello/$to") =>
      Action {
        Ok(s"Hello $to")
      }
  }
}
You can also try this code with Online Java Compiler
Run Code

 

In addition, Play offers component qualities that make it simple to customise components other than the router. For this purpose, the AkkaHttpServerComponents trait is offered, and it may be easily used with BuiltInComponents to create the necessary application. The equivalent of AkkaHttpServerComponents with BuiltInComponents and NoHttpFiltersComponents in this example is DefaultAkkaHttpServerComponents:

Code:

import play.api.http.DefaultHttpErrorHandler
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import play.core.server.DefaultAkkaHttpServerComponents


import scala.concurrent.Future


val components = new DefaultAkkaHttpServerComponents {
  override lazy val router: Router = Router.from {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }


  override lazy val httpErrorHandler = new DefaultHttpErrorHandler(
    environment,
    configuration,
    devContext.map(_.sourceMapper),
    Some(router)
  ) {
    protected override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
      Future.successful(Results.NotFound("Nothing was found!"))
    }
  }
}
val server = components.server
You can also try this code with Online Java Compiler
Run Code

 

In this case, a router is the only technique you need to use. The default implementation of anything else can be changed by overriding specific methods, like in the case of the aforementioned httpErrorHandler. By altering the serverConfig property, the server configuration can be changed.

Once you've started the server, just call the stop method to end it.

Code:

server.stop()
You can also try this code with Online Java Compiler
Run Code

 

Another approach is to use GuiceApplicationBuilder and the fromApplication function to construct a Play Application:

Code:

import play.api.mvc._
import play.api.routing.sird._
import play.core.server.AkkaHttpServer
import play.core.server.ServerConfig
import play.filters.HttpFiltersComponents
import play.api.Environment
import play.api.ApplicationLoader
import play.api.BuiltInComponentsFromContext


val context = ApplicationLoader.Context.create(Environment.simple())
val components = new BuiltInComponentsFromContext(context) with HttpFiltersComponents {
  override def router: Router = Router.from {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }
}


val server = AkkaHttpServer.fromApplication(
  components.application,
  ServerConfig(
    port = Some(19000),
    address = "127.0.0.1"
  )
)
You can also try this code with Online Java Compiler
Run Code

Logging configuration

There are no logging dependencies added by default when using Akka HTTP as an embedded server. The Play logback module can be added to the embedded program if you also want to include logging:

Code:

libraryDependencies ++= Seq(
  logback
)
You can also try this code with Online Java Compiler
Run Code

 

Calling the LoggerConfigurator API later

Code:

import play.api.mvc._
import play.api.routing.sird._
import play.filters.HttpFiltersComponents
import play.core.server.AkkaHttpServer
import play.core.server.ServerConfig
import play.api.Environment
import play.api.ApplicationLoader
import play.api.LoggerConfigurator
import play.api.BuiltInComponentsFromContext


val context = ApplicationLoader.Context.create(Environment.simple())
// Do the logging configuration
LoggerConfigurator(context.environment.classLoader).foreach {
  _.configure(context.environment, context.initialConfiguration, Map.empty)
}


val components = new BuiltInComponentsFromContext(context) with HttpFiltersComponents {
  override def router: Router = Router.from {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }
}


val server = AkkaHttpServer.fromApplication(
  components.application,
  ServerConfig(
    port = Some(19000),
    address = "127.0.0.1"
  )
)
You can also try this code with Online Java Compiler
Run Code

 

 Let's look at the details of embedding a Netty server in your application.

Embedding a Netty server in your application

You can embed a Play server within your own existing application, even though Play apps are most frequently utilised as their own containers. The Twirl template compiler and the Play routes compiler can be used in conjunction with this, but they are not required. An application with just a few straightforward routes is a typical use case. You must the following requirement in order to use Netty Server embedded:

Code:

libraryDependencies ++= Seq(
  nettyServer
)
You can also try this code with Online Java Compiler
Run Code

 

Using the NettyServer factory methods is one option for starting a Play Netty Server. You might choose to utilise the String Interpolating Routing DSL in conjunction with the fromRouterWithComponents method if all you need to do is supply a few simple routes:

Code:

import play.api.mvc._
import play.api.routing.sird._
import play.core.server._


val server = NettyServer.fromRouterWithComponents() { components =>
  import components.{ defaultActionBuilder => Action }
  {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }
}


By default, a server in prod mode will be started on port 9000. A ServerConfig can be used to configure the server.
Code:
import play.api.mvc._
import play.api.routing.sird._
import play.core.server._

val server = NettyServer.fromRouterWithComponents(
  ServerConfig(
    port = Some(19000),
    address = "127.0.0.1"
  )
) { components =>
  import components.{ defaultActionBuilder => Action }
  {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }
}
You can also try this code with Online Java Compiler
Run Code


In addition, Play offers component qualities that make it simple to customise components other than the router. For this purpose, the NettyServerComponents trait is offered, and it may be easily used with BuiltInComponents to create the necessary application. The NettyServerComponents with BuiltInComponents with NoHttpFiltersComponents counterpart, DefaultNettyServerComponents, is used in this example:

Code:

import play.api.http.DefaultHttpErrorHandler
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import play.core.server._


import scala.concurrent.Future


val components = new DefaultNettyServerComponents {
  lazy val router = Router.from {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }


  override lazy val httpErrorHandler =
    new DefaultHttpErrorHandler(environment, configuration, devContext.map(_.sourceMapper), Some(router)) {
      protected override def onNotFound(request: RequestHeader, message: String) = {
        Future.successful(Results.NotFound("Nothing was found!"))
      }
    }
}
val server = components.server
You can also try this code with Online Java Compiler
Run Code

 

In this case, a router is the only technique you need to use. The default implementation of anything else can be changed by overriding specific methods, like in the case of the aforementioned httpErrorHandler. By altering the serverConfig property, the server configuration can be changed.

Once you've started the server, just call the stop method to end it.

Code:

server.stop()

Logging configuration

No logging dependencies are added by default when using Netty as an embedded server. The Play logback module can be added to the embedded program if you also want to include logging:

Code:

libraryDependencies ++= Seq(
  logback
)
You can also try this code with Online Java Compiler
Run Code


Calling the LoggerConfigurator API later

Code:

import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import play.api._
import play.core.server._


val environment = Environment.simple(mode = Mode.Prod)
val context = ApplicationLoader.Context.create(environment)


// Do the logging configuration
LoggerConfigurator(context.environment.classLoader).foreach {
  _.configure(context.environment, context.initialConfiguration, Map.empty)
}


val components = new DefaultNettyServerComponents {
  override def router: Router = Router.from {
    case GET(p"/hello/$to") =>
      Action {
        Results.Ok(s"Hello $to")
      }
  }
}

val server = components.server
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions

What is the use of the Play framework?

Scala & Java developers may create web applications quickly and easily with Play Framework. Play's architecture is lightweight, stateless, and suitable for the web. Play, which is based on Akka, gives highly scalable applications predictable and low resource consumption (CPU, memory, threads).

Is Play Framework MVC?

Yes, the Open-source web application framework Play Framework uses the model-view-controller (MVC) design principle.

Which server is used as an embedded play server? 

The NettyServer is used to embed a play server.

Conclusion

In this article, we have extensively discussed the details of Embedding Play in Scala developers, along with the details of Embedding an Akka Http server and Embedding a Netty server in your application.

We hope that this blog has helped you enhance your knowledge regarding the Twirl template engine, and if you would like to learn more, check out our articles on Play. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow. Happy Coding!!

Thank You Image
Live masterclass