Sunday, 30 March 2014

Using the play Application in a play2 console

For people coming from java, one of the most useful tools in scala is REPL. With sbt applications (and therefore play) you can launch the console and have access to the whole classpath of the application you are working on.

In play2 applications, many times you’ll find you need an instance of play.apli.Application to be able to instantiate some classes.

In your tests you can simply create a FakeApplication as documented on the playframework website. Unfortunately the console does not have access to the test context by default. (There might be a way to force that, not sure..maybe some sbt expert out there can leave a comment?)

Here follows a way to create an application in the play2 console. In my case I am using the securesocial plugin and I wanted to generate a password hash to use for testing. Here is what I’ve done

val application = new play.api.DefaultApplication(new java.io.File("."), classOf[play.api.Play].getClassLoader, None, play.api.Mode.Test)

import securesocial.core.providers.utils.BCryptPasswordHasher

val hasher = new BCryptPasswordHasher
hasher.hash("hello")
res2: securesocial.core.PasswordInfo = PasswordInfo(bcrypt,$2a$10$lR6KZixogW95QbfwX7P4tuLvWlbqyp36Xw4PhVTqERRjyxy7OJ/lO,None)

That first line is the one you might want to copy ;)

Sunday, 16 June 2013

git configuration on a new machine

Whenever I start using a new machine for development these are the first options I setup.

First things first - Your name

git config --global user.name "Andrea Salvadore"
git config --global user.email "me@here.com"

Better log messages

git config --global alias.lg "log --color --graph 
  --pretty=format:'%Cred%h%Creset 
  -%C(yellow)%d%Creset %s %Cgreen(%cr) 
  %C(bold blue)<%an>%Creset' 
  --abbrev-commit"
This command will generate nicely coloured and formatted git logs. See more details in here

Some common aliases

git config --global alias.st status
git config --global alias.ck=checkout

merge tool

I use diffmerge or meld. The following configuration is for diffmerge
git config --global merge.tool diffmerge
git config --global mergetool.diffmerge.trustexitcode true
git config --global mergetool.keepbackup false
git config --global mergetool.diffmerge.cmd
  "/usr/bin/diffmerge --merge
  --result=\"$MERGED\" \"$LOCAL\" \"$BASE\" \"$REMOTE\""

diff tool

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd diffmerge '$LOCAL' '$REMOTE'

push current folder

git config --global push.default current
This will allow you to type
git push origin
instead of
git push origin <current_branch_name>

Tell git to ignore file permission changes

git config --global core.filemode false

Monday, 18 March 2013

stop writing unit tests in java - Groovy part 1

Many people are concerned with the libraries they use in production code, and you know maybe I can understand that. You can say that introducing them might have some unexpected consequences.
What I can't understand is why we keep using java to write unit tests when we have some awesome languages like groovy and scala.
To that goal, I am going to write a couple of articles to help you start using them today. That's right, don't wait till tomorrow. Just do it for your finger tips' sake.
Will start with groovy. Our build tool will be maven, not my favourite, simply the most popular.
Also, I will be using eclipse. I did not bother using m2eclipse.

The base project

Will start creating a new service project using maven archetypes:
mvn archetype:generate -DgroupId=info.devinprogress -DartifactId=PostService -DarchetypeArtifactId=spring-data-basic -DarchetypeGroupId=com.cloudfoundry.tothought -DinteractiveMode=false
//Generate the eclipse project files
mvn eclipse:eclipse
Unfortunately I could not get maven to generate a proper eclipse .classpath file for groovy files.
After trying to tweak the maven-compiler plugin and then using the build-helper-maven-plugin eventually I gave up and had to manually change the eclipse
If you get it working well, let me know. Otherwise add this line to the .classpath file.
<classpathentry including="**/*.groovy" kind="src" output="target/test-classes" path="src/test/groovy"/>

Add the groovy source code to your maven build

We need to tell maven we also have some groovy files to be compiled. To do that we'll change the build step and add the groovy compiler.
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <compilerId>groovy-eclipse-compiler</compilerId>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-eclipse-compiler</artifactId>
                    <version>2.7.0-01</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
Also you'll need the groovy dependency added for your test scope.
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
    <version>2.1.0</version>
    <scope>test</scope>
</dependency>

Install groovy plugin

The groovy plugin will help when creating a new groovy class. It comes with code completion, syntax highlight and all those nice things. But probably most importantly it will compile your groovy files to bytecode. That will be handy when running test units from your IDE.
You can get the update site for your eclipse version here
Make sure you pick the features as shown in the screenshot below:
Once you install it, restart eclipse. Right click on the project and add the groovy nature.

You are ready to test

Create a new folder src/test/groovy and add all your groovy tests in there. To run the in eclipse make sure you select the class in the explorer and not the file, like shown in the screenshot below.


You are ready to test and roll.
Check the project on github.
Next post we'll right some more unit test for the PostRepository taking advantage of the groovy features.

Thursday, 7 March 2013

maven - only build what you need

Building a specific project

// syntax: mvn clean package -pl <groupId>:<artifactId>
mvn clean package -pl com.mycompany:myproduct

// build to succeed **You need to have dependencies installed (you must have run mvn install first)**

Building a specific project and its dependencies

mvn clean package -pl com.mycompany:myproduct -am

// The -am option means also-make and will build dependent projects

Monday, 11 February 2013

My favourite programming quotes

I find myself thinking about some of these quotes every now and then and I just wanted to share them here.

Some of them are kind of funny but mostly I believe they all should make us think for a second about our job and how many times you've been in that situation...


If you have some pearl of wisdom please share it at the bottom leaving a comment. I will keep this page updated!



Premature optimization is the source of all evil

-Donald Knuth


There are two ways of constructing a software design:

One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.

-C.A.R. Hoare, The 1980 ACM Turing Award Lecture


Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

-Martin Fowler


Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

-Brian W. Kernighan and P. J. Plauger in The Elements of Programming Style.


[Most managers] may defend the schedule and requirements with passion; but that's their job. It's your job to defend the code with equal passion

-Robert Martin (Uncle Bob), Clean code


The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time

-Tom Cargil Bell labs


Before software can be reusable it first has to be usable.

-Ralph Johnson


Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

-Rick Osborne


The best way to predict the future is to implement it.

-Alan Key


Talk is cheap. Show me the code.

-Linus Torvalds


Perl – The only language that looks the same before and after RSA encryption.

-Keith Bostic


I invented the term 'Object-Oriented', and I can tell you I did not have C++ in mind.

-Alan Kay


Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.

-Linus Torvalds


Controlling complexity is the essence of computer programming.

-Brian Kernighan


Finally I'd like to throw one in there myself...

I lost count of how many times I've seen that quick, little, insignificant proof of concept going to production

Wednesday, 30 January 2013

A Meteor nodejs app to heroku in 5 minutes

Meteor is an amazing framework to rapidly build fully interactive web applications based on node.js and MongoDB.

I had a look at the video on the home page and I was quite impressed. I wanted to check it out myself on the web so I installed the framework

curl https://install.meteor.com | /bin/sh

and then went ahead with creating a new app.

If you create a new app you probably won't have a feeling of where to start. So instead of starting from scratch, try starting from one of the examples

meteor create --example parties

Now that you have the code just browse through the client and the server folders, you can get a feeling of how to structure a web app.

Ok now, let's chuck it on heroku

cd parties
heroku create devparties --stack cedar --buildpack https://github.com/jordansissel/heroku-buildpack-meteor.git

The command above will create a new heroku app called devparties using this buildpack that has all the configuration to use a MongoHQ free db.

Now let's use git to add to heroku

git init
git commit -a -m "Initial commit"

Before pushing you will have to add the remote (heroku) git url

git remote add heroku git@heroku.com:devparties.git
git push heroku master

OK, that's it. You have your app running.

There is one last thing you command you'll have to run to set the ROOT_URL ( not sure, must be in the buildpack somewhere.. ) Anyway, if you get an error like

Starting process with command `PATH=.meteor/local/usr/bin:.meteor/local/usr/lib/meteor/bin:bin:/usr/local/bin:/usr/bin:/bin NODE_PATH=.meteor/local/usr/lib/meteor/lib/node_modules MONGO_URL=mongodb://heroku:1e2cc27d5f5415f5cd31783b6fa29afa@linus.mongohq.com:10011/app11455582 node .meteor/local/build/main.js`
2013-01-31T00:03:57+00:00 app[web.1]:             ^
2013-01-31T00:03:57+00:00 app[web.1]: app/packages/meteor/url_common.js:14
2013-01-31T00:03:57+00:00 app[web.1]: 
2013-01-31T00:03:57+00:00 app[web.1]:     at Object.Meteor.absoluteUrl (app/packages/meteor/url_common.js:14:13)
2013-01-31T00:03:57+00:00 app[web.1]:     at app/packages/accounts-password/email_templates.js:3:20
2013-01-31T00:03:57+00:00 app[web.1]:       throw new Error("Must pass options.rootUrl or set ROOT_URL in the server
2013-01-31T00:03:57+00:00 app[web.1]: Error: Must pass options.rootUrl or set ROOT_URL in the server environment
2013-01-31T00:03:57+00:00 app[web.1]:     at Array.forEach (native)
2013-01-31T00:03:57+00:00 app[web.1]:     at Function._.each._.forEach (/app/.meteor/local/build/server/node_modules/underscore/underscore.js:79:11)
2013-01-31T00:03:57+00:00 app[web.1]:     at run (/app/.meteor/local/build/server/server.js:99:7)
2013-01-31T00:03:57+00:00 app[web.1]:     at /app/.meteor/local/build/server/server.js:113:21
2013-01-31T00:03:58+00:00 heroku[web.1]: Process exited with status 1

then run the command

heroku config:add ROOT_URL=http://devparties.herokuapp.com

Monday, 28 January 2013

MongoDB online course videos and how to download them

hey guys, The MongoDB guys are doing some free online course on MongoDB. The MongoDB for DBAs is already online with the first two weeks
if you want to download the videos and watch them online (like me on the tube) you can check you this project on github.
To get it running on Ubuntu make sure you have python 2.7 and a few other dependencies.

Run

Run the following commands and you'll be downloading in secs.

git clone git://github.com/nonsleepr/edu_10gen_dl.git
vi config.py // change email and password in the config file. 
// Also set domain to 'education.10gen.com'
sudo apt-get install python-bs4
sudo apt-get install python-mechanize
python edu_10gen.py


The config.py needs to have your 10gen username (email) and password.

Hope it helps!