Getting started with Scala

This is a list of Scala resources to get started and beyond.

1. Setting up the environment (installation guides):
* if you just want to experiment with scala there is no need to setup anything, you can use an online interactive interpreter like http://scalatutorials.com/ and http://www.simplyscala.com/.

Mac OS X guide
Windows 7 guide
Ubuntu guide

2. Editors and IDEs
There are plugins for all major IDEs:

Scala IDE for eclipse
Scala plugin for NetBeans
Scala Plugin for InteliJ IDEA

Syntax highlighting plugins are available for jEdit, Notepad++, TextMate, TextWrangler etc.

3. Online Free Resources
Scala School @ twitter: http://twitter.github.io/scala_school/
http://www.tutorialspoint.com/scala/index.htm this is a tutorial for beginners.
There is a free course at coursera: Functional Programming Principles in Scala don’t miss it but I suggest that you go through the basics first.

4. Scala and Functional Programming Books
– Scala
Programming in Scala 2nd Edition (I really liked this book, but one of my colleagues found it a little to academic and moved on to the next book)
Scala for the Impatient
Scala in Depth
Scala in Action
Testing in Scala (if you are serious about Scala this book is a must)

-Functional Programming
Functional Programming in Scala (I included this book here because it’s mainly about functional programming and less about Scala, it’s a five star recommendation though)
Purely Functional Data Structures (More theoretical and all examples are in ML and Haskel but it’s easy to translate them to Scala)
Functional Programming for the Object-Oriented Programmer (if you come from object oriented world this book will help you)

5. Scala for the Web
Play Framework 2.x (This is my favourite framework, all my web projects are based on play)
Lift (I have never used it in real project but it looks really good)
Scalatra (I don’t know much about it but I will give it a try soon)
Skinny (this is Scala on Rails and it’s in alpha version)

6. Scala Object Relational Mapping
Slick (I have been using slick with play and I’m quite happy but I’m sure all the others are equally good)
Squeryl
Circumflex
Lift ORM (included in the lift framework)

7. Scala for NoSQL
The list on nosqls is really big these are the ones that I have been using
MongoDB
Redis
Cassandra
Hadoop
ElasticSearch

8. Other
Akka (A toolkit – and runtime – for highly concurrent, distributed, and fault tolerant applications)
Scalaz (library for functional programming to complement those provided by Scala itself)

Final note: all software mentioned here is open source so you can get your hands dirty.. fork them and enjoy scala.

Advertisements

Redoing Guestbook example with Stripes

Google has created an example on how to use google app engine with java. In this example they demonstrate the basic usage of Servlet API and JDO, it’s a simple example that stores, retrieves and renders entities in google app engine.
After the first tutorial on how to deploy Stripes in google app engine I decided to re-write this example using the Stripes framework of course.

Download the source code!

Steps:

1. Create a project and name it Guestbook

2. Follow the Getting started with Stripes and google app engine to configure Stripes

3. Add the JSTL jars (standard.jar and jstl.jar) in the lib directory

4. Create an ActionBean that will handle the greeting requests


package com.guestbook.action;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.guestbook.manager.PMF;
import com.guestbook.model.Greeting;

/**
 * @author 110j
 */
public class GreetingActionBean implements ActionBean {
	private static final String VIEW = "/guestbook.jsp";
	private ActionBeanContext ctx;
	private UserService userService = UserServiceFactory.getUserService();
	private Greeting greeting;

	@DefaultHandler
	public Resolution welcome() {
		return new ForwardResolution(VIEW);
	}

	public Resolution addGreeting() {
		if (greeting != null) {
			greeting.setAuthor(getUser());
			greeting.setDate(new Date());

			PersistenceManager pm = PMF.get().getPersistenceManager();
	        try {
	            pm.makePersistent(greeting);
	        } finally {
	            pm.close();
	        }
		}
		return new ForwardResolution(VIEW);
	}

	public Resolution signin() {
		ForwardResolution fd = new ForwardResolution(VIEW);
		if (!userService.isUserLoggedIn())
			fd = new ForwardResolution(userService.createLoginURL("/Greeting.action"));
		return fd;
	}

	public Resolution signout() {
		ForwardResolution ForwardResolution ">fd = new ForwardResolution(VIEW);
		if (userService.isUserLoggedIn())
			fd = new ForwardResolution(userService.createLogoutURL("/Greeting.action"));
		return fd;
	}

	@SuppressWarnings("unchecked")
	public List getGreetings() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Greeting.class.getName() + " order by date desc range 0,5";
	    return (List) pm.newQuery(query).execute();
	}

	public Greeting getGreeting() {
		return greeting;
	}

	public void setGreeting(Greeting greeting) {
		this.greeting = greeting;
	}

	public User getUser() {
		return userService.getCurrentUser();
	}

	public ActionBeanContext getContext() {
		return this.ctx;
	}

	public void setContext(ActionBeanContext ctx) {
		this.ctx = ctx;
	}
}

5. Create the model class called Greeting (as described in the google example, no changes here!)


package com.guestbook.model;

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.users.User;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Greeting {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private User author;

    @Persistent
    private String content;

    @Persistent
    private Date date;

    public Greeting() {}

    public Greeting(User author, String content, Date date) {
        this.author = author;
        this.content = content;
        this.date = date;
    }

    public Long getId() {
        return id;
    }

    public User getAuthor() {
        return author;
    }

    public String getContent() {
        return content;
    }

    public Date getDate() {
        return date;
    }

    public void setAuthor(User author) {
        this.author = author;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

6. Create the utility class that will instantiate the EntityManager (no changes here also!)

package com.guestbook.manager;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

public final class PMF {
    private static final PersistenceManagerFactory pmfInstance =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");

    private PMF() {}

    public static PersistenceManagerFactory get() {
        return pmfInstance;
    }
}

7. Modify the guestbook.jsp, there are a lot of changes here since in their example google uses scriptlets, I have replaced the scriptlets with jstl tags and Stripes tags, all the logic has moved to the ActionBean.

8. Modify the welcome file list in the web.xml and set as welcome file the Greeting.action

Download the source code!

Moving around a room

Today was a holiday here in Belgium, I suppose in other countries too, so I had a chance to work a bit more with JavaFX. I have created a simple example where a sphere moves around a room. There are few points to notice about this example:

1. How to make an object move around automatically using Timeline and KeyFrame classes.

2. How to control the movement of your object in the x and y axis.

3. How to use colors that are not listed in the Color class.

4. How to create CustomNode.

5. How to make a 2D object look like 3D.

6. Adding effects to an object.

I am sure you can find -if not all- most of this points in other examples but I have put them all together and I hope it is helpful.

Note: You can download the code from JavaFXExamples at google code.
svn checkout http://javafxexamples.googlecode.com/svn/trunk/ javafxexamples-read-only

Update:
The rotate() method in class Ball has changed so the ball goes to the corners of the Frame, also the speed of the ball is almost the same in all directions as suggested by Ruth in the comment.

Here is a picture of the application:

The code of the application follows:

import javafx.scene.*;
import javafx.scene.*;
import javafx.scene.effect.*;
import javafx.scene.geometry.*;
import javafx.scene.paint.*;
import javafx.application.*;
import javafx.animation.*;
import javafx.input.*;
import javafx.scene.transform.*;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;

/**
 * @author Omer Haderi
 */

var heightPlus: Integer = 35;
var widthPlus: Integer = 9;

var height: Integer = 400 + heightPlus;
var width: Integer = 400 + widthPlus;
var interval: Integer = 1;
var ball: Ball = Ball {}
/*
 * Point 1. How to make an object move around automatically
 * using Timeline and KeyFrame classes.
 */
var timer : Timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames :
    KeyFrame {
        time : 15ms
        action : function() : Void {
            ball.rotate(interval);
        }
    }
};

Frame {
    stage: Stage {
        // Point 3. How to use colors that are not listed in the Color class.
        fill: Color.web("#2E2E2E")
        content: [Room {}, ball]
    };
    visible: true
    title: "Moving around room!"
    width: width
    height: height

    closeAction : function() {
        java.lang.System.exit( 0 );
    }
}
timer.start();

//Point 4. How to create CustomNodes + implements create() function.
public class Room extends CustomNode {
    public function create(): Node {
        // Point 5. Using basic shapes you can make 2D object look like 3D
        return Group {
            translateX: 0
            translateY: 0
            content: [
                Polyline {
                    points: [ 0,400, 100,300, 300,300, 400,400]
                    strokeWidth: 1
                    stroke: Color.GRAY
                },
                Line {
                    startX : 100, startY : 0
                    endX : 100 endY : 300
                    stroke : Color.GRAY
                },
                Line {
                    startX : 300, startY : 0
                    endX : 300, endY : 300
                    stroke : Color.GRAY
                }
            ]
        }
    }
}

//Point 4. How to create CustomNodes + implements create() function.
public class Ball extends CustomNode {
    public attribute x : Number = 100;
    public attribute y : Number = 300;
    public attribute radius : Number = 15;
    public attribute color : Color = Color.BLUE;

    /*
     * Point 2. How to control the movement of your object in the x and y axis.
     */
    public function rotate(interval: Number) {
        if (x <= 100 and y < 380 ) {
            y += interval / 2; 
            x -= interval / 2; 
            radius += 0.04;
        }
        if (y == 380 and x  300 and y > 300) {
            y -= interval / 2; 
            x -= interval / 2; 
            radius -= 0.04;
        }
        if (y == 300 and x > 100) {x -= interval;}
    }

    public function create(): Node {
        return Circle {
            centerX: bind x
            centerY: bind y
            radius: bind radius
            // Point 6. Adding effects to an object.
            effect: Reflection {
              fraction: 1
              topOpacity: 0.3
            }
            fill: RadialGradient {
                centerX: 200
                centerY: 350
                radius: 200
                proportional: false
                stops: [
                    Stop {offset: 0.0 color: Color.WHITE},
                    Stop {offset: 0.5 color: bind this.color},
                    Stop {offset: 1.0 color: Color.WHITE},
                ]
            }
        };
    }
}