Skip to content

Month: October 2008

Monkeys Playing Pacman

Another impressive talk from TED Ideas Worth Spreading about bonobos monkeys, abilities, language and culture.

Description: Savage-Rumbaugh’s work with bonobo apes, which can understand spoken language and learn tasks by watching, forces the audience to rethink how much of what a species can do is determined by biology — and how much by cultural exposure.

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

SmugMug experience with OpenSolaris + ZFS + MySQL

Take a look in this interesting post of Dan MacAskill, CEO of SmugMug, about his experiences on OpenSolaris servers with ZFS and MySQL.

SmugMug is a digital photo sharing website, focused on professional photographers. The site is also famous for storing huge amounts of data (photos) using local filesystems and the Amazon S3 service. Just on S3 are 100 800 terabytes of data (according to this and this).

Very interesting pots because he tels in details his experieces over some diferents points of view.

O que é o Open Source University Meetup?

O osum.sun.com é um portal de comunidades universitárias voltadas para os projetos de Software Livre e Open Source da Sun. Cada universidade pode possuir uma comunidade no Osum. Aquelas universidade onde há um Embaixado de Campus já possuem uma comunidade no Osum. Osum é o acrônimo para Open Source University Meetup.

Lá você pode:

  • Criar uma comunidade para sua universidade (se você é da UFC, já existe uma comunidade).
  • Conhecer outros estudantes do mundo todo. A interface também está disponível em português mas você pode conversar com as outras pessoas em suas linguas nativas.
  • Entrar em contato com tecnologias de ponta como Java, OpenSolaris, NetBeans, Glassfish, Lustre, Virtual Box, MySQL e muitas outras.
  • Saber mais sobre o Sun Academic Initiative, como obter os beneficios, descontos e acessar o sistema.
  • Ficar a par dos próximos eventos de Software Livre que vão acontecer perto de você. Inclusive os Embaixadores vão usar o OSUM para registrar todas as suas atividades como palestras, install fests, reuniões, etc.
  • No OSUM também é uma grande rede social onde você pode criar seu próprio blog, álbum de fotos, participar de fóruns, enviar vídeos, criar seu perfil e interagir com outros perfis.
  • E finalmente, através do OSUM você pode saltar para em outras comunidades, jugs e participar de outros projetos fora do OSUM.

OSUM em três passos:

  1. Entre e se cadastre em osum.sun.com.
  2. Será lhe mostrado uma lista de países, escolha Brazil como país.
  3. Será lhe mostrado uma lista de universidades, não esqueça de escolher a sua. Se esta ainda não foi criada, você pode cria-la ou procurar por um embaixador para cria-la.

OSUMs do Ceará

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

JavaFX, Duke Potato

Do you know the toy Mr. Potato Head? Now meet the Java Potato.

[youtube]6NrUdp5XX_o[/youtube]

Duke images here from previous dukes I posted and other images from Open Clipart Project.

Java Web Start:

The code:

package dukepotato;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.CustomNode;
import javafx.scene.Node;
import javafx.scene.Group;
import javafx.input.MouseEvent;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;

public class Img extends ImageView{
    public  attribute content: Node[];
    public  attribute src: String;

    private attribute endX = 0.0;
    private attribute endY = 0.0;
    private attribute startX = 0.0;
    private attribute startY = 0.0;

    override attribute translateX = bind endX;
    override attribute translateY = bind endY;
    override attribute blocksMouse = true;

    init {
        image = Image {
            url: "{__DIR__}/{src}"
        }
    }

    override attribute onMousePressed = function(e:MouseEvent):Void {
        startX = e.getDragX()-endX;
        startY = e.getDragY()-endY;
    }

    override attribute onMouseDragged = function(e:MouseEvent):Void {
        endX = e.getDragX()-startX;
        endY = e.getDragY()-startY;
    }
}

var dukesimages = ["duke1.png", "duke2.png", "duke3.png", "duke4.png"];
var dukes = for (image in dukesimages){
    Image {
        url: "{__DIR__}/{image}"
    }
}
var index = 0;
var duke = ImageView {
    x: 200, y:170
    image: bind dukes[index];
    onMouseClicked: function( e: MouseEvent ):Void {
        index = (index + 1) mod sizeof dukesimages;
    }
}

var hat = Img { src: "hat.png", x: 370 }
var partyhat = Img { src: "party_hat.png", x: 160, y: 5 }
var cap = Img { src: "cap.png", x: 230, y: 10 }
var cake = Img { src: "cake.png", x: 526, y: 190 }
var glove = Img { src: "glove.png", x: 338, y: 363 }
var baseball = Img { src: "baseball.png", x: 548, y:373 }
var pencil = Img { src: "pencil.png", x: 451, y: 365 }
var camera = Img { src: "camera.png", x: 125, y: 380 }
var coffee = Img { src: "coffee.png", x: 541, y: 114 }
var burger = Img { src: "burger.png", x: 542, y: 282 }
var diamond = Img { src: "diamond.png", x: 243, y: 383 }
var pliers = Img { src: "pliers.png", x: 20, y: 368 }
var rubikcube = Img { src : "rubikcube.png", x: 37, y: 295 }
var syringe = Img { src: "syringe.png", x: 35, y: 245 }
var hourglass = Img { src: "hourglass.png", x: 35, y: 127 }
var adventurehat = Img { src: "adventurehat.png", x: 8, y:30 }
var tie = Img { src: "tie.png", x: 547, y:35 }

Frame {
    title: "Duke Potato"
    width: 640
    height: 480
    closeAction: function() {
        java.lang.System.exit( 0 );
    }
    visible: true

    stage: Stage {
        content: [duke, hat, partyhat, cake, adventurehat, cap, glove,
            baseball, pencil, camera, coffee, burger, diamond,
            pliers, rubikcube, syringe, hourglass, tie]
    }
}
  • Lines 14 to 42 is the same dragging approach I showed in the post Draggable Nodes, but this time creating a class that inherits the behavior of ImageView.
  • Lines 44 to 57 is the Duke that changes when you click on it. It cycles over the dukesimages list.
  • Lines 59 to 75 is just instantiations of all toys and objects we will use to dress the Duke. Look how easier was to create and place a image.
  • Lines 78 to the end is just creating a Frame and putting all elements on it.

Download a package with the NetBeans project, sources, libraries and images, DukePotato.tar.gz.