Monday, March 28, 2016

Programmatically get routes in Play! Framework 2.5.x

Leave a Comment

In the play-swagger module, we used the play.routes.compiler.RoutesFileParser to get all registered routes from Play and further parse them to an API documentation:

val parsedRoutes = RoutesFileParser.parse(new File(app.classloader.getResource(routesFile).toURI)) val routes = parsedRoutes.right.get.collect {   case (route: PlayRoute) => {     logger.debug(s"Adding route '$route'")     Seq(route.copy(path = route.path.copy(parts = StaticPart(prefix + "/") +: route.path.parts)))   }   case (include: PlayInclude) => {     logger.debug(s"Processing route include $include")     parseRoutesHelper(playRoutesClassNameToFileName(include.router), include.prefix)   } }.flatten 

This results in the following error: java.lang.NoClassDefFoundError: play/routes/compiler/RoutesFileParser

It seems that the RoutesFileParser became private in Play! 2.5.

What is the correct way to fetch all Play routes like in the example above?

2 Answers

Answers 1

This is definitely a dependency problem. Check the dependencyTree.

If it's not already there, then add the following to the build file:

"com.typesafe.play" %% "routes-compiler" % "2.5.0" 

Then this will compile and run nicely:

val routesURI = app.classloader.getResource("routes").toURI val parsedRoutes = play.routes.compiler.RoutesFileParser.parse(new File(routesURI)) println(parsedRoutes) 

(where app is a running instance of play.api.Application)

Answers 2

When looking through the sourcecode of Play, I found that I can use the following:

class HomeController @Inject() (router: Provider[Router]) { ....     router.get().documentation.foreach(println) .... } 

This will print out String tuples with HTTP method, path, method invocation. This is how the routes on the DEV 404 page are rendered.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment