Tag Archives: java

Simple Build Tool for Scala

Recently I started looking at some alternatives for increasing productivity when writing code and building systems in Scala. One option that is getting some attention is SBT – Simple Build Tool. In some ways, it is similar to Spring Roo. It generates some skeleton code (not sure how much though) and has an interactive shell that allows us to execute some tasks like compile and building, and even running in an application server if you are building an web application – which is what I was testing.

After some trouble installing, you can simply type sbt in a terminal to start the interactive shell. If the current directory doesn’t have an sbt project created, it will ask you to create one. Then, you can use commands like ~jetty-run to start your web application and make it run with jetty.

One thing I noticed is that it uses maven internally a lot (or seems to…) – at least for downloading dependencies and storing them in the local maven repository. But differently from maven, it copies the libraries used by the project to the project folder and use them from there. Also, although I’m not sure what this means exactly, sbt has several commands that have maven equivalents.

The web application I was trying was the Lift Chat Demo which you can find here: http://liftweb.net/getting_started. It is a pre-made sbt project; after downloading the sample, you execute sbt in the command line and can start playing (they have maven and other tool’s versions as well). When running this application with ~jetty-run changes made to the html files are detected on the fly. And so are the changes made to the Scala code. This is nice, but doable with maven as well.

This last statement leads to this post’s conclusion: sbt is a nice tool, but I’ll stick to maven for now, for one main reason: IDE support. Maven is greatly integrated with NetBeans (and Eclipse as well, I suppose), and I couldn’t find a nice way to use sbt with any IDE. Since I’m NOT a vi programmer, this leaves me with no option for now.

As a last note, please keep in mind that I only took a quick look at the most basic features of sbt – they probably have a whole lot more to offer. It just happens that I’m ok with the NetBeans + Maven combination for now.

And finally, a link that helped me clearing some ideas: http://php.jglobal.com/blog/?p=363

EDIT: Paul Phillips corrected me in an email in the Bay Area Scala Enthusiasts list about sbt using maven. Well, it doesn’t. It uses only the maven repositories, which is absolutely reasonable. Still, it certainly learned a lot with what maven does – again, very reasonable.


N900 Trial

Hello!

After a big pause, I’m back =)

For this comeback I’ll be talking about something off topic, yet interesting: a high end mobile phone.

Out of the blue, I got a chance to try out the Nokia N900. In this post I’ll describe my impressions.

First of all, I own a Nokia N97. Compared to it, the N900′s touch screen feels more responsive. The general impression I got is that this device is more polished than the one I have.

One characteristic that will please some people and make others hate the mobile is that it feels more like a computer than like a phone. The ‘average’ user will hate, the geek user will love. It comes with a Linux version, Maemo, with a nice package manager that allows you to install a lot of stuff easily. But you can fall-back to the command line if you want.

N900

N900

It comes with a ‘stylus’ pen, which is very handy, again better than the N97 one – actually, it seems that the newer versions of the N97 doesn’t even include the pen. I liked using the N900′s pen better than my fingers actually, and mainly when I was playing Mahjongg with it – one of the few games I downloaded from the application manager.

Since I’m a Java developer, I had to try and install Java. Its a bit more trouble than normal, but doable. You install a full Java SE, not a Java ME implementation, which is nice. But the rather small screen won’t help you when you try to run applications developed for a full size monitor. Anyway, I didn’t find much use for it, but it works.

Some readers probably already know that I love podcasts. This means that I HAD to try to use the N900 as a podcatcher. It has a gPodder version that works nicely. Thumbs up, and once again it is much better than the option available on the N97.

One last consideration is regarding the language support. In summary, the language support in Symbian (the N97 is a Symbian device) seems crap to me. I never could get japanese stuff to display properly. With Maemo on the other hand, it worked out of the box. I finally could open japanese websites correctly.

There are some drawbacks as well. But there is only a couple of things that I really disliked in the device: its size and weight. It won’t fit in any pocket, and forget about your shirt’s pocket: it would be really annoying to carry it there.

Finally, I would like to thank womworld for the opportunity. I loved the device and I would buy one if it wasn’t expensive, even more here in Brazil. Also, I would like to apologize to them for the delay when returning the device. It happens that the Brazilian customs puts a lot of bureaucracy on us, so returning the device was a pain.

That’s all, next time I’ll be back on track with Java or Scala or something along those lines. See ya!


Profissao Java 2010

Hi!

Talking again about events: Profissao Java 2010 (something like Java Profession 2010 in english). This event happened yesterday, Saturday, June 26th, 2010 (obviously :P ). Was an one-day event, right to the point filled with information regarding a lot of different topics, from JavaEE to Digital TV to entrepreneurship.

Talking about market opportunities and the right frame of mind when approaching career decisions, Bruno Sousa suggested a few books that we should read:

Bruno Sousa and a few book suggetions

Bruno Sousa and a few book suggetions

One other topic covered by the event was mobile platforms. Including some Java ME, Android and, despite the fact of not being Java, iPhone. I liked it. Here is a picture of Helder da Rocha talking about iPhone development:

Helder da Rocha on iPhone development

Helder da Rocha on iPhone development

Overall, I liked the event. The technical parts were interesting but what I liked the most was the focus on entrepreneurship that a lot of the presentations had. Hearing how others are building their business in our market is always interesting and fun – and help us avoiding some mistakes, when our time comes. The event run a little bit late, having ended after 8 pm, and we left really tired, but it was worth it.

Congratulations to the Globalcode team for one more great event =)


KeyStore Explorer and Digital Certificates

Ok, one more post aimed at my memory, but that can end up helping others as well ;)

I’ve been playing around with digital certificates in Java, because I’ll have to implement some stuff here that requires secure calls to web services using them.

One of the requirements for the secure connection is that our server trusts the Web Service’s server. To do this we have to, somehow, install a certificate chain provided by the Web Service provider. Sounds pretty simple, but can be a little bit troublesome if you are not familiar with how Java works with digital certificates and also with how to handle the keystore tool that comes with the JVM.

At first, I tried to import the certificate chain using the keystore directly, without success. The chain provided is a .pb7 file, which I discovered later that follows the PKCS #7 format / standard / whatever. Having never dealt with such a file before, I had no idea of what to do with it. I just knew I had to import it in my local (or server, when in production) trusted certificate store. But I couldn’t find the proper parameters to pass to keystore so that it would do the right thing…

I gave up this approach for a while and started to google around for some solution. This is when I found the KeyStore Explorer application. It is a free tool that really helps visualizing digital certificates, both installed and the ones available in specific certificate files. I installed the tool, and with some guessing I found how to visualize the .pb7 file mentioned before. Strangely, I had to do some manual labour to import the chain of certificates: I visualized, one by one, all of the certificates in the chain, and exported each one to .cer files. After that, I opened the trusted store and imported all of those certificates into it. Done.

Of course, this solution is not ideal, but works. The ideal would be to import the chain directly using the keystore tool, which is probably possible, I just could find exactly how. If you do know how to do this, please leave a comment =)


DSL in Scala for Date Calculation

I’ve been attending a course about Java Architecture in Caelum these last weeks. In one of those Saturdays, the instructor mentioned a little bit about DSLs. Better yet, he gave us an example using Scala =)

Now, the example was intriguing and interesting, at least for a Scala beginner like me, so I decided to translate it to English (the original was in Portuguese) and post it here. If you want, you can see the original in Portuguese, created by Sergio Lopes, here.

Before seeing the translated version of the DSL implementation, lets take a look on how you would use it – which is the most interesting part:

Tomorrow minus 1 month and plus 10 years and plus 1 day

Although the code above looks like a (almost?) proper sentence, it is valid Scala source code. That’s the beauty of writing DSLs in Scala =)

One thing that took me a while to understand regarding this code is the Conjunction part. Represented by the and instance in this case, its purpose is simple (at least after you understand it): pass a partial result to the next part of the calculation, when necessary. Notice in the code how months, years and days have one overloading that receives a Conjunction. This is what makes possible to yield a result that will be passed to the next calculation step.

Here is the full implementation code of the DSL:

import java.util.Calendar

class Date(val data: Calendar) {
 data.clear(Calendar.HOUR)
 import Date.Conjunction

 private var last = 0;

 def plus(num: Int) = { last = num; this }
 def minus(num: Int) = { last = -num; this }

 def +(num: Int) = plus(num)
 def -(num: Int) = minus(num)

 def months = { data.add(Calendar.MONTH, last); this }
 def months(and: Conjunction): Date = months
 def month = months
 def month(and: Conjunction): Date = months

 def years = { data.add(Calendar.YEAR, last); this }
 def years(and: Conjunction): Date = years
 def year = years
 def year(and: Conjunction): Date = years

 def days = { data.add(Calendar.DAY_OF_MONTH, last); this }
 def days(and: Conjunction): Date = days
 def day = days
 def day(and: Conjunction): Date = days

 override def toString = "%1$Td/%1$Tm/%1$TY" format data
}

object Date {
 class Conjunction
 val and = new Conjunction

 def Today = new Date(Calendar.getInstance)
 def Tomorrow = Today + 1 day
 def Yesterday = Today - 1 day

 def today = Today
 def tomorrow = Tomorrow
 def yesterday = Yesterday
}

The only thing I added to the code was operator overloading, so that the usage can be even more interesting, allowing stuff like this:

Today + 2 months

So, the def + and the def - are not present in the original code. I just added those as an exercise to understand how to use operator overload in Scala, which ended up being ridiculously simple. If you want to learn more about operator overloading, Joey Gibson has a nice blog entry about this here.


TDD Talk at UMC

Yesterday I gave a speech, with two friends, about Test Driven Development at UMC, here in Mogi das Cruzes – SP – Brazil. The talk was nice, and this post is just to thank Claudinho and Fabio, the two friends mentioned previously, and Rodrigo Rocha and the University, for providing the space.

Thank you all =)


Scala Pattern Matching: the reason to fall in love with Scala

Scala has a lot of interesting features and, among them, one of the most interesting ones is Pattern Matching. If you still need a reason to try Scala this is the one. Actually, I might be exaggerating a little bit, but this feature is really interesting. Really. ;)

In summary, Pattern Matching looks like switch statements in Java. But there are a couple of things to keep in mind:

  • Using switch statements in Java is usually a code smell, i.e., something to avoid, risking your good OO design. This is not the case in Scala, where pattern matching is a core feature of the language, and should be leveraged by your applications.
  • Unlike in Java, there is basically no limits in terms of what you can use in the case clause. This, combined with the fact that Scala is a functional language, letting you pass functions around, gives you insane flexibility.

Lets go through a (very) simple example so that you can see by yourself at least part of this power. Suppose you are writing a function that takes an object of any type, and prints some information about it. Here is how you could do this:

class PrettyPrinter {
  def print(obj: Any) = {
    obj match {
      case 1 => println("number one")
      case Client("john") => println("special client: john")
      case Client(name) => println("client: " + name)
      case other => println(other)
    }
  }
}
case class Client(name: String)

object PatternMatchingTest {
  def main(args: Array[String]): Unit = {
    var printer = new PrettyPrinter
    printer.print(1)
    printer.print(new Client("jcranky"))
    printer.print(new Client("john"))
    printer.print("RandomStuff")
  }
}

Notice that, in the same clause, we are matching:

  • an integer number;
  • a specific Client
  • any other Client
  • any object of any class

Very flexible. For instance, in the case where we match any client, notice also that we capture the client’s name “automagically”, and use it in the println call.

That’s all for now. What do you think? Is this powerful enough for you? =D

EDIT:

I forgot to mention the expected output of the code above… so here it is:


number one
client: jcranky
special client: john
RandomStuff


Globalcode’s Casual Class: Digital TV

I just came out from one more of the Globalcode‘s casual classes. The topic this time: Digital TV.

It usually takes me a few days before I write something about an event I attended. Well, its time to change this. But why now?

One of the speakers at the event was Dimas Oliveira. He opened the event (unofficially) asking the audience several different questions that seemed somewhat disconnected at first. But in the end he came to a conclusion that is similar to my reasoning to have this post out quickly. Timing.

Dimas Oliveira

Dimas Oliveira

Do we know Digital TV related buzzwords and/or its related technologies? Or at least know what they are? Do we want to? If so, the time is now. Actually, we might be a little late already. So, learn now, earn the dividends, or give up and move away to something else – later will be too late.

Makes sense? Hope so. Now, to some more concrete stuff. Dimas talked about opportunity, and remembered us that Ginga-J was just approved as an official Digital TV system (system? framework? API? I’m not sure yet about how to call it) down here in Brazil – as of a few weeks ago, actually. There is at least one TV device already available for sale, and there is certainly more to come. Good timing to get in this market for us developers.

Next, Thiago Vespa talked about BD-J – Java for Blue Ray devices. If you live in Mars, you might not know yet that Java runs on Blue Ray devices, like the Playstation 3. BD-J is the technology to use when developing applications that run on such devices. This part of the casual class was a little bit (just a little ;) ) offset from the rest.

Thiago Vespa

Thiago Vespa

Then Neto Marin talked about LWUIT. LWUIT is an API/Framework to develop user interfaces for mobile devices. He explained quickly how it works and followed to a demonstration, given by Thiago again. He demostrated how to develop an Xlet (a Digital TV application), using LWUIT interface. The point being: LWUIT was added as part of the Ginga-J specification, and thus can be used to develop the interface of any Digital TV application.

In time: today they decided to exchange the pizza time to the start of the event instead of the end. What was happening before was that we reached the end of the talkings being really hungry, and couldn’t pay too much attention to the last speakers. Only the beers stayed at the end this time. Good call – I can’t talk for the rest of the attendees, but I liked the change.

No promises, but I might try to play a little bit with Ginga-J. If so, I’ll post whatever results I get here. See you next time!


GridGain first impressions

I’ve been working on a peer-to-peer project for a while. We are trying to build something new and interesting regarding transactions on top of a peer-to-peer network. Hopefully it will be useful =P. I’m not going to talk about that project now; the important point is that I’m aware about how hard setting up and configuring peer-to-peer nodes can be. And making everything work out of the box seamlessly, with an easy to use API at the same time.

A couple of weeks ago, GridGain came to may attention, totally out of the blue. Now imagine my surprise when I decided to test it, following some of their examples. The freaking thing is easy to use and works out of the box. Run a script, a node is running. Do it again, a second one is running. Of course, for more complex scenarios you will have to configure a few things, but the point is that I could starting testing it right away.

The way to build and “deploy” services is ridiculously easy as well. I coded the Hello World example. When running, you start a new node in your main class, and in it you say what tasks you want to execute. GrigGain will then find all other available nodes and, depending on the task implementation, split the jobs between those nodes. Something I liked here is that the task implementation is sent to the other peers in a completely transparent way – you don’t even notice what’s happening.

I won’t dive too much into GridGain here, nor show any code, simply because of another great quality it has: documentation. There is a lot of stuff available, including a lot of easy-to-follow examples. Take a look for yourself. I won’t be using this framework for now, but if I end up needing to implement grid-related stuff, I certainly know where to start looking.

Direct link to the GridGain documentation.


Dynamic namespaces with XSLT and Java

Recently I had to implement an XSLT transformation for a project here. It didn’t seem too complicated at first, since XSLT is not an alien technology – actually, it is pretty simple to use / develop with.

The problem was that, in this particular scenario, we needed namespaces whose URIs were generated dynamically, on pre-defined prefixes. The first idea that comes to mind is to write something like this:

<xsl:attribute name="xmlns:ns">
  <xsl:value-of select="$dynamicURI"/>
</xsl:attribute>

BUT… you can’t do this. Namespaces can’t be declared as normal attributes; the command above is illegal and won’t be processed by your XLST processor – you will probably get an XSLT compilation error.

If you google this problem for a while (which I did) you will find a few workarounds to make dynamic namespaces work. They basically involve creating dummy elements and copying them around. I tried using such approach for some time, but it started to consume too much time to work, and the resulting XLST code was getting really ugly – which also means that I was getting upset with the problem and its solution.

So I decided to look for a better way, and I found out that you could do this:

<xsl:namespace name="ns" select="$dynamicURI"/>

Amazing! Easy! Beautiful! And it doesn’t work with the standard XSLT processor that comes with Java – even Java 6, which I am using. The problem is that this command is specific to XSLT 2.0, which doesn’t seem to be supported by the default XSLT processor that comes bundled with the JDK distribution.

Although I was trying to avoid using external libraries, I had to do it this time. I added Saxon to the project and added this simple line in the code before calling the transformation:

System.setProperty(
  "javax.xml.transform.TransformerFactory",
  "net.sf.saxon.TransformerFactoryImpl");

Of course, there are other, more maintainable, ways to change this property, but you get the idea. Now I have my nice XLST with dynamic namespaces working, in a nice, simple and readable fashion =D


Follow

Get every new post delivered to your Inbox.