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 =)

Posted in java | Tagged , , , , , , , | 5 Comments

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.

Posted in scala | Tagged , , , , , , | 11 Comments

Scala Problem Number Two

Following with my take on the Scala 99 Problems that I started here, lets talk a little bit about the second one. Here is the problem definition, from the original page:

P02 (*) Find the last but one element of a list.
Example:

scala> penultimate(List(1, 1, 2, 3, 5, 8))
res0: Int = 5

This one is very similar to the last problem and has similar solutions as well. The first solution I tried was, again, an ugly one:

def penultimate[A](list: List[A]): A = {
  list(list.size-2)
}

Terrible, but works. The second solution is nicer, with pattern matching, as before. But this time I learned a little bit from Phil Gold’s solution for the first problem, so prettier it is:

def penultimateWithPatternMatching[A](list: List[A]): A = list match {
  case x :: y :: Nil => x
  case _ :: tail => penultimateWithPatternMatching(tail)
  case _ => throw new NoSuchElementException
}

You can find Phil Gold’s solution to this problem here. His simpler solution is a bit better than mine, so my mind expands a little bit and I learn =). Also, he plays with a generic finder – interesting to read, and more mind expanding happens.

Posted in scala | Tagged , , , , | 1 Comment

Ninety-Nine Scala Problems

Listening to a few different podcasts (The Java Posse among them), I found out about Ninety-Nine Scala Problems. As the description on the site says, it is an adaptation of the original Ninety-Nine Prolog Problems. I find the idea very interesting and decided to give it a go.

In summary, this is a bunch of (sort-of) small problems to be solved. You can use them to improve your knowledge in a programming language – Scala in this case. I won’t pretend I know where this trend started, but whoever had this idea for the first time, kudos to you!

During the next (bunch of, a lot of, certainly not few) weeks I’ll go through the problems trying to solve them, and post my impressions here. Those impressions will most likely contain my solutions, so please bear that in mind if you intend to try to solve the problems yourself as well. Also, the page mentioned above with the problems has possible solutions available and I’ll mention them, with links to the originals.

US_99

US_99

To allow you to understand what that feels like, lets talk about the first problem, which is really easy.

The definition of the first problem says:

P01 (*) Find the last element of a list.
     Example:
     scala> last(List(1, 1, 2, 3, 5, 8))
     res0: Int = 8

I came up with basically two solutions. One that is pretty obvious and ugly, using the size of the list:

def last(list: List[Any]): Any = {
  list(list.size-1)
}

The other solution used Pattern Matching to decompose the list, until we have only the last element:

def lastUsingCase(list: List[Any]): Any = list match {
  case x :: Nil => x
  case x :: list => lastUsingCase(list)
  case _ => Unit
}

Phil Gold”s solutions include one Pattern Matching version, which is a little more elegant than mine, and a version using a built in feature that gives direct access to the last element of the list (the last function). I didn’t know about this function, so I already learned something new from this whole 99 Problems thing =) You can find Phil Gold’s solutions for this problem here.

Posted in scala | Tagged , , , , | 1 Comment

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 =)

Posted in agile, java | Tagged , , , , , | Leave a comment

Motodev Summit Brasil 2010

One more quick post about an event. This time, the Motodev Summit 2010, that happened this last Wednesday, May 5th, 2010. I don’t have too much to say about it; in summary, it was a lot more marketing from Motorola than I was expecting. I was expecting more deep, technical stuff.

One of the talks...

One of the talks...

But there is one point I would like to make about Motorola, which is the reason to write this post. Motorola is releasing the Shops4Apps store. It is basically one more option for developers to sell mobile applications. It took me a while to understand why they are doing it, since there is already an Android Market, and almost all of their phones are Android phones today.

So here is what I think they’re doing: they are trying to beat Nokia, directly. Nokia has their own market place, called Ovi Store. It is out there, running and being used for a while now. Motorola wants to have their store as well. Simple as that. Also, I can think of one more reason they might be doing this: competitive advantage against other Android devices. Something like “our Android is better than the other’s”.

Boring... lets check e-mail...

Boring... lets check e-mail...

Now, as far as I know, we have quite a few market places / stores to sell mobile applications already: the Apple App Store (iPhone, iPad etc), Android Market, Ovi Store and now Shop4Apps. And this is to talk about the big ones; there are smaller initiatives out there.

What do you think? Is Motorola crazy to try to compete in this market all by itself instead of, for example, joining the Android Market or something like that? Or is this the right move? And what about the other markets? Do you think they are viable options to make some money? I might be wrong, but here in Brazil, at least for now, the Apple App Store seems to be the only place you can make some money today.

Please leave a comment with your thoughts!

Posted in misc | Tagged , , , , , , , , , , , | 6 Comments

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

Posted in scala | Tagged , , , , , | 2 Comments

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!

Posted in java | Tagged , , , , , , , , , | 4 Comments

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.

Posted in java, peer-to-peer | Tagged , , , , | 1 Comment

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

Posted in java | Tagged , , , , , | 1 Comment