Instead of brick and mortar stores where you buy things, why don’t we just have places where you go to TRY things (and then order elsewhere). They can charge you an entry fee or make money from additional services (such as unboxing and installation for large items like TVs) or handling returns (drop it off and they box it up and send it wherever.) I’m sure someone enterprising enough could even work out a deal with Amazon and/or other online-only retailers to help cover costs in return for driving business to their sites.
Sucks for you but if people are using your business as a showroom for online purchases, you may as well learn to deal with it, adapt, and figure out how to make money as a showroom.
Amazon’s recent Price Check promotion has hit a nerve with retailers and unleashed a massive whinefest about how Amazon is destroying brick and mortar businesses. Whatever. You know what? The world changes. Deal with it. If you can’t figure out how to adapt to a changing world, your business deserves to perish.
Spent some time trying to figure out why sbt no longer worked for me when I upgraded the sbt-launch jar to the 0.11.0 version. It would complain about a NoClassDefFoundError on scala/ScalaObject. 0.10.0 and earlier versions of sbt ran perfectly. The problem wasn’t related to a project configuration file as this error occurred even if I ran sbt in a completely empty directory.
Since I’m knew to scala and sbt, I wasn’t sure what it was doing behind the scenes, so I didn’t know where to look. I’m sure it’s documented somewhere but the troubleshooting link I found didn’t help.
I knew sbt managed scala versions behind the scenes, so not finding ScalaObject meant that the download was perhaps corrupt. So the solution was to figure out where sbt puts these things. I knew it created a local boot folder for new projects I created, but it turns out sbt also keeps a global boot folder under your home folder in ~/.sbt/boot/ (which was C:/Users/<username>/.sbt on my Windows 7 machine).
Deleting this global boot folder so sbt recreates it was the key. If you get a similar error message for a specific project, the local boot folder would probably be the culprit in that case.
Recently, I upgraded to XCode 4, and one of my Objective C programs stopped working properly. This particular program uses Three20 to manage the application’s views.
Upon startup, I would get a blank white screen. However, if I closed the app by double tapping on the iPhone’s home button, and then switched back to the already-running instance, I would then see the Three20-managed screens and the app would behave normally.
Like most puzzlers, the solution turned out to be really simple, though figuring it out was not at all obvious. It turns out I had left my NIB referencing a window which I never actually used (since Three20 managed loading and switching between my screens), and the app delegate had an outlet connection that pointed to this unused window. So, apparently, when I converted the app over to use Three20, I hadn’t cleaned up the NIB to remove the unused outlets and resources.
This didn’t cause problems with XCode 3 and earlier, but XCode 4 is pickier, I guess. No problem: the references didn’t belong there anyway. Once I cleaned up the NIB and corresponding @synthesize and IBOutlet references, the programs worked as expected.
Oracle recently released JavaFX 2, which is a rich client API that ditches the JavaFX language from JavaFX 1.x in favor of a pure Java library. And man, is it slick. It makes it very easy to implement rich, graphical applications or applets.
Inspired by @visualrinse’s Cooler Kreator, I created my own (greatly simplified) version of it, which I called “Cooler Kreations FX”. To use it, simply launch it, give it permission to run, type in a tag, and the program will consult Kuler for a random color scheme with the specified tag. Assuming, of course, that the Kuler API is working at the time (which, lately, hasn’t been very often…).
To create an application is as simple as extending the Application class.
public class CoolerKreations extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage stage) {
stage.setScene(createScene());
}
private Scene createScene() {
....
}
}
You can use FXML to create your scenes declaratively, or write pure Java code to create your scenes programatically, or mix and match the two.
// declaratively, via FXML
Group root = FXMLLoader.load(getClass().getResource("my.fxml"));
Scene scene = new Scene(root, Color.BLACK);
// the FXML:
<VBox fx:controller="com.metatrope.controller.Controller" alignment="center" xmlns:fx="http://javafx.com/fxml" style="-fx-spacing: 5;">
<children>
<HBox alignment="center">
<children>
<Label text="Cooler Kreations" style="-fx-font: 42 Tahoma;" textFill="white" fx:id="title"/>
<Label text="FX" style="-fx-font-weight: bold; -fx-font-size: 42; -fx-font-style: italic;" textFill="white" fx:id="titlefx"/>
</children>
</HBox>
</children>
</VBox>
// programatically
Group root = new Group();
Text text = new Text();
text.setText("hi");
root.getChildren().add(text);
Scene scene = new Scene(root, Color.BLACK);
There are a lot of controls available. Visually, you can style your controls with CSS and there are plenty of effects you can use, such as drop shadows, reflections, blurs, and more. You can even chain them:
Bloom bloom = new Bloom(); bloom.setThreshold(2.0); BoxBlur blur = new BoxBlur(4 + randomInt(0, 5), 4 + randomInt(0, 5), 4 + randomInt(0, 6)); blur.setInput(bloom); // the output of bloom will be the input for this effect DropShadow ds = new DropShadow(); ds.setOffsetY(4.0f); ds.setOffsetX(4.0f); ds.setColor(Color.CORAL); ds.setInput(blur); // the output of blur will be the input for this effect // apply bloom AND blur AND a drop shadow to this text text.setEffect(ds);
JavaFX also makes it dead simple to animate controls. Simply bind a property and identify key points in the timeline, and the system will interpolate all the values in between. For example, here I tell JavaFX to rotate one of my nodes repeatedly:
// loop my node from 0 degrees to 360 degrees, completing one rotation every 15 seconds. // repeat ad infinitum. Timeline animation = new Timeline(); animation.getKeyFrames().addAll( new KeyFrame(Duration.ZERO, new KeyValue(node.rotateProperty(), 0d)), new KeyFrame(Duration.seconds(15.0), new KeyValue(node.rotateProperty(), 360d))); ); animation.setCycleCount(Animation.INDEFINITE); animation.play();
This is a huge step forward for rich client development in the Java space and a wonderful replacement for Swing. On modern JVMs, it even loads quickly in the browser; this wasn’t historically the case with JavaFX 1.x, or for applets in general, but nowadays Java applets start up almost as fast as Flash (and this will improve even more when Java becomes modularized in future versions.)
The source code can be viewed on my github account. You can test it out online as well (though only if you use Windows, unfortunately.) The result could look something like this:

Recently, I had decided to adopt Hibernate Envers to audit changes to several tables on my database. I decided to attempt to force create the insert events that would have been generated had I been using Envers from the start. Unfortunately, there wasn’t an obvious way to do this, short of writing my own SQL scripts. That approach is fine, but I had several tables to migrate, and I prefer to avoid bypassing Hibernate when I can.
This is what I came up with:
Envers works by using Ejb3 listeners to find out when an entity is inserted, updated, deleted, etc. So, the obvious solution was to trigger this listener. The listener is an instance of org.hibernate.ejb.event.EJB3PostInsertEventListener and expects to receive PostInsertEvents.
PostInsertEvent pie = new PostInsertEvent(entity, entity.getId(), state, persister, source); eventListener.onPostInsert(pie);
Entity is simply the entity that you saved to the database, so of course we already have that. We just need to figure out what Envers expects for the source, state, and the persister.
The source is simple. This turns out to be the Hibernate session itself, which you can obtain from the JPA EntityManager:
EventSource source = (SessionImpl)jpaEntityManager.getDelegate();
The persister is an instance of an EntityPersister, which just captures the mapping and persistence logic for the given entity. Every entity has one, and this can be obtained from the EventSource.
The state is an object array containing the values of each property that we are persisting. It can be obtained from the EntityPersister.
Object[] state = persister.getPropertyValuesToInsert( entity, null, source );
So, basically, all of that information could be obtained with just the entity and the session. I’m not sure why they make us pass in all these additional fields when you can get them all from just the EventSource and the entity itself, but whatever. Once we have all that information, we assemble the PostInsertEvent and pass it to an instance of the AuditEventListener that will do the work. We don’t even need to hook into the one that Hibernate creates (from your configuration files), we can just create it “by hand”.
The complete code is this:
// instantiate the event listener
AuditEventListener eventListener = new AuditEventListener();
eventListener.initialize(HibConversation.getHibernateConfiguration());
EventSource source = (SessionImpl)jpaEntityManager.getDelegate(); EntityPersister persister = source.getEntityPersister( null, entity );
// create an insertion event for each entity you want to audit
Object[] state = persister.getPropertyValuesToInsert( entity, null, source ); PostInsertEvent pie = new PostInsertEvent(entity, shippingRate.getId(), state, persister, source);
eventListener.onPostInsert(pie);
I had a need to modify the validations for a model in a Rails 2.3.5 app from a plugin. I did not want to directly modify the source code; in my case, I was writing my code as a plugin for an existing Rails application so I could upgrade the base code without worrying about losing my changes, or dealing with the hassle of reapplying my patches. There are several really great Rails frameworks out there that are applications in their own right, such as Redmine and Spree, and writing my customizations as plugins or extensions to them is simply a more flexible solution than modifying the applications directly.
I was modifying a User class, extending the login length to 255 characters. We were using emails as the login, and where I work they can get pretty long because they are usually a concatenation of one’s first and last names. And some of my co-workers have obscenely long names. Directly modifying User would be trivial — you would just increase the value associated with the maximum attribute for the validates_length_of validation we are changing:
validates_length_of :login, :maximum => 255
But, as I mentioned, I did not want to change the original code. So, we need to get at the list of validation callbacks. Luckily, that’s easy: there’s a @validate_callbacks instance method available to us. So, we just need to iterate over it and find the callback that we don’t want.
Each entry in @validate_callbacks is an instance of ActiveSupport::Callbacks::Callback. This class contains an accessor called method which returns the Proc that is executed to run the validation. Unfortunately, we want to get at the values being sent to that proc. We know that the validates_length_of method takes in an attrs parameter, so we just eval that against the callback method’s binding to find the list of attributes that this proc will validate.
Because we know we only passed one attribute in (instead of a chain of them), we just check the first value, and double check that the maximum option was set to 30 (which is the original value). This also allows us to easily filter out the other validations on the login field that we aren’t interested in, such as validates_format_of. The finished product looks something like this:
require_dependency 'user'
require 'dispatcher'
module UserPatch
def self.included(base)
base.class_eval do
@validate_callbacks.reject! { |c| true if Proc === c.method &&
eval("attrs", c.method.binding).first == :login && c.options[:maximum] == 30 rescue false }
validates_length_of :login, :maximum => 255 # new value
end
end
Dispatcher.to_prepare do
unless User.included_modules.include?(UserPatch)
User.send(:include, UserPatch)
end
end
I was experimenting with the Redmine, a popular Ruby on Rails open source project management web application. It’s pretty full featured: you can set up multiple projects, each with its own issue tracking, wikis, document stores, and calendars, all within the same instance of Redmine. But it didn’t have everything I wanted.
One problem that I quickly realized I wouldn’t be able to live with is that emails sent from a Redmine instance all use the same emission address. For me, this was a showstopper, since I had a requirement that each project would be tied to its own email address, which our users email for tech support. So I set out to figure out how to customize Redmine. While it would be trivial to simply modify Redmine’s source code directly, I wanted to be able to upgrade the original system, while preserving my customizations. The ideal way to do that is to create a plugin.
To start a Redmine plugin project is simple - there is a Rails generator for that:
ruby script/generate redmine_plugin <plugin_name>
In my case, I called it “project_email”. This creates your standard folder hierarchy for a Rails app: controllers, helpers, models, views, db, as well as a lib folder. The most important file is init.rb, which is invoked when the plugin is loaded. This contains some information that Redmine needs.
require 'redmine'
require 'mailer_patch'
require 'project_patch'
Redmine::Plugin.register :redmine_redmine_project_email do
name 'Redmine Project Email plugin'
author 'Lawrence McAlpin'
description 'Adds a per-project email emission address'
version '0.0.1'
url 'http://github.com/lmcalpin/redmine_project_email'
author_url 'http://www.lmcalpin.com/'
end
Like any Rails plugin, we can add our own tables and fields. We simply create a new migration that looks like this:
class AddMailFromToProject < ActiveRecord::Migration
def self.up
add_column :projects, :mail_from, :string
end
def self.down
remove_column :projects, :mail_from
end
end
… and run rake db:migrate:plugins to load it up! Now, the “project” model will automagically have a new property called “mail_from.”
At this point, I need to override some of Redmine’s controllers and models. The problem is: anything loaded by the plugin will be overwritten by the base application. That is not quite what we want. Luckily, Ruby makes it incredibly easy to tame those classes: through metaprogramming.
We set up a few modules with our patches and force the class to include it.
require_dependency 'mail_handler'
module MailerPatch
def self.included(base) # :nodoc:
base.send(:include, InstanceMethods)
base.class_eval do
alias_method_chain :issue_add, :project_emission_email
# ... override the rest of the methods as well
end
end
module InstanceMethods
def issue_add_with_project_emission_email(issue)
from_project issue
issue_add_without_project_emission_email issue
end
def from_project(container)
unless container.nil? || container.project.nil? || container.project.mail_from.nil? || container.project.mail_from.empty?
from container.project.mail_from
end
end
end
end
This code is straightforward: we override the issue_add method. alias_method_chain takes in two parameters, the first being a symbol representing the method we are overriding, as well as a suffix. In our case, we use “project_emission_email” as the suffix, so the alias_method_chain call will rename the original issue_add method to “issue_add_without_project_emission_email” and rename the “issue_add_with_project_emission_email” method that we define to “issue_add”. Any existing code that calls issue_add will end up calling our “issue_add_with_project_emission_email” method.
We simply override the original mailer to set the from address to the value set in the new “mail_from” field we added to our project. If no customized “mail_from” is set for a project, the default emission email will be used.
But now we have a problem: Redmine ignores any attributes not specifically marked as “safe.” So we need to modify the project model to add a call to
safe_attributes 'mail_from'
No problem! Monkey patching to the rescue!
module ProjectPatch
def self.included(base) # :nodoc:
base.class_eval do
unloadable
safe_attributes 'mail_from'
end
end
end
Unfortunately, in development mode, our model appears to be reloaded upon every request! And, you know what? The same thing happens to our mailer! Oh nos. But hey, no problem, we’ll just patch the Rails dispatcher to reapply the patch every time:
Dispatcher.to_prepare do
unless Project.included_modules.include?(ProjectPatch)
Project.send(:include, ProjectPatch)
end
unless Mailer.included_modules.include?(MailerPatch)
Mailer.send(:include, MailerPatch)
end
end
Now we’re almost done! We just need to modify the view. The easiest way would be to simply add our own customized _form.rhtml in the app/views/projects folder. Unlike controllers and models, the views in our plugin take precedence, so our _form.rhtml will be loaded instead of the one included in Redmine.
Redmine provides a hook that lets you add new fields, without overriding the entire view file. This would be the better approach (since a future version of Redmine may have other UI changes that we want) but it’s late, and this beer isn’t going to drink itself, so we’ll just stop here. We’ll learn about plugin hooks another time.
something to offer besides waiting to die -
Recently I had a discussion with @SoundSystemSDC about small companies in small towns competing to attract and retain professional tech talent and stem the brain drain. This topic had come up in the recent The Combine conference here in Bloomington, Indiana. A group of Midwestern executives discussed the challenges of tech companies in the Midwest. During the Q&A session, I asked how an Indiana business can compete given the gross disparity in compensation that you have compared to larger cities like New York City and San Francisco. I even pointed out a job description for a Wall Street job that paid in the six digits and pointed out how much more it was than a similar job for something in Indianapolis. The response was simply “well it’s better to raise a family here and you can’t buy a home in San Francisco.” Which no one really cares about when they first go on the job market. And once you’re launched on your career path, moving to the middle of nowhere isn’t generally considered a step up.
Sorry. If you’re in a small town and you want to attract and retain top tech professionals you’re going to have to try harder than that.
What can a small town with small companies do to attract and retain the top tech talent? Well, how about:
Alternate Compensation
Offer equity compensation to make up for the smaller salary compensation. Let them use some company resources for personal projects. Or something else. I don’t know. Be creative. But compensation doesn’t always have to be pecuniary.
Quality of Life
If you can’t pay Wall Street wages, don’t demand Wall Street hours. In New York City, day cares close at 7:30pm. The day care my daughter goes to here in Bloomington closes at 5:30pm. The day cares close at 7:30 in NYC because people are still working then. You want that top talent to move over to you, but you can’t pay the same? Point out that a move from a 60 hour week to a 40 hour week takes into account 33% of that wage difference already.
Embrace Attrition
Developers crave new experiences. Accept it and embrace it. Get smaller companies within the same community to work together to find ways that can allow for employees who want new experiences to move ‘laterally’ to other companies in the area. That is: help your employees get a job with other companies in your area.
If you work for a larger company, chances are they make it easy to apply for dozens of other opportunities as they arise within the same company. Even outside of the larger companies, in NYC, Chicago, or SF, you can find hundreds of job opportunities with the drop of a hat. I got cold calls from recruiters daily. Here in Indiana, not so much. Realize that people want the opportunity to move on to other opportunities and develop new skills or work on something new. Make it easy for them to do so. Brain drain is bad for everyone; but it’s better to lose your best guy to someone up the street than to see them leave the local community (or the state) entirely. And if you help them go on good terms, they’re more likely to come back.
Also, the cross pollination within the community creates additional bonds that help retain that talent.
Promote the Community
Use the power of local government or band together with fellow local businesses to promote each other and local leaders in the tech community. People want to be recognized for their accomplishments. Big companies and big cities tend to anonymize people: even the cream of the crop can easily end up being no more than a small fish in a BIG pond. Maybe they’d rather come here where they can be a big fish in a small pond. But give them the satisfaction of having people around who will notice that. Otherwise, they’re no better off.
Pay Them What They’re Worth, But Be Selective
If you can afford it, suck it up and pay them what they can earn. People like money, and the better cost of living is attractive when your salary is the same. Obviously this is a risky approach. No one wants to get stuck with a total dud who soaks up twice the salary. But if you’re smart and you’re careful, the experiences these developers have honed in the bigger and much more highly competitive markets can be very beneficial to you - and that one developer can very likely be worth a small team.
I noticed a huge increase in the caliber of the developers I worked with when I first moved to Chicago (and, later, New York City) from the smaller Midwestern town I first worked in (even though I worked at a Fortune 50 company that could afford to pay a pretty competitive rate.) Where I worked initially, people usually came in straight out of college and stayed there their entire lives. Developers I worked with in Chicago and New York City, on the other hand, were constantly exposed to new ideas and new concepts and tended to learn a lot more. Sure, the internet helps spread those ideas to even the remote places on Earth, but the fact is the big cities attract the better developers since there are more challenges there and more people to learn from. You can get more developers for the same amount of money here in the Midwest, but you often get what you pay for.
Telework
OK, maybe you can’t match that six digit coastal salary after all. Sadness. But I bet that just as that New York City salary dwarfs our Midwestern Indiana tech salaries, there are places where our measly offering would be pretty attractive. Where people might want to live despite the fact that it’s not here in Bloomington, for whatever inexplicable reason they might have.
Once upon a time, that might have been a deal breaker. Businesses tended to form near related businesses in the past for a reason. Distance made it harder to trade, communicate, and meet one another. Nowadays, a little invention called the Internet makes it easy to do all three of those things in our underwear. With miles and miles between each of us. So why are we still expecting everyone to sit down next to each other? In my experience telecommuting, I can assure you, I am far more productive now that I have fewer officeplace distractions.
So while your Big City competitors are busy paying half of their budget on overpriced real estate and have half of their workforce tied up suiting up and battling a century old subway system, you can focus on more important things like real work with real people wherever they happen to want to live.
Anything Else?
There are probably plenty of ideas out there that a smaller town with small companies can do to make itself more attractive besides compensation. But seriously guys, give up on the cost of living calculator argument. It’s not compelling. If cost of living is your argument, we may as well move to McAllen, Texas. I hear it’s pretty cheap to live there.
You want to stop brain drain? Either match the coastal salaries, drain brains from some other community (via teleworking), and/or find a way to nurture a stronger sense of community that instills a sense of belonging, where ones’ successes are noticed and celebrated, and ones’ skills are actively developed - even if it means working within the local community to make it easier - or encourages - people - and their ideas - to move from company to company.
We’re building out an application to support this high profile effort that involves something like 10 different teams. My team’s application has over a million lines of code, 8000 classes, and Needs To Work(tm). Or heads will roll. And mine doesn’t like to do that, because it might get all scruffed up. So naturally we decided to get down with the BDD and use the Cucumber. But since we’re enterprise Java developers, things get a little more complicated. Because that’s how we roll.
We use JRuby so our Ruby code can talk to our Java code and it’s totally awesome and all that. But when it comes to deploying, right now we have a simple process that involves a script (using a proprietary internal tool that is kind of like SCP except it leaves me wishing it actually was) that bundles up all my deliverables and sticks it on the target server. The application servers and Java platforms and so on are already there, usually maintained by other teams.
I wanted to build the application on a build server where the features will be run whenever code changes (using hudson to trigger the scripts). I know what versions of Java will be available on the target servers, since there are architectural standards within the enterprise that I can count on. And, among those standards, I can count on not having any variety of Ruby anywhere unless I put it there myself. But that complicates our process, because I really shouldn’t be adding things to the server (which my team doesn’t own or control). And even if I did, then the server would have an additional component that existed nowhere else which would need to be maintained and loved and cared for, and I’m not at all into that sort of thing.
So I says to myself: how do I simplify this process? And myself says back: stick your cucumber in it.
So I did. But what does that mean, you say? Well, besides being what the cool Java kids are calling it these days, what I mean is that I stuck Cucumber and its dependent gems inside the JRuby jar which meant that all I needed to do was bundle a single extra jar in with the application that we build. This makes deploying the exact same version of Ruby with the exact same gems to any machine or environment really easy: you just copy one file around the network. Even a caveman could do it. But TCP/Smoke Signal was notoriously slow and error prone so they usually didn’t.
The process is super easy to do. First of all, you need to download the source code. You can get it from github (http://github.com/jruby/jruby) or just download the source jar: http://jruby.org/download
What we want to do is build the jar-complete version of the distributable, which is a completely standalone JRuby environment encapsulated as a single jar. If you inspect the ant build script (which is like a make file in the Java world), you’ll see the target “jar-complete” invokes a command to install additional gems defined in the “complete.jar.gems” property. This will by default be found in the “default.build.properties” file. I just edited it directly, and added a reference to a new property “cucumber.gems” to the end:
complete.jar.gems=${rspec.gem} ${rake.gem} {$ruby.debug.gem} ${ruby.debug.base.gem} ${columnize.gem} ${cucumber.gems}
Then we need to define the cucumber gems we want. To ensure the build is predictable, I specify each gem and dependency along with its version:
cucumber.gems=${build.lib.dir}/cucumber-0.9.2.gem ${build.lib.dir}/builder-2.1.2.gem ${build.lib.dir}/diff-lcs-1.1.2.gem ${build.lib.dir}/gherkin-2.2.9-java.gem ${build.lib.dir}/json-1.4.6-java.gem ${build.lib.dir}/term-ansicolor-1.0.5.gem
Now you need to get the gem files and put them in the jruby_src/build_lib folder. When you run the build, it will download the actual gem sources. I just copied the gem files from an existing JRuby installation’s gem cache (jruby/lib/ruby/gems/1.8/cache), but you can do it any way you want.
Now run “ant dist-jar-complete” and you’ll be presented with a lovely, customized version of jruby-complete-1.x.y.jar in your jruby_src/dist folder ready for the cukes or whatever else you want.
You could then invoke it by calling:
java -jar jruby-complete-1.5.3.jar -S cucumber features
There’s been some buzz lately about Scalatra, which is a Sinatra like framework for Scala. Sinatra is a very scaled down platform for web programming in Ruby. Unlike many web frameworks (such as Lift, JSF, etc.) which tend to be very stateful and try to abstract away from the HTML and web technologies, Sinatra does no such thing. It’s very low level, which can make it very fast to get up and going for smaller, stateless web applications, especially REST based services. Scalatra is an attempt to bring that to the Scala world.
To create our Hello World webapp in Scalatra, we’ll first create a dummy project. Create a new folder to hold our project and use the simple build tool (sbt) to create your project.
md HelloScalatra cd HelloScalatra sbt
You’ll get output like this:
Project does not exist, create new project? (y/N/s) y Name: HelloScalatra Organization: test Version [1.0]: Scala version [2.7.7]: 2.8.0 sbt version [0.7.4]:
Now you need to tell the simple build tool what additional libraries you need for your project. We’ll create a project build file to do that. This works kind of like a Gemfile in the sense that it lets the build tool know what dependencies we have. The build file is written in Scala itself.
Create the file ScalatraBuild.scala in the HelloScalatra/project/build folder.
// save as project/build/HelloScalatraBuild.scala
import sbt._
class ScalatraBuild(info: ProjectInfo) extends DefaultWebProject(info)
{
// scalatra
val sonatypeNexusSnapshots = "Sonatype Nexus Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"
val sonatypeNexusReleases = "Sonatype Nexus Releases" at "https://oss.sonatype.org/content/repositories/releases"
val scalatra = "org.scalatra" %% "scalatra" % "2.0.0-SNAPSHOT"
// jetty
val jetty6 = "org.mortbay.jetty" % "jetty" % "6.1.22" % "test"
val servletApi = "org.mortbay.jetty" % "servlet-api" % "2.5-20081211" % "provided"
}
Now download the dependencies. This is similar to running bundle install in a Rails app.
sbt update
One drawback of Scalatra is that it is a Servlet-based framework. That means we aren’t getting away without creating a web.xml file. So let’s set that up. Since simple build tool uses maven conventions, we need to do that in the HelloWorld/src/main/webapp/WEB-INF folder.
HelloWorld/src/main/webapp/WEB-INF/web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>HelloWorld
<servlet-class>com.test.HelloWorld
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld
<url-pattern>/*
</servlet-mapping>
</web-app>
This says that we will have a Servlet handled by the com.test.HelloWorld.scala file (which we haven’t written yet) and it will respond on all URL patterns.
Now we can actually write our app. Simply create the HelloWorld/src/main/scala/com/test/HelloWorld.scala file:
HelloWorld/src/main/scala/com/test/HelloWorld.scala:
package com.test
import org.scalatra._
class HelloWorld extends ScalatraServlet {
get("/") {
"Hello World"
}
}
Now we can start the web server:
sbt jetty
And we can browse to http://localhost:8080/ and we’ll see:
Hello World