Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Integrating It All


[ 344 ]

Map event(@PathVariable String game,
@PathVariable String event,
@RequestParam Map params ) {
def session = null
if (params.sessionId)
session = sessionRepo.findBySessionId(params.sessionId)

def client = engineService.getEngineInstance(this, game)
def state = client."${event}"(params, session?.cache)

if ( session) {
session.cache = state
} else {
session = new GameSession(
sessionId: session.sessionId, cache: state)
}

sessionRepo.save( session)
session.cache
}
}

Events can arrive asynchronously to the server and we need to be able to maintain
the game state for a player between requests. The event detects if a session already
exists and creates one if it does not. It then uses GameEngineService to get a game
engine client instance to which it delegates the event handling. The latest values for
the state are returned by the DSL handler and saved. Finally, the update state is sent
back as part of the response body. Let's see how all this works.


Controller annotations

This controller has a single action method for event. The @RequestMapping
annotation tells Spring to map any two-part URL requests to the event controller
method. The two @PathVariable annotations on the method parameters for game
and event ensure that the first part of the URL is passed to the action as the game
parameter, and the second as the event. So the URL http://localhost:8080/
tictactoe/play_round will be mapped to a call to GameEngineController with
the statements, game = 'tictactoe' and event = 'play_round'.


We can control how single parameter values are passed with a @RequestParam
annotation. Using the @RequestParam string foo would allow us to map the request
parameter foo to a named method parameter. When we declare @RequestParam as
a map, as is the previous case, all the request parameters are marshaled into a single
parameter called params.


http://www.ebook3000.com
Free download pdf