Tag Archives: java

Slides from my Akka presentation at Just Java 2012

I just uploaded the slides from the Akka presentation I did at Just Java 2012. You can find them here. The slides are in portuguese because the audience were brazilians, of course ;)

By the way, the conference was really nice and I’ll probably write a post about it in the next few days.


Akka at Just Java 2012 in São Paulo

This weekend, 18th and 19th of May, will hold the Just Java 2012 conference down here in São Paulo, Brazil. If you are in the area, please drop by.

This year, I’ll give a presentation about Akka 2.0 – mainly focusing on vertical scaling. I don’t have the talk completely done yet, so if you have something you would like to see, please get in touch. Otherwise, see you there!


The Developers Conference 2011

From July 6 to 10 happened The Developers Conference 2011 down here in São Paulo. The other editions were really good and, better, this one topped all of them. It was a really fun and productive event. I had the chance to meet friends and to get to know new people. If you were not there, #protip for you: BE THERE NEXT YEAR. Really.

Before talking more about the conference, I have to thank Globalcode (in special Vinicius and Yara). They did a great job =)

Since last year, the premise of the conference is to have people from all kinds of backgrounds, from a lot of different communities, like Java, Ruby, Python, Agile, Javascript, .NET and lots more. Each day featured five different tracks, with different topics, to fit all those communities and tools. The result is that we had a lot of different people and lots of opportunities to talk to people you usually would not encounter. This was a really enriching experience.

In a personal level, this conference was special to me: I made two ‘speaking’ participations. In one of them I talked about Scala, an introductory talk (you can find the sample code used in the talk in my github). The other one was a panel consisting of people from different languages on the jvm – lots of fun =)

In the event, I had one personal fail moment, that should remain as a tip for everyone out there. In a given moment, when talking to someone, I was asked for my business card… and didn’t have any on me. So the obvious tip: always have business cards with you. Always.

Now, if you follow my posts about events you may have noticed that this one is a little different. It contains no pictures. This is due to a second fail, that happened on this last Monday. I lost (or it got stolen…) my mobile. And with it, all the pictures from the entire event. Sorry =(


Scala Problem Number Five

From the Scala 99 Problems, the problem number five goes like this:

P05 (*) Reverse a list.
Example:

scala> reverse(List(1, 1, 2, 3, 5, 8))
res0: List[Int] = List(8, 5, 3, 2, 1, 1)

Starting with the obvious solution, using the API:

val list = List(1, 2, 3, 4)
list.reverse

Yes, the List API has a reverse function. Pretty handy =)

How about being more creative now? Like this:

def myReverse[A](list: List[A]): List[A] = list match {
  case head :: tail => myReverse(tail) :+ head
  case Nil => Nil
}

With pattern matching and recursion, the solution is pretty simple. We basically decompose the list, and rebuild it in the opposite order. The code is simple, but it can take a while to understand if you are not used to recursion. The pattern matching part shows how nicely we can decompose Lists in scala =)

Lets try a different solution now:

def myReverse[A](list: List[A]): List[A] = {
  var reversedList = List[A]()
  list.foreach(item => reversedList = item +: reversedList)
  reversedList
}

Here we take a more ‘traditional’ approach – its closer to what we would do in Java, but still more compact and readable. First we create a buffer list, and add each element of the original list to the beginning of the buffer. Finally, we return the reversed list.

You can find the original solution to the problem here. As always, I learned something more after reading the original solution – I always write my solution before reading that. What I found is that it is also possible to solve the problem in a pure functional way, with foldLeft (copied from the original solution):

def reverseFunctional[A](ls: List[A]): List[A] =
    ls.foldLeft(List[A]()) { (r, h) => h :: r }

This solution is probably the most difficult to get at first, but the best after you get used to this kind of ‘extreme’ functional stuff. Nice =)


About nulls and System Properties in Scala

In Scala, it is usually a good idea to avoid nulls in your code. Instead of that, it is recommended that you use the Option class. This is how it works: if the value you are working with is null, it is represented by None, otherwise, it is represented by Some(value). Both None and Some are subclasses of Option.

This allows you to write code that is much more expressive than having ‘if != null‘ all over the place. Also, it is much less likely that you will forget to verify for nullity. One way of leveraging an Option value is through pattern matching:

val myValue: Option[String] = Some("Hello")
myValue match {
  case Some(x) => println("my value is " + x)
  case None => println("nonthing found")
}

The Option class also offers some collection-like functions that allow for great readability as well. From the Scaladoc:

val name: Option[String] = request.getParameter("name")
val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
println(upper.getOrElse(""))

Notice how the code execute transformations and ‘if-like’ filtering, in a very clean way. After that, they try to use the value with the getOrElse function, which allows you to pass a default value to be used if the result from the previous line was None. Finally, if you REALLY want to use an if statement, you can call the isDefined function, which returns true if the value is Some, false otherwise.

Now lets talk about system properties. Lets face it: dealing with System Properties in Java is boring. You have to get each property you are interested in and have to verify if it is null or empty. After all the talk above, you probably are starting to guess where I’m heading, right?

Well, it is better than that. Scala encapsulates the system properties in a way we can leverage all the Option stuff explained above. Those properties are encapsulated in a class named SystemProperties and can be accessed by the object ‘sys.props‘. Try typing it into a scala console session to see for yourself.

Since it is a map, you can use any map function you can use with other maps. Also, you can add and get properties from this object, and they will be reflected in the actual System Properties – which means that your Java code should be able to read the properties as well, even if through more traditional means (i.e. System.getProperty). Printing all system properties is as simple as:

sys.props.foreach(println)

And you clearly could do something more clever and useful with those properties.

There are two functions available in the SystemProperties class that I want to cover here: get and getOrElse. The first one returns a property with a given name, in an Option. With this, you can now handle your property with all the Option goodness we talked about above. The second function, getOrElse, is basically a direct way of calling the same function you could call in an Option. For example, lets say you read a database configuration from the system properties, and want to fall back to a default configuration if the property is not found:

val dbURL = sys.props.getOrElse("myapp.database.url", "jdbc:postgresql://localhost:5432/mydb")

A lot better than reading the property and verifying if it exists ‘by hand‘, right?


Migrating a java project to scala

Hi everybody!

This time I wanted to bring something different about scala – so I decided to migrate a java project to this language. The chosen one is an open source test framework for the Web Objects framework (sorry for the double f* word there) called WOUnit.

Web Objects is a web application framework that is quite old, and is developed by Apple. I’m not the right person to talk about this framework, so I’m not going further than that. The point is that this framework has some specificities that could make writing pure JUnit tests more troublesome than it should be, and this is where WOUnit comes in.

This project is reasonably small, so its a good choice for our small experiment. I’ll talk about what I did bellow, you can take a look in the project in the link above, and in the changes I made in my fork.

The current changes consisted of the following steps:

  • added the scala plugin and scala library dependency to the project’s pom.xml file – more about the maven scala plugin here;
  • renamed the EOAssert.java file to EOAssert.scala;
  • rewrote the contents of the file to use scala sintax

It was not complicated at all. You can find the current version of the file here. And what have we gained with this?

First, the code is now more readable. Which one is easier to read, this:

public static Matcher<EOEnterpriseObject> canBeDeleted() {
    return new CanBeDeletedMatcher<EOEnterpriseObject>();
}

or this:

def canBeDeleted(): Matcher[EOEnterpriseObject] =
  new CanBeDeletedMatcher[EOEnterpriseObject]

Nice, isn’t it? This comes to a point made by Martin Odersky (creator of Scala), where he said that the most important information in a function / method declaration is it’s name. Makes sense.

Second, you might have noticed that something seems to be missing in the scala version above. The java version has a static method, which doesn’t exist in scala. Actually, it isn’t even needed. Our EOAssert in scala is an object, which means scala handles it internally as a singleton. This feels a lot more correct from an object orientation point of view than having static things all over the place. Yet, from Java, you access EOAssert’s methods exactly as before – which means I didn’t have to change ANYTHING in the EOAssert class usages throughout the project, and it kept compiling and the tests passing.

Also, please notice how we are mixing java and scala code seamlessly here. Any doubts you could use scala as part of just about ANY java project without major headaches?

One thing I’m not sure about how it is working right now are the javadocs. In the migration, I kept then exactly how they were, and I’m not sure how the scaladoc would be generated for then. Since EOAssert class is intended as a public API, this is an issue that must be taken into account.

In summary, I didn’t do too much here – it was just a small experiment on migration a java project to scala. I hope you liked it and perhaps felt that scala is really worth considering serious usage. I’m not sure if I’ll continue this migration, but if I do, I’ll have more posts about it.

EDIT:

about the scaladocs point, this link might help a little bit: http://lampsvn.epfl.ch/trac/scala-old/wiki/Scaladoc/AuthorDocs


Just Java 2011

Hi!

Its been a long time since I last posted about an event. So, to recover from the sadness, lets talk about Just Java 2011, a Java event that happened this last weekend here in São Paulo.

The event consisted of two days filled with three simultaneous talks almost the entire time. The first day was nice and, besides meeting some friends and acquaintances, I learned something about Digital TV (App Store for TV applications!), saw some discussions about cloud computing (GAE, AWS and Azzure) and other Java stuff. There was also a Scala presentation, by Alberto Souza, which was very nice.

Cloud computing discussion

Cloud computing discussion

Now, the second day was the most interesting for me. It started with a Java FX presentation by Roger Brinkley. In summary, now they have a java API to do Java FX stuff almost in release version. So is Java FX Script dead for real? I know its officially dead, but I find it a little sad, since the java code seemed a bit too verbose… Perhaps I should learn more about it before coming to conclusions.

Roger Brinkley talks about Java FX

Roger Brinkley talks about Java FX

Anyway… what followed was another Scala presentation… by me! =) It was the first time I presented at this kind of event, so regardless of being doing Scala talks at Globalcode for a while, I was a bit nervous. The audience seemed to like the talk, so I left feeling quite good. Thank you all who attended! If you are curious, I talked about Scala in general, covering basic ideas and features. Like always, I tried to make people want to learn more about the language. Hope it worked =)

I then proceeded to meet more people, and attend more Java talks. One worth mentioning is about EJB and a coffee machine. The presentation was done by Globalcode’s Vininius Senger, and was really energetic, as all his talks always are.

What he did was to control a power plug with an Arduino board, with a coffee machine plugged into that power plug. If I understood correctly, he had an application server installed in this laptop, where he had a Timer EJB. This EJB would be called through an web interface and schedule a time for activating the coffee machine. Finally, the timer would connect to the Arduino board (through bluetooth I think) and get the power plug activated, and thus the coffee machine turned on. Great Fun!

Vinicius and his coffee machine demostration

Vinicius and his coffee machine demostration

It was a great event. To finish, I would to thank the organizers for the opportunity to talk. I’m looking forward to the next event!


Scala at the guardian uk

Hi!

In the news this last week, there was some information regarding the usage of Scala by The Guardian, a UK newspaper, and one of the biggest on the planet. I was aware that they were using Scala internally, but it seems they are starting to use it more and more.

Graham Tackley, a developer at The Guardian, talked about that in this video: http://skillsmatter.com/podcast/scala/how-we-mostly-moved-from-java-to-scala – its really worth while seeing this, he talks about how The Guardian uses Scala, and of course talks a lot about Scala itself – so much that this could be a great introductory video for you if you don’t know Scala yet.

One of the most interesting things shown in the video is a search tool / API they created – with Scala – to allow people to search their articles. I loved it, and more so for being open. Take a look for yourself: http://explorer.content.guardianapis.com/#/search?format=json

Thats all for now, see you next time!


sbt and maven

A few months ago I talked about my first impressions about sbt (simple build tool) here. My conclusion at the time was that NetBeans + Maven combination would suit me better. This changed a little bit, so I’m revisiting this topic to explain why.

First, I explored sbt a little more. I certainly still have a lot to learn, but I found out one thing that is making a lot of difference: you can use a maven pom file to handle your dependencies. This is great for a few reasons:

  • you can leverage your existing knowledge of pom files;
  • I’m not comfortable (yet) with the sbt own way of handing dependencies;
  • you can use tools that doesn’t support sbt directly – actually I don’t know of any that does that.

Lets elaborate some more. First, lets say you have a project that already uses maven. The first point means you can just type ‘sbt’, create an sbt project, and the tool will be able use the pom.xml file as a source for the project dependencies configuration. You will just have to use the sbt command ‘update’ after each time you change the pom file – which is very reasonable.

Second, the way sbt handles dependencies. Code. Basically, you configure the dependencies in a scala file, that gets compiled with the rest of the project. I don’t find this bad nor good. For now, I don’t have a strong opinion about this – but its still not comfortable.

Finally, the third point means you can use, say, NetBeans, with its great maven support, while using sbt as well. For a small personal project I’m currently working on, this is being very useful. My current development setup consists of NetBeans as the IDE, with sbt running in a console window in the ‘~test’ state. Every time I hit save on a source file inside NetBeans, sbt gets it, compiles and runs the tests. Yet, because I’m using an IDE instead of simple a code editor, a have full source code completion – which is really nice.

Of course this doesn’t work perfectly all the time – NetBeans gets confused from time to time and you might have to ignore some editor warnings. Nothing too bad though.


Why I gave up Google App Engine for now

Google App Engine is nice. Cloud Computing is nice. But I’m giving up GAE for now, and bellow is why.

I (re)started to play around with Google App Engine about one or two weeks ago. Of course I read a lot about it in the past, and decided to play a little bit.

The first thing you have to do is to go to http://appengine.google.com/ and Sign Up. You will have to enter a mobile number and they will send you an SMS to validate your registration. The problems started here for me. It simply didn’t work for my number. After trying several times and waiting a few hours, I decided to use my Mom’s mobile – and a few seconds later, she received the message. It should not be that complicated, but at least now I could try GAE out.

Then, I installed the Eclipse plugin and created a sample project. This is the nicer part of all. Just click the “Deploy to Google App Engine” button in the tool bar, fill in your google credentials in the dialog that will appear, and your application will be uploaded and deployed. Really easy and impressive.

So far so good. So why did I gave up using it? If you read this blog for some time, you already know I’m really interested in Scala. So, what I really wanted to do was to deploy something using Scala to the cloud. Specifically, I wanted to deploy a Lift web application.

It turned out that, during some readings, I discovered that the main feature I was using with Lift doesn’t work with GAE: Ajax and (Ajax) Comet. GAE has  some restrictions that you can usually overcome, but there is one that hits this Lift feature pretty hard:  you cannot create Threads in a Google App Engine application. Usually, this is not a problem, but Lift’s implementation of Ajax uses Actors which, if I understood correctly, are implemented with Threads – and this make a lot of sense.

So, no GAE for me, at least for now. At least until I get bored with Lift :p


Follow

Get every new post delivered to your Inbox.