Scalatra Flashcards
Name the 5 CRUD HTTP Methods
POST PUT PATCH GET DELETE
When a user enters an address in the browsers location bar a ____ request is generated
Get
When should you use a GET
- When you are implementing a read-only operation such as the R in CRUD
- When the request can be submitted repeatedly.
- When the response should be bookmarkable or indexed in search engines.
The default method of a web form is ______ but __________________
POST
POST is not limited to web forms.
The request body may contain any arbitrary data, described by the Content-Type header of the request. Other common POST bodies include
JSON, XML and Images
Use POST in the following cases
- When implementing create operations, such as the C in CRUD
- When the server is responsible for generating a URI for the created entity
- When you’re implementing a write operation and nothing else seems to fit.
POST is a good default choice when writing because it is the only CRUD method that is not idempotent. What does this mean
A client should be able to resubmit a GET, DELETE or PUT request and expect the same result. A POST offers no such guarantee and is thus more flexible in its implementation.
Why do web browsers issue a a warning when POST request is resubmitted
A client should be able to resubmit a GET, DELETE or PUT request and expect the same result. A POST offers no such guarantee.
HTML forms only support (which methods?)
GET and POST
PUT requests are most similar to
POST
Use PUT requests when
When implementing update operations such as the U in CRUD
When implementing create operations such as the C in CRUD
Why is it important to follow the conventions with HTTP?
HTTP services are often consumed by clients that are not considered at the time of development.
Also Think of the case where developers implemented delete with simple hyperlinks.
A HEAD Request should be treated the same as a ______ request except that it should not return a ___________________________
GET
Body
If HTTP methods declare the type of action to be performed, then route matchers declare …
the resources on which the action is to be performed.
Name the three types of route matchers that are supported out of the box
Path expressions (string)
Regular expressions
Boolean expressions
The most common type of route matcher is
path expression
A path expression always starts with a
/
get {“/artists”} which is the route matcher
/artists
class RecordStore extends ScalatraServlet { get(“/artists”) {
Artist.getAll.map { artist =>
${artist.name} } } } which is the Action code?
Artist.getAll.map { artist =>
${artist.name} }
How would you parameterise a path expression
use a path parameter (declared by preceding it with a colon character
A path parameter is never …
At least ________ must be matched
an empty string
at least one character must be matched
A path parameter matches everything up to …
the next special character /,?, or #
The “/artists/?” expression would match a request to both of these
■ http://localhost:8080/artists
■ http://localhost:8080/artists/
In the literal URI, ? marks the beginning of
the query string
How is the use of ? different in the literal URI and in a path expression
in a path expression ? means that the preceding character is optional, in a literal URI the ? marks the beginning of a query string
get(“/artists/:name/info.?:format?)
what to the two ?s apply to?
the first ? makes the period optional the second applies to the format param
In this route, you use a single /downloads/* route to serve files under a virtual filesystem. You could have used /downloads/:name, but
ecall that named parameters match up until the next / char- acter in a URL. A splat parameter frees you from this restriction, so that you can match a path in an arbitrary directory structure.
A route matcher returns an
Option[Map[String, Seq[String]]
What does SCALA do to prevent null pointer expressions (NPE)
Uses an Option Type
How would you prevent an object of type String from returning an NPE.
declare it to have a type of Option[String]
what is “implicit”
a compile time decorator for doing type conversions
how does implicit work?
at compile time if there is a cast that the compiler would not know how to do it looks for an implicit function
If you want to use your custom converters across servlets, or if you have more than one of them, it might be a good idea to place them in a
trait
It is possible to run (or not run) filters based on fairly complex conditional code. For example, if you wanted to run a before filter for a specific route, but only on POST requests, you could do this:
before(“/hackers”, request.requestMethod == Post) {
DataBase.connect;
}
It’s possible to use ______________________ to conditionally run filters on your routes.
any boolean expression you can think of
Sometimes you’ll need to read headers off an incoming request. You can do this using :
request.getHeader()
HTTP-based applications can accept input in a variety of ways, including form parameters, path parameters, and query parameters. Scalatra reads all of these types of parameters from incoming requests using the ________ function, which is part of the Scalatra DSL.
params
The params function returns a _______ _____ containing all incoming parameters
Scala map
Map keys and values are all
strings
Scala’s Option type is one of the language’s key features. You can use it to
check your code at compile time, guarding against runtime errors.
What is the advantage of using the ActionResult function
They return the proper HTTP status code for a given situation, and give an English- language explanation of your intentions
Generally, if you intend to output JSON using Scalatra’s JSON support, your JSON routes should always return a value of type
JValue
You can think of a value of type JValue as the _______representation of a JSON document, often called its ___ ____ ____
abstract
abstract syntax tree AST
What are case classes?
plain and immutable data-holding objects that should exclusively depend on their constructor arguments.
Two optional response header fields can be useful when serving files:
Content- Disposition and Content-Description.
The Content-Disposition field contains
information about the processing of the file contained in the response
If the disposition type is set to inline
the document in the response should be displayed directly to the user
The current environment in which a Scalatra application runs can be read using the
environment method defined on ScalatraBase
The application environment is set through the
___________________________ key either as a system property or using the ____________________________
The application environment is set through the org.scalatra.environment key either as a system property or using the web.xml file, found at src/main/webapp/ WEB-INF/web.xml.
xsbt-web-plugin is an extension to __ that integrates a ____________ web application
sbt
servlet based
xsbt-web-plugin, in turn, consists of three other plugins:
WebappPlugin, Container- Plugin, and WarPlugin.
WebappPlugin integrates a _______________ in an sbt build.
web application layout
Following the servlet standard, the WEB-INF directory—which is not publicly accessible—contains
the web.xml deployment descriptor and the dependency JARs in WEB-INF/lib.
The _________________ task copies the web application resources from the web appli- cation’s source directory to the target directory.
webappPrepare
The sbt-less plugin is a generator that generates
CSS assets from Less asset sources. It’s enabled by default.
What is an asset pipeline
The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets
What does WAR stand for in .WAR file
A Web application archive
in sbt you’re dealing with two different scala versions
he one used by sbt for the build process (depending on the sbt version) and the one used to compile your code against (configured with e.g. scalaVersion := “2.11.4” above).
how do you know what scala version you are using
scala> util.Properties.versionNumberString
how do you determine the sbt version
sbt sbtVersion
where would you put the application.conf file
in the resources folder
REPL
Read Evaluate Print Loop
In Slick, a database table is described as a Table in Scala code. This allows it to
formulate statically typed queries against that table without having to write SQL.
The type parameter T is
the Scala type of the column
What does this do? def * = (id, name, location, longitude, latitude, description) <> (Area.tupled, Area.unapply)
Defines the default projection for queries to the table
TableQuery[E]
a Query on the table E using the table’s default projection
What happens when FutureSupport is mixed into your application
It enables asynchronous request processing
A join can be expressed either as an _______ join or as a ______ join.
applicative
monadic
There are Slick methods for each SQL join method:
join for cross or inner joins, and
leftJoin, rightJoin, and outerJoin.
The monadic join style
uses flatMap to construct joins.
Name 6 types of Functor
covariant contravariant exponential applicative monad comonad
Sessions are a core part of Scalatra, and you can start a session in one of several ways. The most explicit way to trigger a session is
mix Scalatra’s SessionSupport trait into one or more of your controllers
What does Flashmap support do
“flash” short amounts of information to a user between requests
The anatomy of any Scentry strategy is fairly simple. Strategies are just
Strategies are just regular Scala classes that inherit from ScentryStrategy.
Strategies must implement two methods
a way to retrieve a user for authentication purposes,
a way to authenticate that the user is who they say they are.
trait OurBasicAuthenticationSupport extends ScentrySupport[User]
with BasicAuthSupport[User] {
self: ScalatraBase => (what does this mean)
Any class that mixes in ourBasicAuthenticationSupport trait must inherit from ScalatraBase. In other words, this trait can only be mixed into Scalatra controllers.
covariant contravariant exponential applicative monad comonad
These are examples of what?
Functors
What is the name of the authentication module shipped with Scalatra
Scentry
Scentry triggers a
cookie based HTTP Session
As soon as you extends Scalatra’s SessionSupport you are
setting a cookie on every request
Scentry is ideally suited to
stateful authentication scenarios, where credentials are submitted at the beginning of a session as opposed to per request.
The pluggable design of Scentry makes it simple to support several authentication mechanisms, such as
- HTTP Basic
- HTML login forms,
- “remember-me” cookies.
Most other languages still rely on old-style concurrency management tools like
locks and threads
locks and threads can be extremely difficult to use because they are
non deterministic
What does non-deterministic mean
you can’t necessarily reproduce your threading bugs when you want, because they can be the result of multiple threads interacting in strange and horrifying ways.
How do you show the full stack trace inside the sbt stacktrace
last *:update
scala has a few different constructs for dealing with asynchronous tasks, name two of them
Actors
Futures
Adding FutureSupport means that you need to define an
ExecutionContext for your Futures to run in.
How do you add an ExecutionContext for your futures to run in?
Adding implicit def executor = ExecutionContext.global
here are quite a few different kinds of ExecutionContexts that you can choose from, each with differ- ent qualities. If in doubt, use
ExecutionContext.global
One thing to watch out for: never close a Future …
over mutable state
Where does the request variable live
Inside the servlet containers thread pool
Why does the request variable living inside the servlet container’s thread pool create a conundrum for a Future?
he request is in the servlet container, but everything inside the Future executes in a totally different thread pool.
What is a tuple
A tuple combines a fixed number of items together so that they can be passed around as a whole
Unlike an array or list, a tuple can
hold objects with different types but they are also immutable.