Archive for the ‘Java’ Tag

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!

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!


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!