Thursday, October 1, 2009

Alternative languages for the JVM @ OpenWorldForum Paris

Today, a was kindly invited by Alexis Moussine - Pouchkine to be the Scala advocate in a roundtable about alternative languages on the JVM, during a session about the Futur of Java in Open World Forum meeting in Paris.

The sessions was brief (3 parts of about 30 minutes), and in my feeling a bit outside the main topic of OpenWorldForum which was more about open source at a strategic an politic level, but (surprisingly for me) our room was quite crowd, with interested people.

Alexis gave the first presentation about the state of Java and OpenJDK, and final presentation,  about forthcoming JavaEE 6. As always, I really liked to hear and see Alexis make the show, his presentations were really good, and he defenitly deserve his "JavaEE and Glashfish Evangelist" title.

The roundtable begun with a presentation from Stéphane Fermigier of the way accomplished by Java and the JVM as a platform for other language since it's first release back in 1996.
Afterwards, Guillaume Laforge (of course for Groovy) and I (for Scala) talked about our prefered language, the "welcomeness" of the JVM plateform, the always funny debate about dynamically and statically typed languages, and the fact that we seem to be going to a world of "polyglotism", where multiple languages would cooperate on top of a highly industrialized, robust and efficient VM, and be selected for their adequacy to the task to accomplish - all that things mixed up with attendees questions. 

And then, even if we went past the given 30 minutes (well, actually, even went past the 40 minutes...) it was already time to stop.

It was a really pleasant meeting, and I'm really happy to see that Groovy is now a first class citizen in the Java world, that Scala is beyond the status of new intriguing thing and becomes to be evaluated in different places, and that we can say "functional programming" elsewhere than in an University or some strange startup without being looked as a dangerous, non business compliant hacker.

Sunday, September 20, 2009

Faster log in in Ubuntu 9.10 "Karmic Koala" and e17

I'm a long time user of Enlightenment 17, or e17. I mean, a really long time user, since I used it since the end of 2004 or so. If I kept it for so a long time dispite of all its rough edges, it's because I love a lot of things in e17, like the default windows and mouse focusing behaviour, the possibility to have a lot of cool and usefull desktop effects with a real open source driver that doesn't support 3D acceleration.


But what I like above all the the speed of the the environement. In e17, everything seems to be quick and responsive - well almost everything, Firefox and OpenOffice are what they are ;)
For example, the login process in e17 takes a couple of second. I mean, really a couple: I validate my user/password in GDM, and hop, my desktop environement is fully-loaded and usable.

OK, so why I'm talking about that ? Lastly, I tried the new Ubuntu Karmic Koala Alpha 5. Before anything else, I do know what alpha means, and I'm not saying anything against Ubuntu, things are expected to enhance until end of october.
Among a loads of other things, Karmic Koala introduces a new transition screen when X is loading, in order to smoothen a little transitions : XSplash. The problem is that XSplash doesn't seem to be aware of the speed of e17, and when you login, it loops for quite a long time (perhaps 20 seconds ?) before letting the desktop be shown.

So, the solution is simply to disable XSplash for the login, and let e17 loads within its 2 seconds:
in the file /etc/gdm/PreSession/Default comments the things related to XSplash, or if "Default" file only contains XSplash related things, disable it like that (of course, be aware that as Ubuntu is only in alpha phase, this file may be use for other things that Xsplash in the future, and you can break other things with that) :


mv /etc/gdm/PreSession/Default /etc/gdm/PreSession/Default.disabled


That's all ! Now, you can enjoy the lightning login speed of e17 on Ubuntu Karmic Koala.

Friday, August 14, 2009

Why simple XML processing is so painful in Java ?


Note: this article is of little interest to learn Scala XML apis, there is far better coverage of them elsewhere in the web, like here and in details here. It's more like a rant against Java, which makes things painful where it should shine...


Nowadays, XML is more or less everywhere, especially when there is data to dispatch between applications, protocols, program languages and other technologies - and no, Json is not (yet ?) as ubiquitous as XML for that.

And still nowadays, parsing simple XML documents in Java is a pain.

Well, actually, I don't speak about complex, normalized documents with defined, huge XSD schemas (perhaps in this situation, you can afford to invest time in Jaxb or Jibx to do it the right way), nor simpler scenario, but where you want to have a real XML/Object mapping - XStream is a kind here, and really does a good job.

I'm talking about kind of XML documents which are more like a database dump, that may be long and with rather deep tree structures, and where you just want to cherry pick some values - of course, in different parts of the tree. You know, when you just want to test ideas, and you have to implement a quick, working thing to see if the overall architecture works [1], and you really don't want to build a full POJO tree to change or erase it the next hour.

That's a kind of place where Java XPath API (jaxp) should shine. But it doesn't. I'm not saying that it's difficult, nor that it doesn't actually work, but that it's painful and you end up with lines and lines and lines of burden (cast, expression compilation, redefinition of higher function than the ones provided by API to do common things, etc) in code that should just expose your intention at first sight.

Well, lets take a super simple example.

Lets say that I have this kind of XML data :


<?xml version="1.0" ?>
<request>
<id>463516</id>
<timestamp>1250240149028</timestamp>
<information>
<person>
<id>463</id>
<firstname>Alex</firstname>
<lastname>Bar</lastname>
<age>34</age>
<gender>male</gender>
<address>
<street>136 W 9th St</street>
<city>Casper</city>
<country>United States</country>
</address>
</person>
</information>
</request>

And I only want to take the timestamp, add the city in a male or female list depending of the gender, and if age > 18, increment the count off adults.

I have a data container that looks like[2]:

public class Data {
public static final String MALE = "male";
public static final String FEMALE = "female";

private final Long timestamp;

private final Map<String, List<String>> stats;

private int adults;

public Data(Long timestamp) {
this.timestamp = timestamp;
this.stats = new HashMap<String, List<String>>();
this.stats.put(MALE, new ArrayList<String>());
this.stats.put(FEMALE, new ArrayList<String>());
}

public void addMale(String city) { this.stats.get(MALE).add(city); }
public void addFemale(String city) { this.stats.get(FEMALE).add(city); }
public Long getTimestamp() { return timestamp; }
public void incAdults() { this.adults = this.adults + 1; }

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("time: ").append(this.timestamp).append("\n");
sb.append("female: ");
for(String s : stats.get(FEMALE)) {
sb.append(s).append("; ");
}
sb.append("\n");
sb.append("male: ");
for(String s : stats.get(MALE)) {
sb.append(s).append("; ");
}
sb.append("\n");
sb.append("adults: ").append(adults);
return sb.toString();
}
}

OK, I now this the simplest Java class I came with to implements this logic:

/*
* So, you need a lots of imports,
* and you must have jaxp-api
* somewhere in you path
*/

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


public class ParseData {

/*
* the "throws Exception" is here to try to remove a
* lot of burden, but of course, don't do that at home !
*/
public static void main(String[] args) throws Exception {

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("data.xml");
XPath xpath = XPathFactory.newInstance().newXPath();

// now, I start to actually do something interesting
Data data = new Data(Long.parseLong(
s(xpath, doc, "//request/timestamp/text()")));

XPathExpression xe = xpath.compile("//request/information/person");
NodeList nodes = (NodeList)xe.evaluate(doc,XPathConstants.NODESET);

for(int i = 0; i < nodes.getLength() ; i++) {
String gender = s(xpath, nodes.item(i), "//gender/text()");
String city = s(xpath, nodes.item(i), "//address/city/text()");

if(Data.MALE.equals(gender.toLowerCase())) {
data.addMale(city);
} else if (Data.FEMALE.equals(gender.toLowerCase())) {
data.addFemale(city);
}

if(Integer.parseInt(s(xpath, nodes.item(i), "//age/text()")) >= 18) {
data.incAdults();
}
}

System.out.println(data);

}

/*
* Why do I have to do that ? Even it it's two lines,
* I just let you imagine the look of the
* main loop without this function...
* But why the Xpath API doesn't have the four of five
* functions alike defined for each XPathConstants types ?
* Before actually begin to use the API, I have to redefine it...
*/
public static String s(XPath xpath, Object root, String expr) throws Exception {
XPathExpression xe = xpath.compile(expr);
return (String)xe.evaluate(root, XPathConstants.STRING);
}

}


As you can see, there is a lots of type cast, and I quickly loose what I'm looking for, even in a so simple class with so little cases and data to retrieve.

So, at the end, what did I do ? Just use the Scala XML library. Same logic, in a scala class:



import scala.xml.XML

object ScalaParseData {

def main(args:Array[String]) {

val doc = XML.load("data.xml")

val data = new Data((doc\\"request"\"timestamp" text).toLong)

for(person <- (doc\\"request"\"information"\"person")) {
val city = person\"address"\"city" text

(person\"gender" text).toLowerCase match {
case Data.MALE => data.addMale(city)
case Data.FEMALE => data.addFemale(city)
}

if((person\"age" text).toInt >= 18) data.incAdults
}

println(data)
}
}


In both case, the same output is printed in stdout:

time: 1250240149028
female:
male: Casper;
adults: 1


Even if you never look at Scala, you understand what is the global logic, what piece of data are looked for. Nothing to add :)


[1]: ok, the question here is: is Java the right language for that ? Well, it seems that the answer, for whose who still had doubts, is DEFINITLY NOT.

[2] OK, even the data container is complex, and Java really miss Tuples structure to prototype efficiently. In such a process, you just don't want to spend time writing POJOs and POJOs and POJOs that are only, meaningless container for two string lists and a long, even if you IDE does 90%of the job. If you are interested by more efficient data structure for Java, you should go and look for Functional Java, that's a really cool project - and at least, you will have tuples (named "products" here), function class (to not have to define again and again that Filter<E> { boolean filter(E element); } class)

Sunday, June 7, 2009

A Tour Of Scala @ OSSGTP - Paris OSS user group

Thursday (4 june 2009), I gave a presentation about the Scala programming language to the OSSGTP group (Open Source Software - Get Together in Paris).

This presentation is available under Creative Common BY-NC-SA, so you are free to download the source, use it, enhanced it and redistribute it !





PS: let me know if you see any errors, or if you use it, it will make me happy
PPS: I took inspiration from "Programming in Scala" book by Martin Odersky, Lex Spoon and Bill Venners, "Pragmatic Real World Scala" by Jonas Boner, "A Scalable Language" by Martin Odersky and "The feel of Scala" by Bill Venners - thanks for their great presentations and books !

Thursday, May 28, 2009

100 problems solved on Project Euler

Today, I just finished my 100th problem on Project Euleur, using Scala - of course.

Project Euler is a really good way to learn a language on small problems, to see its different sides and idiomatic constructs, and be confronted on performance/algorithm optimization choices - that teaches you to feel when something migth make you gain an order or two of execution time / memory consumption, and when you are working for peanuts.

OK, you won't see how the language solves big architectural design and maintenance problems, but you will learn if the language fits your mind, and if you are able to get things done with it. And definitly, Scala shines on such problems, and completly fits my mind.

So, it was a really good learning experience. Now, I need to test it on bigger problem, to see how it goes on the long run, and I have some ideas for that...

  © Blogger template 'Minimalist G' by Ourblogtemplates.com 2008

Back to TOP