Vill du veta mer?

 

Magnus K Karlsson
Senior System Developer
+46 (0)70-218 00 84
magnus.k.karlsson@msc.se magnus-k-karlsson.blogspot.com

Magnus är en erfaren systemutvecklare.
 
Magnus K Karlsson

Våra medarbetares bloggar

2012-01-31 av Magnus K Karlsson

How to install Oracle JDK on Ubuntu 11 from repository.


With Oracle the acquisition of Sun the Oracle have retired the "Operating System Distributor License for Java" (JDL) and the only available JDK release will be the OpenJDK. I had previously some bad experience with the OpenJDK and I prefer to use the official Oracle version of JDK, but I don't want to install the JDK binaries manually – we are using Ubuntu! But the webupd8.org team have been nice to published the binaries in a Personal Package Archives (PPA) and so far I have no problem using it, so I can warmly recommend using it.

To install:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo mkdir -p /usr/lib/mozilla/plugins #just in case, this will be added to the package in the next version
sudo apt-get install oracle-jdk7-installer

And to uninstall:
sudo apt-get remove oracle-jdk7-installer


And to verify your installation:
java -version
java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode)

And to verify the web browser installation:
http://java.com/en/download/installed.jsp
Verified Java Version
Congratulations!
You have the recommended Java installed (1.7.0_02).

And with maven 2:
mvn -version
Java version: 1.7.0_02
Java home: /usr/lib/jvm/java-7-oracle/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "3.0.0-15-generic" arch: "amd64" Family: "unix"

Java Web Start
The only thing that did not work out of the box was the Java Web Start. To fix that open JNLP file link and when asked for application, brows to:
/usr/lib/jvm/java-7-oracle/bin/javaws

For complete reference see:
http://www.webupd8.org/2012/01/install-oracle-java-jdk-7-in-ubuntu-via.html

2012-01-31 av Magnus K Karlsson

How to Make a Launcher (Shortcut) in the New Ubuntu 11.10 (Oneiric Ocelot) Dock.


In my previous blog I wrote about how to create a custom launcher to the Unity dock, but when you upgrade to 11.10 (Oneiric Ocelot) that no longer holds. When you right click on the desktop the menu item Create Launcher... is no longer there.

The simplest way I have yet found is to manually create a desktop file anywhere one the file system, but I would recommend to put it in the same folder as the program you are creating to shortcut to.

Example of my eclipse.desktop:

2012-01-31 av Magnus K Karlsson

How to implement MVC (Model View Controller) Pattern with Swing – Part 3


In my third blog about implementing MVC pattern in Swing I will look at how to implement global actions, context sensitive global actions, updating status bar and popup dialogs. But before delving into these issues and I would like again to repeat each class responsibility in the MVC pattern:

Model:
  1. Simple POJO model.
View:
  1. Layout out the Swing components.
  2. Responds to user action by sending request to Control.
  3. Responds to Controller responds.
Controller:
  1. Receives request from the View.
  2. Do logic.
  3. Sends Responds to View(s).
And a last reminder the Request and Responds to and from the Controller should be TOTALLY view technique neutral as the Model. The view specific code, in our case Swing code, ends in the view. Handling all Swing code is the responsibility of each view.

In my previous blog we have seen that each View is only responsible of its Swing component and what happens in other view is it totally unaware of. Try to think of separation of concern. It is the responsibility of the Controller to call the Response methods in each Views that should be updated.

Example:


And the corresponding Controller code:


The Toolbar is yet Another View

So now lets start with looking how to add a JToolBar to our Swing client. If you think of it for a while you will realize that the toolbar is yet another view. So lets write a new class that extends from our AbstractView.



I have here used javax.swing.Action for base class, since they contain all graphical properties such icon, label and tooltip. But also javax.swing.Action can be used for JButton and in JPopupMenu and JMenuItem.

And I have also deliberately not created a abstract class for our action, which could have loaded our images, since I do not believe that such extra abstraction class will not bring any extra to our code nor reduce the number of lines. It will only make our client code more less understandable. But what would justify an extra abstraction layer is if abstract action class called the Controller in thread safe ways and change cursor to busy and in case of failure show a generic exception dialog. That would really bring something to our code, but not loading icons, using Action is quite straightforward and I like to see directly what my code does.

Handling Context Sensitive Global Actions

So after realized that the toolbar is just another view, lets move onto how to make the toolbar context sensitive, i.e. when switching active panel/window the save actions is replaced with the active panel/window save action. But before we must first decide where the concrete Swing save action should be located. It clearly belong to the concrete view. Think again of separation of concern. But what we must do is to expose the global actions so we can send them to the toolbar view. And lastly where do we wire the views together? In the Controller of course.

Let first add an extra method in our abstract view:


Then in our controller we wire the global actions from the view to the toolbar view.


And in our toolbar view:



The last thing we need is to do is to switch back to the default when changing to other views. Here it can be justified to introduce some kind of View lifecycle mechanism, so the programmer does not have to concern about setting the correct toolbar action each time a new View is retrieved.

Managing a Statusbar

After thinking the GUI as a composition of different views, it should not be surprising to think of the statusbar as yet another view as well. And where is the respond sent to update this view. In the Controller of course. Here is a simple example how to implement a statusbar with swinglabs JXStatusBar.

se.msc.mvcframework.demo.view.StatusBarView


Managing Modular Popup Windows

The modular popup windows is also yet another view. The only difference it needs a parent JFrame to show from. And the solution to that is simple. Each View has a reference to the AbstractFrame that holds the JFrame via getFrame().

2012-01-23 av Magnus K Karlsson

How to Merge PDF Files in Ubuntu


There are so many good web article that you would like to read and sometimes they even stretch over several web pages, but what if you are not online or like to concatenate several different article of your choosing?

One way to do it, it to use the build in print to PDF file in Ubuntu. But what if there are several article? Then you probably want to merge these PDF files. In Ubuntu that is an easy task.

First install pdftk:


Then type the following in the the directory where all the pdf files are:


For a complete reference see http://ubuntuhowtos.com/howtos/merge_pdf_files.

2012-01-23 av Magnus K Karlsson

Putting Logic in finally is not Thread-safe


This is not a very good documented feature in Java. And if you search the web for when to use finally you will find numerous example of using finally for closing resources. And these are good example of when to use finally, but what they will not tell you is that the finally code will run in a separate thread with low priority. This means that if you put logic in your finally block this code will not be thread safe. No matter what you do to make it thread-safe.



The same thing goes if you are depending on the state of the resource. For example if you are building a state machine that should change state whenever a resource is open or closed. And you are relying and whichever the resource is open or closed by calling the resource itself. This will not be thread-safe if you close the resource in a finally block.

2012-01-21 av Magnus K Karlsson

How to Make a Launcher (Shortcut) in the New Ubuntu 11.04 (Natty Narwhal) Dock.


I have been using Ubuntu for some time for writing Java code and for that I use Eclipse. You can install Eclipse via Ubuntu repository, but you probably don't wont to do that because the version in the Ubuntu repository is so old. And installation of Eclipse is so easy, simply download the tar archieve and decompress it to any folder of your liking and then duoble click the eclipse executable.

But after that you probably want a Launcher in the Ubuntu dock? But how do you do that? There is a build in plus icon application for that, but in that program you you can only use installed program, not random program simply unzipped on your disk.

So to make a arbitrary launcher:

1. Right click on you desktop and select 'Create Launcher...'.



2. Type in Name, Command path and optional Comment.
3. And finally click on the default icon and brows to your eclipse home folder and select icon.xpm.
4. Then move the Launcher file to ~/.local/share/applications.
5. And finally drag the Layncher file from ~/.local/share/applications and drop it on the Ubuntu dock.

2012-01-20 av Magnus K Karlsson

How to implement MVC (Model View Controller) Pattern with Swing – Part 2


In my previous blog I lay the ground of the definition of the MVC pattern and showed you have to implement it with Swing technology. I also defined a minimum set of classes that will help you to separate the client code into the MVC components – View, Controller and Model.
In this blog I will implement a more complex Swing client to show you that the minimum set of framework classes still holds for upholding the separation of concern between the View, Controller and Model. And the MVC pattern really deliver a component based architecture. That is even if you decide to rearrange the views, that will not impose the previous written code of the views, you merely need to rewire the code in the controller. And maybe foremost the code will be clean and what I hope most, will be easy read and follow.

But first lets repeat the responsibilities of each class in the MVC pattern

View
Layout the Swing components.
Sends user action request to the Controller.
Updates the View from Controller responses.
Controller
Do business logic.
Sends responses to views.
Model A POJO.

And a few warnings:

Don't do any logic in the Swing Action, e.g. open other dialogs or frames, call for update in other views. All these code will only destroy the maintainability of you application, because what it is breaking the law of seperation of concern. A specific View should not be aware and shoould not care what other Views are doing. What the View should do is merely pass the user action to the Controller and it is the job of the Controller to decide what to do with the request.

For example. The Controller X recieves a request, does some logic, such as calling the Server Facade and recieves the responds. Call for update on View Y, Z and E and open a new dialog.

By keeping the swing logic in the Controller and also keeping the Controller free from Swing code, it will be easy to go back later to understand the logic and flow in the client, but also for other to read and finally to maintain. It will only be in one place you need to change your code if the working flow or logic changes.

So now lets discuss the example. It is a internal frame solution, that only got one internal frame a dossier window. The dossier window contains document and present these structure in a tree. The detail of each tree node is shown in the same internal frame but in a detail panel. Here is a snapshot of the example.



Lets start with Main class.
1. It creates and saves all Views and Controllers in HashMap that the base class holds, so that all Views and Controller will be accessible through the entire client.
2. Lay out the JFrame with a default view.



We have two form views that have simply to to important methods that populates the view – getValues and setValues.

Now for the Tree View. This View is more complex but only because Swing is so verbose. I will leave the detail of how to implement a modifiable tree you can download the source at the end of the blog or google. I will in upcoming blog present a better ways to decorate the existing swing components, to take a POJO Model and populate from that. And to hold that POJO Model, so you can later ask the swing component for a POJO Model instead of making tiring calling of get and set from the model to the swing component and vice versa. But showing you simplifying handling of swing components is out of the scoop of this blog. The import thing is to show you how to seperate the concern of the Views and Controllers and the interaction between them.



As you can see in the code above the the tree View does not do anything in theirs action, just merely call the correct Controller method.

And now the Controller where we wire everything together.



I hope by just reading the code in the Controller you will get the feeling what will happen. But the best part. Everything is type safe! You can click on the method and directly go the code!


The complete source code from https://sourceforge.net/projects/swingframework/files/.

2012-01-17 av Magnus K Karlsson

How to implement MVC (Model View Controller) Pattern in Swing


The MVC pattern is the most common pattern when it comes to web framework, but when building a rich client with swing or by using a rich client framework such as, Eclipse Rich Client Platform, Eclipse RCP , or Spring Rich Client Project, Spring RCP or trying to develop a similar platform yourself, thing tends to fast get very complicated. Why is that? Well, first Swing is very low tech. To do even the most simple thing requires quite a lot of lines of code. Another reason is that a lot of people have not taken their time to fully understand the MVC pattern. And maybe last there are a lot of misunderstanding what a view is in the MVC pattern and the Swing model. The Swing model is entire a presentation necessity and therefore only belong to the view.

So hopefully what I will achieve in this blog is to explain the MVC pattern and how to implement it with Swing. What I will not do in this blog is to explain how to use certain Swing components, their are quite a few tutorials out there, e.g. Oracle own Swing Tutorial, http://docs.oracle.com/javase/tutorial/uiswing/.

Last start with explaining the MVC pattern fundamental. Maybe the easiest way to explain MVC is to look at how things work in the web world.


What happens:
  1. The View builds the graphical interface and reacts to user interaction, by redirecting the request to the Controller.
  2. The Controller respond to the request, do logic and sends response to a view.
  3. The View takes these parameters and presents them in a view to the user.
And as you already might have guessed the above request and response parameters is the Model in the MVC pattern.

Before continue I would like to stress a few things extra hard:
  • All graphical components are created and layed out in the view. Nowhere else!
  • The Controller is neutral to whatever graphical user interface technique used! A simple control question is. Think that you must change graphical technique, from example Swing to SVT. Will you controller classes be affected? This question might feel quite theoretical but is a good eye opener if you have successfully separated the view concern from the controller concern.
  • The Model should also be plain old Java object, POJO, and not infected with presentation specific codes. And again check that by asking yourself if you were forced to change presentation technique. How would that affect your model classes?
And a final reminder about the model in the MVC pattern and the model in Swing. The Swing model should not be confused with the model in the MVC pattern. The Swing model is entirely part of the choosen presentation technique, i.e. Swing and belongs only in the view and should not be mixed with the model in the MVC pattern.

The last thing before diving into concrete code is the concern of Object Instances Lifecycle. Now you might start to wonder what that has to do with MVC. And the question is none, but the problem is still real and I think one must adress this with some thinking and strategy, because it is so vital to the application and programmers daily life. And not to mention testability. Which is something I will not go into any deeper in this blog, but I can recommned the FEST test framework. Anyhow which Swing test framework you choose you must before have a clear lifecycle handle of object in your rich client. Otherwise you will end up with untestable code.

So lest start with the View. What does a view do?
  1. Layout the graphical components.
  2. Responds to user interaction (and sends the request to the Controller).
  3. Updates the view (requested from the Controller).
Lets starts with the layout.





Try not to bother about the static component methods, such as frame, etc. they are all methods in a ComponentFactory that do all the Swing plumbing construction. I will later show them in the Appendix.

But our application will certaintly contains several views, so lets we refactor out the main method in a class thats holds the JFrame instance. What we also will do in our frame class is to solve the problem of object lifecycle and dependencies to those. We will create a map that hold all the views and another that holds the controllers. And finally we will inject the instance of the main frame to all views and controllers. In this way, we will have only one instance of all the views and controllers, but also they will be accessable everywhere.





Now lets get back to the View and add code for the user interaction request.



As you can see, it is easy to get instance references to the controller class, but the controller is also used in a type safe way. This approach have several advances compared with external configuration files where you wire views and controllers together through weak string references. What will happen if decide to refactor and change a controller method name?

The view can in the same manner be accessed in the same type safe way. To need for external configuration files, such as XML files.

So this is the basic of MVC. Now look if this holds for more complex GUI. Lets say we want to make a desktop application. Well the layout stays the same, but we need to put theirs panel in internal frame. We could do that in the view, but what happens if requirement changes and these views wants to put in a tabbed panel instead. No lets leave the views intact and instead lets created a decorating view that takes a view of panel as argument.



Then we need to modify our main frame class.










Conclusion
MVC greatly reducing the coupling between seperated classes, but doing right is not always easy.

The complete source code from https://sourceforge.net/projects/swingframework/files/.

2011-11-22 av Magnus K Karlsson

How to Install Swedish BankID on Ubuntu 11.10 64-bits


First download the Swedish BankID program from https://install.bankid.com/.

Unzip the file.

Install BankID

The last part is only for 64-bit OS and that is to simulate your 32-bit Firefox pluging to run on your 64-bit OS. To do that you need the ia32-libs and nspluginwrapper packages. On a clean installed computer they are not installed.

To install them

Then install the BankID plugin in Firefox.

Now restart Firefox and test your plugin via https://install.bankid.com/

To read more in depth of the installation, see http://ubuntu-se.org/wiki/NexusPersonal.

2011-11-21 av Magnus K Karlsson

Can Programmers Learn Something from Industrial Design?


Another interest of mine is design and art. Which I will not write more about on this technical blog, but I recently got aquinted with the designer Dieter Rams (http://en.wikipedia.org/wiki/Dieter_Rams) who is interesting in many ways, but one thing that I think is of interest to share on this blog is his famous:

Ten Principles for Good Desing


1. Good design is innovative.

2. Good design makes a product useful.

3. Good design is aesthetic.

4. Good desing makes a product understandable.

5. Good design is unobtrusive.

6. Good design is honest.

7. Good design is long-lasting.

8. Good desing is thorough, down to the last detail.

9. Good design is environmentally-friendly.

10. Good design is as little design as possible.

Where my favourite is the last ”Good design is as little design as possible.”. Like James Bond would have said it ”Less is more.” Or maybe as a programmers would have put it ”KISS”.

You can read more of these principles here http://www.vitsoe.com/en/gb/about/dieterrams/gooddesign.

2011-11-21 av Magnus K Karlsson

Is Oracle Making any Progress with Pushing Java Forword?


Well in one sense, Oracle have managed to release a new Java version 7, but there are still some differences to solve to make the work go faster and smother.

Read more about the Java 7 ballot
http://jcp.org/en/jsr/results?id=5111

and for the Java 8 ballot release.
http://jcp.org/en/jsr/results?id=5112

One can clearly see that the fighting of lawyers are still going on for the license of Java. I hope they solve it and comes to an agrement so that the evolving of Java progresses faster, than it has since Java 5.

For history of previous Java releases, please read
http://magnus-k-karlsson.blogspot.com/2010/10/jaoo-day-4-java-future-at-oracle.html

2011-11-21 av Magnus K Karlsson

How to Disable the Overlay Scrollbar in Ubuntu 11.01 and 11.10


How to Disable the Overlay Scrollbar in Ubuntu 11.01 and 11.10

I like the new look of Unity, but there is one thing that keeps bugging me and that is the new Overlay Scrollbar. To remove it, do the following from the Terminal.

First you need to become root

Then export the following setting:

Last reboot and voilà the classical scrollbar is back.

2011-02-28 av Magnus K Karlsson

Java Bug hangs the JVM


I'm not sure about publishing bugs, but I guess it's already out there and there is also a patch available. The problem is in java.lang.Double and the handling of maximum doouble value, i.e. 2.2250738585072012e-308. The following code will send the older JVM to an infinitive loop.

Ok, but is this really a problem? Yes, it is for Java server connected to Internet. Let's imagine a Bank Server written in Java and exposed/available from the Internet. And you can be quite certain there will some fields taking double as input. These html fields are all Strings, but when processing at the server they are parsed to Double. And this is a typical exploit scenario a hacker can use for hanging the server/DoS attack.

The solution is either patching your current JVM version or upgrading to the latest JVM, i.e. Java 6 Update 24.


http://blogs.oracle.com/security/2011/02/security_alert_for_cve-2010-44.html

This bug is foremost for server application, since desktop application can always be restarted, but if you want to upgrade your desktop java version, please go to http://java.com/.

2011-02-23 av Magnus K Karlsson

Best Practice Aspect-Oriented Programming with JBoss AOP


In my recent project I have been working with JBoss AOP. There have been some pitfalls, I have fallen into and in this blog I will share those you.

First of all. Do not choose aspect-oriented programming to solve everyday Java problems. Example of good cases are:
  • Logging
  • Caching
  • Security
  • Error Handling
But why does AOP does not suites to solve common Java problem? Lets look at an example with Spring and AspectJ.

The Logic class:
The Aspect class:Boilerplate XML configuration files

And now call it
The problem with the code above, is that in FooPojo there is no hint at all, that other code will be called. This can be very confusing for a junior programmer and also to a much more skilled programmer that is not familiar with AOP.So how to make AOP more clearer and more understandable?The answer is to look at other framework and how they have solved it. Take for example Spring. They use AOP very heavily under the hood, to solve common tasks as marking classes as transactional (@Transactional). And in J2EE, Oracle uses also Annotation, e.g. in JAX-WS they have the method Annotation @WebMethod, to signal that a method is a Web Service method.So lets copy that pattern, to write your own Annotation, as marker in the code that you want to apply apsect-oriented programming to.Our own Annotation, to trigger Aspect:
Our Aspect. Here we use interface implementation. This solution works on JBoss 4.3.0 - 5.1.0:

The JBoss AOP configuration file, META-INF/jboss-aop.xml

Now lets create a Test class, that we annotate with our own Annotation:

And a Unit Test to verify it is working.

And here is the maven pom.xml

To make the example complete, we also need to supply a log4j configuration file.


To run/debug this inside Eclipse we need to copy the argLine from the maven pom file to the unit test file configuration.



For more about JBoss AOP Maven plugin , see http://community.jboss.org/wiki/JBossAOPMavenPlugin.

2010-10-27 av Magnus K Karlsson

The Default Timeout Value for Standard Java Socket is Infinitive!


In my last week I have been doing some stability testing using both the Java standard java.net.Socket and javax.net.ssl.Socket. Which are both are part of the J2SE standard library. What I found out to my big surprise, was the standard value for socket timeout (getSOTimeout()) is infinitive!

What are the consequences of this? Well, except that all blocking socket operation will hang forever. But maybe the biggest problem is, it opens up for Denial of Service (DoS) problems.

Example DoS: A server is overloaded and services it's request slower and slower. And now, if new additional clients connected, even more resources are consumed. What will happen with this system in the end is it will ran out of memory or IO. This is not wanted!

What is wanted is a fail-fast strategy, i.e. client that do not get response in a certain time will close it Socket and report back to interactive user or machine.

2010-10-24 av Magnus K Karlsson

Ubuntu 10.04 Change Default Size of Terminal


One of the probably first thing you want to change when starting using Ubuntu is to change the default size of the Terminal window. In earlier version of Ubuntu that could be accomplished via the Edit -> Profile Preference menu from the Terminal, but with Ubuntu 10.04 that is no longer possible. Instead do the following:


Go to System -> Preferences -> Preferred Applications -> System (tab)

Change Terminal Emulator to "Custom".
Command: gnome-terminal --geometry=237x24
Execution flag: -x


2010-10-08 av Magnus K Karlsson

JAOO Day 4 – Not Only SQL, NOSQL


Today I listened to Emil Eifrem CTO at Neo Technology. What I liked most of his talk was the categorization of the today existing NOSQL solution:

Key-Value Database
An Amazons project that uses global key-value mapping to for DB.

Dynamo: Amazon's Highly Available Key-value Store (2007) (http://s3.amazonaws.com/AllThingsDistributed/sosp/amazon-dynamo-sosp2007.pdf).

Other Example:



Column Database
A Google project that uses a big table, with column families.

BigTable: A Distributed Storage System for Structured
 Data (2006) (http://labs.google.com/papers/bigtable.html)

Other Example:



Document Database
Data is organized as document and a document is a key-value pair.

Example:



Graph Database
Data is organized in a graph, which Nodes and Relationships have properties.

Example:

Example of company using NOSQL
  • Google: Bigtable
  • Amazon: Dynamo
  • Amazon: SimpleDB
  • Yahoo: HBase
  • Microsoft: Dynomite
  • Facebook: Cassandra
  • LinkedIn: Voldemort 

2010-10-07 av Magnus K Karlsson

JAOO Day 4 – Java Future at Oracle


Today I was listening at Brian Goetz in his talk “Java Future at Oracle”. This talk was a warn welcome, since yesterday Java User Group, where it was not so much warmth about the evolving of the Java language, due to the problem in the Java Community Process (JCP). And how this has set footprint in the deliveries of new JDK version.

JDK 1.0 1996
JDK 1.1 1997
JDK 1.2 1998
JDK 1.3 2000
JDK 1.4 2002
JDK 5.0 2004
JDK 6.0 2006

JDK 7.0 2011?
JDK 8.0 ???

So what about new feature, well he said that they going to push out JDK 7.0, but of the expense of cutting functionality, which means in short:


And that's it.

But on the other hand he also said that JDK 8.0 will be planned to be released thereafter 1-2 years, which sounds promising. Which Project Lambda (http://openjdk.java.net/projects/lambda/) will among other stuff be included. Other stuff in the pipe is also the Project Jigsaw (http://openjdk.java.net/projects/jigsaw/).

But the most interesting stuff was the news that they plan to merge the HotSpot with the JRockit! Wow, what a killer that will be! But, an unanswered question is, if they will change the license model of the JDK. It is like Brian put it: Oracle is really an easy company to understand, it is about making money.

And what about the JCP? Well, he quickly mentioned the problem, and this a top priority for Oracle to solve. And I really do hope that they solve this and quickly.

2010-10-05 av Magnus K Karlsson

JAOO Day 3. The Stagnation of the Java Language


Today I visited one of Java User Group (JUG) at the JAOO conference – the “Next next step for the Java ecosystem.” There were three person in panel James Gosling, Kevlin Henney and Dave Thomas and they all three confirmed on the misfortune fact that the Java Community Process (JCP) is not working properly or as Rod Johnson (member of JCP board) put it in his session “Where Next for Enterprise Java”. Compare the number of Java Specification Request (JSR) produced this year with the number produced 2-3 years back.

And one can really ask when JDK 7 will be released and how much really will be included of the project Coin (minor language feature change), Jigsaw (effort to make Java more modular) and Lambda (bring closure to Java)?!?

And I guess this fact is the why there today are so many new language created for the JVM – the community is responding and will not wait.

But there is rescue to the help and as James put it, if you cannot wait use Scala.

James Gosling
http://nighthacks.com/jag

Kevlin Henney
http://blogs.stickyminds.com
http://programmer.97things.oreilly.com/
http://curbralan.com/

Dave Thomas
davethomas.net
eclipse.org
agilealliance.org

Rod Johnson
http://blog.springsource.com/author/rodj/

2010-10-05 av Magnus K Karlsson

Getting Started with Scala - IDE support


The key thing when start using a new library or as in this blog, start writing a completely new language, is to have an IDE that is working with and not against you.

I had the pleasure of talking with both Martin Odersky and Jonas Bonér at JAOO in Aarhus Denmark and they both recommended the IntelliJ Scala plugin, but Martin also added that he had started a company scalasolutions.com with one of the aim to write a better Scala plugin for Eclipse, and when that comes out, I would really recommend you to test it. Another question which IDE to choose is also of course which IDE you have previously worked with and acquainted with.

In this blog I will share my experience of using both the IntelliJ and Eclipse IDE, but also how to build your Scala code with Maven.

IntelliJ
Since I don't have a business license of IntelliJ I used the Community edition, you can find the comparison matrix between the free and commercial edition and also the download link from.
http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

After installing IntelliJ, you install the Scala plugin with the Plugin Manager

File | Settings | Plugins

Select tab Available and search for Scala, then right click to install.

After restarting, you create a new Java Module and add Scala Library from local downloaded Scala distro.

Experience
Plus:
  • Normal code completion and code navigation works.
  • OBS when debugging, you have to append the name mangling '$1' to every variable to be able to Evaluate. This seems a bug in the Plugin, since the name mangling should be shielded from you and is strict Scala internal, to overcome Java restriction of operating overloading, etc.
Minus
  • The IntelliJ Scala plugin compiler is really slow, even for small amount of code. There are ways to get around this by using Scala background compiler server, but I have not got that up and running yet.

Eclipse
I used the Eclipse 3.5.2 (Galileo) and install the Eclipse Scala plugin (http://www.scala-ide.org/) with the Eclipse built in Software Installation.

Help | Install New Software... | http://download.scala-ide.org/update-current Add

After that you can create a new Scala Eclipse Project.

Experience
Plus
  • The Scala Plugin compiles code enormous time faster compared with the IntelliJ, but it also have drawbacks.
  • Code completion is not always working if program Scala in it most compact form, sometime it then helps to program a little more verbose, e.g. anonymous function "kalOk".exists(char => char.isUpperCase) instead of the more compact "kalOk".exists(_.isUpperCase)
  • OBS when debugging, you have to append the name mangling '$1' to every variable to be able to Evaluate. This seems a bug in the Plugin, since the name mangling should be shielded from you and is strict Scala internal, to overcome Java restriction of operating overloading, etc.
Minus
  • Code completion is not always working.

Conclusion
After testing both IDE, I must say that Eclipse wins, and mostly because of the slow compilation in IntelliJ. But I hope even if you choose to use another IDE, that this blog post helped you with choosing which IDE you will use.

Maven
After choosen IDE, you clearly also want to have build tool support and I will here discuss Maven, but I also knew that SBT (http://code.google.com/p/simple-build-tool/) is also a great alternative, but I will not cover that in this blog.

The simplest way is to use the scala archetype, but before please check the page http://docs.codehaus.org/display/MAVENUSER/Archetypes+List, to see that not a newer version has been released.

To check that everything worked install the new Maven project.

Now lets open the new pom and see what has been generated. The first thing you see is that Scala 2.7.0 is used, change that to 2.8.0 but also remove the Scala Spec Test in

scala-maven/src/test/scala/se/msc/example/MySpec.scala

Finally you can also remove the specs dependency. I will in coming post discuss Scala Unit Testing, but for now simply use JUnit 4, that you are probably familiar with.

Thats it happy coding!

2010-10-05 av Magnus K Karlsson

Day 2 at JAOO. A Compact Day with James Gosling, Jim Webber and GIT


Day 2 was a packed day with big stars as James Gosling and for you that don't know it, Gosling have quited Oracle, if you want to read more, google or read Gosling own blog http://nighthacks.com/roller/jag/.

But the day started with Cliff Click from Azul Systems (azulsystems.com) and talked about top ten performance problem they seen of hosted Java application in production. This was interesting and I will probably get back with a better blog about that. What also was interesting was suggested tools for detecting different kind of problem:

JVM

  • dtrace, hprof, introscope, jconsole, visual vm yourkit

OS

  • dtrace, oprofile

Network

  • Ganglia, iostat, lsof, nagios and netstat


The next talk was from Google about Scalability, Availability and Stability, which in mine humble opinion, brought not so much new solution to the problems. It all cooked down to sharding, fanning out,  replication vs. caching, eventual consistency and asynchronous calling.

After lunch did Jim Webber talked. Jim Webber is mainly the guy behing REST and if you are intrested about that you should definitely read his book. REST in Practise.
http://www.amazon.com/REST-Practice-Hypermedia-Systems-Architecture/dp/0596805829/ref=sr_1_1?s=books&ie=UTF8&qid=1286232319&sr=1-1

At the end of evening I had the pleasure of talking to both Martin Odersky and Jonas Bonér about the new started company Scala Solution (http://www.scalasolutions.com/) IDE plugns, faster compile time, who is owning the code, founding and Scala akka (http://akkasource.org/), but I will get back more about that later.

2010-10-03 av Magnus K Karlsson

Day 1 at JAOO Object-Orienteed meets functional: An Overview of Scala


The first Training at JAOO 2010 was held by Martin Odersky in Scala. Scala is truly an interesting new programming language, it runs on top of the JVM, but brings so much new programming technique that is not possible with the existing Java language.

It was a truly refreshing talk, but also a sadly realization that the evolution of the Java language has really slowed down since the release of Java 5. The difference between Java 6 and Java 5 is mostly a faster JVM, that is not bad, but on the functional side of new language technique is quite depressing to see such a short list of new feature. And it is not getting better. A couple of days ago a checked out the Oracle web page of new programmatic feature in Java 7 one can see the list is short.
http://www.oracle.com/technetwork/java/7-138633.html

And what is happening the other main stream programming corner at Microsoft? Well they have not been lazy. On could right fairly argue that C# has been become a more advance language than Java. So with this in mind, I'm really looking forward to participate the Training. So what did Martin talk about. Well, the Scala language is really huge, so the talk for 4 hours, did not covered all parts, but one thing is sure. Looking at Scala is almost like learning a new language. For you out there, that have not started looking at Scala I only got one question for you:

Do you want to program Java 6 or 10? See the complete video of Martin Odersky. http://www.scala-lang.org/node/1305

"If I were to pick a language to use today other than Java, it would be Scala"
by James Gosling, creator of Java
http://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programming

"I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I’d probably have never created Groovy."
by James Strachan, creator of Groovy
http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html

"Scala, it must be stated, is the current heir apparent to the Java throne. No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable. While Scala is not a dynamic language, it has many of the characteristics of popular dynamic languages, through its rich and flexible type system, its sparse and clean syntax, and its marriage of functional and object paradigms."
Charles Nutter, creator of JRuby
http://blog.headius.com/2009/04/future-part-one.html

2010-08-05 av Magnus K Karlsson

Opening New Window in Ubuntu 10.04 Does Not Get Focused


I had a really annoying problem after installing Ubuntu 10.04 which I found a solution to today. The problem was whenever I was opening a new window that new opened window was not focused. Quite annoying! The solution is following:
  1. System → Preferences → CompizConfig Settings Manager
  2. Select General in the right hand window.
  3. Select General Options.
  4. Select the Focus & Raise Behaviour tab.
  5. Change Focus Prevention Level to Off.


2010-07-05 av Magnus K Karlsson

Your First Cup of Coffee


A friend of mine asked me to provide a simple getting started guide for a first time Java programmer and it so happened it were other people that also wanted the same thing, so all of you out there here it comes, a simple learning by example guide in Java.

The example is a simple Web application that do simple Create, Retrieve, Update and Delete (CRUD) operation against a MySQL database.

Before starting writing you need to install the following on your system.
Installing programs on Windows is a pain and I will leave that as an exercise and instead show you how that this is done on a Linux platform, Ubuntu (ubuntu.com).


That's it! That took 3 minutes on a modest Internet connection. Are you still stuck on downloading the files on your Windows machine? And thereafter looking forward to reboot you system after each installation?

The Eclipse Ubuntu installation bundle is sadly quite old and therefore it is better to download the zip file manually and extracted it anywhere of you liking and run eclipse.exe (eclipse) in the eclipse folder.

Now lets create your database. Start the MySQL Query Browser and right click in the Schemata dockable window and then select Create Schema.... Enter simpledb.
Now double click on the newly created schema and then right click again to create a new table.



From here you can take several paths, either create a new project with maven archetype 'simple-webapp' (http://www.sonatype.com/books/mvnex-book/reference/web-sect-creating-project.html) or you can install the m2eclipse plugin (http://m2eclipse.sonatype.org/installing-m2eclipse.html) and create your project from Eclipse. Here, I will hopefully, choose the easiest way and do it manually, since we only will be needing two source files, where one will be empty – web.xml and index.jsp.


Now create you Maven Project Object Model file pom.xml in first-coffee/pom.xml


Now create your first-coffee/src/main/webapp/WEB-INF/web.xml


And finally your dynamic web page (first-coffee/src/main/webapp/index.jsp), where all your work be done.


To test your application, simply start the Maven built in web server, from your first-coffee directory.



Now open your web browser and enter the address http://localhost:8080/first-coffee/.

If you want to continue to further evolve this simple example, you can leave the jetty server running and simply refresh you web server, after saving your changes.

2010-07-01 av Magnus K Karlsson

Getting Started with Apache Camel and Prepare for Apache ServiceMix Deployment


Apache Camel is dream framework for any developers that is confronting with any type of integration task. What makes Apache Camel so great is:
  • Testability. It is design from the beginning to be a framework that going to support Test Driven Development. With this follows a fast development cycle, since all code can be debugged and executed from a simple JUnit test case.
  • Solves the two foremost problem that an integrator faces:
  • Seamless protocol crossing, i.e. no coding for fetching data from e.g. HTTP and forwarding it to JMS.
  • Default implementation of Enterprise Integration Pattern (http://www.eaipatterns.com/toc.html) that is easy to extend and configure. If you are not familiar with EIP, I recommend you to take the time and read the EIP homepage or if you do not want to miss a thing read the complete book written by Hophe and Woolf (http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683).

The next best thing is that Apache Camel is a POJO based solution, which means that it can be deployed and ran in any deployment environment:
  • Standalone Java Application
  • Web Container
  • J2EE Container

When talking of deployment and integration the most common question is. What about ESB? And this is also when Apache Camel shines. Apache Camel is fully supported by Apache Camel parent project Apache ServiceMix, that supports the industry standard Java Business Integration standard. The JBI specification has been criticized about being a slow way of developing integration software and in many aspect that is true, but with Apache Camel as core developing framework that is no longer true.

The reason to select an ESB platform to deploy your integration software is:
  • Management. The ESB platform is specially design to manage integration programs.
  • Redundancy and Scalability. A good ESB platform is specifically design to handle these issues when the load and uptime requirements increases.

But one thing, that in my opinion, the Apache Camel homepage lack is good starting example of showing the above strength. So lets get started with NOT writing a production code example, but instead lets write a JUnit test case that you can debug, then you can continue of writing your production code.

In the below example I will also take into account that one day, you might want or NOT take the next step and move your Apache Camel code into a full blown ESB environment.

Lets first look at your Maven pom.xml.




To read more about all configuration options for the above endpoints, see http://camel.apache.org/components.html

An Apache Camel route can also be configured in a XML file, which is the natural choice since you want  things to configurable and not static defined in a Java class, but more about in my next blog.