Scalatra in Action

by Dave Hrycyszyn, Stefan Ollinger, Ross A.

Scalatra in Action Summary

Publisher : Manning Publications

Author : Dave Hrycyszyn, Stefan Ollinger, Ross A. Baker

ISBN : 9781617291296

Year : 2016

Language: en

File Size : 3.84 MB

Category : Computers Technology

MANNING

Dave Hrycyszyn
Stefan Ollinger
Ross A. Baker

Scalatra in Action

DAVE HRYCYSZYN
STEFAN OLLINGER
ROSS A. BAKER

MANNING
Shelter Island

For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: [email protected]
©2016 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15 percent recycled and processed without the use of elemental
chlorine.

Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964

Development editor:
Technical development editor:
Copyeditor:
Proofreader:
Technical proofreader:
Typesetter:
Cover designer:

ISBN 9781617291296
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16

Karen Miller
Barry Polley
Andy Carroll
Katie Tennant
Andy Hicks
Gordan Salinovic
Marija Tudor

brief contents
PART 1

PART 2

PART 3

INTRODUCTION TO SCALATRA .............................................1
1



Introduction

3

2



A taste of Scalatra

3



Routing 28

4



Working with user input 49

12

COMMON DEVELOPMENT TASKS .........................................71
5



Handling JSON

73

6



Handling files

7



Server-side templating

8



Testing

9



Configuration, build, and deployment

10



Working with a database

94
104

116
130

154

ADVANCED TOPICS ........................................................169
11
12
13





Authentication 171
Asynchronous programming 197
Creating a RESTful JSON API with Swagger 211
iii

contents
preface xi
acknowledgments xiii
about this book xv
about the cover illustration

xviii

PART 1 INTRODUCTION TO SCALATRA ...................................1

1

Introduction 3
1.1

What’s Scalatra good at?

4

1.2

Hello World 4

1.3

Microframeworks vs. full-stack frameworks

1.4

How does Scalatra compare with other Scala web
frameworks? 6
Scalatra is a lean MVC framework
servlets 7

1.5

Installing Scalatra

6



5

Scalatra runs on

7

Generating a new project 8 Downloading dependencies and
building the app 9 Starting the Hello World application 9
Making changes and seeing them in your browser 10




1.6

Summary

11

v

vi

CONTENTS

2

A taste of Scalatra 12
2.1

Your first Scalatra application

2.2

Designing the UI

2.3

What’s in a Scalatra project?

2.4

Building the data model

2.5

Retrieving pages

13
14

16

17

A page-retrieval route 17

2.6

Rendering the page

A page-retrieval action



Writing tests

20



Adding a layout

21

23

Writing your first test 23
another test 25

3

18

20

A quick introduction to Scalate

2.7

12

Running your tests 25



2.8

Getting ready for deployment

2.9

Summary



Adding

26

27

Routing 28
3.1

Anatomy of a route

29

3.2

Choosing the right method 29
The CRUD methods 29 The lesser-known methods 34
Overriding the methods 36


3.3

Route matchers

38

Path expressions 38
expressions 45

3.4



4

43



Boolean

Advanced route matching 46
Conflict resolution 46

3.5

Regular expressions

Summary



Rails-style path expressions 47

48

Working with user input

49

4.1

The life of a request 49

4.2

Routes and actions

4.3

HTTP parameter handling in Scalatra

50
50

Query string parameters 51 Path parameters 52 Form
parameters 52 Params versus multiParams 54 Dealing
with unexpected input 55 Typed parameters 59










4.4

Filters

63

Selectively running filters 65



Filter conditions 65

vii

CONTENTS

4.5

Other kinds of user input 66
Request headers 66

4.6

Request helpers
Halting

4.7

67

Summary

Cookies



66

67

Redirecting 68





ActionResult

68

69

PART 2 COMMON DEVELOPMENT TASKS................................71

5

Handling JSON
5.1

73

Introducing JsonSupport 73
Adding JSON support to an application
JValue type 75

5.2

Producing and consuming JSON
Producing JSON 79

5.3



74



Introducing the

77

Consuming JSON 81

Customizing JSON support and handling mismatches

84

Customizing JSON support and using field serializers 84
Handling polymorphism with type hints 87 Handling
heterogeneity with custom serializers 89


6

5.4

JSONP 92

5.5

Summary

93

Handling files 94
6.1

Serving files

95

Serving files through a route 95 Serving static resources
Applying gzip compression to responses 98


6.2

Receiving files

98

98

Supporting file uploads 99 Configuring the upload
support 101 Handling upload errors 103




6.3

7

Summary

103

Server-side templating 104
7.1

Deciding whether server-side templating is right for you 104
Websites

7.2

105



Web APIs

Introducing Scalate

106

107

Installing Scalate in a Scalatra app
structure 108

107



Scalate directory

viii

CONTENTS

7.3

Serving content with the Scalate template system
Your first Scaml template 109 Layouts 110
template 112 A comparison of dialects 113




108

Invoking your



7.4

Serving content with Twirl 113
Configuring your project

7.5

8

Summary

113



Using Twirl

114

115

Testing 116
8.1

Integration testing with Specs2

116

Getting started with Specs2 117 Asserting over the entire
response 120 Testing as JValues 121 Running your
tests 122




8.2



Unit testing with Specs2

123

Testing with stubbed dependencies
into a servlet 125

8.3

124

9

Injecting dependencies

Testing with ScalaTest 127
Setting up Scalatra’s ScalaTest 127
Running ScalaTest tests 129

8.4



Summary



Your first ScalaTest 128

129

Configuration, build, and deployment 130
9.1

9.2

Configuring a Scalatra application

131

Working with application environments
application configuration 132

131

Building a Scalatra application



Using a type-safe

136

A Scalatra application as an sbt project 136 Working with the
xsbt-web-plugin 139 Using sbt-web to simplify working with web
assets 140 Precompiling Scalate templates with the scalategenerator plugin 143






9.3

Deploying as a web archive

144

9.4

Deploying as a standalone distribution 145
Embedding a servlet container in an application 145
distribution package 146

9.5

Running Scalatra as a Docker container 148

9.6

Summary

153



Building a

ix

CONTENTS

10

Working with a database 154
10.1
10.2

Working with a relational database and example scenario
Integrating Slick and working with a DBIO action 156

10.3
10.4

Defining table models and working with a TableQuery
Using the query language 163

154

159

Defining queries 163 Defining joins 166 Using update and delete
statements 166 Organizing queries as extension methods 167






10.5

Summary

168

PART 3 ADVANCED TOPICS...............................................169

11

Authentication

171

11.1

A new, improved Hacker Tracker

11.2

An introduction to Scentry

174

Session handling in Scalatra

11.3

172

174



Scentry setup

175

Protecting routes with HTTP Basic authentication

175

The simplest possible Scentry strategy 175 A basic auth
strategy 176 A basic authentication support trait 178
Protecting the DatabaseSetupController 180




11.4

Using forms authentication

181

Creating a simple login form 181 Building a
UserPasswordStrategy 182 Creating an AuthenticationSupport
trait 184 Protecting your controllers with AuthenticationSupport 185
Deciding whether to run a strategy 187 Logging out 188








11.5

A fallback Remember Me cookie strategy
Building the RememberMeStrategy class

11.6

12

Summary

192

196

Asynchronous programming 197
12.1

Exploring concurrency in Scalatra

12.2

Using Futures in Scalatra

12.3

Using Akka Actors from Scalatra

12.4

Using Scalatra for big data

12.5

Summary

210

198

200
207

203

191


Scentry callbacks 193

x

CONTENTS

13

Creating a RESTful JSON API with Swagger 211
13.1

An API for the Hacker Tracker

13.2

Adding an API controller 212

212

Returning Hacker JSON from the ApiController
to remove duplication 218

13.3

Self-documenting APIs using Swagger

214



Refactoring

220

Swagger—what is it? 220 Swaggerize the application 223
Documenting the routes 225 Cross-origin API security and
Swagger UI 231




13.4

Securing your API

232

HMAC—what is it? 232 An HMAC calculator in Scala
Protecting the API with a trait 234


13.5
appendix

Summary

237

Installation and development setup
index

253

239

233

preface
Most web frameworks have a lot of assumptions built into them. When you’re building
whatever the framework designers envisaged, they work very well. But if you need to
depart from their happy paths, all that prescriptiveness starts to work against you.
Full-stack web frameworks with server-side rendering, using a relational database
are common, and in the past I used them all the time. But over time, I progressively
departed from using their standard components.
I began to build web APIs and microservices, often using nonrelational data stores,
asynchronous requests, and server-push technologies. I was installing more dependencies to layer extra functionality on top of already large and complex frameworks. Simple tasks were difficult, because I was fighting against the basic assumptions of the
frameworks I was using.
Then I discovered Scalatra. The language was unfamiliar at first, but the friendly
community and incredibly simple HTTP DSL made it easy to get started.
Suddenly I was working in the environment I always wanted. The Scala language
gave me all the speed and correctness benefits of static typing without the Java or C#
boilerplate, a simple and productive language syntax akin to Ruby or Python, and
access to a wealth of high-quality libraries.
Scalatra, with its minimalistic style, does one thing well: it makes HTTP actions trivially easy to express. Beyond that, it gets out of your way. This makes it easy to pick and
choose from tens of thousands of Java and Scala libraries to build exactly the application you need.

xi

xii

PREFACE

We wrote this book to bring this minimal style of application development to a
wider audience. The web’s not new technology any more, and if the history of computing tells us anything, it’s that common tasks get simpler over time.
The modern internet wouldn’t be much fun if people sent input using punched
cards and had to wait several hours to get their output back, as though it were the 1960s.
We think that the acrobatics coders go through to quickly set up high-performance
HTTP interfaces to their programs are similarly outdated. It’s not 1996 anymore. HTTP
can be easy.
Scalatra is one of the easiest ways to build a web application. This book will show
you pretty much the entirety of the framework in the first four chapters. The other
nine chapters explain how to integrate with other interesting components, customize
the framework, and deploy your applications. Because really, it’s not about us: it’s
about you, your ambitions, and the next thing you want to make.
DAVE HRYCYSZYN

acknowledgments
We’d like to collectively thank everyone at Manning, especially Karen Miller, Michael
Stephens, Ozren Harlovic, Rebecca Rinehart, Candace Gillhooley, and Ana Romac.
And thanks to Christina Rudloff, who helped us get started.
We’d also like to thank our technical editor, Barry Polley, and our technical proofreader, Andy Hicks. Their help was invaluable. The MEAP reviewers provided great
feedback: Brian Hanafee, Jeff Condal, Chuck Daniels, Christian Horsdal, Ronald
Tischliar, M. Marc-Philippe Huget, Ramsés Morales, Craig Aspinall, Helmuth Breitenfellner, Adam Slysz, Alain Couniot, Carlos Aya, Emre Kucukayvaz, Charles Feduke,
Alberto Quario, Scott Dierbeck, Dimitrios Liapis, and Dr. Dan Klose.
Dave: I want to thank Tanya Gouthro, Bettina Wittneben, and Katrin Hellermann,
who encouraged me to go for it. Thanks also to employers and friends past and present, including Dave Else, Pete Boyle, Rebecca Simmonds, and Ramsey Khoury, who
set me up to experiment with weird technologies as part of my job. And I thank my
parents, Bill and Carol, who stimulated my career in tech by encouraging me to mess
with computers, guns, exploration, and music (happily not all at the same time).
Ross: I’d like to thank Jim Plush, who reached out from California all the way to
Indiana and gave me the opportunity to turn my hobby into a part of my daily job.
Also thanks to my wife, Brooke, and children, Will and Cara, who let me continue to
write about and work on my hobby after hours on said job.
Stefan: I thank my friends and family for their support—especially my parents,
Edwin and Irmgard, as well as my sister, Patricia. Also thanks to the University of Trier

xiii

xiv

ACKNOWLEDGMENTS

for a good learning environment. Big thanks to the Scala community for the continuous evolution of the language and the ecosystem.
The whole Scalatra core crew has been incredibly supportive and helpful, especially Ivan Porto Carrero. Early contributions and enthusiasm from Ivan, Jared Armstrong, and Mikko Nylen were part of the mix that got the book off the ground.
Thanks, guys!
Lastly, thanks from all of us to everyone who contributes code to framework, and
to everyone who uses Scalatra. We hope you enjoy it as much as we do.

© 2018-2019 uberlabel.com. All rights reserved