Skip to content

Tag: Java

Short urls with Glassfish+MySQL


Pipes, Creative Commons photo by flattop341.

1. The Problem

Internet is full of long urls and meaningless.

Long urls are difficult to remember or print, usually full of redundancy and low semantic. With short and meaningful urls you can avoid thes problems and even achieve profitable goals with SEO
SEO (search engine optimization) technics.

There are services like Tiny URL, Fancy URL, Moo URL and others. Although they solve part of the problems, they bring several others. Another problem is if you have a web site like example.com and use a third-party service for short urls you are losing part of your mind-share with your users and clients.

As an example, if a example.com company wants to promote a open work position would be preferable spread a example.com/jobs instead of a tinyurl.com/examplejobs, or even worst, a tinyurl.com/3i4i592 (meaningless hash).

2. Solution Approach

I created a little program called xort that can be placed on your own server and provide you own short maintening your base url.

I use a pipe abstraction. Each pipe redirects from a key url to an output url.

The idea is that you have xort installed and associated into your domain (preferably on /x). A pipe inside example.com would be like example.com/x/jobs.

3. Tools

All those tools are multi platform, open source and free.

3.1 Glassfish Application Server

Glassfish is an open source application server project led by Sun Microsystems for the Java Enterprise Edition (Java EE) platform. It’s very easy to install and run and have a very nice administration web interface where you can do from simple tasks like deploy a application to more complexes like clustering.


Glassfish Admin Console

To develop the application I’m using NetBeans 6.5 Beta that comes with Glassfish V3 prelude b15b. Netbeans also provides a integration of project, database and web server.

Nevertheless, Glassfish has no dependencies with any IDE and perfectly works by alone. If you need I wrote this post explaining how to install and deploy a application on Glassfish from scratch.

3.2 MySQL Relational Database

MySQL is a relational database management system and probably the most used database on internet (has more than 11 million installations). It’s also very easy to install and administer, through command line or many gui interfaces.

To install MySQL and JDBC driver on Ubuntu just run as root:

# apt-get install mysql-server libmysql-java

After installing and configuring it you can test the jdbc driver throught this servlet code. You can optionally register the MySQL on NetBeans to have a easier access to it thought the service tab.

At the command line you can invoke mysql command line interface and use MySql commands or SQL queries. I’ll login and create a database called xort:

$ mysql -u username -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 5.0.51a-3ubuntu5.3 (Ubuntu)

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

mysql> create database xort;
Query OK, 1 row affected (0.06 sec)

You could also create this database by an SQL statement:

CREATE DATABASE xort;

To select the database xort:

mysql> use xort;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql>

Now we create a database called pipes with fields pin (pipe in) and pout (pipe out). They represent the input url and the output url of our pipe abstraction.

CREATE TABLE pipes (
   pin varchar(255) NOT NULL,
   pout varchar(255)
);

As we expect a lot of searches queries on this table, we can optionally create a index for it on pin field. This can reduce ours searches from O(n) to O(logn) (because pin’s will be ordered so don’t need to look all pipes, we can use logn algorithms like binary search).

CREATE INDEX pinindex ON pipes (pin);

Another trick to improve our speed is recycling connections through connection pools.

Creating a pool of MySQL connections on Glassfish is very easy. There’re two good tutorials on this subject:

And now we populate the database with some initial pipes.

INSERT INTO pipes VALUES ('blog','http://silveiraneto.net');
INSERT INTO pipes VALUES ('cejug','http://cejug.org/display/cejug/Home');
INSERT INTO pipes VALUES ('orkut','http://www.orkut.com.br/Main#Profile.aspx?rl=ls&uid=12443310329436634134');
INSERT INTO pipes VALUES ('glassfish','http://glassfish.dev.java.net');
INSERT INTO pipes VALUES ('mysql','http://dev.mysql.org');
INSERT INTO pipes VALUES ('twitter','http://twitter.com/silveira');
INSERT INTO pipes VALUES ('lab', 'http://maps.google.com/maps?f=q&geocode=&q=campus+do+pici&g=Fortaleza,+Brazil&ie=UTF8&t=h&ll=-3.745978,-38.574023&spn=0.002452,0.004823&z=18');
INSERT INTO pipes VALUES ('videos', 'http://br.youtube.com/user/NetoSilveira');
INSERT INTO pipes VALUES ('photos', 'http://flickr.com/photos/silveiraneto/');

4. Program

Basically we have just a program that implement this simple behavior:

  1. separate the key from the url.
  2. if the key is a pin from a pipe then redirect to that pout.
  3. else provide a way to create a new pipe.
  4. list all pipes.
  5. provide a way to remove a pipe.

To get the key we need to separate the proper part of the request uri:

String uri = request.getRequestURI();
String key = uri.substring(request.getContextPath().length()+1);

After that we check if it matches with a pin of some pipe. In this case we redirect user for the correspondent pout:

response.sendRedirect(pout);

Notice that using this approach we can connect a url to a extern or intern url (even to another pipe).

5. Download

Check out the xort project and sources at xort.dev.java.net:

Or grab sources and the current build with:

svn checkout https://xort.dev.java.net/svn/xort/trunk xort

Parameters can be passed by the the web.xml file:

   Set if users can add new pipes using the web interface.
allowNewPipes
true

   JDBC driver to use
driver
com.mysql.jdbc.Driver

   Username to login on the database.
username
root

   Password for the given username.
password
yourpassword

   JDBC path to database.
database
jdbc:mysql://localhost:3306/xort

Xort up and running:

[youtube]b2Mrk8XfvKk[/youtube]

JavaFX Overview Slides

My slides about a overview on JavaFX at our last CEJUG event.

JavaFX Overview

View SlideShare presentation or Upload your own. (tags: javafx ria)

Downloads:

Café com Tapioca na Christus

Café com Tapioca na Christus

Here a little screncast showing the live preview feature on the NetBeans JavaFX Plugin.

[youtube]vCWQtQgdpUA[/youtube]

You can also download the orignal screencast in higher resolution netbeans_javafx_preview.ogg (15 Mb). Photos of the presentation at my Flickr album.

Criando Imagens Dinâmicas em Java na Web

Durante a apresentação do Tarso Bessa em Sobral alguém na platéia perguntou sobre um equivalente a biblioteca GD no PHP. O GD é uma biblioteca para manipulação de imagens comumente usado para criação de imagens dinâmicas (como gráficos) ou miniaturização de imagens. A libGD está disponível para várias linguagens além do PHP.

A respostá para a pergunta é bem simples, você pode usar todo o suporte para imagens disponível no Java SE (inclusive toda a API de Java2D).

Alguns links que podem ajudar:

Viagem a Sobral

Esse fim de semana eu, o Rafael Carneiro, Tarso Bessa e o Paulo Sobreira viajamos para Sobral pelo CEJUG para participarmos enquanto palestrantes do 1º Café com Tapioca Sobral.


Café com Tapioca Sobral
Da esquerda para a direita, Yuri Steindorfer, Paulo Sobreira, Adriano Patrick, Rafael Carneiro, eu, Adriano Pereira e Tarso Bessa.

A minha primeira palestra foi sobre o NetBeans. Hora nós conversei um pouco sobre a história do projeto, a plataforma e as funcionalidades do NetBeans e o que está por vir na próxima versão. Aqui estão meus slides: netbeans_sobral.odp e netbeans_sobral.pdf. Aqui está a versão online em Flash:

NetBeans: a IDE que você precisa

View SlideShare presentation or Upload your own. (tags: cejug cct)

Algumas fotos das palestras:

Café com Tapioca Sobral

Café com Tapioca Sobral

A idéia era fazer a palestra pela manhã e na tarde fazer a prática de NetBeans no laboratório. Porém tivemos alguns impercílios e o laboratório não aconteceu. Para quem ficou na vontade, eu recomendo dar assistir o Guided Video Tour do NetBeans.

O Rafael Caneiro apresentou a palestra “Apresentando o CEJUG e o poder do Java“, o Tarso Bessa “Simplificando o Desenvolvimento Web com Java Server Faces” (inclusive me fez ficar bastante motivado para aprender mais sobre JSF) e o Paulo Sobreira “Relatórios em Java com iReport“.

Nossa grande surpresa na viagem foi a presença massiva a do pessoal de Parnaíba, Piauí, notadamente alunos do Sistemas de Informação da Faculdade Piauiense. Eles  vieram em Caravana de ônibus e percorreram quase 300km para chegar em Sobral (segundo o Google Maps). Isso sem contar que o ônibus quebrou quando já estava bem perto de Sobral. Eles estão de parabéns pelo empenho.

Durante a tarde eu aproveitei que nós tínhamos dois laboratórios e bastante gente e improvisamos uma apresentação sobre certificações Java. Foi bom porque podemos tirar muitas dúvidas e como o Tarso Bessa (SCJP, SCWCD e SCEA) estava lá e pode nos tirar várias dúvidas. Também é uma boa para eles porque eles tem boar oportunidades como o CEJUG Certified e o SAI. Além disso houveram também os mini-cursos “JPA com Hibernate” com o Carneiro e o JSP e JSF” com o Tarso .

Café com Tapioca Sobral

Depois do evento tivemos um tempinho para conhecer mais a cidade. Eu sempre tive muita vontade de conhecer Sobral. Existe uma imensa quantidade de praças, igrejas, locais tombados e museus na cidade. A cidade em si é muito limpa e bem cuidada, os monumentos e a arquitetura original da cidade são muito bem preservados.

Ao lado disso a cidade é bastante desenvolvida, há vários campus universitários e bons restaurantes. Eu confirmei o que eu já tinha ouvido falar mas achei que era só boato, há realmente uma grande rede pública de wifi na cidade. É possível sentar no banquinho da praça, se conectar a rede sem senha e navegar. Um sonho. Além disso há também redes privadas de wifi de provedores de Internet locais.

Nós no “Arco do Triunfo” (na verdade se chama Arco de Nossa Senhora de Fátima) que ilustrou o cartaz do evento.

Café com Tapioca Sobral

As crianças de Sobral me ensinaram o grass-surf, uma nova modalidade esportida.

[youtube]10xd9Uw-4OI[/youtube]

Nós de volta a Fortaleza ao lado do “Carneiromóvel”.

Eu adorei a viagem, faço uma avaliação muito positiva do evento e acredito que vamos colher ótimos frutos. Meu obrigado a todos que organizaram, participaram e patrocinaram o evento.

Há mais fotos da viagem nesse meu álbum.

Looking for databases drivers

A simple Java servlet that looks for some well known databases drivers.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestDB extends HttpServlet {
    public void tryDataBase(String name, String url, PrintWriter out){
        String fail = "fail";
        String sucess = "Ok";
        out.println("Looking for the "+ name +" driver...");
        try {
            Class.forName(url);
            out.println(sucess);
        } catch (ClassNotFoundException ex) {
            out.println(fail);
        }
        out.println("
");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("Looking for databases");
            out.println("

Looking for databases

"); tryDataBase("MySQL", "com.mysql.jdbc.Driver", out); tryDataBase("Derby", "org.apache.derby.jdbc.EmbeddedDriver", out); tryDataBase("PostgreSQL", "org.postgresql.Driver", out); tryDataBase("Oracle", "oracle. jdbc.driver.OracleDriver", out); tryDataBase("SQLite", "org.sqlite.JDBC", out); out.println(""); } finally { out.close(); } } }

When compiling and running this make sure you put your drivers in your classpath.

A example of output:

example

Example of Unix commands implemented in Java

I created some illustrative and simple implementations of common Unix commands. For those who are familiar with Unix-like systems them make easier to understand Java. For those who are familiar with Java them make easier to understand Unix-like systems. 🙂

1. PWD

The first one is pwd that show the current working directory.

public class Jpwd {
    public static void main(String[] args) {
        String pwd = System.getProperty("user.dir");
        System.out.println(pwd);
    }
}

Running this at /home/silveira directory gives us as output:

$ java Jpwd

/home/silveira

1. CAT

The command cat is usually utilized for displaying files.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Jcat {
    public static void main(String[] args) {
        if(args.length==1){
            try {
                FileReader fileReader = new FileReader(args[0]);
                BufferedReader in = new BufferedReader(fileReader);
                String line;
                while((line = in.readLine())!= null){
                    System.out.println(line);
                }
            } catch (FileNotFoundException ex) {
                System.out.println(args[0]+", file not found.");
            }
            catch (IOException ex) {
                System.out.println(args[0]+", input/output error.");
            }
        }
    }
}

$ java Jcat /etc/timezone

America/Fortaleza

3. LS

The command ls is to list files. The File API (java.io.File) is very flexible and portable, but in this example I want just list files and directories of the current directory.

import java.io.File;

public class Jls {
    public static void main(String[] args) {
        File dir = new File(System.getProperty("user.dir"));
        String childs[] = dir.list();
        for(String child: childs){
            System.out.println(child);
        }
    }
}

Usage:

$ java Jpwd

/home/silveira/example

$ java Jls

directoryA

fileA

.somefile

4. CD

The cd command changes the current working directory.

import java.io.File;

public class Jcd {
    public static void main(String[] args) {
        if(args.length==1){
            File dir = new File(args[0]);
            if(dir.isDirectory()==true) {
                System.setProperty("user.dir", dir.getAbsolutePath());
            } else {
                System.out.println(args[0] + "is not a directory.");
            }
        }
    }
}

Usage:

$ java Jpwd
/home/silveira
$ java Jcd /tmp
$ java Jpwd
/tmp

More Dukes

More Dukes we’re creating to use in the 6th CEJUG’s birthday.

The first one is a Duke intented to be used as a badge. We should tie string in both hands and transform it in a badge for the event.

Original SVG version: duke_badge.svg

The second is a general purpouse Duke sign. You can print them in blank and use a brush to write on it.

Original SVG version: duke_sign.svg

Java, showing script engines

A simple code to show the script engines installed in your system.

As it uses the JSR-223 you need at least java 6.

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngineFactory;
import java.util.List;

public class ListEngines {
    public static void main(String[] args){
	ScriptEngineManager manager = new ScriptEngineManager();
	List  engines = manager.getEngineFactories();
	for(ScriptEngineFactory engine: engines){
		String name = engine.getEngineName();
		String lang = engine.getLanguageName();
		String ver = engine.getLanguageVersion();
		System.out.println(name+" "+lang+" "+ver);
	}
    }
}

$ java -version
java version “1.6.0_0”
OpenJDK Runtime Environment (build 1.6.0_0-b11)
OpenJDK Client VM (build 1.6.0_0-b11, mixed mode, sharing)
$ javac ListEngines.java
$ java ListEngines
Mozilla Rhino ECMAScript 1.6

For now I just have Rhino ECMAScript (JavaScript) engine accessible that comes with Java 6. I’m trying now to call Jython and JRuby code.

Glassfish on Linux

First, check if you have Java installed:

$ java -version
java version “1.6.0_10-rc”
Java(TM) SE Runtime Environment (build 1.6.0_10-rc-b28)
Java HotSpot(TM) Client VM (build 11.0-b15, mixed mode, sharing)

Now download the last version of Glassfish application server, I’m using Glassfish V2 for Linux. It’s a jar package. Execute it.

$ java -Xmx256m -jar glassfish-installer-v2ur2-b04-linux.jar

You be asked about the license agreement (CDDL+GPL).

Files will be decompressed in a directory named glassfish.

$ cd glassfish

Now we need to continue the installation. You can have Ant installed in your system or, like I’m doing, use a version that comes the Glassfish package.

$ chmod +x -R lib/ant/bin
$ lib/ant/bin/ant -f setup.xml

Tip: if you have more servers and want to create a cluster for load balancing, see this documentation. After ajust the setup-cluster.xml file you just need to run ant on it.

Let’s execute the server:

$ bin/asadmin start-domain

The default instance port is 8080. Try it on http://localhost:8080.

The default administrator port is 4848. Try it on http://localhost:4848.

The default user is admin and password is adminadmin. Log in.

Tip: you be asked for register your version. This register is not mandatory and not doing it will not limit the features of your Glassfish. It’s just a way they use to track the number of users. Aditionaly can have acess to newsletters, tutorials, screencasts, services and support. If you already have a SDN (Sun Developer Network) or Sun Online account you can use it for registration. If you simply doesn’t want to, you can skip this step.

For security reassons, click in the Application Server icon on the left sidebar and so in the Adminstrator Password tab. Chose a new password and click Save.

Let’s deploy a application. Download the file http://glassfish.dev.java.net/downloads/quickstart/hello.war.

Go to Applications → Web Applications on the sidebar.

No application will be there. Click on the Deploy button.

In the next screen, on Location select the .war that you downloaded. Click Ok.

Your application is now deployed.

Try the application on http://localhost:8080/hello.

There other ways  less easy but more flexible) to deploy your application, you can take a look on this and others topics on Glassfish Quick Start Guide.

Try to explore the Glassfish admin interface. It’s very easy and intuitive.