Archive for the ‘Java’ Category

Glassfish v3 as Windows Service

That’s is something simple but I’ve taken a long time to figure out how to set my Glassfish v3 server as a Windows Service.

After a long time doing google searching, I came across a simple solution. All that you need to do is enter in your Glassfish v3 bin directory and run the command:

c:\glassfishv3\bin\asadmin create-service

Yeah! Just it will work!

I hope this tip be useful for you too!

See you . . .

Getting Parameters from HttpExchange

You now in Java 6 has some APIs to create lightweight HTTP server. Well, today, I had to created a lightweight HTTP server embedded in an application, but when I try to get the parameters for a request I noticed the HttpExchange class doesn’t have a method for that.

After some researches on Google, I come across a solution.

What I did was to create a Filter class which will deal with the parameters parse:

public class ParameterFilter extends Filter {

    public String description() {
        return "Parses the requested URI for parameters";

    public void doFilter(HttpExchange exchange, Chain chain)
        throws IOException {

    private void parseGetParameters(HttpExchange exchange)
        throws UnsupportedEncodingException {

        Map<String, Object> parameters = new HashMap<String, Object>();
        URI requestedUri = exchange.getRequestURI();
        String query = requestedUri.getRawQuery();
        parseQuery(query, parameters);
        exchange.setAttribute("parameters", parameters);

    private void parsePostParameters(HttpExchange exchange)
        throws IOException {

        if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
            Map<String, Object> parameters =
                (Map<String, Object>)exchange.getAttribute("parameters");
            InputStreamReader isr =
                new InputStreamReader(exchange.getRequestBody(),"utf-8");
            BufferedReader br = new BufferedReader(isr);
            String query = br.readLine();
            parseQuery(query, parameters);

     private void parseQuery(String query, Map<String, Object> parameters)
         throws UnsupportedEncodingException {

         if (query != null) {
             String pairs[] = query.split("[&]");

             for (String pair : pairs) {
                 String param[] = pair.split("[=]");

                 String key = null;
                 String value = null;
                 if (param.length > 0) {
                     key = URLDecoder.decode(param[0],

                 if (param.length > 1) {
                     value = URLDecoder.decode(param[1],

                 if (parameters.containsKey(key)) {
                     Object obj = parameters.get(key);
                     if(obj instanceof List<?>) {
                         List<String> values = (List<String>)obj;
                     } else if(obj instanceof String) {
                         List<String> values = new ArrayList<String>();
                         parameters.put(key, values);
                 } else {
                     parameters.put(key, value);

After that you can add this filter to your HttpServer context:

HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
HttpContext context = server.createContext("/myapp", new myHttpHandler());
context.getFilters().add(new ParameterFilter());

Then you can do something like below in your HttpHandler to get the parameters:

public class MyHttpHandler implements HttpHandler {

    public void handle(HttpExchange exchange) throws IOException {
        Map<String, Object> params =
           (Map<String, Object>)exchange.getAttribute("parameters");

        //now you can use the params

Well, that’s all! I hope you enjoy the tip!

Getting start with Scala

In this post we will introduce Scala programming language. Also we will learn how to install it and create a famous Hello World application.

Scala as it’s own site says, is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothy integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.

The name Scala stands for “scalable language”. You can use Scala to a wide range of programing tasks, from writing small scripts to building large systems.

Scala runs on the standard Java platform and interoperates seamlessly with all Java libraries.

Technically, Scala is a blend of object-oriented and functional programing concepts in a statically typed language.

Scala is expressive & light-weight

var capitals = Map (
  "Brazil" -> "Brasilia",
  "US" -> "Washington",
  "France" -> "Paris"
capitals += ("Japan" -> "Tokio")

Everything is an object

Scala is a pure object-oriented language in the sense that everything is an object, including numbers or functions.

Numbers are objects

Since numbers are objects, they also have methods. And in fact, an arithmetic operations + – * / consists exclusively of method calls.

This expression:

1 + 2 * 3 / x

Is equivalent to the following:


Functions are objects

Functions are also object in Scala. It’s possible to pass functions as arguments, to store them in variables, and return them from other functions. This ability to manipulate functions as values is one of the cornerstone of a very interesting programming paradigm called functional programming.

See the code example:

object Timer {
  def oncePerSecond(callback: () => Unit) {
    while (true) { callback(); Thread sleep 1000 }
  def timeFlies() {
    println("time flies like an arrow")

  def main(args: Array[String]) {


Classes in Scala are declared using a syntax which is close to Javaś syntax. One important different is that classes in Scala can have parameters:

class Complex(real: Double, imaginary: Double) {
  def re() = real
  def im() = imaginary

This class takes two arguments. These arguments must be passed when creating an instanceof class Complex, as follow: new Complex(1.5, 2.3). Also the class contains two methods, called re and im, which give access to these two parts.

Inheritance and overriding

All classes in Scala inherit from a super-class. Whem no super-class is specified, scala.AnyRef is implicity used.

It is possible to override methods inherited from a super-class. It is however mandatory to explicity specify that a method overrides another one using the override modified:

class Complex(real: Double, imaginary: Double) {
  def re = real
  def im = imaginary

  override def toString() =
    "" + re + (if (im < 0) "" else "+") + im + "i"


Apart from inheriting code from a super-class, a Scala class can also import code from one or server traits.

The easiest wary to understand what traits are is to view them as interfaces which can also contains code. When a class inherits froma trait, it implements the trait’s interface, and inherits all the code contained in the trait.

Let’s look a classical example: ordered object. It is often useful to be able to compare objects of a given class among themselves, for example to sort them. In Java, object which are comparable implement the Comparable interface. In Scala, we can do a bit better by defining our equivalent of Comparable as a trait:

trait Ord {
  def <  (that: Any): Boolean
  def <= (that: Any): Boolean = (this < that) || (this == that)
  def >  (that: Any): Boolean = !(this <= that)
  def >= (that: Any): Boolean = !(this < that)

The type Any which is used above is the type which is a super-type of all other types in Scala.

Let’s define a Date class representing date:

class Date(y: Int, m: Int, d: Int) extends Ord {
  def year = y
  def month = m
  def day = d

  override def toString(): String = year + "-" + month + "-" + day

  override def equals(that: Any) : Boolean =
    that.isInstanceOf[Date] && {
      val o = that.asInstanceOf[Date] == day && o.month == month && o.year == year

  def < (that: Any): Boolean = {
    if (!that.isInstanceOf[Date])
      error("cannot compare " + that + " and Date")

    val o = that.asInstanceOf[Date]
    (year < o.year) ||
    (year == o.year && (month < o.month ||
                        month == o.month && day <

The last method to define is the predicate which tests for inferiority. It makes use of a predefined method, error, which throws an exception with the given error message.

Installing Scala

To install Scala is pretty simple. First you need to download Scala from

Then unpack the Scala installation file and set the environment variables:

Environment Variable Value
Windows %SCALA_HOME%

Run it interactively

The scala command starts an interactive shell where Scala expressions are interpreted interactively.

> scala
  This is a Scala shell.
  Type in expressions to have them evaluated.
  Type :help for more information.

  scala> object HelloWorld {
       |   def main(args: Array[String]) {
       |     println("Hello, world!")
       |   }
       | }
  defined module HelloWorld

  scala> HelloWorld.main(null)
  Hello, world!
  unnamed0: Unit = ()

Compile it

The scalac command compiles Scala source files and generates Java bytecode which can be executed on any standart JVM

> scalac HelloWorld.scala

Execute it

The scala command executes the generated bytecode with the appropriate options:

> scala -classpath . HelloWorld

The Hello World Program

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello World!")

If the object extends Application, then all the statements contained in that object will be executed, so we don’t need a main method:

object HelloWorld extends Application {
  println("Hello World")

Here is another HelloWorld example in Scala:

object HelloWorld extends Application {
  for(i<-List("olleH", " ", "!dlrow")) {

I intend to write more about Scala here, but if you want to lean more right now go to Scala site:

That’s all folks!

Semana de Palestras

Essa semana que passou foi a semana das palestras. Quinta-feria passada dia 23, eu estive na ETEC de Vargem Grande do Sul apresentando uma palestra sobre Tecnologia Java. Tivemos um auditório lotado e parece que o pessoal gostou. Agradeço a todos da ETEC de Vargem Grande do Sul pela oportunidade e também pela participação dos alunos.

Na última sexta-feira, dia 24, foi um dia da minha apresentação sobre JRuby on Rails. Na verdade foi uma sessão técnica onde eu mostrei como fazer uma aplicação usando JRuby e Rails e depois usando Warbler para empacotar a aplicação e fazer o deployment no Glassfish. Também foi muito bacana mostrar para o pessoal como Rails é produtivo e fácil e o mais importante mostrar que é possível através do JRuby usar todos os recursos de uma plataforma Java. Obrigado ao pessoal que esteve presente na apresentação.



Sun Certified Developer for Java Web Services 5.0 Results

Hi All,

Today I am very happy to inform that I got the Sun Certified Developer for Java Web Services 5.0.

After a hard study and a very stressed exam test with 150 questions I got this good news. Looks our Study Group worked!

I really thought that I would not get this result since I thought the exam very hard, but everything went well.

Have a nice day,

Leo (SCDJWS 5.0)

Transaction strategies


I’ve just read a very interesting article in DeveloperWorks about Transaction strategies to avoid some common transaction pitfalls. I thought that very useful to understand how transactions work in EJB3 and Spring Framework.

Take a look at that:

Transaction strategies: Understanding transaction pitfalls

All the best,


SCDJWS 5.0 My Study Notes

Hello Folks!

Yesterday I finished doing my notes for the SCDJWS 5.0 Beta exam. It’s a lot of stuffs to study and my test is coming (next week). I prepared a document with some information I found on the internet. There so many sources. The document is not 100% covering the exam, but it has a lot of information that will help you on your studying.

As a good person! 😀 I will share with you this material. You can download it from here.

Good Study and Good Luck on the test!

Have a nice week!


Studying for SCDJWS 5.0 Beta Exam

Yeah! I’ve already begun studying for the SCDJWS 5.0 Beta Exam. We have either create a study group for this exam in our company. We have about 22 members, each one cooperating for get material for this exam.

This weekend I will be studying about subjects in Section 1, 2 and 3.

I am actualy in Section 1 and using as base of my studying the material from

I am using that for XML documents syntax and for XSD, SOAP, WSDL, and UDDI 2.0 as well.

The others materials I am using are the following:

Web Services Overview:

Basic Profile 1.1:

I am creating a resume of all those subjects and hope to share with you in this Blog. Also I will be updating this post as soon as I get more materials.

Have a great day!


FREE BETA: Sun Certified Developer for Java Web Services (SCDJWS)

Sun Microsytems has announced the new FREE BETA Sun Certified Developer for Java Web Services exam. This new exam tests on the Java 2 Platform, Enterprise Edition 5.

As a FREE BETA test you don’t need a voucher to take the exam.

Beta Dates: October 31st, 2008 thru November 21st, 2008

Registration Exam Start Date: October 29th, 2008 – November 7th, 2008

Recommended Prerequisites

  • Prior to attempting this certification, candidates MUST be certified as a Sun Certified Programmer (SCJP), any edition
  • Candidates should have at least six to twelve months experience developing Java Web Service

To see the test objectives go to the site:

I hope to take this Beta Exam so probably I will post some material I got here! Stay tuned.

See you!


Launched the Java 6 Update 10

Sun has launched the Java 6 Update 10 that solves several issues and also brings some new features.

New features:

  • Next Generation Java Plug-in
  • New Direct3D Accelerated Rendering Pipeline for Microsoft Windows Platforms, Enabled by Default
  • Applet Deployment using Java Network Launch Protocol
  • Java Web App and Next Generation Web Browser Plugin
  • Java Kernel
  • Java Quick Starter
  • JRE Update (static vs patch in place)
  • Windows JRE Autodownload Files (online update only)
  • Unsigned Java Applet Window Change on Windows

Also with this version you can create Translucent and Shaped Windows.

I am updating my Ubunty Hardy to test the new features.

See you!