The most of J2EE applications developed are usually web + database applications. There’s usually a web framework like Java Server Faces used and jdbc, JPA, Hibernate, etc are used for the database interactions.
I’m on the quest to do all the above in Scala, and make life simpler because of Scala’s concise way of writing code and its various other advantages which have been elaborated on elsewhere.
So for my web application which was a Java EE 6, I chose:
JSF 2.0 for the MVC framework.
JPA for the database interactions.
Session Beans to interact with the Entity Beans.
Glassfish v3 prelude application server
Java derby Database(default)

All of the web pages were written in xhtml. The application I chose to rewrite was Dr. Cay Horstmann’s Simple Quiz web application from his blog here.

The design of the application is simple. It is a simple quiz based on common known facts of Java. So there’s a question and choices(using radio buttons) and at the end, there’s a page which displays the score.
For this, we use:
1. A managed bean.
2. A session bean.
3. 2 Entities.
4. index.xhtml and done.xhtml pages(one for the quiz, one for the score at the end)

To begin with, I simply rewrote all the Java code in Scala. Including the annotations used. However, the manner in which Scala annotations are written are different. For example, in JSF 2.0, the managed bean is annotated like this(thats right! No XML!):


@ManagedBean(name = "quiz")
@SessionScoped
public class QuizMB

In Scala:


@ManagedBean{val name = "test"}
@SessionScoped
class ScalaMB 

Again, in Java:

@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)    
private Collection<Choice> choices = new ArrayList<Choice>();

In Scala((the targetEntity is only necessary to work around a bug in 2.7 that will be fixed in 2.8 apparently):

@OneToMany{val cascade = Array(CascadeType.ALL),val targetEntity=classOf[Choice], val fetch = FetchType.EAGER } 
var choices: java.util.List[Choice] = new java.util.ArrayList[Choice]();

And my Session Bean looked like this:


@Stateless class QuizSB {

 @PersistenceContext private[this] var em: EntityManager = _

 def getQuestions():JList[Question]= {
 ................
 }

 def makeQuestions() {
 ...........
 }

def makeQuestion( _text:String, answer:String, otherChoices:String*) {
 ...........
 }
}

I then tried to access an instance of the SessionBean through the ManagedBean like this:

@ManagedBean{val name = "test"}
@SessionScoped
class ScalaMB {

@EJB private[this] var slsb : ScalaSB = _

def getCurrentQuestion():Question = {
 questions = slsb.getQuestions();
 questions.get(currentQuestionIndex);
}
...........
}

And my JPA beans were written as I have done before. A more detailed explanation of JPA for scala can be found here.

So this didnt work! No matter what I tried. Some of the things I tried:
1. Using setter injections instead of field injections for the session and entity beans.
2. Using JSF 1.2, incase the managed bean annotations were not being processed properly.
3. Looked at the bytecode to check the annotations were processed properly.
4. Looked at the glassfish code which handles the dependency injection.

I hung around on the #scala irc room on freenode asking questions. Dr. Horstmann asked around on java.net and after a while, I was very frustrated that a lot of experimentation was leading to little or no progress.
Dr. Horstmann then figured out from looking at this blog that the session bean implementing an interface and being annotated @Local would work! We then realized that we dont even need the interface, we just need to use a @LocalBean annotation, make sure the scala-library.jar was available properly and it would work!
So the final version of the session bean looked like this:


@Stateless 
@LocalBean 
class ScalaSB {

 @PersistenceContext private[this] var em: EntityManager = _

 def getQuestions():JList[Question]= {
 ................
 }

 def makeQuestions() {
 ...........
 }

 def makeQuestion( _text:String, answer:String, otherChoices:String*) {
 ...........
 }
}

To keep the process of deploying the war to glassfish simple and reliable, I wrote an ant script for it instead of relying on Eclipse to do the job for me.

So after 2 months of working on an already functional Java web app and getting it to work with Scala, whats next? :)
Well, whatever is next, will be easier since I’ve already figured out most of the kinks in the process. Or I hope I have…

adventures with liftweb

March 16, 2009

On the journey to create a JSF like scala framework, I’m currently in the process of studying how LiftWeb works. Obviously, the first step is to build something tangible and see what it does. A few observations to begin with:
1. Scala’s Eclipse support is not enough to provide a “create new liftweb project” option in Eclipse.

Instead, its a 2 step process:

Create a project using maven on the command line with:
mvn org.apache.maven.plugins:maven-archetype-plugin:1.0-alpha-7:create  \
-DarchetypeGroupId=net.liftweb                             \
-DarchetypeArtifactId=lift-archetype-basic                 \
-DarchetypeVersion=0.8                            \
-DremoteRepositories=http://scala-tools.org/repo-releases  \
-DgroupId=PROJECTNAME -DartifactId=PROJECTNAME

This generates a project outline,and to make it suitable for Eclipse, from the project folder, run the command:

mvn eclipse:eclipse

To set this project up in Eclipse, you do:
“Import -> General -> Existing Projects into workspace -> Project”

And this sets up a liftweb project in your Eclipse workspace. I havent yet figured out how to deploy the project into Glassfish directly, right now, to generate a war, from the project directory: mvn install

This install command generates a war in the “target” folder which I then deploy in glassfish using the admin console.

Again, because I havent figured out how to deploy into glassfish from Eclipse, I’m not sure how hot deploy works with Lift,but this blog assures us its possible.

Will keep posting updates as I continue my exploration of Lift Web.

I was reading this entry by Ted Neward on IBM’s Developer Works analyzing if Java’s demise is imminent.
Like it or not, Java is now competing with languages which are faster, less verbose along with the positives of functional programming like closures, monads, etc.
So whats Java’s defense?
1. Java Virtual Machine(hell yeah!)
2. Java libraries – although there’s one too many, no other language even comes close in providing multiple tools for every possible situation.
3. Third and most importantly, I think Java language is going to survive because of the multi-paradigm languages which will run on the JVM (scala, groovy, Jaskell, Jruby, Jython, etc).
These multi-paradigm languages are going to succeed because they are less verbose, have most of the features which the functional programming crowd approves of, easy to learn syntax and we don’t have to give up our favorite editor! This is great news for us.
As soon as IDE support for these languages improves, I believe there will be a big wave of adoption of these languages.

One thing this does imply is that we cannot stay content in just knowing Java along with a few frameworks, we have to stretch ourself go through the learning curve and learn these languages, if not, its Java’s demise which is imminent, but its the Java Programmer’s.

Whats my preparation for the future? Scala and JavaScript baby!!

Day 3 of JavaOne!

May 23, 2008

Day 3 was a short one for me, I had a project to present in the evening for my Web Intelligence class.
I went with my classmate Glenn on this day, I attended only 3 talks this day:
1.Using FindBugs in Anger – Bill Pugh :- This talk by the creator of findbugs was pretty good, he spoke about using findbugs on large projects. My take away from the talk was how to configure findbugs to report bug patterns you want to see, etc.

2. Mylyn: Code at the Speed of Thought – Mik Kersten :- This talk was awesome! Mik leads the Mylyn open source project, which I have always been interested in. I loved the way he started and ended the talk, he hit the sweet spot for every developer, the lure of the “zen programmer’s mind”. That state of mind where code just seems to flow, where we make no mistakes and are invincible! He then presented mylyn as an aid. Really cool.

3. Programming with Functional Objects in Scala :- This talk by Martin Odersky was very good again, but after learning scala all semester as a part of my Programming Languages course under Dr.Horstmann, I was left wanting more from the founder himself! I’m really happy the langauge is being appreciated by a lot of the big names in the industry and I hope it gets used a lot more. I’m sure it will once the IDE support for Eclipse, IDEA and Netbeans gets better.

Martin Odersky

Dr. Horstmann with Martin Odersky after the Scala talk.

Other interesting things from the day was the afternoon chat between Dr.Horstmann and Joshua Bloch which I was fortunate to be around. Joshua bloch was showing code examples which used the new closures proposal and the possible confusions which could come from the new proposed syntax. Dr.Horstmann was still pro BGGA closures, but he sees how the new syntax can definitely be confusing and lead to problematic code. After sitting around listening to them for a while, we went to the room where the Scala talk was meant to be, and I continued talking with Dr.Horstmann about Closures, Scala and other programming topics, which was really interesting.

Dr. Horstmann chatting with Joshua Bloch at the java.net booth
After the scala talk, I headed back home, the project presentation on my mind! Oh and it went really well :-) :D

Follow

Get every new post delivered to your Inbox.