Java Reference
In-Depth Information
sum
. These methods are then available in any Groovy collection, whether they include ob-
jects from Java or Groovy.
I've already spent a fair amount of time on collections, though, and I'll revisit them fre-
quently in the topic. So to choose an example from a different Java class, let's illustrate
why it's a bad idea to use basic authentication over HTTP.
In basic authentication a username and password are transmitted in encoded form to a serv-
er. Basic authentication concatenates the username and the password together, separated by
a colon, performs a Base 64 encoding on the resulting string, and sends the result as part of
the authenticated HTTP request header.
There's a big difference, however, between encoding and encrypting. Encoded strings can
just as easily be decoded. Groovy makes it easy to demonstrate this, because the Groovy
JDK adds a method called
encodeBase64
to, of all things, byte arrays. It also adds a
decodeBase64
method to
String
. The following listing demonstrates both.
Listing 4.4. Base 64 encoding and decoding username/password information
There's a lot going on in this short script. First, a username and password are assembled
into a Groovy string. Then the
getBytes
method is invoked on the combined string,
which encodes the string into a sequence of bytes using the default character encoding.
That method is from Java. The result is a byte array. Check the Groovy JDK and you'll
find that Groovy has added the method
encodeBase64
to
byte
[], which returns an in-
stance of
groovy.lang.Writable
. Here I just use its
toString
method (from Java,
of course, though it's overridden in the Groovy class) to see the resulting values. In effect I
went from Java to Groovy to Java in one chained method call.