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 . . .

Aprenda DB2, um dos bancos que mais cresce no mercado!

Não conhece o Banco de Dados IBM DB2?

Ele é um dos bancos com maior participação corportiva! Grandes empresas o utilizam e estão migrando para o mesmo! Recentemente a IBM ganhou uma conta num dos maiores bancos do Brasil para implementar a solução de DataWarehouse, baseada no DB2 é claro! E essa conta não foi a primeira e nem será a última!

A IBM está altamente comprometida com sua área de Information Management, e está investindo pesado em desenvolvimento, pesquisa e marketing. Um ponto importantíssimo para o Brasil, é que a IBM recentemente inaugurou um Laboratório de desenvolvimento do DB2 em São Paulo, no qual eu trabalho!

Já percebeu então que é importante conhecer DB2 para conseguir uma boa alocação no mercado de TI não é? Então ai vão alguns links para você começar sua brincadeira:

Para baixar gratuitamente o Banco de dados DB2, clique aqui.
Aqui temos um livro gratuito em português com tudo que você precisa para começar.
A página do Developer Works do DB2 tem vários artigos e tutóriais, em português para sua comodidade!
Caso precise de suporte, pode pedir em nosso fórum.
Finalmente temos uma série de vídeos sobre banco de dados aqui.

É isso ai, faça bom proveito dos recursos e participe ativamente da comunidade!

Post original por Juliano Martins

Balsamiq Mockups

Hello All,

If you like me work with application development, you know how difficult is sometimes to produce screen mockups to show to your customers. I’ve used to do that using pencil and paper but today I’ve run into Balsamiq Mockups which is a application developed in Flash specially for design screen mockups. It works on Windows, Linux and Mac OS.

You can take a look how easy is to produce mockups watching the video below:

Balsamiq has a lot of components available:  Labels, Textbox, Combos, Buttons, List, etc.

Another interesting feature is you can export the screen mockup as PNG.

Balsamiq is not free. You can try it online, but I think it’s tool which values each cent.

See ya!

Installing CouchDB on Mac OS X Leopard

Howdy!

I had installed CouchDB using Mac Ports but looks like ports installs an old and bugged version of CouchDb. So I decided to uninstall the couchdb and install it straight from source.

Here we go. Open your terminal and follow the instructions.

Installing CouchDB dependencies

First step is to install the ICU (International Components for Unicode). Execute the following commands:

$ curl -O http://download.icu-project.org/files/icu4c/4.2.1/icu4c-4_2_1-src.tgz
$ tar xvf icu4c-4_2_1-src.tgz
$ cd icu/source
$ ./configure --prefix=/usr/local
$ make
$ make install
$ cd ~

Now, we need to install another dependency, the SpiderMonkey, which is a Mozilla Foundation Javascript engine.

$ curl -O ftp://ftp.mozilla.org/pub/mozilla.org/js/js-1.7.0.tar.gz
$ tar xvf js-1.7.0.tar.gz
$ cd js/src
$ make BUILD_OPT=1 -f Makefile.ref
$ sudo mkdir -p /usr/include/smjs
$ sudo cp *.(h,tbl} /usr/include/smjs/
$ cd Darwin_OPT.OBJ
$ sudo cp *.h /usr/include/smjs/
$ sudo cp js /usr/local/bin/
$ sudo cp libjs.dylib /usr/local/lib/
$ cd ~

CouchDB is developed in Erlang, so we also need to install Erlang

$ curl -O http://www.erlang.org/download/otp_src_R13B01.tar.gz
$ tar xzf otp_src_R13B01.tar.gz
$ cd otp_src_R13B01
$ ./configure --prefix=/usr/local \
  --enable-smp-support --enable-hipe --enable-darwin-universal \
  --enable-threads
$ make
$ make install
$ cd ~

Installing CouchDB

$ svn co http://svn.apache.org/repos/asf/couchdb/trunk couchdb
$ cd couchdb
$ ./bootstrap
$ ./configure --prefix=/usr/local
$ make
$ sudo make install
$ cd ~

After the compiling and installing, you can check the couchdb version

$ couchdb -V

To start the couchdb:

$ sudo couchdb -b

Now, you can open your browser and access the couchdb:

http://127.0.0.1:5984/_utils

To stop couchdb:

$ sudo couchdb -d

That’s all folks

Tutorial de Scala – Parte 1

O que é?

Scala é uma linguagem de programação hibrida, isto é, ele é uma linguagem orientada a objetos e funcional. Scala foi desenvolvida para rodar em um Máquina Virtual, primeiramente em um Java Virtual Machine. O principal compilador, scalac, gera bytecodes que rodam na JVM. Entretanto, existe outro compilador que pode gerar código para rodar em .NET CLR.

Scala é uma linguagem produtiva e concisa.

Donwload and Instalação

Faça download da última versão de Scala na página de download. Depois do download faça a instalação e não se esquece de adicionar o diretório bin no seu PATH. E neste diretório que se encontra os executáveis, incluindo o compilador e o interpretador.

Usando o Interpretador Scala

O jeito mais fácil de começar com Scala é através do seu intepretador que é um “shell” interativo para escrever código Scala.

Para iniciar o interpretador, abra seu terminal e digite: scala

leonardo:~$ scala
Welcome to Scala version 2.7.5.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_13).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

Tente digitar no interpretador algo como  1 + 1 e pressione enter.

scala> 1 + 1

O interpretador vai imprimir:

res0: Int = 2

Você pode usar esse resultado para fazer outras operações, por exemplo:

scala> res0 * 10

E você agora terá o resultado:

res1: Int = 20

Para imprimir valores, você pode fazer assim:

scala> println("Hello Scala")
Hello Scala

Definindo Variáveis

Para definir variáveis em Scala nos usamos a palavras chaves val e var, a diferença é que quando usamos val, estamos definindo uma variável imutável, isto é, somente podemos definir o valor uma única vez e não será permitido alterá-la. Já com var, podemos mudar o valor normalmente quando necessário.

Vamos dar um exemplo usando val:

scala> val msg = "Hello Scala"
msg: java.lang.String = Hello Scala

Este exemplo também mostra um caracteristica importante de Scala, o type inference (inferência de tipo). Como pode perceber nos definimos a variável msg e não especificamos o tipo da variável, porém o interpretador (compilador) Scala inferiu definindo o tipo automaticamente. Ele faz isso com base no valor que está sendo usado para iniciar a variável. Como nesse exemplo estamos inicializando a variável com “Hello Scala”, isto é, uma String, o interpretador (compilador) vai dar o tipo java.lang.String para a variável automaticamente.

Bom, mas lembre-se que estamos usando val, portanto não vamos setar um novo valor para essa variável. Se tentarmos isso vamos receber um erro como abaixo:

scala> msg = "Hello Folks"
<console>:5: error: reassignment to val
 msg = "Hello Folks"

Se o que queremos é poder alterar o valor da variável, então devemos usar var para definir a variável:

scala> var greeting = "Hello Scala"
greeting: java.lang.String = Hello Scala

Agora que greeting é uma variável definida com var não um valor (definido com val), podemos redefinir seu valor a qualquer momento.

scala> greeting = "Hello Folks"
greeting: java.lang.String = Hello Folks

Definindo Métodos

Em Scala nós usamos def para definir um método, veja um exemplo:

scala> def max(x: Int, y: Int):Int =  if (x < y) y else x
max: (Int,Int)Int

O nome do método, neste caso max, é seguido por uma lista de parâmetros entre parenteses. Os parâmetros precisam ter seus tipos definidos porque o interpretador (compilador) não infere nos tipos dos parâmetros. Neste exemplo, o método max tem dois parâmetros do tipo Int. Após a definição dos parâmetros, você pode notar que temos “:Int”. Isto define o tipo de retorno do método.

As vezes o compilador vai requerer que você defina o tipo de retorno. Se o método é recursivo, por exemplo, você deve explicitamente declarar o tipo de retorno do método. No caso do nosso método max não é necessário. Neste caso o compilador vai inferir definindo o tipo de retorno automaticamente. Então nesse caso podemos definir o método max da seguinte forma:

scala> def max(x: Int, y: Int):Int =  if (x < y) y else x
max: (Int,Int)Int

Perceba que no caso dos parâmetros nos sempre devemos definir os tipos independente se definimos o tipo de retorno do método ou não.

O nome, os parâmetros e tipo de retorno formam a assinatura do método. Após a assinatura do método, devemos colocar um sinal de igual (=) e então o corpo do método. Como nosso método max consistem em apenas um linha não é necessário colocar o corpo do método entre chaves { }. Mas você pode se quiser:

scala> def max(x: Int, y: Int) = {     
 |   if (x < y) y else x
 | }
max: (Int,Int)Int

Se seu método for ter mais que uma linha, então será necessário colocar o corpo do método entre chaves.

Uma vez que temos nosso método definido, podemos usá-lo invocando da seguinte forma:

scala> max(3, 5)
res5: Int = 5

Quando temos um método que não tem parâmetros como esse:

scala> def greet() = println("Hello Scala")
greet: ()Unit

Podemos invocá-lo usando ou não parenteses:

scala> greet()
Hello Scala

scala> greet
Hello Scala

Por hoje é tudo pessoal.

Prentendo escrever a segunda parte desse tutorial em breve.

I do Mac now!

Hello Fellows,

After a long time desiring and dreaming, I got bought my first Mac Book. No, I didn’t buy an Aluminum, but I bought the White.

I’m still adapting with it, specially with the keyboard, but I can tell you guys that’s the Apple is amazing! Everything detail is so special and thought here. The Mac OS X Leopard is very stable and also very easy to use. Looks everything you try here is pretty easy to do.

The Mac OS X Leopard already comes with many tools for development. I already have Java, Ruby and Rails. You just have to update them to the latest version and that tasks is to easy.

I am still preparing my development environment, but I’ve already installed Eclipse, Git, Flex SDK, MySQL. For development with Ruby and Rails, I’ve installed Mac Vim and the Ruby plugin, but I am thinking of buying the famous Text Mate editor.

Well, now I’ll install JRuby and also Scala to keep by studies with Scala programming language.

I hope to back here soon sharing my experiences with Mac.

See you soon!

8 Regular Expressions You Should Know

This is a quick post with a tip. In this tutorial you can learn the 8 Regular Expression you should know. That’s very useful.

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 {

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

    @Override
    public void doFilter(HttpExchange exchange, Chain chain)
        throws IOException {
        parseGetParameters(exchange);
        parsePostParameters(exchange);
        chain.doFilter(exchange);
    }    

    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())) {
            @SuppressWarnings("unchecked")
            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);
        }
    }

     @SuppressWarnings("unchecked")
     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],
                         System.getProperty("file.encoding"));
                 }

                 if (param.length > 1) {
                     value = URLDecoder.decode(param[1],
                         System.getProperty("file.encoding"));
                 }

                 if (parameters.containsKey(key)) {
                     Object obj = parameters.get(key);
                     if(obj instanceof List<?>) {
                         List<String> values = (List<String>)obj;
                         values.add(value);
                     } else if(obj instanceof String) {
                         List<String> values = new ArrayList<String>();
                         values.add((String)obj);
                         values.add(value);
                         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());
server.start();

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

public class MyHttpHandler implements HttpHandler {

    @Override
    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!

How to run JRuby on Rails on Google’s App Engine

Are you wondering how to install your JRuby on Rails application on Google’s App Engine?

If so, go to this cookbook.

I have not tried yet, but I’ll try soon.

See you! Leo

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")
println(capital("Brazil"))

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:

(1).+(((2).*(3))./(x))

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]) {
    oncePerSecond(timeFlies)
  }
}

Classes

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"
}

Traits

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]
      o.day == 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 < o.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 http://www.scala-lang.org/downloads.

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

Environment Variable Value
Unix $SCALA_HOME
$PATH
usr/local/share/scala
$PATH:$SCALA_HOME/bin
Windows %SCALA_HOME%
%PATH%
c:\Progra~1\Scala
%PATH%;%SCALA_HOME%\bin

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 = ()
  scala>:q

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")) {
    print(i.reverse)
  }
}

I intend to write more about Scala here, but if you want to lean more right now go to Scala site: http://www.scala-lang.org.

That’s all folks!

Next Page »