come with me, on the way I'll explain.
Posts tagged tutorial
Twitter Bot @rudaufc versão 1
Nov 9th

Este aqui é um bot bem simples para Twitter.
Diariamente, as nove da manhã ele posta qual vai ser o cardápio do RU (Restaurante Universitário) da UFC naquele dia.
Assim, quando vai batendo a hora da fome, os alunos podem entrar no perfil @rudaufc e olhar qual vai ser o prato do dia, ou quem está seguindo ele no Twitter pode ter a agradável surpresa de ver todo dia o que vai ser servido hoje.
Aqui está o código fonte do arquivo rudaufc.sh:
#!/bin/sh # Twitter bot @rudaufc login="rudaufc" senha="suasenhaaqui" segunda="Picadinho com legumes ou bife na chapa. Salada de macarrão com cenoura. Arroz. Feijão com abóbora e batata doce." terca="Franco guisado ou coxas de frango ao forno . Salada de acelga, cenoura e passas. Arroz. Feijão com abóbora e batata doce." quarta="# Feijoada à moda RU ou bisteca . Salada de repolho branco, cenoura e abacaxi. Arroz. Feijão com abóbora e batata doce" quinta="Frango à passarinho ou frango chinês. Salada de Alface, Tomate e Cebola. Arroz. Feijão com abóbora e batata doce." sexta="# Isca ao molho ou maravilha de carne. Salada de acelga com cenoura. Arroz. Feijão com abóbora e batata doce." dia=`(date +%w)` log=`(date +%Y-%m-%d-%s)`"-$$.log" dir="/home/silveiraneto/rudaufc" msg="" case "$dia" in # "0") msg=$domingo ;; "1") msg=$segunda ;; "2") msg=$terca ;; "3") msg=$quarta ;; "4") msg=$quinta ;; "5") msg=$sexta ;; # "6") msg=$sabado ;; esac curl -u $login:$senha -d status="$msg" http://twitter.com/statuses/update.xml > $dir/$log
A mágica toda está na capacidade do Curl de acessar facilmente a API do Twitter para enviar mensagens.
Para que o script execute diariamente as nove da manhã ele está alocado em um servidor com a crontab configurada da seguinte maneira:
0 5 * * * . /caminho_para_onde_ele_esta/rudaufc.sh
ps: leve em conta que o servidor está em um fuso horário diferente do Brasil.
Nessa versão o prato de cada dia está hardcoded no script, o que não é o ideal e faz com que semanalmente eu tenha que atualizar o script inserindo os pratos da semana manualmente. Eu espero que a próxima versão seja capaz de descobrir esses pratos e se atualizar sem nenhuma interferência.
BumbaBot-1
Mar 16th
I got a simple motor from a broken domestic printer. It’s a Mitsumi m355P-9T stepping motor. Any other common stepping motor should fits. You can find one in printers, multifunction machines, copy machines, FAX, and such.
With a flexible cap of water bottle with a hole we make a connection between the motor axis and other objects.
With super glue I attached to the cap a little handcraft clay ox statue.
It’s a representation from a Brazilian folkloric character Boi Bumbá. In some traditional parties in Brazil, someone dress a structure-costume and dances in circular patterns interacting with the public.

Photos by Marcus Guimarães.
Controlling a stepper motor is not difficult. There’s a good documentation on how to that on the Arduino Stepper Motor Tutorial. Basically it’s about sending a logical signal for each coil in a circular order (that is also called full step).

Animation from rogercom.com.

You’ll probably also use a driver chip ULN2003A or similar to give to the motor more current than your Arduino can provide and also for protecting it from a power comming back from the motor. It’s a very easy find this tiny chip on electronics or automotive stores or also from broken printers where you probably found your stepped motor.

With a simple program you can already controlling your motor.
// Simple stepped motor spin // by Silveira Neto, 2009, under GPLv3 license // http://silveiraneto.net/2009/03/16/bumbabot-1/ int coil1 = 8; int coil2 = 9; int coil3 = 10; int coil4 = 11; int step = 0; int interval = 100; void setup() { pinMode(coil1, OUTPUT); pinMode(coil2, OUTPUT); pinMode(coil3, OUTPUT); pinMode(coil4, OUTPUT); } void loop() { digitalWrite(coil1, step==0?HIGH:LOW); digitalWrite(coil2, step==1?HIGH:LOW); digitalWrite(coil3, step==2?HIGH:LOW); digitalWrite(coil4, step==3?HIGH:LOW); delay(interval); step = (step+1)%4; }
Writing a little bit more generally code we can create function to step forward and step backward.
My motor needs 48 steps to run a complete turn. So 360º/48 steps give us 7,5º per step. Arduino has a simple Stepper Motor Library but it doesn’t worked with me and it’s also oriented to steps and I’d need something oriented to angles instead. So I wrote some routines to do that.
For this first version of BumbaBot I mapped angles with letters to easy the communication between the programs.

Notice that it’s not the final version and there’s still some bugs!
// Stepped motor control by letters // by Silveira Neto, 2009, under GPLv3 license // http://silveiraneto.net/2009/03/16/bumbabot-1/ int coil1 = 8; int coil2 = 9; int coil3 = 10; int coil4 = 11; int delayTime = 50; int steps = 48; int step_counter = 0; void setup(){ pinMode(coil1, OUTPUT); pinMode(coil2, OUTPUT); pinMode(coil3, OUTPUT); pinMode(coil4, OUTPUT); Serial.begin(9600); } // tells motor to move a certain angle void moveAngle(float angle){ int i; int howmanysteps = angle/stepAngle(); if(howmanysteps<0){ howmanysteps = - howmanysteps; } if(angle>0){ for(i = 0;i<howmanysteps; i++){ step(i%4); delay(delayTime); } }else{ for(i=0;i<howmanysteps;i++){ backstep(i%4); delay(delayTime); } } } // tells motor to move to a certain angle void moveToAngle(float angle){ moveAngle(angle-actualAngle()); } // actual stepper motor angle float actualAngle(){ return step_counter*stepAngle(); } // angle made by each step float stepAngle(){ return 360.0/steps; } // backward step void backstep(int coil){ digitalWrite(coil1, (coil==3)?HIGH:LOW); digitalWrite(coil2, (coil==2)?HIGH:LOW); digitalWrite(coil3, (coil==1)?HIGH:LOW); digitalWrite(coil4, (coil==0)?HIGH:LOW); step_counter--; } // forward step void step(int coil){ digitalWrite(coil1, (coil==0)?HIGH:LOW); digitalWrite(coil2, (coil==1)?HIGH:LOW); digitalWrite(coil3, (coil==2)?HIGH:LOW); digitalWrite(coil4, (coil==3)?HIGH:LOW); step_counter++; } void loop() { byte val; if(Serial.available()){ val = Serial.read(); switch (val) { case 'A': moveToAngle( 0); break; case 'B': moveToAngle( 45); break; case 'C': moveToAngle( 90); break; case 'D': moveToAngle(135); break; case 'E': moveToAngle(180); break; case 'F': moveToAngle(225); break; case 'G': moveToAngle(270); break; case 'H': moveToAngle(315); break; case 'I': backstep(1); backstep(0); break; case 'J': step(0); step(1); break; } Serial.print(val); } }
In another post I wrote how create a Java program to talk with Arduino. We’ll use this to send messages to Arduino to it moves.

[put final video here]
To be continued…
JavaFX, how to create a rpg like game
Dec 8th
JavaFX 1.0 is out and there are tons of new cool features, specially for game development.trans
I’ll show in this tutorial how to create a very simple demo that shows how to load imtrages, handle sprites, collisions and keyboard events that you can use to create a game with a old school rpg like vision.
For the background scenario I’m using the house that I drew and we’ll call as house.png.
That we load as a Image and place into a ImageView.
ImageView{ image: Image {url: "{__DIR__}house.png"} }
For the character I’m using the last character I drew, the nerdy guy.

To make the animation easier, I spited it into 9 pieces:
down0.png, down1.png and down2.png
left0.png, left1.png and left2.png
right0.png, right1.png and righ2.png
up0.png, up1.png and up2.png
All images I’m using should be in the same directory of source code.
Let’s start loading the scenario and a single character sprite.
import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.image.*; Stage { title: "RPG-like demo", width: 424, height: 412 visible: true scene: Scene{ content: [ ImageView{ image: Image {url: "{__DIR__}house.png"} }, ImageView{ x: 320 y: 80 image: Image {url: "{__DIR__}down1.png"} } ] } }
Saved as Game.fx you can compile and run with in your terminal:
$ javafxc Game.fx
$ javafx Game
Hint: You can use NetBeans 6.5 JavaFX plugin to easier the JavaFX development.
To put animation on the character we load all sprites into four lists. Each list for each direction.
// sprites def up = for(i in [0..2]) { Image {url: "{__DIR__}up{i}.png" } } def right = for(i in [0..2]) { Image {url: "{__DIR__}right{i}.png" } } def down = for(i in [0..2]) { Image {url: "{__DIR__}down{i}.png" } } def left = for(i in [0..2]) { Image {url: "{__DIR__}left{i}.png" } }
And create vars to store the character position and frame of animation.
var frame = 0; var posx = 320; var posy = 80;
Also store the house background.
// house background
def house = ImageView{ image: Image {url: "{__DIR__}house.png"} };
I create booleans to store some key states and at each interval of time I see how they are and do something about. You can handle keyboard event with less code but I like this way because keep visual and game logics a little bit more separated.
// keyboard var upkey = false; var rightkey = false; var downkey = false; var leftkey = false; // player var player = ImageView{ x: bind posx y: bind posy image: Image {url: "{__DIR__}down1.png"} onKeyPressed: function(e:KeyEvent){ if (e.code == KeyCode.VK_DOWN) { downkey = true; } else if (e.code == KeyCode.VK_UP) { upkey = true; }else if (e.code == KeyCode.VK_LEFT) { leftkey = true; }else if (e.code == KeyCode.VK_RIGHT) { rightkey = true; } } // onKeyPressed onKeyReleased: function(e: KeyEvent){ if (e.code == KeyCode.VK_DOWN) { downkey = false; } else if (e.code == KeyCode.VK_UP) { upkey = false; }else if (e.code == KeyCode.VK_LEFT) { leftkey = false; }else if (e.code == KeyCode.VK_RIGHT) { rightkey = false; } } // onKeyReleased }
See a video of the game working so far:
Now we will add collisions. In a previous post I showed some math behind bounding box game collisions. The good news are that you no longer need to worry about that. There are a lot of API improvements in JavaFX 1.0 that do all the hard work for you, specially the new classes on javafx.geometry package, Rectangle2D and Point2D.
We create rectangles that represent the obstacles in the house.
// collidable obstacles def obstacles = [ Rectangle { x: 0 y: 0 width: 32 height: 382 stroke: Color.RED }, Rectangle { x: 0 y: 0 width: 414 height: 64 stroke: Color.RED }, Rectangle { x: 384 y: 0 width: 32 height: 382 stroke: Color.RED }, Rectangle { x: 0 y: 192 width: 128 height: 64 stroke: Color.RED }, Rectangle { x: 192 y: 192 width: 64 height: 64 stroke: Color.RED }, Rectangle { x: 224 y: 0 width: 32 height: 288 stroke: Color.RED }, Rectangle { x: 288 y: 128 width: 96 height: 64 stroke: Color.RED }, Rectangle { x: 0 y: 352 width: 128 height: 32 stroke: Color.RED }, Rectangle { x: 192 y: 352 width: 192 height: 32 stroke: Color.RED }, Rectangle { x: 224 y: 320 width: 32 height: 32 stroke: Color.RED }, Rectangle { x: 32 y: 64 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 64 y: 64 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 96 y: 64 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 128 y: 64 width: 64 height: 32 stroke: Color.YELLOW }, Rectangle { x: 192 y: 32 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 64 y: 128 width: 64 height: 32 stroke: Color.YELLOW }, Rectangle { x: 32 y: 250 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 64 y: 250 width: 64 height: 32 stroke: Color.YELLOW }, Rectangle { x: 200 y: 255 width: 20 height: 20 stroke: Color.YELLOW }, Rectangle { x: 200 y: 170 width: 20 height: 20 stroke: Color.YELLOW }, Rectangle { x: 257 y: 32 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 288 y: 32 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 320 y: 192 width: 64 height: 64 stroke: Color.YELLOW }, Rectangle { x: 352 y: 295 width: 32 height: 60 stroke: Color.YELLOW }, Rectangle { x: 32 y: 327 width: 64 height: 23 stroke: Color.YELLOW }, ];

We just have to change a little bit the game logics in order to handle collisions.

We define a bounding box around the player, it’s a rectangle from (4, 25) at the player coordinates system and with width 19 and height 10. The idea is to prospect where the player will be in the next step, see if it’s bouding box don’t collide with any obstacle and so pass it to the real game position.
// game logics var gamelogics = Timeline { repeatCount: Timeline.INDEFINITE keyFrames: KeyFrame { time : 1s/8 action: function() { var nextposx = posx; var nextposy = posy; if(downkey) { nextposy += 5; player.image = down[++frame mod 3]; } if(upkey) { nextposy -= 5; player.image = up[++frame mod 3]; } if(rightkey) { nextposx += 5; player.image = right[++frame mod 3]; } if(leftkey) { nextposx -= 5; player.image = left[++frame mod 3]; } for(obst in obstacles) { if(obst.boundsInLocal.intersects(nextposx + 4, nextposy + 25, 19, 10)) { return; } } posx = nextposx; posy = nextposy; } } }
This is enough to do the trick but I also added a way to smoothly show the obstacles when pressing the space key.
Here is the complete source code.
package Game; import javafx.stage.Stage; import javafx.scene.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.animation.*; var frame = 0; var posx = 320; var posy = 80; // sprites def up = for(i in [0..2]) { Image {url: "{__DIR__}up{i}.png" } } def right = for(i in [0..2]) { Image {url: "{__DIR__}right{i}.png" } } def down = for(i in [0..2]) { Image {url: "{__DIR__}down{i}.png" } } def left = for(i in [0..2]) { Image {url: "{__DIR__}left{i}.png" } } // house background def house = ImageView{ image: Image {url: "{__DIR__}house.png"} }; // keyboard var upkey = false; var rightkey = false; var downkey = false; var leftkey = false; // player var player = ImageView{ x: bind posx y: bind posy image: down[1] onKeyPressed: function(e:KeyEvent){ if (e.code == KeyCode.VK_DOWN) { downkey = true; } else if (e.code == KeyCode.VK_UP) { upkey = true; }else if (e.code == KeyCode.VK_LEFT) { leftkey = true; }else if (e.code == KeyCode.VK_RIGHT) { rightkey = true; } if(e.code == KeyCode.VK_SPACE){ if(fade==0.0){ fadein.playFromStart(); } if(fade==1.0){ fadeout.playFromStart(); } } } // onKeyPressed onKeyReleased: function(e: KeyEvent){ if (e.code == KeyCode.VK_DOWN) { downkey = false; } else if (e.code == KeyCode.VK_UP) { upkey = false; }else if (e.code == KeyCode.VK_LEFT) { leftkey = false; }else if (e.code == KeyCode.VK_RIGHT) { rightkey = false; } } // onKeyReleased } // collidable obstacles def obstacles = [ Rectangle { x: 0 y: 0 width: 32 height: 382 stroke: Color.RED }, Rectangle { x: 0 y: 0 width: 414 height: 64 stroke: Color.RED }, Rectangle { x: 384 y: 0 width: 32 height: 382 stroke: Color.RED }, Rectangle { x: 0 y: 192 width: 128 height: 64 stroke: Color.RED }, Rectangle { x: 192 y: 192 width: 64 height: 64 stroke: Color.RED }, Rectangle { x: 224 y: 0 width: 32 height: 288 stroke: Color.RED }, Rectangle { x: 288 y: 128 width: 96 height: 64 stroke: Color.RED }, Rectangle { x: 0 y: 352 width: 128 height: 32 stroke: Color.RED }, Rectangle { x: 192 y: 352 width: 192 height: 32 stroke: Color.RED }, Rectangle { x: 224 y: 320 width: 32 height: 32 stroke: Color.RED }, Rectangle { x: 32 y: 64 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 64 y: 64 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 96 y: 64 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 128 y: 64 width: 64 height: 32 stroke: Color.YELLOW }, Rectangle { x: 192 y: 32 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 64 y: 128 width: 64 height: 32 stroke: Color.YELLOW }, Rectangle { x: 32 y: 250 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 64 y: 250 width: 64 height: 32 stroke: Color.YELLOW }, Rectangle { x: 200 y: 255 width: 20 height: 20 stroke: Color.YELLOW }, Rectangle { x: 200 y: 170 width: 20 height: 20 stroke: Color.YELLOW }, Rectangle { x: 257 y: 32 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 288 y: 32 width: 32 height: 32 stroke: Color.YELLOW }, Rectangle { x: 320 y: 192 width: 64 height: 64 stroke: Color.YELLOW }, Rectangle { x: 352 y: 295 width: 32 height: 60 stroke: Color.YELLOW }, Rectangle { x: 32 y: 327 width: 64 height: 23 stroke: Color.YELLOW }, ]; // game logics var gamelogics = Timeline { repeatCount: Timeline.INDEFINITE keyFrames: KeyFrame { time : 1s/8 action: function() { var nextposx = posx; var nextposy = posy; if(downkey) { nextposy += 5; player.image = down[++frame mod 3]; } if(upkey) { nextposy -= 5; player.image = up[++frame mod 3]; } if(rightkey) { nextposx += 5; player.image = right[++frame mod 3]; } if(leftkey) { nextposx -= 5; player.image = left[++frame mod 3]; } for(obst in obstacles) { if(obst.boundsInLocal.intersects(nextposx + 4, nextposy + 25, 19, 10)) { return; } } posx = nextposx; posy = nextposy; } } } gamelogics.play(); // obstacles view var fade = 0.0; var obstacleslayer = Group { opacity: bind fade content: [ Rectangle { x:0 y:0 width:500 height: 500 fill: Color.BLACK }, obstacles, Rectangle { x: bind posx + 4 y: bind posy + 25 width: 19 height: 10 fill: Color.LIME } ] } var fadein = Timeline { keyFrames: [ at (0s) {fade => 0.0} at (1s) {fade => 1.0} ] } var fadeout = Timeline { keyFrames: [ at (0s) {fade => 1.0} at (1s) {fade => 0.0} ] } // game stage Stage { title: "RPG-like demo", width: 424, height: 412 visible: true scene: Scene{ fill: Color.BLACK content: [house, player, obstacleslayer] } }
Play Through Java Web Start
or click here to play via applet, inside your browser.
update: The applet version and Java Web Start versions should be working now. The applet version on Linux seems to be having problems with the keyboard handling, use the Java Web Start version while I’m trying to fix it.
Downloads:
- Source, images and jars, nerdy.zip
- All content
- First video, javafx_nerdy_without_collision.ogv
- Second video, javafx_nerdy.ogv
JavaFX SDK 1.0 on Linux
Dec 6th
JavaFX 1.0 is out and is absolutely amazing. You guys did really a great work on it.
As I really need a working SDK on Linux to continue to study and I don’t have any Windows/Mac near me, I’m using the Weiqi Gao’s workaround. I tried to simplify a little bit more the process for those who need JavaFX SDK working on Linux right now.
Download javafxsdk_linux_unofficial.tar.bz2 (~18Mb).
And then
tar -xjvf javafxsdk_linux_unofficial.tar.bz2
sudo cp javafx /opt/javafx
echo “PATH=\$PATH:/opt/javafx/bin” >> ~/.profile
echo “JAVAFX_HOME=/opt/javafx” >> ~/.profile
source ~/.profile
Now you can call javafx, javafxc, javafxdoc and javafxpackager from your terminal. Don’t forget that you need Java 1.6 or greater installed.
Here’s a video showing the SDK working, I’m compiling and running two sample applications. Remeber that as a temporary unofficial port for Linux, there’s not native video support nor hardware acceleration.
JavaFX, rectangular collision detection
Oct 30th
In a game I wrote some years ago we handled simple rectangular collisions. Given the points:

We did:
// returning 0 means collision int collision(int ax, int ay, int bx, int by, int cx, int cy, int dx, int dy){ return ((ax > dx)||(bx < cx)||(ay > dy)||(by < cy)); }
I’ll show here a little demo about how implement simple rectangular collisions on JavaFX.
First I created a movable rectangle using the same idea of draggable nodes I already had posted before.
import javafx.input.MouseEvent; import javafx.scene.geometry.Rectangle; public class MovableRectangle extends Rectangle { private attribute startX = 0.0; private attribute startY = 0.0; public attribute onMove = function(e:MouseEvent):Void {} override attribute onMousePressed = function(e:MouseEvent):Void { startX = e.getDragX()-translateX; startY = e.getDragY()-translateY; onMove(e); } override attribute onMouseDragged = function(e:MouseEvent):Void { translateX = e.getDragX()-startX; translateY = e.getDragY()-startY; onMove(e); } }
In the main code I some important things:
- colide, a color that represents the collision effect. White means no collision and gray means collision.
- rec1 and rec2, the two rectangles that can collide.
- checkcollision() the function that checks and handles a possible collision.
Here is the main code:
import javafx.application.Frame; import javafx.application.Stage; import javafx.scene.geometry.Rectangle; import javafx.scene.paint.Color; import javafx.input.MouseEvent; var colide = Color.WHITE; function checkcollision():Void { if ( (rec1.getBoundsX() > rec2.getBoundsX() + rec2.getWidth()) or (rec1.getBoundsX() + rec1.getWidth() < rec2.getBoundsX()) or (rec1.getBoundsY() > rec2.getBoundsY() + rec2.getHeight()) or (rec1.getBoundsY() + rec1.getHeight() < rec2.getBoundsY()) ) { colide = Color.WHITE } else { colide = Color.LIGHTGRAY } } var rec1: MovableRectangle = MovableRectangle { x: 10, y: 10, width: 50, height: 60, fill: Color.RED onMove: function(e:MouseEvent):Void { checkcollision() } } var rec2: MovableRectangle = MovableRectangle { x: 100, y: 100, width: 70, height: 30, fill: Color.BLUE onMove: function(MouseEvent):Void { checkcollision() } } Frame { title: "Rectangular Collisions", width: 300, height: 300 closeAction: function() { java.lang.System.exit( 0 ); } visible: true stage: Stage { fill: bind colide content: [rec1, rec2] } }
Try it via Java Web Start:

Some considerations:
- You can use rectangular collisions to create bounding boxes to handle collisions in more complex shapes or sprites. Is a common approach in 2d games to avoid more expensive calculations.
- There are space for optimizations.
- In this case I’m using only two objects. Some problems raises when I have N objects to handle.
More generally, we can code:
function collission(ax, ay, bx, by, cx, cy, dx, dy): Boolean { return not ((ax > dx)or(bx < cx)or(ay > dy)or(by < cy)); } function hitnode(a: Node, b:Node): Boolean{ return (collission( a.getBoundsX(), a.getBoundsY(), a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(), b.getX(), b.getY(), b.getX() + b.getWidth(), b.getY() + b.getHeight() )); }
This way we can pass just two bounding boxes to hitnode and easily check collision of a node against a list of bounding boxes nodes.
Using the same approach I also wrote this function to test if a Node is inside another Node:
function inside (ax, ay, bx, by, cx, cy, dx, dy):Boolean{ return ((ax > cx) and (bx < dx) and (ay > cy) and (by < dy)); } function insidenode(a:Node,b:Node):Boolean{ return (inside( a.getBoundsX(), a.getBoundsY(), a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(), b.getBoundsX(), b.getBoundsY(), b.getBoundsX() + b.getWidth(), b.getBoundsY() + b.getHeight() )); }
Soon I’ll post game examples showing how to use this method and others collission detection methods.
Downloads:
- The original video, javafx_rectangular_collision_detection.ogg
- NetBeans 6.1 Project with sources, javafx_rec_col.tar.gz. Needs JavaFX module installed.
Short urls with Glassfish+MySQL
Oct 21st

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 -ADatabase 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:
- separate the key from the url.
- if the key is a pin from a pipe then redirect to that pout.
- else provide a way to create a new pipe.
- list all pipes.
- 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:




















