Appendix. Installation and development setup

Installation

In order to run the code in this book, you need to set up your development machine with several components that will help you generate, build, and run Scalatra applications. This appendix will give you a quick start.

Installing JDK 7

Scalatra runs on the Java Virtual Machine (JVM), so you need a Java Development Kit (JDK). Many systems come with a JDK preinstalled; let’s check first to see whether you’ve got one. Run this in a DOS or Unix console:

java -version

This should give back the following:

java version "1.7.0_65"
Java(TM) SE Runtime Environment (build 1.7.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)

Also run this:

javac -version

You should see something like this:

javac 1.7.0_65

If both commands spew forth responses like those shown here, you’re all set. The key thing is the number 1.7 in the responses. If you see 1.6, your version of Java is too old, and you’ll need to upgrade.

Scalatra 2.4.0 requires Java 7 (a JVM version of 1.7). As of this writing, the Scala 2.11.x language has experimental support for Java 8 (JVM 1.8.x). This means Java 8 may work for you, but you probably shouldn’t depend on it in a production situation until Scala 2.12 is available. If you don’t already have a JDK, or if your version is too old, go here and follow the install instructions: http://docs.oracle.com/javase/7/docs/webnotes/install/index.html.

Now that you’ve got Java installed and working, you need to install some tools to generate code and build your application.

Installing conscript and giter8

Although it’s theoretically possible that you could open your favorite code editor and start working on your first Scalatra application, it would take you a long time to get all the files into place and lay them out with the proper structure. To simplify this process, most people use a tool called giter8.

Giter8, which depends on another tool called conscript, generates customized Scalatra projects for you. When you run giter8, it uses conscript to retrieve template files from GitHub, and it asks you several questions about your project—its name and version number, for example. Once you’ve answered these questions, giter8 injects your answers into the retrieved template code, and the result is a customized, buildable, runnable project skeleton on your machine. This is the recommended way of getting started with Scalatra.

Install conscript first by following the instructions for your platform at https://github.com/foundweekends/conscript. Conscript will install itself into your home directory, in a folder called bin. You’ll probably need to add this folder to your system’s PATH variable so you can run the conscript utility, cs.

Setting PATH on Windows

There are quite a few versions of Windows in use, and each version has a slightly different way of setting the PATH environment variable. Go to https://www.java.com/en/download/help/path.xml, and follow the instructions for the version of Windows you’re using.

In the PATH editing box, type a ; (semicolon) character at the end of it, and then enter the path to your new bin folder. On our system, it’s at C:UsersIEUserin. Once this is set, close and open your terminal. If you’ve entered your PATH correctly, you should now be able to type cs at the DOS prompt and see the output shown in figure A.1.

Figure A.1. Making sure conscript works on Windows

Setting PATH on Mac or Linux

Setting PATH on a Mac OS X or a Linux system is a fairly simple matter. If you’re on Linux, open the .bashrc file in your home directory. On Mac OS X, open the .bash_profile file in your home directory.

Add the following line at the end of the file: export PATH=$PATH:~/bin. Close and reopen any terminals you have open so that you pick up the new $PATH variable. Now, type cs at your command prompt, and you should see the output shown in figure A.2.

Figure A.2. Making sure conscript works on Mac or Linux

Installing giter8

Now that conscript is installed, you can proceed with installing giter8. This is much easier. Run the following command from a DOS or Unix terminal, and giter8 will be retrieved from GitHub:

cs foundweekends/giter8

Conscript will download the giter8 utility into the bin folder in your home directory and make it available as the command-line utility g8. To test that it works, run it. The output should be like that shown in figure A.3.

Figure A.3. Making sure giter8 works

With conscript and giter8 installed, you have everything you need to generate a Scalatra project. You’ll try it in the next section.

Generating your first Scalatra project

The Scalatra team maintains a giter8 template for a standard Scalatra project skeleton on GitHub. To generate your own project code from it, run the following code in your terminal:

g8 scalatra/scalatra-sbt

Giter8 will reach out to GitHub and download a full Scalatra application skeleton. It will then ask you a series of questions about your project. Answer as shown in figure A.4.

Figure A.4. Generating a Scalatra project

Each question customizes a specific aspect of your application:

  • organization is used for publishing. Most people use either their organization’s domain name (such as com.constructiveproof in our case) or the reverse of their GitHub username (for example, com.github.futurechimp).
  • package is the namespace you want to use for this particular application. Use something unique for each of your web apps.
  • name is the particular name for this application. Type it as a free-form sentence; giter8 will automatically turn it into a project name.
  • servlet_name is the name of the first servlet, or controller, that you want to generate.
  • version is the version number of your application. It starts at 0.1.0, and you can increment it in your build file as you do releases.
  • scala_version is the version of the Scala language you’d like to use.

If you don’t know the answers to some of the questions, press Enter to accept the default; you can always change the generated code later. When you’re finished answering, giter8 injects your answers into the templates it downloaded from the internet. The template files for any giter8 project are typically stored on GitHub. The ones you downloaded are found in the project https://github.com/scalatra/scalatra-sbt.g8.

Using conscript and giter8, you can generate a new project. Next, you need the build tool that lets you run your generated project.

Building your code with the simple build tool (sbt)

The simple build tool (sbt) is the standard build system for Scala projects. Like any software with the word simple or lightweight in it, sbt is complex. It has quite a few functions:

  • It automatically downloads and installs a full Scala installation, including a Scala compiler, on first use.
  • It builds your application.
  • It runs your automated tests.
  • It manages dependencies, rather like Maven, Ruby Gems, and Python Eggs do in other languages.
  • It can automate common tasks, as Ant and Rake do in other languages.

Scalatra conveniently bundles its own copy of sbt for use on Unix-style systems. This means that on Linux and Mac systems, you don’t necessarily need to install sbt, if all you’re using it for is Scalatra development. But if you want to do general non-Scalatra development in Scala, or if you’re on Windows, follow the installation instructions for your platform at http://scala-sbt.org to install sbt.

Let’s run your newly generated Scalatra project using sbt. To do so, cd into the top-level my-scalatra-web-app project by typing cd my-scalatra-web-app. Then type either ./sbt (Linux or Mac) or sbt (Windows) at the command prompt to start sbt. The first time you do this, you may as well go get a cup of coffee; sbt will download an entire Scala development environment, including the language, a compiler, and the Scala standard libraries, and then grab all the dependencies needed to run a Scalatra application. This can take a while, depending on the speed of your internet connection. At the end, you’ll see the > character, which is the sbt command prompt, as shown in figure A.5.

Figure A.5. Running Scalatra using sbt

Scalatra’s sbt setup packages a web server, so you can get to work right away. To run your new project, type the command jetty:start at the sbt prompt. You’ll see output something like that shown in figure A.6.

Figure A.6. Starting the Scalatra app in a web server

sbt will start a web server and make your application available on port 8080. You can view your application by going to http://localhost:8080. To enable automatic code reloading, so the web server reloads itself to pick up changes whenever you save a file, use this command:

~jetty:start

You now have all the mandatory components installed, and you’ve seen how to generate and run a Scalatra application. If you were in the middle of chapter 1 and you’re eager to get busy constructing your application, you can go back there now. The rest of this appendix will guide you through the Scalatra project structure and give you a few tips on working with sbt, adding and removing project dependencies, and setting up Scalatra with your favorite IDE.

The structure of a Scalatra project

The structure of your new project will look like that shown in figure A.7. Let’s take a quick tour of the project.

Figure A.7. A Scalatra project’s structure

The project directory contains project-related files. The build.properties file specifies which version of sbt should be used to build the project. build.scala is the project’s build file, and it’s where you can configure all aspects of the build. This is one of the most important files in the entire application, and you’ll open it frequently when you want to add dependencies to or remove them from your project. The plugins .sbt file allows you to add sbt plugins to your project, extending the capabilities of sbt itself.

The src/main/scala directory is where you’ll do most of your application development work. By default, the giter8 template generates package directories for you, composed of your organization name and the package name you entered when you generated the project. There’s no reason to use packages like this if you don’t want to; you can, for instance, put all your Scala code in src/main/scala, and everything will build and run without any trouble.

The src/main/resources directory can contain any project-specific resource files that you need to build into your web application. Configuration files, I18N files, and any other files you want to bundle into your application go here.

The src/main/webapp directory is where your web resources live. Except for WEB-INF, all files and directories placed in webapp are served publicly. This is where you’ll typically keep any static HTML, CSS, and JavaScript needed to serve your application. The contents of the WEB-INF directory aren’t served; this is where Scalatra keeps the files for its web-templating system by default (see chapter 7 for details).

The src/main/test directory is where you keep your automated test code. The sbt file in the project root contains the sbt launcher, so you don’t need to install sbt globally on your system if you’re on Mac OS X or Linux.

With the overview out of the way, let’s zoom in and focus specifically on two files: we’ll look at dependency management in project/build.scala and also examine the ScalatraBootstrap init file.

Configuring your application with sbt

As mentioned, you can configure most aspects of your project’s build settings, including what dependencies it pulls in, using the configuration file at project/build.scala. This is an sbt configuration file.

One thing you may find confusing when you’re first using Scala is that sbt can have its configuration in two locations. Simple sbt projects typically have a build.sbt file in the project root; this file lets you configure your application with a limited subset of Scala. More-complex projects, including Scalatra, instead use the file at project/build.scala. This file is an actual Scala file, laid out in a specific structure, and it provides for more-complex configurations than build.sbt. It’s worth noting that you can use project/build.scala and build.sbt in the same sbt project, and settings in both will work.

Let’s turn our attention to dependency management in sbt. Scalatra depends on Java JAR files to make dependencies available. A JAR file is basically a zip file containing JVM bytecode, laid out in a specific structure.

When you want to make a new capability available to your Scalatra application, you add a new dependency listing to project/build.scala. sbt will then take care of downloading the JAR file for this dependency and making it available to your application. Let’s see how this works. Open project/build.scala; halfway through the file, you’ll see a series of lines like the following.

Listing A.1. Dependencies in sbt
"org.scalatra" %% "scalatra" % ScalatraVersion,

In the Java (and thus Scala) world, every library JAR has at least three pieces of information associated with it:

  • An organization, typically defined by its domain name
  • A name
  • A version number

Those are the pieces of information you see here. The organization name of this file is "org.scalatra", the library’s name is "scalatra", and the version number is ScalatraVersion (look further up the file, and you’ll see that it’s "2.4.0").

Any time you want to add a new dependency to your Scalatra application, you determine these three pieces of information and put them in the file. Any Scala library will list an sbt dependency line in this format.

You also have the entire world of Java libraries available to you. If you want to use a Java library, it may not have an sbt dependency line listed in its documentation. Your best bet is to go to http://search.maven.org and search for the library name. Clicking a library name and then clicking the Scala sbt link in the Dependency Information box on the left side of the window will display the sbt dependency line, as shown in figure A.8.

Figure A.8. sbt dependencies on search.maven.org

To add a dependency, add the dependency line to project/build.scala, adding a comma at the end of the line if it’s not the last line in the Seq. Then you can type the reload command at the sbt prompt, which will cause sbt to look for any new dependencies. Alternately, you can type the exit command to leave sbt; the dependency will become available the next time you run sbt. For more-detailed information on sbt project definitions, see chapter 9.

sbt tasks

When you run jetty:start to start your web server, you’re running an sbt command. It’s not the only one available; to see a list of available sbt tasks, run tasks. Other useful tasks include the following:

  • compile—Compiles without running the web server
  • jetty:stop—Stops the web server
  • reload—Reloads the sbt environment to pick up new dependencies
  • test—Runs your application’s tests
  • testQuick—Runs all tests that failed during the previous test run

Mounting servlets in ScalatraBootstrap

The default generated template contains only a single servlet, or controller (the terms are used interchangeably by many Scalatra developers). If you’ve generated a fresh project and specified ArticlesController as the default servlet when answering g8’s questions, the file src/main/scala/ScalatraBootstrap.scala will contain the following lines.

Listing A.2. ScalatraBootstrap with a single mounted controller

In a real application, it’s unlikely that you’ll have only a single controller—you may have dozens of them in a large application. If you add another controller, such as a CommentsController, you need to mount it in ScalatraBootstrap’s init method before it will become available to your application. The next listing shows a stubbed CommentsController.

Listing A.3. The CommentsController
package com.example.app

import org.scalatra._
import scalate.ScalateSupport

class CommentsController extends MyScalatraWebAppStack {

  get("/") {
    //We would list comments here
  }

  get("/new") {
    //We would show a new comment form here
  }
}

The controller is now defined, but it’s not available for HTTP requests. You need to mount it so that it becomes requestable. To do so, you add it to the list of instantiated classes using context.mount.

Listing A.4. Mounting a second controller

The CommentsController’s routes are now available at GET http://localhost:8080/comments/ and GET http://localhost:8080/comments/new. To keep things clean, it’s a good idea to also mount ArticlesController at the path "/articles/*".

Note that you could just as easily have mounted CommentsController at "/*" and then set up the controller class’s routes as in the following listing. As with most things in Scalatra, how you structure your routes is up to you.

Listing A.5. Namespaced routes in the controller

You can also run any other initialization code you want in the init method of ScalatraBootstrap. Add a destroy method if you want to do some cleanup when your application exits, as shown next.

Listing A.6. Cleaning up at application shutdown
override def destroy(context: ServletContext) {
  // clean up database connections, close resources, etc.
}

For a more detailed discussion of ScalatraBootstrap, see chapter 9.

Do you need an IDE?

The short answer is no: nothing about Scala requires an IDE. If you’re thinking about trying Scala but the thought of losing your regular text editor gives you the shudders, take heart: nothing in this book assumes or requires that you have an IDE. If you’re a happy vi, Emacs, Sublime, gedit, or jEdit user, you should probably stick with a familiar setup for the moment. There’s a lot to learn, and learning an entirely new IDE while you’re learning all about sbt, Scala, Scalatra, Scalate, servlet configuration, and the million other details of an unfamiliar environment may be too much.

But speaking from experience as former Rubyists, we were p1easant1y surprised by the speed boost we got when we started using Inte11iJ Idea and its Sca1a p1ugin, which is now our environment of choice for Sca1atra deve1opment. The refactoring, code comp1etion, and integrated docs support make it much easier to 1earn Sca1atra, Sca1a, and dozens or hundreds of 1ibraries. The syntax high1ighting is near1y perfect, making it easy to see when you’ve made a mistake before you compi1e. Having said that, you’re spoi1ed for choice. If you don’t care about compi1er-aware syntax high1ighting, automated typesafe refactoring, and integrated docs, you can skip this section. If you’re interested in these things, there are three ways to get them: Emacs, Inte11iJ, or Ec1ipse.

Emacs

If you’re an Emacs user, you can use the Enhanced Scala Interaction Mode for text Editors (ENSIME). It has quite a few features, including the following:

  • Showing the type of the symbol under the cursor
  • Contextual completion for vars, vals, and defs
  • Adding imports for the symbol under the cursor
  • Classpath search for types and members
  • Browsing packages and type hierarchies
  • Finding all references to a symbol
  • Refactorings such as (rename, organize imports, extract method)
  • A REPL with stack-trace highlighting
  • Red squiggles for errors and warnings in your code
  • Debugger support

You begin by installing the scala-mode2 Emacs mode from https://github.com/hvesalai/scala-mode2. Once that’s running, follow the installation instructions at https://github.com/ensime/ensime-server to install ENSIME. Next, install the ENSIME sbt plugin and generate an .ensime configuration file by following the instructions at https://github.com/ensime/ensime-sbt.

Eclipse

If you’re already an Eclipse user, you can add the Scala plugin to your current installation. Alternately, you can download a version of Eclipse with the Scala plugin already installed. In either case, go to http://scala-ide.org, which is where the downloads live.

Eclipse requires an Eclipse project file to be present so it can figure out dependencies for syntax highlighting and other IDE features. Follow the instructions at https://github.com/typesafehub/sbteclipse to install the sbteclipse plugin.

If you want to use Eclipse’s integrated debugging, start sbt like this:

./sbt -jvm-debug 8000

You can then set up your Eclipse debugger. Go to Run > Debug configurations, select Remote Java Application, and click New Configuration. Select Remote to make a new remote debugging configuration, and give it a name. The default debugging port should already be 8000 (matching the port you started sbt with earlier), so clicking Debug and setting some breakpoints should result in a working debugger.

IntelliJ IDEA

You can use the Community Edition of IntelliJ IDEA and add the Scala plugin. There’s no need to add any extra sbt plugins to your projects, because IDEA’s Scala plugin recognizes sbt projects without any further configuration.

To debug in IntelliJ IDEA, start sbt like this:

./sbt -jvm-debug 5005

Next, go to Run > Edit Configurations. Click the + button, and select Remote to make a new remote debugging configuration. Give it whatever name you like, such as Scalatra Debug. The default run configuration, -agentlib:jdwp=transport=dt_socket, server=y,suspend=n,address=5005, should work (note that the port 5005 you started sbt with should match the run configuration).

Set some breakpoints and refresh your browser. The debugger should start up when you select Run Debug ‘Scalatra Debug’.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.44