ZiltiTech

Desktop and server programming with the JVM

Subscribe to RSS feed

Code showdown: Java vs Scala - Round 2 - Mathematics

, ,

So here's my second code showdown. This time I compared Java and Scala in how efficient one can use these languages to solve mathematical problems.
For this comparison I used the Problem 3 of Project Euler. The goal is to find the biggest prime factor of 600851475143.
Now there is something I have to say before presenting the code. This time I respected the different paradigms of coding of both Scala and Java. While the Java version is written very imperative and object oriented (is recursion imperative programming?), the Scala version is very functional and implemented as a script executable by the Scala interpreter, although there wouldn't be much overhead (~4 additional lines of code) to make it a full Scala class.
Some might argue that the usage of different coding paradigms renders the whole comparison unusable. But remember that, even though to a certain degree Java can be programmed functional and Scala imperative, this isn't what they where made for.

In Java, the code is as follows:

 1 public class PrimeFactors {
 2 
 3         LazyList lazyList = new LazyList();
 4         public static void main(String[] args) {
 5                 PrimeFactors primeFactors = new PrimeFactors();
 6                 System.out.println(primeFactors.getPrimeFactors(600851475143L));
 7         }
 8         
 9         public java.util.Stack<Long> getPrimeFactors(Long target) {
10                 java.util.Stack<Long> factors = new java.util.Stack<Long>();
11                 return getPrimeFactors(target, factors);
12         }
13         
14         public java.util.Stack<Long> getPrimeFactors(Long target, java.util.Stack<Long> factors) {
15                 for(int i=0;;i++) {
16                         Long prime = lazyList.get(i);
17                         if(prime <= target && target%prime == 0) {
18                                 factors.push(prime);
19                                 return getPrimeFactors(target/prime, factors);
20                         }
21                         else if(prime >= target) {
22                                 return factors;
23                         }
24                 }
25         }
26         
27         class LazyList {
28                 
29                 private java.util.List<Long> primeNumbers = new java.util.ArrayList<Long>();
30                 
31                 public LazyList() {
32                         primeNumbers.add(2L);
33                 }
34                 
35                 public Long get(int i) {
36                         if(primeNumbers.size() <= i) {
37                                 int diff = i - (primeNumbers.size() - 1);
38                                 for(int x = 0; x < diff; x++)
39                                         calcNextPrime();
40                         }
41                         return primeNumbers.get(i);
42                 }
43                 
44                 private void calcNextPrime() {
45                         Long start = primeNumbers.get(primeNumbers.size()-1);
46                         for(Long counter=start;;counter++) {
47                                 boolean isPrime = true;
48                                 for(Long i=2L;i<counter;i++) {
49                                         if(counter%i == 0) {
50                                                 isPrime = false;
51                                                 break;
52                                         }
53                                 }
54                                 if(isPrime) {
55                                         primeNumbers.add(counter);
56                                         break;
57                                 }
58                         }
59                 }
60         }
61 }

And now, the equivalent Scala code:

   1 val target = 600851475143L
   2 val primeList = nextPrime(2L)
   3 println(factor(target))
   4 
   5 def nextPrime(start:Long):Stream[Long] = {
   6     isPrime(start) match {
   7         case false => nextPrime(start+1L)
   8         case true => Stream.cons(start, nextPrime(start+1L))
   9     }
  10 }
  11 
  12 def isPrime(num:Long, mod:Long = 2L):Boolean = {
  13     num < mod*mod || (num%mod match {
  14         case 0 => if(num == mod) true else false
  15         case _ => isPrime(num, mod + 1L)
  16     })
  17 }
  18 
  19 def factor(num:Long, factors:List[Long] = List()):List[Long] = {
  20     println("Get factor for "+num)
  21     primeList takeWhile(_ <= num) find(num%_ == 0) match {
  22         case None => factors
  23         case Some(x) => factor(num/x, x::factors)
  24     }
  25 }

So this time it's pretty obvious. The Scala code is a lot shorter. Of course, the programming paradigm plays an important role in this. Functional programming just is better suited for mathematical problem solving. Especially the extensive use of pattern matching makes the code a lot shorter and better readable. In Java, on the other hand, recursive functions can cause quite some redundant code by requiring very verbose method overloading. Additionally I had to implement a lazy loading list in Java since there is no equivalent to Scala's "Stream" collection. Regarding this Java stands quite well compared to Scala despite being known as a language that's very verbose.
As for readability, usually a bit more verbose code is more readable. But here, the difference is quite big. Additionally, the Java code uses loops with increment variables, which makes the code less readable.
So this round goes to Scala and functional programming.

Code showdown statistics:

  • Readability: Java 0:1 Scala
  • length: Java 0:1 Scala

Code showdown: Java vs. Scala - Round 1

, ,

I don't know if I'll do more than one of these, but here is my first "code showdown", comparing length and readability of a function written in both Java and Scala.
Let's assume we have a class "Map" which contains a variable "map" of type List[ List[ Tile]] (or, in Java, List<List<Tile>>).
Now we want to fill this empty list with "height" lists each containing "width" entries.
In Java, we need the following code:
public Map createMap(int width, int height) {
   Map map = new Map();

   for(int i=0;i<height;i++)
      map.map.add(new ArrayList<Tile>());
   
   for(List<Tile> list : map.map)
      map.add(Tile.create(0));
   
   return map;
}

And in Scala, the equivalent code is:
def createMap(width:Int, height:Int):Map = {
    var map = new Map
    map.map = List.fill(height) { List[Tile]() }
    map.map.foreach(x => Seq.fill(width) { Tile.create(0) } )
    map
  }

As we can see in this case, there is no big difference in length (both have 4 lines of code) or readability - but Scala definitely is more elegant. In this example, readability is a matter of taste, but for me both examples are equally easy to read. That's a draw.

Code showdown statistics:
readability:
Java 0:0 Scala
length:
Java 0:0 Scala

Use Scala as a JSR-223 Scripting Language

, ,

Today I started working with Apache Pivot, and I wanted to use Scala as the scripting language. Since Apache Pivot accepts all languages that support JSR 223, I had to find an implementation to do this.
Actually, Apache Sling, a web framework, contains an implementation of JSR 233 for Scala, so I downloaded it and integrated it into my project.
The sources of that "sub-project" are located at http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/scala/script/ and are easily to fetch and can then be built using Maven.
After doing this, you have a jar-file ready for usage - the only dependency is the slf4j-api-package which you can get from http://www.slf4j.org, and, of course, the scala-compiler jar with the scala.tools-packages (Both are available via Maven as well).
A script must be wrapped inside an object - which can either be a class or an object.
Either you can just use this plain object as a starting point. Or, and now it's getting more interesting, you can use the ScriptArgs argument:
import org.apache.sling.scripting.scala._
class Script(arg:ScriptArgs) {}

ScriptArgs contains methods to access the surrounding environment. You can use the standard java.reflection classes to find out more about the methods, e.g. to print out all method names:
var methods:Seq[Method] = arg.getClass.getMethods
methods.foreach(p => println(p.getName))

Unfortunately, that's not yet a very comfortable way to script using scala - it would be much better if it would work in a way like the scala interpreter does. In that way we have it here we have to define a class and an import even before we can even start to script.

Why we need to change the way we think about the future of desktop technologies

, ,

The end-user experience of computing has changed dramatically during the last 10 years. Ten years ago, end-users used a lot of locally installed applications and stored their data locally. Today, many people mostly use the webbrowser and store their data remotely. Because the managers did want it like that. Of course, this has advantages, but it also has disadvantages.
But I think it's time to re-think today's application concept.
We should start to see the world wide web as an at least two-layered construct for the end user:
First, there's "HTML" as in "Hypertext markup language". As webpages guiding the users to new information and to applications.
And as second part, there are the actual applications. Those applications should be self-actualizing. And there should be more than one platform for them. Today most web-applications are done in HTML/CSS/JS, because all internet users have a browser.
But there should be more than one platform - and there actually is more than one. Almost every computer has Java and Flash installed as well. And all those three platforms have technologies to keep their applications up-to-date. The webbrowser does this naturally, by downloading the page each time it gets called, Java has Java WebStart and Flash has Flex.
All three platforms have their specific advantages. As of today, the browser is best suited for "normal" displaying of all kind of things, Flash has its advantage in vector animation, and Java definitely is the platform of choice for complex end-user applications.
Today, developers try to force their ideas into the corset called HTML/CSS/JS. I think that's wrong. All three technologies are well-suited for end users by easily supplying applications for them, and there's place for at least those three. We should start to really use them before it is too late and alternatives to browsers aren't available anymore (as in: no one has installed them).
Java doesn't rival Flash, and Flash doesn't rival the Browser. They are just three different approaches for doing basically the same thing: Delivering applications to end-users. All three are great technologies, and we should ensure that we keep those different options to develop and deploy applications. To have competition is good and results in many advantages for both developers and consumers.

And there is some other thing I don't like about the "RIA" platforms (Apache Pivot, JavaFX, Flex): They all try to somehow imitate the browser. You can design and position UI elements in a CSS-like manner or even have to write the UI as if it was HTML. I think that has its place, too, but that this is basically the wrong way to do it. Because by imitating the browser, they rival it, and they will lose. They have to be different to the browser to win and have their part of the cake.

Why JavaFX for devices most likely will fail

The developments on mobile devices and digital TVs was overwhelming lately.
Java ME is literally inexistant for today's phone users. There aren't any appealing consumer apps at all. And Adobe began taking over the position Java ME had by providing mobile versions of their Flash player. And they're doing for real devices what JavaFX only offers in emulators: write once, run anywhere, across all devices. And the final release of Flash 10.1 is just months away, with Adobe heavily pushing their platform. Meanwhile, Oracle didn't tell anything. Not about a JavaFX roadmap nor about when there finally will be JavaFX enabled smartphones, settop-boxes and TVs.
And the concurrence isn't sleeping, especially on TVs Oracle/JavaFX won't have a chance as soon as Microsoft, Apple and Google (and Adobe) have established their platform.
If Oracle doesn't start to invest approx. millions of dollars into PR and Development, JavaFX will stay what it is today: literally inexistant. And completely inexistant on devices.
Especially the old way of licensing the technology (as they did with Java ME) won't work anymore: The handset manufacturers and os developers just don't need it. There are good, free alternatives out there today.
Just my 5 cents to the situation of the JavaFX platform.

A Library as an interface between RESTful webservices and JavaBeans

, , ,

Yesterday I started a small project (as part of a bigger one). My bigger project will contain a server-side part and a client-side part. Because I can't use Java EE for the server side, I decided to build a REST-service for supplying my Java SE part with the data.
Now I'm developing a small library which uses the Reflection, Bean, Net and XML-APIs to simplify the process of "converting" the JavaBeans into XML for REST and inversely.
The whole thing seen from the outside is an interface which is used to mark Beans as "REST-able" and a class to perform the REST actions GET, POST, PUT and DELETE.
Right now the Rest-Class manages the connection itself, but I think I'll change that to create the connection outside and just pass the stream to the Rest-Class.
The XML gets parsed and built using the StAX API.
The only thing I don't really like is the way I read and write the JavaBean. I'm just using the simple pattern that I read all the methods and check if they start with set, get or is. Isn't there a better way to do this? After all, JavaBean is a standard, and there should be reflection methods to use the setters and getters of the bean.
The library will get released some day next week.

Lopia opensourced under the GPL

I decided to opensource my social network client Lopia. The project is available at Kenai.com.

Feel free to join the project to contribute graphics, code or just ideas.

I just uploaded the code and put some better documentation than I had before (speak: almost none) into it.

I'm right now writing a document about my plans of what to integrate into the project.

See you on kenai.com!

Howto: Doing some storage in JavaFX

, ,

Today I'll show you an example of how you can use the storage API efficiently. For my social-networking-app Lopia I wrote some wrapper code around the JavaFX Storage API. I won't write about the Storage API itself, because there's a detailed description using examples in the JavaFX API.

I'm not an expert in code design or design patterns at all, but nonetheless I want to share my work with the hope that people which are new to JavaFX will find it helpful and that I'll get some feedback when I've designed it badly.

So why do I use the JavaFX Storage API? For me it's pretty clear: For signed applications it provides a huge lot of storage (as far as I remember over 80 MiB), it provides still some storage for unsigned ones, and it's platform independent, which means it will work without changes on a TV or a mobile. The second reason is that the files get removed, too, if the user decides to uninstall the application. This can be a problem in some situations. But I'll give my users the possibility to save their settings "in the cloud" anyway.

For my storage implementation, I used key/value pairs which get stored in one file per class. The files are by "convention" named as "package.class.param1.param2" (add more params if you like to).
I then made three .fx-Files, two of them simply holding data:

  • Store.fx which manages the storage itself trought the storage API
  • Setting.fx a class which simply holds a key/value-pair
  • SettingsContainer.fx a class which holds all Setting-classes of one class and provides functions (well, as of now, only one) to access (and later maybe write) the settings stored inside and direct access to the Setting-classes.


Well, let's start with the simplest part: The Setting.fx:
public class Setting {
    public var key:String;
    public var value:String;
}

I think that's pretty obvious. Now we have the SettingsContainer.fx which manages the setting-classes:
public class SettingsContainer {
    public var settings:Setting[];
    public function getSettingValue(key:String):String {
        var value:String;
        for(setting in settings) {
            if(setting.key == key) {
                value = setting.value;
            }
        }
        return value;
    }
}

Now, as we have the data-holding classes, we get to the Store.fx which is - surprise! - not a class but simply a script file, because it doesn't make sense to have multiple instances of it:
public function store(component:String, settings:SettingsContainer):Void {
    var store = Storage {
        source: "{component}"
    }
    var writer = new BufferedWriter(new OutputStreamWriter(store.resource.openOutputStream(true)));
    for(setting in settings.settings) {
        writer.write("{setting.key}~{setting.value}");
        writer.newLine();
    }
    writer.close();
}
public function load(component:String):SettingsContainer {
    var store = Storage {
        source: "{component}"
    }
    var reader = new BufferedReader(new InputStreamReader(store.resource.openInputStream()));
    var line:String;
    var ret = SettingsContainer{};
    while((line = reader.readLine()) != null) {
        var lineSplit = line.split("~");
        insert Setting {
            key: lineSplit[0]
            value: lineSplit[1]
        } into ret.settings;
    }
    return ret;
}

As you can read out of the code, the "library" unfortunately isn't capable of being used in the JavaFX Mobile runtime, because it uses the String.split() method. I have to figure out how to replace this functionality (with the substring method if it's available, or by writing the key and value on different lines), but as of now it's ok. There aren't any JavaFX-capable phones, anyway.

"Proof of concept" Series: Drag and Drop

, ,

Before implementing some technologies, I'm creating a proof of concept to get some efficient, working code I can simply copy-and-paste into my project.
Today, I've done some drag and drop. I'm not sure if I've done it efficient, but it was the most efficient way that came to my mind.
I slightly altered my example into a "Human resources manager". Ok, I just added some labels bigsmile Click the launch button at the end of this post to launch it. (There's some strange layout problem. Just click on "New draggable" to re-layout it.)
There are actually 5 classes inside my drag-and-drop-"component":
  • Main Main contains the stage and scene. The scene contains a Stack containing the "normal" content, and, on top of it, a sequence which is used to store the node(s) (multitouch, anywhere? bigsmile ) which should float above the components.
  • Box I couldn't figure out a good name for the component which is able to hold draggable components, so I simply called it "Box". The Box has functions to add and remove the draggable nodes from/to the scene graph.
  • Draggable Just as the name says: A component which is draggable.
    Well, the "draggable" part actually was difficult to master, I ended up with this code:
    onMousePressed:function(e:MouseEvent):Void {
                offsetX = e.x;
                offsetY = e.y;
    
                this.layoutX = 0;
                this.layoutY = 0;
    
                this.translateX = e.sceneX - offsetX;
                this.translateY = e.sceneY - offsetY;
                dragContainer = DragContainer {
                    draggable: this
                    origin: box
                }
            }
    
            onMouseDragged:function(e:MouseEvent):Void {
                this.translateX = e.dragAnchorX + e.dragX - offsetX;
                this.translateY = e.dragAnchorY + e.dragY - offsetY;
            }
    
            onMouseReleased:function(e:MouseEvent):Void {
                this.translateX = 0;
                this.translateY = 0;
                dragContainer.drop(e.sceneX, e.sceneY);
            }
  • DragContainer this class manages the Draggable by setting the references to the scene graph parts ("dropping" the draggable to the right target, removing it from a Box, usw).
    I think it's alright if I show the code here, because it's the main component which manages the dragging and it's quite short:
    public-init var draggable:Draggable;
        public-init var origin:Box;
    
        init {
            origin.drag(draggable); // Forces the Box "origin" to delete the draggable from its scenegraph.
            insert draggable into Main.floating; // Main.floating is a sequence which is held on top of a Stack layout.
        }
    
        public function drop(x:Number,y:Number):Void {
            var boxBelow:Box;
            if(BoxStore.isBoxAt(x, y)) {
                boxBelow = BoxStore.getBoxAt(x, y);
            }
            else {
                boxBelow = origin;
            }
    
            delete draggable from Main.floating;
            boxBelow.drop(draggable); // Adds the draggable to the Box "boxBelow"
            draggable.box = boxBelow;
            println("{draggable.name} dropped onto {boxBelow.name}");
        }
  • BoxStore each Box has to register itself in this "static class". The DragContainer uses the isBoxAt(x,y) and getBoxAt(x,y) methods to decide where to drop the Draggable and to drop it.
    The BoxStore itself uses the method "box.boundsInParent.contains(x, y)" to determine if the pixel is on the area of a Box.




Get the source code
I've uploaded the source code here: Source

Lopia: User interface concepts

,


Well, yet another post about Lopia smile. This time I'll show you two concepts for the user interface. They might look very confusing, but remember that there will be rounded rectangles and quite a lot of colors.

First, here's the concept of the desktop layout:

Ok, I'll go trough the different labeled areas now.
  • Logo Well, I don't think I have to say much about that bigsmile
  • Toolbar Now that's where it starts to get interesting. Basically, the toolbar is divided into two areas: On the left, there's a drop-down-menu with options, sorted by network, to create "temporary timelines" (e.g. display a Twitter list), and on the right a "classical" toolbar with an option menu.
  • Scroll areas These scroll areas are activated by mouseover and scroll into the pointing directory. There will be a scroll indicator, too.
  • Timeline menu this drop-down-menu contains options to modify, add and remove filters assigned to the timeline below it. Again, this menu will be very graphical, not just filled with text entries one below each other as we know it from classical menus.
  • Dock area That's another new idea for Lopia. You can drag-and-drop timelines onto this dock area to, well, "dock" them onto it. They'll be there one below each other with a small title and behave like a normal timeline, except for that they only show the most recent entry.


And now - *drumroll* - the mobile interface!
    [LIST]
  • Top area There's that top area I don't exactly know how to design. Maybe there will be a small toolbar, too. Or I'll just place everything into the menu which will fill the screen - including the filtering options for the currently opened timeline.
  • Draggable area The other part of the screen is just a draggable area - displaying a timeline, and, if dragged to the left, a dock area like the desktop version of it.


And what about a TV layout (the third device supported by JavaFX)? Well, I didn't create this yet. But I think it will be as similar as possible to the desktop version.

Thanks for reading, and I would be glad to hear some feedback smile

P.S. expect a Lopia beta the next few days wink