GERANDO PDF`s EM JAVA

GERANDO PDF`s EM JAVA

Hoje precisei gerar PDF em JAVA, numa pesquisa rápida pela internet encontrei a biblioteca iText
http://itextpdf.com/

É bem simples, com ela, criar os PDF`s!
Em http://www.roseindia.net/java/itext/index.shtml tem uma série de exemplos bem explicados de como usar a ferramenta.
Aqui também tem alguns exemplos: http://www.ibm.com/developerworks/br/library/os-javapdf/

Outra solução, que eu achei bem mais elegante, foi a proposta por esse cara
"Converta HTML para PDF com 06 linhas de Código"
http://javafree.uol.com.br/artigo/866449/Converta-HTML-para-PDF-com-06-linhas-de-Codigo.html

E funcionou mesmo! :D

JAVA | WEB-CRAWLERS DIA 1

POST 1:
Não vou reinventar a roda, pesquisei na internet possíveis web-crawlers.
No site a seguir existe uma lista com alguns crawlers open-source.

http://java-source.net/open-source/crawlers

---

POST 2:
Bom, pelo visto não vou ter que reinventar a roda... vou ter que INVENTA-LA mesmo!
Não encontrei nenhum crawler que seja só uma biblioteca que me permita trabalhar em cima :(
Mas, seguindo as recomendações desse cara http://lembra.wordpress.com/tag/crawler/
eu posso usar esse tal de httpunit (http://sourceforge.net/projects/httpunit/files/httpunit/1.7/httpunit-1.7.zip/download)
pra catar as informações dos sites... Vamos ver como funciona...

---

POST 3:
Em primeiro momento, o httpUnit se mostrou realmente muito bom! em poucas linhas de código ele conseguiu me retornar
quantos links um determinado site tem.

try {
// create the conversation object which will maintain state for us
WebConversation wc = new WebConversation();

// Obtain the main page on the meterware web site
String url="http://www.meterware.com";
WebRequest request = new GetMethodWebRequest( url );
WebResponse response = wc.getResponse( request );

// find the link which contains the string "HttpUnit" and click it
WebLink httpunitLink = response.getFirstMatchingLink( WebLink.MATCH_CONTAINED_TEXT, "HttpUnit" );
response = httpunitLink.click();

// print out the number of links on the HttpUnit main page
System.out.println( "The HttpUnit main page '"+url+"' contains " + response.getLinks().length + " links" );

} catch (Exception e) {
System.err.println( "Exception: " + e );
}

Se bem que ele demorou quase 3 segundos pra fazer isso... Mas tudo bem...

---

POST 4:
É, parece que o mar não está para peixe... Tentei iniciar um crawler pro site do terra. Ou eu não estou sabendo fazer direito ou o httpUnit
não é tão bom assim. Ele da erro ao tentar executar o código:

try {
// create the conversation object which will maintain state for us
WebConversation wc = new WebConversation();

// Obtain the main page on the meterware web site
String url="http://www.terra.com.br";
WebRequest request = new GetMethodWebRequest( url );
WebResponse response = wc.getResponse( request );

// find the link which contains the string "HttpUnit" and click it
//WebLink httpunitLink = response.getFirstMatchingLink( WebLink.MATCH_CONTAINED_TEXT, "HttpUnit" );
//response = httpunitLink.click();

System.out.println(response.getLinks().length);

//for(int i = 0; i < response.getLinks().length; i++){
// System.out.println(response.getLinks()[i].getURLString());
//}

} catch (Exception e) {
System.err.println( "Exception: " + e );
}

---

POST 5:
Bom, acho que encontrei a explicação aqui: http://httpunit.sourceforge.net/doc/faq.html#norhino
O httpunit não vem com essa biblioteca no pacote, acho que vou ter que baixa-la a parte.
Link para download do Rhino: http://www.mozilla.org/rhino/download.html
Agora é só colocar o arquivo js.jar no classpath e testar...

---

POST 6:
Não funcionou.
Mas esse link http://httpunit.sourceforge.net/doc/faq.html#disable%20scripting me deu uma luz:

HttpUnitOptions.setScriptingEnabled( false );

e o código agora funciona corretamente:

try {
HttpUnitOptions.setScriptingEnabled( false );
// create the conversation object which will maintain state for us
WebConversation wc = new WebConversation();

String url="http://www.terra.com.br";
WebRequest request = new GetMethodWebRequest( url );
WebResponse response = wc.getResponse( request );

// find the link which contains the string "HttpUnit" and click it
//WebLink httpunitLink = response.getFirstMatchingLink( WebLink.MATCH_CONTAINED_TEXT, "HttpUnit" );
//response = httpunitLink.click();

//System.out.println(response.getLinks().length);

for(int i = 0; i < response.getLinks().length; i++){
System.out.println(response.getLinks()[i].getURLString());
}

} catch (Exception e) {
System.err.println( "Exception: " + e );
}

Ele mostra todos os links do site do terra :D

---

POST 7:
Ok, agora que sei que é possível fazer isso, quero pegar algum dado de verdade.
Vamos ao site da iMasters. Quero pegar todas as noticias do site referentes a JAVA.
Primeiramente, pegaremos uma noticia qualquer:

Eu percebi que o conteudo do artigo fica em strConteudo e o titulo na tag title mesmo. então:

try {
HttpUnitOptions.setScriptingEnabled( false );
// create the conversation object which will maintain state for us
WebConversation wc = new WebConversation();

String url="http://imasters.uol.com.br/artigo/15674/java/jpa_com_jboss_tools_no_eclipse/";
WebRequest request = new GetMethodWebRequest( url );
WebResponse response = wc.getResponse( request );

// find the link which contains the string "HttpUnit" and click it
//WebLink httpunitLink = response.getFirstMatchingLink( WebLink.MATCH_CONTAINED_TEXT, "HttpUnit" );
//response = httpunitLink.click();

//System.out.println(response.getLinks().length);

System.out.println(response.getTitle());

HTMLElement[] divs = response.getElementsByTagName("div");
for(int i=0; i < divs.length; i++) {
if(divs[i].getID().equals("strConteudo"))
System.out.println(divs[i].getText());
}

for(int i = 0; i < response.getLinks().length; i++){
//System.out.println(response.getLinks()[i].getURLString());
}

} catch (Exception e) {
System.err.println( "Exception: " + e );
}

Funcionou corretamente :D
Próximo passo é, a partir da primeira página (http://imasters.uol.com.br) ele tem que me dar uma lista de links.
Depois de pegar a lista de links, ele vai link a link procurando a palavra JAVA no LINK, no TITULO e no CORPO do artigo.
Se encontrar, quero que o artigo seja retornado, senão, não :)

Programação de Jogos usando C++ & OpenGL - Dia 1

Programação de Jogos usando C++ & OpenGL

Primeiros Passos: Configurando

Para meus experimentos, vou utilizar S.O. Ubuntu 9.10 com o Eclipse para C++ (http://www.eclipse.org/downloads/).
Após instalar o Eclipse e fazer um Olá Mundo, chegou a hora de pegar as bibliotecas p/ trabalhar com o openGL.
Segui as recomendações desse blog: http://www.ferdychristant.com/blog/articles/DOMM-72MPPE
Entrei no Synaptic e procurei o pacote freeglut3-dev ( o freeglut3 já etava instalado para mim ).
No Eclipse, fui em Project > Properties > C/C++ Builder > Settings > GCC C++ Linker > Libraries e adicionei nas libraries ( -l ) "glut".
Compilei, então, o código proposto pelo próprio blog.


Entendendo o openGL. 1ª Parte: O Básico

Como eu sou novato no openGL, vou primeiro fazer uns testes para saber do que ele é capaz.
Eu sei que ele tem capacidade para programação 3D com super efeitos e etc, mas o meu objetivo aqui é começar de baixo.
De acordo com o GameDev (http://www.gamedev.net/reference/design/features/makegames/page2.asp) um bom jogo para iniciar
é TETRIS.
Talvez eu esteja me subestimando, mas quero algo ainda mais simples. Acho que um jogo estilo SNAKE é mais fácil que TETRIS.

Bom, meu primeiro teste funcionou normalmente. Desenhei um TRIANGULO numa janela.
Estranhamente eu tive que usar esse método glutInit(&argc, argv);
Acho que só é necessário no Linux.

glutDisplayFunc(void)
Seta o metodo que vai desenhar as coisas na janela.
O legal é que, sem isso, vc roda o programa e nao acontece nada.

glutMainLoop
http://www.opengl.org/documentation/specs/glut/spec3/node14.html#SECTION00041000000000000000
Loop principal. Evita o programa de ser finalizado.

openGlTest001


Entendendo o openGL. 2ª Parte: Fullscreen

Eu pretendo fazer todos os meus jogos serem FULLSCREEN, portanto, esse tópico é de grande importancia.
O tutorial http://www.swiftless.com/tutorials/opengl/fullscreen.html ensina bem como resolver isso.
Basicamente, vc tem o glutGameModeString com o parametro a larguraxaltura:colordepth@hertz
Exemplo:
glutGameModeString( "990x768:32@75" );
990x760 pixel
32bits de cores
75hz

Para aplicar usa-se glutEnterGameMode(); e para sair usa-se glutLeaveGameMode();
Claro que, se eu fizer o meu jogo fullscreen eu nao vou ter como FECHAR o aplicativo.
Sendo assim, preciso setar um método que me garanta que, ao pressionar ESC, o programa vá fechar:

NOTA: PARA USAR O exit(0) É NECESSARIO #include

void keyboard(unsigned char key, int x, int y) {
if (key == 27) {
glutLeaveGameMode();
exit(0);
}
}

e depois dizer ao openGL que esse método existe:

glutKeyboardFunc (keyboard);

Bom, parece que com o freeGlut3 as coisas não saem como planejado. Eu não consegui que meus aplicativos ficassem
fullscreen corretamente :(
Com SDL eu consegui o truque. É bem provavel, entao, que eu prefira aderir ao SDL por essa limitação do openGL.