<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>JESJOBLOG</title>
	
	<link>http://blog.jesjobom.com</link>
	<description>O blog do Jesjobom</description>
	<lastBuildDate>Sat, 15 Oct 2011 03:32:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jesjoblog" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="jesjoblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Luminolaser – Eletrônica e Arduino na Prática 2</title>
		<link>http://blog.jesjobom.com/2011/08/luminolaser-eletronica-na-pratica-2/</link>
		<comments>http://blog.jesjobom.com/2011/08/luminolaser-eletronica-na-pratica-2/#comments</comments>
		<pubDate>Sat, 27 Aug 2011 02:24:00 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Laser]]></category>
		<category><![CDATA[LDR]]></category>
		<category><![CDATA[Luminolaser]]></category>
		<category><![CDATA[Protótipo]]></category>
		<category><![CDATA[Servomotor]]></category>
		<category><![CDATA[Transistor]]></category>
		<category><![CDATA[Vídeo]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=209</guid>
		<description><![CDATA[Seguindo com as publicações de meus protótipos com o Arduino, hoje mostro o Luminolaser. Será nos mesmos moldes da última publicação, resumido e direto (ou seja, conhecimento prévio se fará necessário). O objetivo do Luminolaser foi, principalmente, estudar o uso de Servo Motores e o controle sob eles. Sempre tentando criar algo um pouco além [...]]]></description>
			<content:encoded><![CDATA[<p>Seguindo com as publicações de meus protótipos com o <a title="Arduino Wiki" href="http://pt.wikipedia.org/wiki/Arduino" target="_blank">Arduino</a>, hoje mostro o Luminolaser. Será nos mesmos moldes da <a title="Colorino – Eletrônica e Arduino na Prática 1" href="http://blog.jesjobom.com/2011/06/colorino-eletronica-e-arduino-na-pratica-1/" target="_blank">última publicação</a>, resumido e direto (ou seja, conhecimento prévio se fará necessário).</p>
<p>O objetivo do Luminolaser foi, principalmente, estudar o uso de <a title="Servo Motor Wiki" href="http://pt.wikipedia.org/wiki/Servomotor" target="_blank">Servo Motores</a> e o controle sob eles. Sempre tentando criar algo um pouco além do simples exemplo, procurei fazer uma espécie de scanner de ambiente que identifica o ponto mais luminoso (eu só tinha um sensor de luminosidade &#8211; LDR &#8211; a disposição) e marca esse ponto com um <em>laser pointer</em>.</p>
<p>Posteriormente incrementei um pouco mais de modo que fosse possível controlar o laser através de um controle analógico.<span id="more-209"></span></p>
<p>Bem, vamos aos materiais usados:</p>
<ul>
<li>Arduino &#8220;Brasileirino&#8221; (Duemilanove) ATMega328 [<a title="Arduino Uno" href="http://arduino.cc/en/Main/ArduinoBoardUno" target="_blank">Arduino Uno</a>];</li>
<li>Bateria recarregável de 9V [<a title="MAXUSS Rechargeable Ni-MH 9V 260mAh Battery" href="http://www.dealextreme.com/p/maxuss-rechargeable-ni-mh-9v-260mah-battery-54456" target="_blank">Deal Extreme</a>];</li>
<li>Bateria de 4V de alta descarga para alimentar o módulo laser;</li>
<li>Bateria de 7,4V de alta descarga para os servos;</li>
<li>2 Mini Servos Motores [<a title="TowerPro SG90 9G Mini Servo with Accessories" href="http://www.dealextreme.com/p/towerpro-sg90-9g-mini-servo-with-accessories-12859" target="_blank">Deal Extreme</a>];</li>
<li>Módulo de laser vermelhor 5mW [<a title="Red Laser Module - Focused Dot (3.5V~4.5V 9mm 5mW)" href="http://www.dealextreme.com/p/red-laser-module-focused-dot-3-5v-4-5v-9mm-5mw-5900" target="_blank">Deal Extreme</a>];</li>
<li>Botão de lanterna para mudar a função do protótipo [<a title="Clicky Switch for Flashlights (11.8mm 5-Pack)" href="http://www.dealextreme.com/p/clicky-switch-for-flashlights-11-8mm-5-pack-5604" target="_blank">Deal Extreme</a>];</li>
<li>Muitos fios conectores para protoboard [<a title="Breadboard Jumper Wires for Electronic DIY (70-Cable Pack)" href="http://www.dealextreme.com/p/breadboard-jumper-wires-for-electronic-diy-70-cable-pack-80208" target="_blank">Deal Extreme</a>];</li>
<li>Analógico do PSP [<a title="Replacement PSP Analog Switch Button Module Black" href="http://www.dealextreme.com/p/replacement-psp-analog-switch-button-module-black-3373" target="_blank">Deal Extreme</a>];</li>
<li>LDR (sensor de luminosidade) [<a title="LDR Wiki" href="http://pt.wikipedia.org/wiki/LDR" target="_blank">Wiki</a>].</li>
<li>Transistor NPN Tip122 [<a title="Transistor Wiki" href="http://pt.wikipedia.org/wiki/Trans%C3%ADstor" target="_blank">Wiki</a>];</li>
</ul>
<p>Como pode-se notar, existem muitos componentes <em>from China</em>. Realmente acredito que valha a pena, principalmente quando não existe pressa para receber os produtos.</p>
<p>À esquemática:</p>

<a href="http://blog.jesjobom.com/wp-content/gallery/arduino/lumino_laser.jpg" title="" class="shutterset_singlepic17" >
	<img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/cache/17__320x240_lumino_laser.jpg" alt="lumino_laser" title="lumino_laser" />
</a>

<p>Observem que, por não ter uma imagem do controle analógico para o <a title="Fritzing" href="http://fritzing.org/" target="_blank">Fritzing</a>, acabei substituindo por 2 potenciômetros rotatórios&#8230; Até porque são equivalentes. Assim como o Led vermelho da imagem simboliza o módulo do laser.</p>
<p>E para simplificar a visualização, incluí apenas 1 servo motor na esquemática e separei os componente. Na versão final o laser e o LDR ficam juntos na ponta do segundo servo.</p>
<p>O botão incluí para alterar o modo de controle dos servos entre automático (busca o ponto mais luminoso do ambiente) e manual (permitindo o direcionamento do laser através do controle analógico).</p>
<p><em>Now it&#8217;s time to code!</em></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;Servo.h&gt; </span>
&nbsp;
Servo servo_base<span style="color: #339933;">;</span>
Servo servo_upper<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Posição dos servos inferior e superior</span>
<span style="color: #993333;">int</span> servo_base_pos <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> servo_upper_pos <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Posição para onde os servos devem se mover</span>
<span style="color: #666666; font-style: italic;">//para apontar onde está a mais forte fonte de luz</span>
<span style="color: #993333;">int</span> final_base_pos <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> final_upper_pos <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Pinos dos servos, sensor ldr e sinal do laser</span>
<span style="color: #993333;">int</span> servo_base_pin <span style="color: #339933;">=</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> servo_upper_pin <span style="color: #339933;">=</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> ldr_pin <span style="color: #339933;">=</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> laser_pin <span style="color: #339933;">=</span> <span style="color: #0000dd;">13</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Pinos do analógico e do botão</span>
<span style="color: #993333;">int</span> dpad_x <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> dpad_y <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> button_pin <span style="color: #339933;">=</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
<span style="color: #009900;">&#123;</span> 
  servo_base.<span style="color: #202020;">attach</span><span style="color: #009900;">&#40;</span>servo_base_pin<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  servo_upper.<span style="color: #202020;">attach</span><span style="color: #009900;">&#40;</span>servo_upper_pin<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  pinMode<span style="color: #009900;">&#40;</span>laser_pin<span style="color: #339933;">,</span> OUTPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  pinMode<span style="color: #009900;">&#40;</span>button_pin<span style="color: #339933;">,</span> INPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> 
&nbsp;
<span style="color: #993333;">void</span> loop<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
<span style="color: #009900;">&#123;</span> 
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>verificaClick<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//Função de direcionamento manual do laser</span>
    ligarLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    readAnalogPad<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    direcionaLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//Busca automática pela maior luminosidade</span>
    desligaLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    buscaMaiorLuminosidade_1<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    direcionaLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    ligarLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    delay<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">10000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Percorre todo o alcance dos servos buscando a maior luminosidade</span>
<span style="color: #666666; font-style: italic;">//detectada pelo LDR e salva essa posição para mover depois</span>
<span style="color: #993333;">void</span> buscaMaiorLuminosidade_1<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">int</span> maior_luminosidade <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>servo_base_pos <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> servo_base_pos <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">180</span><span style="color: #339933;">;</span> servo_base_pos <span style="color: #339933;">+=</span> <span style="color: #0000dd;">20</span><span style="color: #009900;">&#41;</span> 
  <span style="color: #009900;">&#123;</span>
    servo_base.<span style="color: #202020;">write</span><span style="color: #009900;">&#40;</span>servo_base_pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    delay<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">500</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>servo_upper_pos <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> servo_upper_pos <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">180</span><span style="color: #339933;">;</span> servo_upper_pos <span style="color: #339933;">+=</span> <span style="color: #0000dd;">5</span><span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#123;</span>
      servo_upper.<span style="color: #202020;">write</span><span style="color: #009900;">&#40;</span>servo_upper_pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      delay<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>verificaClick<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//Se o botão foi clicado, encerra a busca</span>
        <span style="color: #b1b100;">return</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #993333;">int</span> ldr <span style="color: #339933;">=</span> obtemLuminosidade<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>ldr <span style="color: #339933;">&gt;</span> maior_luminosidade<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        maior_luminosidade <span style="color: #339933;">=</span> ldr<span style="color: #339933;">;</span>
        final_base_pos <span style="color: #339933;">=</span> servo_base_pos<span style="color: #339933;">;</span>
        final_upper_pos <span style="color: #339933;">=</span> servo_upper_pos<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    servo_upper.<span style="color: #202020;">write</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  servo_base.<span style="color: #202020;">write</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> obtemLuminosidade<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">return</span> analogRead<span style="color: #009900;">&#40;</span>ldr_pin<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> direcionaLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  servo_upper.<span style="color: #202020;">write</span><span style="color: #009900;">&#40;</span>final_upper_pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  servo_base.<span style="color: #202020;">write</span><span style="color: #009900;">&#40;</span>final_base_pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> ligarLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  digitalWrite<span style="color: #009900;">&#40;</span>laser_pin<span style="color: #339933;">,</span> HIGH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> desligaLaser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  digitalWrite<span style="color: #009900;">&#40;</span>laser_pin<span style="color: #339933;">,</span> LOW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
boolean verificaClick<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">return</span> digitalRead<span style="color: #009900;">&#40;</span>button_pin<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HIGH<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Obtem a leitura do controle analógico.</span>
<span style="color: #666666; font-style: italic;">//Devido à baixa qualidade do mesmo, não foi possível fazer </span>
<span style="color: #666666; font-style: italic;">//simplesmente um mapeamento do sinal de entrada para a posição final.</span>
<span style="color: #993333;">void</span> readAnalogPad<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">int</span> analog_x <span style="color: #339933;">=</span> analogRead<span style="color: #009900;">&#40;</span>dpad_x<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span> analog_y <span style="color: #339933;">=</span> analogRead<span style="color: #009900;">&#40;</span>dpad_y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #993333;">int</span> y <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span> x <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>analog_y <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">620</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    y <span style="color: #339933;">=</span> analog_y <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">680</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">5</span> <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>analog_y <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">540</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    y <span style="color: #339933;">=</span> analog_y <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">480</span> <span style="color: #339933;">?</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">5</span>  <span style="color: #339933;">:</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    y <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>analog_x <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">330</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    x <span style="color: #339933;">=</span> analog_x <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">380</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">5</span> <span style="color: #339933;">:</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>analog_x <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">280</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    x <span style="color: #339933;">=</span> analog_x <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">190</span> <span style="color: #339933;">?</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">5</span> <span style="color: #339933;">:</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    x <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  final_upper_pos <span style="color: #339933;">=</span> final_upper_pos <span style="color: #339933;">+</span> y<span style="color: #339933;">;</span>
  final_base_pos <span style="color: #339933;">=</span> final_base_pos <span style="color: #339933;">-</span> x<span style="color: #339933;">;</span>
&nbsp;
  final_upper_pos <span style="color: #339933;">=</span> final_upper_pos <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">180</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">180</span> <span style="color: #339933;">:</span> final_upper_pos<span style="color: #339933;">;</span>
  final_upper_pos <span style="color: #339933;">=</span> final_upper_pos <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">:</span> final_upper_pos<span style="color: #339933;">;</span>
&nbsp;
  final_base_pos <span style="color: #339933;">=</span> final_base_pos <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">180</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">180</span> <span style="color: #339933;">:</span> final_base_pos<span style="color: #339933;">;</span>
  final_base_pos <span style="color: #339933;">=</span> final_base_pos <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">:</span> final_base_pos<span style="color: #339933;">;</span>
&nbsp;
  delay<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Existem algumas melhorias para serem feitas no código, mas uma funcionalidade adicional que quero implementar é a capacidade de seguir. Imagino que seja possível fazer isso através de micro ajustes (ou micro buscas em uma área menor). Assim, teoricamente, seria possível seguir a fonte de luz mesmo se houver deslocamento da mesma. Além disso, pretendo trocar o sensor de luminosidade por um sensor de infra vermelho e, se funcionar como eu espero, poder detectar e seguir fontes de calor, como o corpo humano.</p>
<p>Bem, por fim vamos ao resultado final atual:</p>
<p><a href="http://www.youtube.com/watch?v=6bPUj58ctBw"><img src="http://img.youtube.com/vi/6bPUj58ctBw/2.jpg"></a></p>
<p><a href="http://www.youtube.com/watch?v=6bPUj58ctBw">Click here</a> to view the video on YouTube.</p>

<p>Por hora é só&#8230; Quando eu tiver tempo de dar um upgrade nesse protótipo, edito esse post para incluir as alterações.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2011%2F08%2Fluminolaser-eletronica-na-pratica-2%2F&amp;title=Luminolaser%20%26%238211%3B%20Eletr%C3%B4nica%20e%20Arduino%20na%20Pr%C3%A1tica%202" id="wpa2a_2"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/vksHDp5Omrg-iLLBDd2P4rWM844/0/da"><img src="http://feedads.g.doubleclick.net/~a/vksHDp5Omrg-iLLBDd2P4rWM844/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/vksHDp5Omrg-iLLBDd2P4rWM844/1/da"><img src="http://feedads.g.doubleclick.net/~a/vksHDp5Omrg-iLLBDd2P4rWM844/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2011/08/luminolaser-eletronica-na-pratica-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Colorino – Eletrônica e Arduino na Prática 1</title>
		<link>http://blog.jesjobom.com/2011/06/colorino-eletronica-e-arduino-na-pratica-1/</link>
		<comments>http://blog.jesjobom.com/2011/06/colorino-eletronica-e-arduino-na-pratica-1/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 04:26:49 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Colorino]]></category>
		<category><![CDATA[Led RGB]]></category>
		<category><![CDATA[Potenciômetro]]></category>
		<category><![CDATA[Protótipo]]></category>
		<category><![CDATA[Transistor]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=192</guid>
		<description><![CDATA[Depois de muuuito tempo inativo aqui no blog, volto para tentar tirar a poeira com uma nova área para mim e para muitos amigos &#8220;computeiros&#8221;: a eletrônica. Mais especificamente, o Arduino. Nos últimos meses estive consideravelmente ocupado (e preguiçoso) para voltar a escrever, principalmente devido ao padrão de post gigantes que habitam esse blog. Por [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de muuuito tempo inativo aqui no blog, volto para tentar tirar a poeira com uma nova área para mim e para muitos amigos &#8220;computeiros&#8221;: a eletrônica. Mais especificamente, o <a title="Arduino Wiki" href="http://pt.wikipedia.org/wiki/Arduino" target="_blank">Arduino</a>.</p>
<p>Nos últimos meses estive consideravelmente ocupado (e preguiçoso) para voltar a escrever, principalmente devido ao padrão de post gigantes que habitam esse blog. Por isso, dessa vez, tentarei fazer algo mais resumido e, conseqüentemente, voltado a quem já possui o mínimo de conhecimento sobre o assunto.</p>
<p>Vou me ater a apresentar o protótipo que fiz, a esquemática e código fonte sem entrar em maiores explicações de funcionamento.<span id="more-192"></span></p>
<p>Bem, o Colorino, como foi nomeado pelo meu caro amigo <a title="João Paulo Twittter" href="http://twitter.com/#!/jopss" target="_blank">@jopss</a>, é um experimento que fiz com o Arduino para aprender sobre e testar um led RGB que comprei do Deal Extreme usando resistores variáveis, transistores e uma programação bastante simples. O objetivo era controlar a intensidade de cada cor do led (vermelho, verde e azul) através dos resistores deslizantes. Através do uso de transistores, pude controlar a intensidade da corrente através do sinal digital do Arduino.</p>
<p>Primeiramente vamos ao componentes usados:</p>
<ul>
<li>1 Arduino Duemilanove ATMega328 (&#8220;Brasileirino&#8221;) [<a title="Arduino Uno" href="http://arduino.cc/en/Main/ArduinoBoardUno" target="_blank">Arduino Uno</a>];</li>
<li>1 Led RGB 5W 70 Lumen [<a title="Led RGB DX" href="http://www.dealextreme.com/p/5-watt-70-lumen-rgb-led-emitter-20999" target="_blank">Deal Extreme</a>];</li>
<li>3 Potenciômetros deslizantes 20 kΩ [<a title="Potenciômetro Google Images" href="http://www.google.com.br/search?q=potenci%C3%B4metro+deslizante&amp;hl=pt-BR&amp;safe=off&amp;prmd=ivns&amp;tbm=isch&amp;tbo=u&amp;source=univ&amp;sa=X&amp;ei=RuTqTYGxGci3tweZzaSYAQ&amp;ved=0CEQQsAQ&amp;biw=1366&amp;bih=677" target="_blank">Google Images</a>] [<a title="Potenciômetro Wiki US" href="http://en.wikipedia.org/wiki/Potentiometer" target="_blank">Wiki US</a>];</li>
<li>3 Transistores NPN Tip122 [<a title="Transistor Wiki" href="http://pt.wikipedia.org/wiki/Trans%C3%ADstor" target="_blank">Wiki</a>];</li>
<li>1 Bateria 4V de alta descarga (pode ser uma bateria de 3,7V de celular)*;</li>
<li>1 Bateria 9V convencional para alimentar o Arduino (opcional) [<a title="Bateria 9V Google Images" href="http://www.google.com.br/search?q=bateria%209v&amp;um=1&amp;ie=UTF-8&amp;tbm=isch&amp;source=og&amp;sa=N&amp;hl=pt-BR&amp;tab=wi&amp;biw=1366&amp;bih=677" target="_blank">Google Images</a>];</li>
<li>Muitos fios.</li>
</ul>
<p>* No caso da bateria de alta descarga, usei uma de 4V (de lítio) de um fone de ouvido bluetooth que eu tinha. Uma bateria de celular pode ser usada se retirado o limitador de descarga (fusível). Considerando uma fonte de 5V, o Led de 5W consumiria 1A (ampér), o que é bastante. Na prática, cheguei ao máximo de 0,5A.</p>
<p>Agora vamos à esquemática dos componentes.</p>
<p style="text-align: center;"><a href="http://blog.jesjobom.com/wp-content/gallery/arduino/colorino_bb.jpg" target="_blank"><img class="ngg-singlepic ngg-center aligncenter" src="http://blog.jesjobom.com/wp-content/gallery/arduino/colorino_bb.jpg" alt="colorino_esquema" width="430" height="347" /></a></p>
<p style="text-align: left;">Espero ter feito um bom trabalho ao desenhar esse esquema com o <em><a title="Fritzing" href="http://fritzing.org/" target="_blank">Fritzing</a></em>.</p>
<p style="text-align: left;">Hora do código fonte feito na <a title="Arduino Software" href="http://www.arduino.cc/en/Main/Software" target="_blank">IDE do Arduino</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">//Define as portas analógicas de entrada dos potenciômetros</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> pot_r <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> pot_g <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> pot_b <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">//Define as portas PWM de saída analógica para os transistores</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> led_r <span style="color: #000080;">=</span> <span style="color: #0000dd;">3</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> led_g <span style="color: #000080;">=</span> <span style="color: #0000dd;">5</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> led_b <span style="color: #000080;">=</span> <span style="color: #0000dd;">6</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">//Flag para ativar o debug pelo monitor da porta serial</span>
<span style="color: #0000ff;">const</span> boolean debug <span style="color: #000080;">=</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> setup<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  pinMode<span style="color: #008000;">&#40;</span>led_r, OUTPUT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  pinMode<span style="color: #008000;">&#40;</span>led_g, OUTPUT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  pinMode<span style="color: #008000;">&#40;</span>led_b, OUTPUT<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
  <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>debug<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> Serial.<span style="color: #007788;">begin</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">9600</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">void</span> loop<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
  <span style="color: #666666;">//Obtem a leitura dos potenciômetros nas portas analógicas</span>
  <span style="color: #0000ff;">int</span> pot_r_signal <span style="color: #000080;">=</span> analogRead<span style="color: #008000;">&#40;</span>pot_r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  <span style="color: #0000ff;">int</span> pot_g_signal <span style="color: #000080;">=</span> analogRead<span style="color: #008000;">&#40;</span>pot_g<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  <span style="color: #0000ff;">int</span> pot_b_signal <span style="color: #000080;">=</span> analogRead<span style="color: #008000;">&#40;</span>pot_b<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
  <span style="color: #666666;">//Converte os sinais dos potenciômetros para a escala de escrita das PWM</span>
  <span style="color: #666666;">//O led vermelho recebe menos energia por ser naturalmente mais forte</span>
  <span style="color: #0000ff;">int</span> pot_r_digital <span style="color: #000080;">=</span> map<span style="color: #008000;">&#40;</span>pot_r_signal, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">1023</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">150</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  <span style="color: #0000ff;">int</span> pot_g_digital <span style="color: #000080;">=</span> map<span style="color: #008000;">&#40;</span>pot_g_signal, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">1023</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">255</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  <span style="color: #0000ff;">int</span> pot_b_digital <span style="color: #000080;">=</span> map<span style="color: #008000;">&#40;</span>pot_b_signal, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">1023</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">255</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
  <span style="color: #666666;">//Escreve o sinal convertido para os transistores que deverão liberar</span>
  <span style="color: #666666;">//a quantia equivalente de corrente ao led</span>
  analogWrite<span style="color: #008000;">&#40;</span>led_r, pot_r_digital<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  analogWrite<span style="color: #008000;">&#40;</span>led_g, pot_g_digital<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  analogWrite<span style="color: #008000;">&#40;</span>led_b, pot_b_digital<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
  <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>debug<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;RED: &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span>pot_r_signal<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot; =&gt; &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">println</span><span style="color: #008000;">&#40;</span>pot_r_digital<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;GREEN: &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span>pot_g_signal<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot; =&gt; &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">println</span><span style="color: #008000;">&#40;</span>pot_g_digital<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;BLUE: &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span>pot_b_signal<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot; =&gt; &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Serial.<span style="color: #007788;">println</span><span style="color: #008000;">&#40;</span>pot_b_digital<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    delay<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1000</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p style="text-align: left;">Finalmente o resultado.</p>
<p><a href="http://www.youtube.com/watch?v=MtrYlR1_gAA"><img src="http://img.youtube.com/vi/MtrYlR1_gAA/2.jpg"></a></p>
<p><a href="http://www.youtube.com/watch?v=MtrYlR1_gAA">Click here</a> to view the video on YouTube.</p>

<p style="text-align: left;">Por hora é só. Espero voltar logo com outro pequeno projeto de Arduino voltado a estudo de componentes. Fui!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2011%2F06%2Fcolorino-eletronica-e-arduino-na-pratica-1%2F&amp;title=Colorino%20%26%238211%3B%20Eletr%C3%B4nica%20e%20Arduino%20na%20Pr%C3%A1tica%201" id="wpa2a_4"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/idZg-3Z3E4JCeqda500od8itvF0/0/da"><img src="http://feedads.g.doubleclick.net/~a/idZg-3Z3E4JCeqda500od8itvF0/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/idZg-3Z3E4JCeqda500od8itvF0/1/da"><img src="http://feedads.g.doubleclick.net/~a/idZg-3Z3E4JCeqda500od8itvF0/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2011/06/colorino-eletronica-e-arduino-na-pratica-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Novas Políticas de RH</title>
		<link>http://blog.jesjobom.com/2010/07/novas-politicas-de-rh/</link>
		<comments>http://blog.jesjobom.com/2010/07/novas-politicas-de-rh/#comments</comments>
		<pubDate>Fri, 30 Jul 2010 15:04:18 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Descontração]]></category>
		<category><![CDATA[Piada]]></category>
		<category><![CDATA[Recursos Humanos]]></category>
		<category><![CDATA[RH]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=180</guid>
		<description><![CDATA[Como, aparentemente, certos lugares não oferecem liberdade para disseminação de pequenas piadas visando uma rápida descontração no trabalho, posto aqui fugindo um pouco do padrão do blog. ^^ Com as novas regras vigentes no mercado e a necessidade de adaptação, tanto por parte das empresas quanto dos funcionários, informamos aos nossos colaboradores as novas regras [...]]]></description>
			<content:encoded><![CDATA[<p>Como, aparentemente, certos lugares não oferecem liberdade para disseminação de pequenas piadas visando uma rápida descontração no trabalho, posto aqui fugindo um pouco do padrão do blog. ^^</p>
<p>Com as novas regras vigentes no mercado e a necessidade de adaptação, tanto por parte das empresas quanto dos funcionários, informamos aos nossos colaboradores as novas regras aprovadas pelo RH de nossa empresa, e vigente a partir desta data:<span id="more-180"></span></p>
<p><strong><span style="color: #003366;">AUSÊNCIA DEVIDO À ENFERMIDADE:</span></strong><br />
Não vamos mais aceitar uma carta do médico como prova de enfermidade.<br />
Se o funcionário tem condições de ir até o consultório médico, pode vir trabalhar.</p>
<p><strong><span style="color: #003366;">CIRURGIA:</span></strong><br />
As cirurgias são proibidas. Enquanto o funcionário trabalhar nesta empresa precisará de todos os seus órgãos, portanto, não deve pensar em remover nada. Nós o contratamos inteiro. Remover algo constitui quebra de contrato.</p>
<p><strong><span style="color: #003366;">AUSÊNCIAS DEVIDO A MOTIVOS PESSOAIS:</span></strong><br />
Cada funcionário receberá 104 dias para assuntos pessoais a cada ano&#8230;<br />
Chamam-se sábado e domingo.</p>
<p><strong><span style="color: #003366;">AUSÊNCIA DEVIDO À SUA PRÓPRIA MORTE:</span></strong><br />
Isto será aceito como desculpa. Entretanto, exigimos pelo menos 15 dias de aviso prévio, visto que cabe ao funcionário treinar o seu substituto.</p>
<p><strong><span style="color: #003366;">O USO DO WC:</span></strong><br />
Os funcionários estão passando tempo demais no toalete. No futuro, seguiremos o sistema de ordem alfabética. Por exemplo, todos os funcionários cujos nomes começam com a letra &#8216;A&#8217;  irão entre 8:00 e<br />
8:20, aqueles com a letra &#8216;B&#8217; entre 8:20 e 8:40, etc. Se não puder ir na hora designada, será preciso esperar a sua vez, no dia seguinte. Em caso de emergência, os funcionários poderão trocar o seu horário com um colega.<br />
Os supervisores dos funcionários deverão aprovar essa troca, por escrito.<br />
Adicionalmente: agora há um limite estritamente máximo de 3 minutos no banheiro.<br />
Acabando esses 3 minutos, um alarme irá tocar, o rolo de papel higiênico será recolhido, a porta do banheiro abrirá e uma foto será tirada. Se for repetente, a foto será fixada no quadro de avisos da empresa sob o título: &#8220;Infrator Crônico&#8221;.</p>
<p><strong><span style="color: #003366;">INDUMENTÁRIA:</span></strong><br />
Informamos que o funcionário deverá trabalhar vestido de acordo com o seu salário.<br />
Se o percebermos calçando um tênis Nike de R$ 350,00 e carregando uma bolsa Gucci de R$ 600,00 presumiremos que vai bem de finanças e, portanto, não precisa de aumento.<br />
Se ele se vestir de forma pobre, será um sinal de que precisa aprender a controlar melhor o seu dinheiro para que possa comprar roupas melhores e, portanto, não precisa de aumento.<br />
E, se ele se vestir no meio termo, estará perfeito e, portanto, não precisa de aumento.</p>
<p><strong><span style="color: #003366;">A HORA DO ALMOÇO:</span></strong><br />
Os magros têm 30 minutos para o almoço, porque precisam comer mais para parecerem saudáveis. As pessoas de tamanho normal têm 15 minutos para comer uma refeição balanceada que sustente o seu corpo mediano. Os gordos têm 5 minutos, porque é tudo que precisam para tomar um &#8220;Slim Fast&#8221; e um remédio de regime.</p>
<p>Muito obrigado pela sua fidelidade à nossa empresa. Estamos aqui para proporcionar uma experiência empregatícia positiva. Portanto, toda dúvida, comentário, preocupação, reclamação, frustração, irritação, agravo, insinuação, alegação, acusação, observação, consternação e &#8220;input&#8221; deverá ser dirigida para qualquer outro lugar.</p>
<p>Atenciosamente,</p>
<p>Setor de Recursos Humanos</p>
<p>Fonte: <a title="Vila Vilão Viola Violão" href="http://vilavilaoviolaviola.blogspot.com/search?updated-max=2010-07-22T13:22:00-04:00&amp;max-results=10" target="_blank">Vila Vilão Viola Violão</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2010%2F07%2Fnovas-politicas-de-rh%2F&amp;title=Novas%20Pol%C3%ADticas%20de%20RH" id="wpa2a_6"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/SniokAeN4ULUqPsAJOmA_Rj10KE/0/da"><img src="http://feedads.g.doubleclick.net/~a/SniokAeN4ULUqPsAJOmA_Rj10KE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/SniokAeN4ULUqPsAJOmA_Rj10KE/1/da"><img src="http://feedads.g.doubleclick.net/~a/SniokAeN4ULUqPsAJOmA_Rj10KE/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2010/07/novas-politicas-de-rh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Munin: Configurações Avançadas de Plugins – parte 1</title>
		<link>http://blog.jesjobom.com/2010/05/munin-configuracoes-avancadas-de-plugins-parte-1/</link>
		<comments>http://blog.jesjobom.com/2010/05/munin-configuracoes-avancadas-de-plugins-parte-1/#comments</comments>
		<pubDate>Mon, 17 May 2010 20:46:00 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Ferramentas]]></category>
		<category><![CDATA[Ferramenta]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Munin]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Servidores]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=166</guid>
		<description><![CDATA[Voltando com mais um post atrasado e começando uma nova pequena série, venho apresentar alguns plugins do Munin (comentado no post anterior) muito legais e as suas configurações. Apesar de ter dito anteriormente que a instalação de um plugin basea-se na simples criação de um link simbólico, alguns plugins dependem de configurações específicas e, muitas [...]]]></description>
			<content:encoded><![CDATA[<p>Voltando com mais um post atrasado e começando uma nova pequena série, venho apresentar alguns plugins do Munin (comentado no <a title="Ferramentas Gratuitas para Manutenção de Servidores – Parte 1 (Munin)" href="http://blog.jesjobom.com/2010/01/ferramentas-gratuitas-para-manutencao-de-servidores/" target="_self">post anterior</a>) muito legais e as suas configurações. Apesar de ter dito anteriormente que a instalação de um plugin basea-se na simples criação de um link simbólico, alguns plugins dependem de configurações específicas e, muitas vezes, complexas.</p>
<p>Diferentemente do post anterior, terei que me ater a um ambiente específico, mas informarei quais as aplicações envolvidas e suas versões quando for o caso. No geral, utilizei o CentOS 5.3 para a instalação e configuração do Munin e seus plugins.</p>
<p>Desde já, informo que, na maioria das vezes, ler a documentação de um determinado plugin com problemas me ajudou muito. Geralmente a documentação está junto ao código, no próprio plugin. Então basta abri-lo com algum editor de textos.<span id="more-166"></span></p>
<h3>1. Conceitos Básicos:</h3>
<p>Não é necessário saber desenvolver plugins para conseguir instalá-los corretamente, mas alguns conceitos ajudarão muito a entender a documentação e os requisitos.</p>
<p>Primeiramente, os plugins são desenvolvidos em Perl. Com isso em mente, muitas vezes a solução de algum problema é simplesmente a instalação do pacote apropriado, como o perl-DBD-Pg para conexões com o PostgreSQL. USE O &#8216;<em>YUM SEARCH</em>&#8216; (ou &#8216;<em>apt-get</em>&#8216; ou <em>whatever</em>)!</p>
<p>Em alguns casos, serão necessários &#8220;variáveis de ambiente&#8221; para a correta execução do plugin. Por exemplo, um plugin para banco de dados precisa do usuário e senha de acesso; um plugin para o Tomcat precisará da porta de acesso.</p>
<p>Essas variáveis deverão ser configuradas no arquivo &#8216;<em>/etc/munin/plugin-conf.d/munin-node</em>&#8216;. Por padrão, algumas configurações e documentações já estão inclusas. E cada configuração relaciona-se ao plugin através do nome. Por exemplo:</p>
<blockquote>
<pre>[mysql*]
user root
group wheel
env.mysqladmin /usr/bin/mysqladmin
env.mysqlopts -u munin -pmunin1234</pre>
</blockquote>
<p>As configurações acima servirão para todos os plugins cujo nome comece com &#8220;<em>mysql</em>&#8220;. Esse plugin rodará como o usuário <em>root</em> e terá as permissões de super usuário. Além disso, fornecemos ao plugins alguns dados através de variáveis de ambiente (<em>env.</em>). No caso, o plugin usará o <em>mysqladmin </em>do local informado e usará o usuário &#8216;munin&#8217; para obter as informações necessárias.</p>
<p>Na documentação dos plugins geralmente é informado quais variáveis de ambiente devem ou podem ser setadas.</p>
<p>Além de configurações, existem alguns comandos úteis no processo de configuração de plugins. Através do &#8220;<em>munin-run</em>&#8221; podemos executar o plugin na hora, obtendo um valor numérico, se bem configurado, ou &#8216;<em>U</em>&#8216; se ocorrer algum problema interno. Por exemplo:</p>
<blockquote>
<pre># munin-run  tomcat_jvm
free.value 42133328
used.value 301537456
max.value 775487488</pre>
</blockquote>
<p>Adicione o argumento &#8220;<em>autoconf</em>&#8221; para receber uma resposta booleana:</p>
<blockquote>
<pre># munin-run mysql_queries autoconf
yes</pre>
</blockquote>
<h3>2. Plugin: MySQL</h3>
<p>Tratarei aqui sobre as configurações dos plugins &#8220;<em>mysql_queries</em>&#8221; e &#8220;<em>mysql_threads</em>&#8220;. O primeiro apresenta a quantidade de requisições ao banco por tipo (selects, updates, deletes, etc); o segundo mostra a quantidade de threads criadas internamento no MySQL.</p>
<p style="text-align: center;"><img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/redes/mysql_queries.png" alt="mysql_queries" /><br />
mysql_queries</p>
<p style="text-align: center;"><img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/redes/mysql_threads.png" alt="mysql_threads" /><br />
mysql_threads</p>
<p>Essencialmente, precisamos apenas criar um usuário do MySQL sem permissão alguma e informar os dados de acesso ao plugin. Então criemos um usuário:</p>
<blockquote>
<pre>mysql -uroot -p -e 'CREATE USER munin IDENTIFIED BY "munin1234"'</pre>
</blockquote>
<p>Adicione as informações de acesso no arquivo &#8216;<em>/etc/munin/plugin-conf.d/munin-node</em>&#8216;:</p>
<blockquote>
<pre>[mysql*]
user root
group wheel
env.mysqladmin /usr/bin/mysqladmin
env.mysqlopts -umunin -pmunin1234</pre>
</blockquote>
<p>Através desse usuário o plugin obterá os dados necessários para geração do gráfico. Utilize o comando &#8220;<em>munin-run</em>&#8221; para testar:</p>
<blockquote>
<pre># munin-run mysql_queries
delete.value 35756
insert.value 231054
replace.value 20
select.value 10460090
update.value 5261807
cache_hits.value 52529748</pre>
</blockquote>
<blockquote>
<pre># munin-run mysql_threads
threads.value 14</pre>
</blockquote>
<p>Simples, não? Muitas vezes a dificuldade não é configurar, mas sim descobrir o que configurar.</p>
<h3>3. Plugin: PostgreSQL</h3>
<p>Dessa vez falarei sobre um plugin para PostgreSQL, o &#8220;<em>postgres_connections_db</em>&#8220;. Ele gera um gráfico com os valores de conexões por banco de dados.</p>
<p style="text-align: center;"><img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/redes/postgres_connections_db.png" alt="postgres_connections_db" /><br />
postgres_connections_db</p>
<p>Dessa vez, além de criar um novo usuário para o Munin, temos que liberar o acesso livre desse usuário a partir do servidor. Então, primeiramente, criamos o usuário com senha aleatória (segura):</p>
<blockquote>
<pre>psql -U postgres -c "CREATE ROLE munin NOSUPERUSER NOCREATEDB
NOCREATEROLE NOINHERIT LOGIN ENCRYPTED PASSWORD 'LjkJ9JUha2';"</pre>
</blockquote>
<p>Utilizamos uma senha segura porque não usaremos ela na configuração do plugin. Ao invés disso, liberaremos o acesso sem senha para o usuário &#8220;munin&#8221; a partir do servidor para uma determinada tabela. Então, abriremos para edição o arquivo &#8220;<em>/var/lib/pgsql/data/pg_hba.conf</em>&#8221; e adicionamos a linha:</p>
<blockquote>
<pre>local   template1   munin   trust</pre>
</blockquote>
<p>Com isso, todas as conexões para o usuário &#8220;munin&#8221; na tabela &#8220;template1&#8243; a partir do servidor local serão aceitas sem a necessidade de senha. Basta dar um reload no postgre e podemos incluir as configurações do plugin no arquivo &#8220;<em>/var/lib/pgsql/data/pg_hba.conf</em>&#8221; :</p>
<blockquote>
<pre>[postgres*]
user munin
env.dbuser munin</pre>
</blockquote>
<p>Depois disso, basta testar:</p>
<blockquote>
<pre># munin-run postgres_connections_db
postgres.value 0
template1.value 0
...</pre>
</blockquote>
<p>Bem. Acredito que seja o suficiente por hora&#8230; Espero voltar logo com a continuação apresentando outros Plugins para o Munin, incluindo um plugin não oficial para monitorar memória usada pelo Passenger (RoR).</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2010%2F05%2Fmunin-configuracoes-avancadas-de-plugins-parte-1%2F&amp;title=Munin%3A%20Configura%C3%A7%C3%B5es%20Avan%C3%A7adas%20de%20Plugins%20%26%238211%3B%20parte%201" id="wpa2a_8"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/BJdBi1RB7L352VqsItQDG1B6tmE/0/da"><img src="http://feedads.g.doubleclick.net/~a/BJdBi1RB7L352VqsItQDG1B6tmE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/BJdBi1RB7L352VqsItQDG1B6tmE/1/da"><img src="http://feedads.g.doubleclick.net/~a/BJdBi1RB7L352VqsItQDG1B6tmE/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2010/05/munin-configuracoes-avancadas-de-plugins-parte-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ferramentas Gratuitas para Manutenção de Servidores – Parte 1 (Munin)</title>
		<link>http://blog.jesjobom.com/2010/01/ferramentas-gratuitas-para-manutencao-de-servidores/</link>
		<comments>http://blog.jesjobom.com/2010/01/ferramentas-gratuitas-para-manutencao-de-servidores/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 20:34:55 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Ferramentas]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Monitoramento]]></category>
		<category><![CDATA[Munin]]></category>
		<category><![CDATA[Servidores]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=148</guid>
		<description><![CDATA[Após muuuito tempo sem escrever, volto tentando reanimar escrevendo algo um pouco diferente do usual. Irei apresentar algumas ferramentas gratuitas que podem ajudar bastante no gerenciamento e manutenção de servidores.

Estou há alguns poucos meses trabalhando nessa área, mas aprendi muito. Perdi o medo que tinha do Linux e agora configuro e monitoro servidores utilizando ferramentas que, uma vez configuradas corretamente, tornam a vida muito mais simples.

Não irei me focar em ensinar a configurar cada uma visto que as configurações variam de OS para OS e  existem tutoriais no site oficial da respectiva ferramenta e no Google. Simplesmente darei um <em>overview</em> apresentando as principais características, prós, contras e outras observações pertinentes.

Dividirei os posts, apresentando uma aplicação de cada vez. E começarei com o Munin.]]></description>
			<content:encoded><![CDATA[<p>Após muuuito tempo sem escrever, volto tentando reanimar escrevendo algo um pouco diferente do usual. Irei apresentar algumas ferramentas gratuitas que podem ajudar bastante no gerenciamento e manutenção de servidores.</p>
<p>Estou há alguns poucos meses trabalhando nessa área, mas aprendi muito. Perdi o medo que tinha do Linux e agora configuro e monitoro servidores utilizando ferramentas que, uma vez configuradas corretamente, tornam a vida muito mais simples.</p>
<p>Não irei me focar em ensinar a configurar cada uma visto que as configurações variam de OS para OS e  existem tutoriais no site oficial da respectiva ferramenta e no Google. Simplesmente darei um <em>overview</em> apresentando as principais características, prós, contras e outras observações pertinentes.</p>
<p>Dividirei os posts, apresentando uma aplicação de cada vez. E começarei com o Munin.</p>
<h3><span id="more-148"></span></h3>
<h2>1. Munin (<a title="Munin" href="http://munin.projects.linpro.no/" target="_blank">http://munin.projects.linpro.no/</a>)</h2>
<p>É uma aplicação bastante simples de monitoramento de recursos de servidores. Permite a visualização via navegador de diversos gráficos referentes à uso de memória, espaço em disco, uso de CPU, tráfego de saída e entrada de dados, e outros. Sendo que cada fonte de dados, por padrão, é compilada em quatro gráficos (diário, semanal, mensal e anual). A coleta de dados é realizada através de um agendamento no <em>cron</em> do sistema, criado na instalação do Munin.</p>
<p><img class="ngg-singlepic ngg-right" src="http://blog.jesjobom.com/wp-content/gallery/redes/munin1.jpg" alt="munin1" /></p>
<p><img class="ngg-singlepic ngg-right" src="http://blog.jesjobom.com/wp-content/gallery/redes/munin2.jpg" alt="munin2" /></p>
<h3>a. Instalação e configuração</h3>
<p>No próprio site existe um <a title="Munin - Guia Instalação Linux" href="http://munin.projects.linpro.no/wiki/LinuxInstallation" target="_blank">guia</a> abrangendo a instalação do Munin em diversas distribuições do Linux e até mesmo para o <a title="Munin - Guia Instalação MacOS" href="http://munin.projects.linpro.no/wiki/DarwinInstallation" target="_blank">MacOS</a> (<em>no donuts for you, Windows users</em>). Após esse processo, basta configurar o grupo e nome do servidor (como mostrado <a title="Munin - Configuração Inicial" href="http://munin.projects.linpro.no/wiki/munin.conf" target="_blank">aqui</a>) e configurar o Apache para permitir acesso ao &#8220;home&#8221; da aplicação (por padrão <em>/var/www/munin/ </em>) através de algum URL.</p>
<p>O Munin é baseado em plugins, sendo que cada conjunto de gráficos é um plugin que pode ser instalado ou desinstalado fácil e independentemente. Basta criar ou excluir um link simbólico (atalho) na pasta <em>/etc/munin/plugins </em>do plugin desejado localizado em <em>/usr/share/munin/plugins</em>.</p>
<p>Além disso, é possível facilmente <a title="Munin - Configuração Alertas" href="http://munin.projects.linpro.no/wiki/HowToContact" target="_blank">configurar</a> o Munin para emitir alertas em certas condições como, por exemplo, quando o uso de CPU for maior que 80%. Isso pode ser feito integrando com o <a title="Nagios" href="http://www.nagios.org/" target="_blank">Nagios</a> ou enviando e-mail através de do serviço <em>sendmail</em> ou um script externo.</p>
<h3>b. Prós</h3>
<ul>
<li>Simples, direto e rápido;</li>
<li>Fácil configuração e permite a edição de plugins ou criação de novos;</li>
<li>Possui opção de alertas em determinadas condições.</li>
</ul>
<h3>c. Contras</h3>
<ul>
<li>A configuração do envio de alertas é muito básica, não permitindo controlar a quantidade ou a periodicidade dos envios. Se utilizado o Nagios, é possível configurá-lo para isso;</li>
<li>Depende da disponibilidade do sistema para realizar o monitoramento. Se o servidor travar do nada, o Munin ficará travado também;</li>
<li>Documentação online bagunçada e muitas vezes insuficiente para orientar novos usuários.</li>
</ul>
<h3>d. Observações adicionais</h3>
<p>Por padrão, o Munin não apresenta um sistema de segurança para o acesso às suas informações. Uma forma bastante simples de fazer essa segurança é configurando o Apache para utilizar um arquivo de autenticação:</p>

<div class="wp_syntax"><div class="code"><pre class="apache" style="font-family:monospace;">    &lt;<span style="color: #000000; font-weight:bold;">Directory</span> /var/www/html/munin&gt;
        <span style="color: #00007f;">Order</span> <span style="color: #00007f;">deny</span>,<span style="color: #00007f;">allow</span>
        <span style="color: #00007f;">Deny</span> from <span style="color: #0000ff;">all</span>
        <span style="color: #00007f;">Allow</span> from 127.0.0.1
&nbsp;
        <span style="color: #00007f;">AuthType</span> Basic
        <span style="color: #00007f;">AuthName</span> <span style="color: #7f007f;">&quot;My Server Munin&quot;</span>
        <span style="color: #00007f;">AuthUserFile</span> /var/www/html/.htpasswd
        <span style="color: #00007f;">require</span> valid-<span style="color: #00007f;">user</span>
&nbsp;
        <span style="color: #00007f;">Satisfy</span> Any
    &lt;/<span style="color: #000000; font-weight:bold;">Directory</span>&gt;</pre></div></div>

<p>Então é isso. ^^ </p>
<p>Espero em breve voltar com outro post sobre outra aplicação para o gerenciamento de servidores ou dando continuidade à série &#8220;Java para Web&#8221; =P</p>

<p><a href="http://feedads.g.doubleclick.net/~a/aGMz7Wnm3dwPypjWTaUN8Xshtjc/0/da"><img src="http://feedads.g.doubleclick.net/~a/aGMz7Wnm3dwPypjWTaUN8Xshtjc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/aGMz7Wnm3dwPypjWTaUN8Xshtjc/1/da"><img src="http://feedads.g.doubleclick.net/~a/aGMz7Wnm3dwPypjWTaUN8Xshtjc/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2010/01/ferramentas-gratuitas-para-manutencao-de-servidores/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Maven em um Teclado Virtual</title>
		<link>http://blog.jesjobom.com/2009/08/maven-em-um-teclado-virtual/</link>
		<comments>http://blog.jesjobom.com/2009/08/maven-em-um-teclado-virtual/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 03:12:36 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Applet]]></category>
		<category><![CDATA[Codificação]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[MD5]]></category>
		<category><![CDATA[Segurança]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=122</guid>
		<description><![CDATA[Para quem não sabe, <a title="Apache Maven" href="http://maven.apache.org/" target="_blank">Maven</a> é uma excelente ferramenta para o gerenciamento de projetos, principalmente por facilitar <strong>muito </strong>o controle de dependências e automatizar o processo de inclusão dessas. Mas o seu papel não se limita a essa tarefa; uma grande ajuda dada pelo Maven é a automatização de outras tarefas como descompactar um determinado arquivo ou publicar um jar. De certa forma, pode-se até comparar o Maven com o velho Ant.

Neste post iremos ver como o Maven pode ajudar tanto na inclusão de dependências como em outras tarefas antes realizadas manualmente. Como o foco não será o projeto em si, utilizaremos o projeto do <a title="Applet de um Teclado Virtual" href="http://blog.jesjobom.com/2009/05/applet-de-um-teclado-virtual/" target="_self">Teclado Virtual</a> do post anterior.

Ao final do post existirão links para um pacote compactado com o projeto do tutorial e um exemplo (parcial) online do mesmo.

Ah... Quando criei esse blog alguns amigos de trabalho me disseram que logo logo eu pederia o ânimo pra postar... Pois é... &#62;.&#60;]]></description>
			<content:encoded><![CDATA[<p>Para quem não sabe, <a title="Apache Maven" href="http://maven.apache.org/" target="_blank">Maven</a> é uma excelente ferramenta para o gerenciamento de projetos, principalmente por facilitar <strong>muito </strong>o controle de dependências e automatizar o processo de inclusão dessas. Mas o seu papel não se limita a essa tarefa; uma grande ajuda dada pelo Maven é a automatização de outras tarefas como descompactar um determinado arquivo ou publicar um jar. De certa forma, pode-se até comparar o Maven com o velho Ant.</p>
<p>Neste post iremos ver como o Maven pode ajudar tanto na inclusão de dependências como em outras tarefas antes realizadas manualmente. Como o foco não será o projeto em si, utilizaremos o projeto do <a title="Applet de um Teclado Virtual" href="http://blog.jesjobom.com/2009/05/applet-de-um-teclado-virtual/" target="_self">Teclado Virtual</a> do post anterior.</p>
<p>Ao final do post existirão links para um pacote compactado com o projeto do tutorial e um exemplo (parcial) online do mesmo.</p>
<p>Ah&#8230; Quando criei esse blog alguns amigos de trabalho me disseram que logo logo eu pederia o ânimo pra postar&#8230; Pois é&#8230; &gt;.&lt;<br />
<span id="more-122"></span><br />
<h3>1. Ambiente e Criação do Projeto</h3>
<p>Primeiramente, utilizarei o NetBeans 6.5 com o plugin do Maven (basta buscar por &#8220;Maven&#8221; no filtro de plugin). E o Tomcat 6 (inclua-o no NetBeans). O código do teclado virtual será o mesmo do post anterior, com algumas pequenas alterações. Então vamos lá!</p>
<p>Tendo o plugin do Maven instalado, crie um novo projeto para o novo teclado virtual (Novo Projeto -&gt; Maven -&gt; Maven Project). Escolha o &#8220;<em>Maven Quickstart Archetype</em>&#8221; mesmo. Nomeei o meu projeto de &#8220;teclado-mvn&#8221; e coloquei o &#8220;Group Id&#8221; e o &#8220;Package&#8221; como &#8220;br.com.teclado.virtual.mvn&#8221;. Finalize.</p>
<p>Será criado um projeto java já nos moldes do Maven. Observe na pasta &#8220;Project Files&#8221; o arquivo &#8220;pom.xml&#8221;. Ele é o centro das configurações do Maven no seu projeto. Dentro da tag &#8220;dependency&#8221; haverá algumas entradas referentes ao &#8220;junit&#8221;. Isso quer dizer que o seu novo projeto é dependente do JUnit e tentará baixar o .jar referente do repositório padrão do Maven quando você for realizar algum teste (neste caso é em testes devido ao &#8220;scope&#8221; da dependência).</p>
<p>Agora vamos efetivamente &#8220;recriar&#8221; o teclado virtual. Apague as classes criadas automaticamente nos pacotes do projeto e copie a classe &#8220;TecladoVirtual.java&#8221; do projeto do post anterior para o pacote principal do novo projeto. Diversos erros deverão ser visíveis e, se você leu o post anterior, deverá saber o porquê.</p>
<p>No projeto original do teclado virtual, tínhamos que manualmente copiar o plugin.jar da pasta do JRE instalado para podermos utilizar a classe JSObject. Agora utilizaremos o Maven para fazer isso de uma maneira mais &#8220;elegante&#8221;.</p>
<h3>2. Instalação e Utilização de Nova Dependência</h3>
<p>Abra o &#8220;pom.xml&#8221; e vamos customizar a construção (<em>build</em>) do projeto. Em suma, o que faremos, é instalar o &#8220;plugin.jar&#8221; no repositório local e adicionar essa dependência ao teclado.</p>
<p>Para deixar mais claro, o que o Maven faz é, artravés do arquivo de configurações dele (pom.xml), identificar as dependências do projeto e baixar os seus <em>jars</em> do <a title="Maven Repository" href="http://www.mvnrepository.com/" target="_blank">repositório remoto</a> para uma pasta local na própria máquina (é chamado de &#8220;Repositório Local&#8221;). Então temos que incluir o &#8220;plugin.jar&#8221; no repositório local para podermos utilizá-lo.</p>
<p>No &#8220;pom.xml&#8221; adicione o seguinte treço dentro da tag <strong>&lt;project&gt;</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugins<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-install-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2.3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;phase<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>generate-sources<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/phase<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>generate-sources<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;inherited<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/inherited<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>java.plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.6.0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;packaging<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>jar<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/packaging<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>${env.JAVA_HOME}/jre/lib/plugin.jar<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/file<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>install-file<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
               <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-compiler-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2.0.2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;source<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.5<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/source<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;target<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.5<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/target<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-compiler-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2.0.2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;encoding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>ISO-8859-1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/encoding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-resources-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2.2<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;encoding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>ISO-8859-1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/encoding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugins<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Observando apenas a primeira tag <strong>&lt;plugin&gt;</strong>, temos que durante a <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html" target="_blank">fase (<strong>&lt;phase&gt;</strong>) do clico de vida de construção do projeto</a> &#8220;generate-sources&#8221; (antes da compilação), irá executar a tarefa (<strong>&lt;goal&gt;</strong>) &#8220;install-file&#8221; da entidade (<strong>&lt;artifactId&gt;</strong>) &#8220;maven-install-plugin&#8221;. O arquivo a ser instalado (<strong>&lt;file&gt;</strong>) será o &#8220;plugin.jar&#8221; da JRE instalada e referenciada pela variável de ambiente &#8220;JAVA_HOME&#8221;. Após instalado, o jar poderá ser encontrado no repositório local pelo grupo &#8220;java.plugin&#8221;, artefato &#8220;plugin&#8221; e versão &#8220;1.6.0&#8243;.</p>
<p>Os plugins restantes na tag &#8220;build&#8221; são necessário para a execução completa do ciclo de vida da compilação feita pelo Maven.</p>
<p>Agora dê um &#8220;Limpar e Construir&#8221; (Clean and Build) no projeto e verifique se os erros no TecladoVirtual.java permanecem. Se sim, então está correto! =P</p>
<p>O que nós fizemos foi incluir o &#8220;plugin.jar&#8221; no repositório local, mas ainda não o incluimos no projeto. Antes disso, vamos conhecer o repositório local. Abra no Windows a sua pasta do &#8220;Documents and Settings&#8221; (C:\Documents and Settings\Usuario) e verá uma pasta &#8220;.m2&#8243;. Nela está o seu repositório local do Maven. Todas as dependências de projeto são baixadas para esta pasta de modo que não seja necessário baixar tudo novamente caso um novo projeto seja criado. Se você tentou construir o nosso novo projeto do teclado virtual, então já deve exisitir a pasta &#8220;.m2\repository\java\plugin\plugin\1.6.0&#8243; com o &#8220;plugin-1.6.0.jar&#8221;. Agora, adicione esta dependência ao projeto.</p>
<p>No &#8220;pom.xml&#8221;, dentro da tag <strong>&lt;dependencies&gt;</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>java.plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.6.0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Salve, limpe, compile e veja os erros do TecladoVirtual.java sumirem. Caso algum erro tenha ocorrido até este ponto, verifique se a variável de ambiente &#8220;JAVA_HOME&#8221; está devidamente setada e o caminho no &#8220;pom.xml&#8221; até o &#8220;plugin.jar&#8221; está correto.</p>
<p>Uma pequena alteração deve ser feita em relação ao projeto anterior do teclado virtual. Através do Windows, crie a pasta &#8220;resources&#8221; (&#8220;teclado-mvn\src\main\resources&#8221;) no novo projeto e copie as imagens do teclado para esta pasta. No NetBeans deverá aparecer a pasta &#8220;Other Sources&#8221;. E no &#8220;TecladoVirtual.java&#8221; altere o caminho à imagem de &#8220;/resources/teclado1.JPG&#8221; para &#8220;/teclado1.JPG&#8221;.</p>
<p>Veja a imagem de como ficou:<br />
<a class="shutterset_" href="http://blog.jesjobom.com/wp-content/gallery/java/teclado-mvn-status1.jpg"><img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/java/thumbs/thumbs_teclado-mvn-status1.jpg" alt="teclado-mvn-status1" /></a></p>
<p style="text-align: center;"><a href="http://blog.jesjobom.com/wp-content/gallery/java/teclado-mvn-status1.jpg" target="_blank">(abrir em nova janela)</a></p>
<p style="text-align: left;">
<h3 style="text-align: left;">3. Codificação da Senha do Teclado</h3>
<p>O que faremos agora é uma alteração no código do teclado virtual para que a senha copiada ao campo oculto do formulário HTML seja previamente codificada com <a title="MD5 Wikipédia" href="http://pt.wikipedia.org/wiki/MD5" target="_blank">MD5</a> impossibilitando a obtenção da senha original mesmo que o valor do campo oculto seja lido.</p>
<p>Mas antes precisamos incluir uma dependência ao projeto; é o &#8220;commons-codec&#8221;. Se você está utilizando o NetBeans e ainda não descobriu a grande vantagem da IDE sobre a edição de XMLs, tente usar agora o auto-completar (CTRL+espaço) para encontrar o <strong>&lt;groupId&gt;</strong> e o <strong>&lt;artifactId&gt;</strong> desta nova dependência. Assim que o projeto foi criado, o plugin do Maven deve ter baixado (ou tentado baixar) um índice de dependências do repositório remoto contendo os grupos e artefatos disponíveis. A única demora deverá ser para encontrar as versões (<strong>&lt;version&gt;</strong>) disponíveis, pois ele precisará procurar em tempo real no repositório remoto.</p>
<p>Então adicione dentro da tag <strong>&lt;dependencies&gt;</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>commons-codec<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>commons-codec<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Com isso, podemoremos usar o pacote &#8220;<em>java.security.MessageDigest</em>&#8221; para codificar a senha. Sem maiores explicações (para não fugir do foco e para não me estender demais), o métodos para codigicação de Strings em MD5 deverá ficar assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">   <span style="color: #008000; font-style: italic; font-weight: bold;">/**
    * Encripta um texto em MD5
    *
    * @param texto
    * @return String
    */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> md5Encrypt<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> texto<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
       <span style="color: #003399;">String</span> encripted <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
       <span style="color: #000000; font-weight: bold;">try</span><span style="color: #009900;">&#123;</span>
          <span style="color: #003399;">MessageDigest</span> md <span style="color: #339933;">=</span> <span style="color: #003399;">MessageDigest</span>.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;MD5&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          md.<span style="color: #006633;">update</span><span style="color: #009900;">&#40;</span> texto.<span style="color: #006633;">getBytes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          <span style="color: #003399;">BigInteger</span> hash <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BigInteger</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">1</span>, md.<span style="color: #006633;">digest</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          encripted <span style="color: #339933;">=</span> hash.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">16</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span>
       <span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">NoSuchAlgorithmException</span> ns<span style="color: #009900;">&#41;</span>  <span style="color: #009900;">&#123;</span>
          ns.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span>
       <span style="color: #000000; font-weight: bold;">return</span> encripted<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Agora basta utilizar este método codificar a senha no momento de enviar ao HTML:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    win.<span style="color: #006633;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;recebeSenha('&quot;</span> <span style="color: #339933;">+</span> md5Encrypt<span style="color: #009900;">&#40;</span>senha<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;',&quot;</span> <span style="color: #339933;">+</span> senha.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>4. Criação do Projeto Web para Utilização do Teclado Virtual</h3>
<p>Vamos criar outro projeto Maven seguindo os mesmos passos do projeto anterior, mas escolheremos &#8220;<em>Maven Webapp Archetype</em>&#8221; depois de Arquivo -&gt; Novo Projeto -&gt; Maven -&gt; Maven Project. Os nomes que utilizei foram &#8220;teste-teclado-mvn&#8221; no nome e &#8220;br.com.teclado.virtual.mvn&#8221; como nome de grupo e empacotamento.</p>
<p>Alguém notou alguma semelhança dos dados que incluímos na criação de um projeto Maven com os dados utilizados para a adição de uma dependência? Pois é, quando compilamos um projeto, uma das fases executada é a instalação desse projeto no repositório local, sob o Grupo e Artefato utilizados na criação do mesmo. Assim, outros projetos podem ser dependentes do projeto instalado. Mas não é exatamente este o caso da relação Teclado Virtual &#8211; Projeto Web.</p>
<p>O projeto web não é exatamente dependente do Teclado Virtual para realizar alguma tarefa ou utilizar algum método. O jar do teclado deve apenas estar presente para que o navegador do usuário possa baixar e executá-lo. Então, ao invés de simplesmente adicioná-lo como um dependência, iremos copiar o jar que se encontra no repositório local para uma pasta do projeto web, tornando-o diponível ao usuário.</p>
<p>Sem mais enrolação, insira o trecho a seguir dentro da tag <strong>&lt;project&gt;</strong> do &#8220;pom.xml&#8221; do projeto web.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"> <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;finalName<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>teste-teclado-mvn<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/finalName<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugins<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>maven-dependency-plugin<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>2.1<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
             <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;phase<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>compile<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/phase<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>copy-teclado<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;inherited<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/inherited<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactItems<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.com.teclado.virtual.mvn<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>teclado-mvn<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.0-SNAPSHOT<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;destFileName<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>teclado-mvn.jar<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/destFileName<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>commons-codec<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>commons-codec<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.3<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;destFileName<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>commons-codec.jar<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/destFileName<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactItems<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;overWriteIfNewer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/overWriteIfNewer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;overWriteSnapshots<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/overWriteSnapshots<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;overWriteReleases<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/overWriteReleases<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;outputDirectory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/src/main/webapp/applet<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/outputDirectory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>copy<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goal<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/goals<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
             <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/execution<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/executions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugin<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plugins<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/build<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Em suma, durante a fase (<strong>&lt;phase&gt;</strong>) de compilação o Maven irá copiar (<strong>&lt;goal&gt;</strong>) as dependências (<strong>&lt;artifactItems&gt;</strong>) referentes ao projeto do Teclado Virtual e ao pacote do &#8220;commons-codec&#8221;, renomeando-os para &#8220;teclado-mvn.jar&#8221; e &#8220;commons-codec.jar&#8221;, para a pasta (<strong>&lt;outputDirectory&gt;</strong>) &#8220;/src/main/webapp/applet&#8221;. Esta pasta estará no mesmo nível do &#8220;index.jsp&#8221; do projeto.</p>
<p>O &#8220;commons-codec&#8221; teve que ser copiado também pois onde o jar do teclado executará (no navegador do usuário) nem sempre existe esta biblioteca. Se quiser testar sem a instrução para copiar este pacote, não tem problema, a princípio.</p>
<p>Por último, podemos alterar o &#8220;index.jsp&#8221; para utilizar o Teclado Virtual. Vamos simplesmente copiar o código do HTML de teste do post sobre o Teclado Virtual, lembrando de alterar os valores da variáveis &#8220;clazz&#8221; e &#8220;jar&#8221; para &#8220;br.com.teclado.virtual.mvn.TecladoVirtual.class&#8221; (ou como você nomeou sua classe/pacote) e &#8220;applet/teclado-mvn.jar&#8221;, respectivamente.</p>
<p>Se deu tudo certo, ao executar o projeto web, deverá aparecer o teclado virtual e, ao submeter a página, no endereço da mesma deverão estar o nome do usuário e a senha codificada.</p>
<p>Então é isso! Finalmente consegui publicar um post depois de tanto tempo! \o/</p>
<p>Para encontrar outras operações disponíveis pelo Maven, tente o <a title="Google.com" href="http://www.google.com.br/" target="_blank">Oráculo</a> ou tente explorar os artefatos do Grupo &#8220;org.apache.maven.plugins&#8221; (incluso em ambas operações descritas anteriormente).</p>
<p>cya.</p>
<p>Projeto do Teclado Virtual com Maven compactado e configurado no NetBeans: <a href="http://blog.jesjobom.com/wp-content/uploads/2009/08/teclado-mvn.rar">teclado-mvn</a></p>
<p>Exemplo Online do teclado com a codificação da senha: <a title="Exemplo Online do Teclado Virtual criado com Maven" href="http://jesjobom.com/files/blog/teclado_mvn/" target="_blank">teclado-mvn-online</a></p>

<p><a href="http://feedads.g.doubleclick.net/~a/-heR7HfxaXTUJruhaRQTxnw24Zw/0/da"><img src="http://feedads.g.doubleclick.net/~a/-heR7HfxaXTUJruhaRQTxnw24Zw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/-heR7HfxaXTUJruhaRQTxnw24Zw/1/da"><img src="http://feedads.g.doubleclick.net/~a/-heR7HfxaXTUJruhaRQTxnw24Zw/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2009/08/maven-em-um-teclado-virtual/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Workshop de Mídias Sociais em Campo Grande – MS</title>
		<link>http://blog.jesjobom.com/2009/08/134/</link>
		<comments>http://blog.jesjobom.com/2009/08/134/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 22:22:50 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Eventos]]></category>
		<category><![CDATA[Mídia Social]]></category>
		<category><![CDATA[Workshop]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=134</guid>
		<description><![CDATA[Nos dias 20 e 21 de agosto, vai rolar em Campo Grande – MS o Workshop de Mídias Sociais no Auditório do Sebrae. Vai ter palestras com gente que manja do assunto como Luli Radfahrer, Interney e Marcelo Tas. Você pode Conferir uma das palestras do Luli aqui no blog do focezar mesmo, enjoy! O Evento: [...]]]></description>
			<content:encoded><![CDATA[<p>Nos dias 20 e 21 de agosto, vai rolar em Campo Grande – MS o Workshop de Mídias Sociais no Auditório do Sebrae.</p>
<p>Vai ter palestras com gente que manja do assunto como <a href="http://www.luli.com.br/" target="_blank">Luli Radfahrer</a>, <a href="http://www.interney.net/" target="_blank">Interney</a> e <a href="http://marcelotas.blog.uol.com.br/" target="_blank">Marcelo Tas</a>.</p>
<p>Você pode Conferir uma das palestras do Luli <a href="http://blog.fernandocezar.net/2009/02/03/luli-radfahrer-para-que-serve-uma-monocotiledonea-nerds-midias-sociais-e-a-escola-do-seculo-21/" target="_blank">aqui</a> no <a href="http://blog.fernandocezar.net/tag/luli-radfahrer/" target="_blank">blog</a> do <a title="Blog do Focezar" href="http://blog.fernandocezar.net/" target="_blank">focezar</a> mesmo, enjoy!<span id="more-134"></span></p>
<p>O Evento:</p>
<div class="wp-caption aligncenter" style="width: 410px"><a href="http://wsms2009.files.wordpress.com/"><img title="Workshop de Mídias Sociais" src="http://wsms2009.files.wordpress.com/2009/08/blog-banner.jpg" alt="Workshop de Mídias Sociais" width="400" height="166" /></a><p class="wp-caption-text">Workshop de Mídias Sociais</p></div>
<p>A programação do Evento está <a href="http://wsms2009.wordpress.com/2009/08/05/programacao/" target="_blank">aqui</a>!</p>
<p>E as inscrições para as palestras gratuitas podem ser feitas por <a href="http://intranet.ms.sebrae.com.br/crie_cadastro/">aqui</a>! (Tem que fazer inscrição para cada uma das palestras desejadas)</p>
<p>A palestra do Marcelo Tas custa 30 reais, 15 reais para estudantes, e os ingressos podem ser adquiridos direto no Sebrae.</p>
<p>Além das palestras, vão ocorrer oficinas de diversos temas.</p>
<p>É isso, até lá!</p>
<p>PS: Post <em><a title="Definição de &quot;kibar&quot;" href="http://desciclo.pedia.ws/wiki/Descion%C3%A1rio:Kibar" target="_blank">kibado</a> </em>do focezar ^^</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2009%2F08%2F134%2F&amp;title=Workshop%20de%20M%C3%ADdias%20Sociais%20em%20Campo%20Grande%20%26%238211%3B%20MS" id="wpa2a_10"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/QblxNJ-jQsrqpCYuXTSU8F2hmXE/0/da"><img src="http://feedads.g.doubleclick.net/~a/QblxNJ-jQsrqpCYuXTSU8F2hmXE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/QblxNJ-jQsrqpCYuXTSU8F2hmXE/1/da"><img src="http://feedads.g.doubleclick.net/~a/QblxNJ-jQsrqpCYuXTSU8F2hmXE/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2009/08/134/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Applet de um Teclado Virtual</title>
		<link>http://blog.jesjobom.com/2009/05/applet-de-um-teclado-virtual/</link>
		<comments>http://blog.jesjobom.com/2009/05/applet-de-um-teclado-virtual/#comments</comments>
		<pubDate>Sat, 16 May 2009 22:30:06 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Applet]]></category>
		<category><![CDATA[JSObject]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Segurança]]></category>
		<category><![CDATA[Teclado Virtual]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=96</guid>
		<description><![CDATA[Bem, após um período de inatividade no blog (o meu caro colaborado está demorando pra postar a parte 4 do tutorial java para web =P), venho trazendo um tutorial para a implementação de teclados virtuais em java.

O teclado virtual representa uma forma de inserir a senha para uma autenticação de usuário sem correr o risco de ter a senha capturada pelos comuns <em>keyloggers</em>. Entretanto, realmente existem complicações na utilização de um teclado virtual e <a href="http://www.guj.com.br/posts/list/25377.java" target="_blank">tem gente que realmente abomina esse tipo de recurso</a>. Mas como todo bom programador, muitas vezes a decisão de usar ou não um teclado virtual não é sua.

Então vamos ao que interessa! Implementaremos uma applet de um teclado virtual para ser adicionada em um HTML qualquer com um campo para senha.]]></description>
			<content:encoded><![CDATA[<p>Bem, após um período de inatividade no blog (o meu caro colaborado está demorando pra postar a parte 4 do tutorial java para web =P), venho trazendo um tutorial para a implementação de teclados virtuais em java.</p>
<p>O teclado virtual representa uma forma de inserir a senha para uma autenticação de usuário sem correr o risco de ter a senha capturada pelos comuns <em>keyloggers</em>. Entretanto, realmente existem complicações na utilização de um teclado virtual e <a href="http://www.guj.com.br/posts/list/25377.java" target="_blank">tem gente que realmente abomina esse tipo de recurso</a>. Mas como todo bom programador, muitas vezes a decisão de usar ou não um teclado virtual não é sua.</p>
<p>Então vamos ao que interessa! Implementaremos uma applet de um teclado virtual para ser adicionada em um HTML qualquer com um campo para senha. Ao final do post, existem os links para download do projeto e para visualização online do teclado.</p>
<p><span id="more-96"></span>Vou utilizar o NetBeans 6.5 e JDK6 apenas. Neste caso, o cliente que deverá visualizar o teclado deverá ter o JRE6 instalado, já que a applet é <em>client side</em>. Mas o JDK5 também pode ser usado. Sobre o 1.4 eu não tenho muita certeza. =P</p>
<p>Crie um novo projeto java (no Netbeans é <em>Arquivo -&gt; Novo Projeto -&gt; Java -&gt; Aplicativo Java</em>). Nomeie como preferir (no meu caso ficou &#8220;teclado&#8221; mesmo) e crie uma nova classe java na pasta de códigos-fontes para o teclado virtual (a minha classe ficou <em>br.com.teclado.virtual.TecladoVirtual</em>).</p>
<h2>Visualizando o Teclado Virtual</h2>
<p>Acredito que o primeiro passo seja a construção visual do teclado. E para isto deverá ser criada a imagem base do dele. Então abra o seu PainBrush e mãos à obra! ^^</p>
<p>Ah. Tenha em mente que a disposição e dimensão das teclas é muito importante, pois você deverá ser capaz de dizer qual a tecla pressionada através das coordenadas de um clique. O ideal é fazer um teclado com as teclas de mesmo tamanho e dispostas em um grid, onde uma tecla está sempre exatamente alinhada verticalmente e horizontalmente com outras. Mas isso fica a cargo de cada um. Vejam o teclado que fiz para este tutorial:</p>
<p><img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/java/teclado1.jpg" alt="teclado1.jpg" /></p>
<p>Cada tecla possui tamanho 30&#215;30 pixels, exceto o <em>backspace</em> e o <em>enter</em> que possuem 30&#215;60. Assim, considerando o canto superior esquerdo a origem do sistema de coordenadas (0,0), podemos obter a tecla pressionada dividindo por 30 o valor da posição <em>x </em>e  <em>y</em>. Se <em>y &lt; 1</em> a tecla pressionada é <em>backspace</em>. Se <em>y &gt; 5</em>, é <em>enter</em>. Caso contrário, faça <em>x+(y*5)-1</em> para descobrir qual tecla foi pressionada. (Se quiser, pode conferir as contas&#8230; =P)</p>
<p>Depois adicione esta imagem em seu projeto. Eu criei uma pasta &#8220;resources&#8221; no pacote de códigos fontes mesmo.</p>
<p>Bem, chega de brincar de designer e voltemos ao java! Vou listar as operações que devem ser feitas e depois mostrar o código resultante:</p>
<ol>
<li>Na nossa classe do teclado virtual, vamos extender a classe Applet (<em>java.applet.Applet</em>) e implementar a interface MouseListener (<em>java.awt.event.MouseListener</em>). Inclua a implementação dos métodos da interface MouseListener mas sem conteúdo algum, por enquanto (se quiser, altere o cursor do mouse, como fiz a seguir);</li>
<li>Vamos criar dois atributos privados na classe do teclado virtual; um vetor de caracteres (<em>char[]</em>) que possuirá os valores das teclas numéricas, e uma imagem (<em>java.awt.Image</em>) que carregará a imagem que fizemos anteriormente;</li>
<li>Vamos sobre-escrever o método <em>init() </em>da classe Applet, e nele vamos inicializar o vetor com os valores das teclas, setar o tamanho da applet, inicializar a imagem do teclado com o arquivo de imagem que incluimos no projeto, e adicionar um MouseListener à classe;</li>
<li>Por fim, sobre-escreva o método <em>paint(Graphics g)</em> fazendo com que a imagem do teclado seja pintada na tela.</li>
</ol>
<p>A classe fica mais ou menos assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> teste <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">Applet</span> <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">MouseListener</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Vetor com os valores das teclas
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> teclas<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Imagem do teclado
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Image</span> teclado<span style="color: #339933;">;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        iniciaTeclado<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setLocation<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setSize<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">211</span>, <span style="color: #cc66cc;">61</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        teclado <span style="color: #339933;">=</span> getImage<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResource</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/resources/teclado1.JPG&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        addMouseListener<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setLayout<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Inicializa os atributos do teclado
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> iniciaTeclado<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        teclas <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'0'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'1'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'2'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'3'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'4'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'5'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'6'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'7'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'8'</span><span style="color: #339933;">;</span>
        teclas<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'9'</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> paint<span style="color: #009900;">&#40;</span><span style="color: #003399;">Graphics</span> g<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        g.<span style="color: #006633;">drawImage</span><span style="color: #009900;">&#40;</span>teclado, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mouseClicked<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mouseReleased<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mouseEntered<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setCursor</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Cursor</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Cursor</span>.<span style="color: #006633;">HAND_CURSOR</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mouseExited<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">setCursor</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Cursor</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Cursor</span>.<span style="color: #006633;">DEFAULT_CURSOR</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Lembrando que o tamanho do applet deverá ser o mesmo da imagem adicionada.</p>
<p>Feito isto, tente rodar o arquivo. Deverá aparecer uma pequena tela com o teclado que desenhamos.</p>
<h2>Capturando a Senha</h2>
<p>Com o teclado aparecendo, podemos implementar a construção da senha a partir da detecção do clique nas teclas.</p>
<p>Basicamente, no método <em>MousePressed()</em>, faremos a verificação das coordenadas do clique assim como foi mostrado anteriormente. Por agora, cada tecla obtida afetará uma <em>String</em> &#8220;senha&#8221; e será impressa no console do java.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        iniciaTeclado<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setLocation<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setSize<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">211</span>, <span style="color: #cc66cc;">61</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        teclado <span style="color: #339933;">=</span> getImage<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResource</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/resources/teclado1.JPG&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        addMouseListener<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setLayout<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        senha <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span> x <span style="color: #339933;">=</span> e.<span style="color: #006633;">getX</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">30</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> y <span style="color: #339933;">=</span> e.<span style="color: #006633;">getY</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">30</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>x <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;BACKSPACE&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>senha.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                senha <span style="color: #339933;">=</span> senha.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, senha.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>x <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ENTER&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>teclas<span style="color: #009900;">&#91;</span>x<span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>y<span style="color: #339933;">*</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            senha <span style="color: #339933;">+=</span> <span style="color: #003399;">String</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>teclas<span style="color: #009900;">&#91;</span>x<span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>y<span style="color: #339933;">*</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Bem simples&#8230; Agora execute o arquivo e verifique se para cada tecla clicada o valor impresso está correto.</p>
<h2>Comunicação com o HTML</h2>
<p>Agora vem a parte mais chatinha. Não é por ser complicada, mas se há de ocorrer algum problema no teclado virtual, provavelmente será a seguir.</p>
<p>Para que o teclado virtual  seja realmente funcional, este deve, de alguma forma, se comunicar com o HTML no qual o applet está incluso. A maneira mais direta e sem muita complicação, é realizar a comunicação através de javascript. E para isso, utilizaremos uma biblioteca que você deverá incluir em seu projeto. É <em>a netscape.javascript </em>que pode ser encontrada no <em>plugin.jar</em> dentro da pasta do JDK que você está usando (<em>%JAVA_HOME%/jre/lib/plugin.jar</em>). Basta clicar com o direito sobre a pasta &#8220;bibliotecas&#8221; de seu projeto e então escolher &#8220;Adicionar JAR/Pasta&#8221;.</p>
<p>Tendo adicionado esta biblioteca, é hora de criarmos um HTML para os testes. No pacote de testes mesmo eu criei um &#8220;testeTecladoVistual.html&#8221;.</p>
<p>Basicamente, a comunicação entre a applet e o HTML será feito por chamadas javascript. Dessa forma, se quisermos passar a senha para um campo do HTML, usaremos uma chamada em javascript para isso. Para facilitar, criarei um método para essa operação, de modo que basta a applet chamar esse método para passar a senha.</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">html</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span>
var clazz = &quot;br.com.teclado.virtual.TecladoVirtual.class&quot;;
var jar =  &quot;../dist/teclado.jar&quot;;
var width = &quot;282&quot;;
var height = &quot;97&quot;;
function escreveTecladoGeral() {
    var applet = &quot;&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">object</span> <span style="color: #000066;">classid</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\&quot;</span> <span style="color: #000066;">width</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + <span style="color: #000066;">width</span> + <span style="color: #ff0000;">&quot;\&quot;</span> <span style="color: #000066;">height</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + <span style="color: #000066;">height</span> + <span style="color: #ff0000;">&quot;\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;archive\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + jar + <span style="color: #ff0000;">&quot;\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;codebase\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;.\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;code\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + clazz + <span style="color: #ff0000;">&quot;\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;cache_option\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;no\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #808080; font-style: italic;">&lt;!--[if gte IE 7]&gt; &lt;!--&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">object</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;application/x-java-applet\&quot;</span> <span style="color: #000066;">classid</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;java:&quot;</span> + clazz + <span style="color: #ff0000;">&quot;\&quot;</span><span style="color: #ff0000;">&quot;;</span>
<span style="color: #009900;">    applet += &quot;</span><span style="color: #000066;">archive</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + jar + <span style="color: #ff0000;">&quot;\&quot;</span> <span style="color: #000066;">codebase</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;.\&quot;</span> <span style="color: #000066;">width</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + <span style="color: #000066;">width</span> + <span style="color: #ff0000;">&quot;\&quot;</span> <span style="color: #000066;">height</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + <span style="color: #000066;">height</span> + <span style="color: #ff0000;">&quot;\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #808080; font-style: italic;">&lt;!-- Konqueror browser needs the following param --&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;archive\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + jar + <span style="color: #ff0000;">&quot;\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;code\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;&quot;</span> + clazz + <span style="color: #ff0000;">&quot;\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #808080; font-style: italic;">&lt;!-- Safari browser needs the following param --&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;JAVA_CODEBASE\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;.\&quot;</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">param</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;cache_option\&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span>\<span style="color: #ff0000;">&quot;no\&quot;</span>&gt;</span>&quot;;
    applet += &quot;Você necessita de um navegador que suporte Java<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">br</span><span style="color: #66cc66;">/</span>&gt;</span>Baixe o plugin java <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">'http://www.java.com/pt_BR/download/'</span> <span style="color: #000066;">target</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">'_blank'</span>&gt;</span>aqui<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;</span>.&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">object</span>&gt;</span>&quot;;
    applet += &quot;<span style="color: #808080; font-style: italic;">&lt;!--&lt;![endif]--&gt;</span>&quot;;
    applet += &quot;<span style="color: #808080; font-style: italic;">&lt;!--[if lt IE 7]&gt;&quot;;</span>
<span style="color: #808080; font-style: italic;">    applet += &quot;Você necessita de um navegador que suporte Java&lt;br/&gt;Baixe o plugin java &lt;a href='http://www.java.com/pt_BR/download/' target='_blank'&gt;aqui&lt;/a&gt;.&quot;;</span>
<span style="color: #808080; font-style: italic;">    applet += &quot;&lt;![endif]--&gt;</span>&quot;;
    applet += &quot;<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">object</span>&gt;</span>&quot;;
    return applet;
}
function escreveApplet() {
	if(navigator.appName.indexOf('Internet Explorer') &gt; 0) {
		document.write(escreveTecladoGeral());
	} else {
		document.write(escreveTecladoGeral());
	}
}
function recebeSenha(senha,tamanho) {
    document.getElementById('pass').value = senha;
    var str = '';
    for(i=0;i<span style="color: #009900;">&lt;tamanho;i++<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>str +<span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'*'</span>;<span style="color: #66cc66;">&#125;</span></span>
<span style="color: #009900;">    document.getElementById<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'fakePass'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #000066;">value</span> <span style="color: #66cc66;">=</span> str;</span>
<span style="color: #009900;"><span style="color: #66cc66;">&#125;</span></span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">body</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span>escreveApplet();<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">form</span>&gt;</span>
    Login: <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;login&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">br</span><span style="color: #66cc66;">/</span>&gt;</span>
    Senha: <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text&quot;</span> <span style="color: #000066;">readonly</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;fakePass&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">br</span><span style="color: #66cc66;">/</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;pass&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;hidden&quot;</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;pass&quot;</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">form</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">body</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">html</span>&gt;</span></pre></div></div>

<p>Primeiramente observem a escrita do applet no HTML através de javascript. Realizei muitos testes em diversos navegadores e cheguei no método acima (<em>escreveTecladoGeral()</em>) que, até onde testei, funciona perfeitamente. Existem alternativas utilizando as tags <em>applet </em>ou <em>embed</em>, caso tenha interesse em utilizá-las.</p>
<p>E temos o método <em>recebeSenha(senha, tamanho)</em> que será utilizado pela applet. Esta função javascript simplesmente repassa a senha para um campo oculto (<em>hidden</em>) e preenche o campo senha a mostra com &#8216;<strong>*</strong>&#8216; conforme a quantidade repassada. Não utilizei a quantidade de caracteres da senha para o preenchimento dos &#8216;*&#8217; porque o correto seria que a senha seja encriptada.</p>
<p>Agora voltemos ao java e façamos a comunicação efetiva com o HTML.</p>
<p>Temos que criar um novo atributo da classe TecladoVirtual; um <em>netscape.javascript.JSObject</em> que servirá para executar as chamadas em javascript a partir do applet. Fazendo uso da função em javascript <em>recebeSenha</em>, os métodos <em>init() </em>e <em>mousePressed(MouseEvent e)</em> deverão ficar assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        iniciaTeclado<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setLocation<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setSize<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">211</span>, <span style="color: #cc66cc;">61</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        teclado <span style="color: #339933;">=</span> getImage<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResource</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/resources/teclado1.JPG&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        addMouseListener<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        setLayout<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            win <span style="color: #339933;">=</span> JSObject.<span style="color: #006633;">getWindow</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>JSException jse<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            win <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
            jse.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        senha <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #003399;">MouseEvent</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span> x <span style="color: #339933;">=</span> e.<span style="color: #006633;">getX</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">30</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">int</span> y <span style="color: #339933;">=</span> e.<span style="color: #006633;">getY</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">30</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>x <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;BACKSPACE&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>senha.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                senha <span style="color: #339933;">=</span> senha.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, senha.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>win <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                win.<span style="color: #006633;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;recebeSenha('&quot;</span> <span style="color: #339933;">+</span> senha <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;',&quot;</span> <span style="color: #339933;">+</span> senha.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>x <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ENTER&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>win <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                win.<span style="color: #006633;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;document.forms[0].submit()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>teclas<span style="color: #009900;">&#91;</span>x<span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>y<span style="color: #339933;">*</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            senha <span style="color: #339933;">+=</span> <span style="color: #003399;">String</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>teclas<span style="color: #009900;">&#91;</span>x<span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>y<span style="color: #339933;">*</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>win <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                win.<span style="color: #006633;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;recebeSenha('&quot;</span> <span style="color: #339933;">+</span> senha <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;',&quot;</span> <span style="color: #339933;">+</span> senha.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Observe que no caso da tecla <em>enter</em>, o applet repassa ao navegador uma instrução para submeter o fomulário do HTML que fizemos. Como no <em>form</em> não está definido nenhum <em>action </em>ou <em>method</em>, o formulário submeterá para si próprio por GET e poderemos ver os dados (login e senha) como parâmetros na barra de endereço do navegador.</p>
<p>Se tudo der certo, podemos testar. Como o <em>JSObject </em>opera sobre o navegador, não adianta mais tentarmos executar o arquivo do teclado virtual. Até por isso incluí os testes <em>if(win != null)</em> ao fazer as chamadas javascript. Então temos que testar rodando o HTML que fizemos.</p>
<p>Mande compilar (<em>build)</em> o projeto para criar o JAR na pasta &#8220;dist&#8221; ou &#8220;target&#8221;. Feito isso, abra o <em>testeTecladoVirtual.html</em> para avaliar o funcionamento do applet. Caso não tenha aparecido, primeiramente verifique se o caminho para o jar e a classe do teclado (ambos no javascript do HTML) estão corretos. Se mesmo assim não funcionar, verifique o console java (qualquer exceção aparecerá lá, e não na IDE de desenvolvimento).</p>
<p>O java console deverá ser acessível através do ícone que aparecerá na barra de sistema do Windows (próximo ao relógio). Se não aparecer, talvez seja necessário habilitá-lo (<em>Painel de Controle -&gt; Java -&gt; Advanced -&gt; Java Console -&gt; Show Console</em>).</p>
<h2>Considerações Finais</h2>
<p>Apesar de evitar a captura da senha por um <em>keylogger</em>, o teclado virtual não garante 100% da segurança. Por exemplo, ainda é possível obter a senha através de uma variação de <em>keylogger </em>que, ao invés de capturar o valor das teclas pressionadas, fotografa cada clique do mouse. Ou então ainda é possível &#8220;escutar&#8221; as requisições de modo que o re-envio de uma requisição de login pode conceder uma autorização indevida ao sistema.</p>
<p>Por isso, o teclado virtual, num caso ideal, não deve ser o único meio de segurança. A utilização de uma autenticação SSL ou de um teclado virtual com um sistema de alternância das teclas (<del datetime="2010-02-05T18:38:27+00:00">vide <a href="http://www.bb.com.br" target="_blank">bb.com.br</a>, necessário ter conta</del> (O Banco do Brasil retirou o teclado virtual da tela de login)) é altamente recomendado.</p>
<p>Na verdade, acredito que um teclado virtual sirva mais para passar a sensação de segurança do que para realmente assegurar.</p>
<p>Bem, este tutorial abrangeu uma abordagem à implementação de um teclado virtual. Mas existem outras alternativas (inclusive em outras linguagens). É possível, ainda utilizando java, incluir no próprio applet os campos de login e senha e enviá-los como parâmetros de um request à página de login.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #003399;">AppletContext</span> ac <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getAppletContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
        ac.<span style="color: #006633;">showDocument</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">URL</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;http://localhost:8080/login.jsp?user=&quot;</span> <span style="color: #339933;">+</span> user <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&amp;pass=&quot;</span> <span style="color: #339933;">+</span> pass<span style="color: #009900;">&#41;</span>, <span style="color: #0000ff;">&quot;_self&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">MalformedURLException</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Logger.<span style="color: #006633;">getLogger</span><span style="color: #009900;">&#40;</span>TecladoVirtual.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">log</span><span style="color: #009900;">&#40;</span>Level.<span style="color: #006633;">SEVERE</span>, <span style="color: #000066; font-weight: bold;">null</span>, ex<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Realizando a autenticação desse modo, requer que o processo de login altere o <em>response</em> para que a requisição não retorne para o cliente e os parâmetros fiquem visíveis (o <a href="http://static.springsource.org/spring-security/site/index.html" target="_blank">Spring Security </a>é um exemplo). Não é um bom jeito de fazer as coisas, mas é uma alternativa.</p>
<p>E caso o teclado não seja visível em algum navegador em alguma máquina de alguma pessoa (não todos), antes de pensar em mexer no teclado, verifique as versões do JRE e do navegador no cliente. Atualizar o JRE consertou as coisas algumas vezes para mim.</p>
<p>Estão é isso! ^^</p>
<p>No mais, nada mais.</p>
<p>Projeto Teclado-Virtual compactado e configurado para NetBeans: <a href='http://blog.jesjobom.com/wp-content/uploads/2009/05/teclado-virtual.rar'>teclado-virtual compactado</a> </p>
<p>Exemplo online do resultado final do tutorial: <a href='http://jesjobom.com/files/blog/teclado_virtual/testTecladoVirtual.html' target='_blank'>teclado-virtual online</a></p>

<p><a href="http://feedads.g.doubleclick.net/~a/RgVkLvKoUFaVbUZRYCFxw1N7pIc/0/da"><img src="http://feedads.g.doubleclick.net/~a/RgVkLvKoUFaVbUZRYCFxw1N7pIc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/RgVkLvKoUFaVbUZRYCFxw1N7pIc/1/da"><img src="http://feedads.g.doubleclick.net/~a/RgVkLvKoUFaVbUZRYCFxw1N7pIc/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2009/05/applet-de-um-teclado-virtual/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Básico de Java para Web – parte 3</title>
		<link>http://blog.jesjobom.com/2009/04/basico-de-java-para-web-parte-3/</link>
		<comments>http://blog.jesjobom.com/2009/04/basico-de-java-para-web-parte-3/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 18:50:08 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[Lazy Connection]]></category>
		<category><![CDATA[Persistência]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Teste Unitário]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=80</guid>
		<description><![CDATA[Com um pouco de atraso, finalmente estou postando a parte 3 deste tutorial voltado para a introdução ou fixação de conceitos utilizados na programação para web usando Java. Nesta parte, criaremos uma busca de models pelo id e implementaremos uma idéia bastante legal e &#8220;preguiçosa&#8221; usada em JPA ou Hibernate. Vejam também a parte 1 [...]]]></description>
			<content:encoded><![CDATA[<p>Com um pouco de atraso, finalmente estou postando a parte 3 deste tutorial voltado para a introdução ou fixação de conceitos utilizados na programação para web usando Java.</p>
<p>Nesta parte, criaremos uma busca de models pelo id e implementaremos uma idéia bastante legal e &#8220;preguiçosa&#8221; usada em JPA ou Hibernate.</p>
<p>Vejam também a <a title="Básico de Java para Web - parte 1" href="http://blog.jesjobom.com/2009/03/basico-de-java-para-web-parte-1/" target="_self">parte 1</a> e a <a title="Básico de Java para Web - parte 2" href="http://blog.jesjobom.com/2009/04/basico-de-java-para-web-parte-2/" target="_self">parte 2</a> do tutorial, caso ainda não o tenham feito.<span id="more-80"></span>No final da parte anterior concluimos a persistência de um novo model com retorno do id gerado e implementamos a atualização de um model já persistido. Entretanto, não pudemos testar propriamente sem uma busca de model pelo seu id. Podemos começar por este ponto.</p>
<h2>Find by Private Key</h2>
<p>Caso você tenha lido as partes anteriores, provavelmente deve estar imaginando (ou já ter implementado =P) como poderia ser este método. Se pensou em construir um SQL para a busca como &#8220;<em>SELECT * FROM Pessoa WHERE id = 1</em>&#8220;, pensou certo.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Retorna um BasicModel persistido através do seu id
     *
     * @param id
     * @return {@link BasicModel}
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> BasicModel findByPk<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> clazz, <span style="color: #003399;">Integer</span> id<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">String</span> select <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT id, &quot;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> from <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; FROM &quot;</span> <span style="color: #339933;">+</span> clazz.<span style="color: #006633;">getSimpleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> where <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; WHERE id = &quot;</span> <span style="color: #339933;">+</span> id.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">boolean</span> primeiro <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Field</span> field <span style="color: #339933;">:</span> clazz.<span style="color: #006633;">getDeclaredFields</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">//Se o campo for uma coleção de objetos ou um basic model</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span>.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span>
                    BasicModel.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">//DO NOTHING</span>
                <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>primeiro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    primeiro <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                    select <span style="color: #339933;">+=</span> <span style="color: #0000ff;">&quot;, &quot;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
            select <span style="color: #339933;">+=</span> field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #003399;">ResultSet</span> keys <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Connection</span> conn <span style="color: #339933;">=</span> getConnection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">PreparedStatement</span> pstmt <span style="color: #339933;">=</span> conn.<span style="color: #006633;">prepareStatement</span><span style="color: #009900;">&#40;</span>select <span style="color: #339933;">+</span> from <span style="color: #339933;">+</span> where<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            pstmt.<span style="color: #006633;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            keys <span style="color: #339933;">=</span> pstmt.<span style="color: #006633;">getResultSet</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>keys.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> ResultSet2BasicModel<span style="color: #009900;">&#40;</span>keys, clazz<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro na operação de busca por id. A operação foi abortada.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> ex<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Após construirmos o SQL e realizarmos a consulta, convertemos o ResultSet obtido para um BasicModel da seguinte forma:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Monta uma nova instância de um model a partir das informações contidas no resultSet passado
     *
     * @param keys
     * @param clazz
     * @return {@link BasicModel}
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> BasicModel ResultSet2BasicModel<span style="color: #009900;">&#40;</span><span style="color: #003399;">ResultSet</span> keys, <span style="color: #000000; font-weight: bold;">Class</span> clazz<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>keys <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            BasicModel model <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>BasicModel<span style="color: #009900;">&#41;</span>clazz.<span style="color: #006633;">newInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Field</span> field <span style="color: #339933;">:</span> clazz.<span style="color: #006633;">getDeclaredFields</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">//Se o campo for uma coleção de objetos ou um basic model</span>
                <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span>.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span>
                        BasicModel.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #666666; font-style: italic;">//DO NOTHING</span>
                    <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #666666; font-style: italic;">//Se o campo for uma string</span>
                <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #003399;">Method</span> method <span style="color: #339933;">=</span> model.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getDeclaredMethod</span><span style="color: #009900;">&#40;</span>getFieldSetterName<span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #003399;">String</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    method.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>model,keys.<span style="color: #006633;">getString</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #666666; font-style: italic;">//Se o campo for um date</span>
                <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Date</span>.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #003399;">Method</span> method <span style="color: #339933;">=</span> model.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getDeclaredMethod</span><span style="color: #009900;">&#40;</span>getFieldSetterName<span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #003399;">Date</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    method.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>model,keys.<span style="color: #006633;">getDate</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #666666; font-style: italic;">//Se é outra coisa</span>
                <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #003399;">Method</span> method <span style="color: #339933;">=</span> model.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getDeclaredMethod</span><span style="color: #009900;">&#40;</span>getFieldSetterName<span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #003399;">Object</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    method.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>model,keys.<span style="color: #006633;">getObject</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
            model.<span style="color: #006633;">setId</span><span style="color: #009900;">&#40;</span>keys.<span style="color: #006633;">getInt</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;id&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">return</span> model<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Gera o nome do setter para o dado atributo
     * @param fieldName
     * @return String
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> getFieldSetterName<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> fieldName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;set&quot;</span> <span style="color: #339933;">+</span> fieldName.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toUpperCase</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> fieldName.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Então temos o model buscado pelo seu id. =)</p>
<p>Podemos atualizar o teste e criar um novo teste apenas para esta operação. E falando em testes, eu alterei um pouquinho a classe BasicDaoTest para ficar melhor apresentada. Antes de cada teste o banco é limpo, melhorando o isolamento dos testes.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> BasicDaoTest <span style="color: #000000; font-weight: bold;">extends</span> TestCase <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@link BasicDao}
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> BasicDao basicDao<span style="color: #339933;">;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> setUp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">setUp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BasicDao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">limparTabela</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testBasic<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        basicDao.<span style="color: #006633;">testConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertTrue<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testPersistNew<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        Pessoa pessoa <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Qualquer 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pessoa<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertNotNull<span style="color: #009900;">&#40;</span>pessoa.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testFindByPk<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        Pessoa pessoa <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Qualquer&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pessoa<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa pessoaTest <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span>basicDao.<span style="color: #006633;">findByPk</span><span style="color: #009900;">&#40;</span>Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, pessoa.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertNotNull<span style="color: #009900;">&#40;</span>pessoaTest.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertEquals<span style="color: #009900;">&#40;</span>pessoa.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, pessoaTest.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testPersistUpdate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        Pessoa pessoa <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Qualquer 2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pessoa<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa pessoa2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa2.<span style="color: #006633;">setId</span><span style="color: #009900;">&#40;</span>pessoa.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa2.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pessoa2.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Qualquer 3&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pessoa2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa pessoaTest <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span>basicDao.<span style="color: #006633;">findByPk</span><span style="color: #009900;">&#40;</span>Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, pessoa.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertEquals<span style="color: #009900;">&#40;</span>pessoa2.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, pessoaTest.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E no BasicDao, implementei um método simples para limpeza de tabelas.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Deleta todas as entradas da tabela cujo nome foi passado.
     *
     * @param nome
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> limparTabela<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">String</span> delete <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;DELETE FROM &quot;</span> <span style="color: #339933;">+</span> nome<span style="color: #339933;">;</span>
        <span style="color: #003399;">Connection</span> conn<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            conn <span style="color: #339933;">=</span> getConnection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">PreparedStatement</span> ps <span style="color: #339933;">=</span> conn.<span style="color: #006633;">prepareStatement</span><span style="color: #009900;">&#40;</span>delete<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            ps.<span style="color: #006633;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao deletar os dados da tabela '&quot;</span> <span style="color: #339933;">+</span> nome <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> ex<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Lazy Connection</h2>
<p>Bem, será que alguém notou que, ao buscar um BasicModel, nenhum outro model ou collection relacionados são obtidos?  Na linha 15 do <em>findByPK</em> nada é feito quando o atributo do model é do tipo model ou collection.</p>
<p>Isso é feito visando a questão de performace, apesar de se tratar de um exemplo meramente didático.</p>
<p>Para visualizar o problema, imagine que tenhamos muitos dados (pessoas) no banco. Se na busca por id incluíssemos todos os atributos, acabaria gerando uma busca recursiva (busca uma pessoa, e os pais dessa pessoa, e os pais dos pais&#8230;), passando por todas as pessoas com alguma ligação à pessoa buscada. Se necessitarmos apenas dos dados de uma pessoa, todas as outras muitas buscas realizadas foram um desperdício de processamento, conexão com o banco e tempo.</p>
<p>Para resolver isso, o Java Persistence API (JPA) possui o conceito de <em>Lazy Connection</em> (ou conexão preguiçosa ^^). Utilizando essa especificação, podemos mapear modelos de dados utilizando relacionamentos &#8220;preguiçosos&#8221;. No nosso exemplo, poderíamos mapear o relacionamento pai-filho como <em>lazy</em> de modo que, ao obter uma pessoa, o seu pai não é imediatamente consultado no banco. Ao invéz disso, um <em>proxy</em> fica no lugar do pai até que este seja requerido através, por exemplo, de um <em>getPai().</em></p>
<p>Como não utilizaremos nenhum framework, teremos que implementar esse conceito no braço! =D</p>
<p>Mas não será nada muito complexo&#8230; A idéia é basicamente implementar uma busca por pai, mãe e filhos partindo de uma pessoa e, então, alterar os <em>getters</em> do model Pessoa para realizar a busca se necessário.</p>
<h2>Lazy getMae() / getPai()</h2>
<p>Como pai e mãe de uma pessoa obtida através de uma consulta ao banco estarão nulos, não temos informação para realizar uma busca por essas pessoas. Por isso, antes de fazer um <em>findByPK</em> para pai e mãe, temos que obter os seus id consultando o próprio filho.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Obtem o model pai de um model filho já instanciado.
     *
     * @param child
     * @param parentClazz
     * @param fieldName
     * @return BasicModel
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> BasicModel getLazyBasicModel<span style="color: #009900;">&#40;</span>BasicModel child, <span style="color: #000000; font-weight: bold;">Class</span> parentClazz, <span style="color: #003399;">String</span> fieldName<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">String</span> select <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT &quot;</span> <span style="color: #339933;">+</span> fieldName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; FROM &quot;</span> <span style="color: #339933;">+</span> child.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSimpleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; WHERE id = &quot;</span> <span style="color: #339933;">+</span> child.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Connection</span> conn <span style="color: #339933;">=</span> getConnection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">PreparedStatement</span> ps <span style="color: #339933;">=</span> conn.<span style="color: #006633;">prepareStatement</span><span style="color: #009900;">&#40;</span>select<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">ResultSet</span> keys <span style="color: #339933;">=</span> ps.<span style="color: #006633;">executeQuery</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>keys.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> keys.<span style="color: #006633;">getObject</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> findByPk<span style="color: #009900;">&#40;</span>parentClazz, keys.<span style="color: #006633;">getInt</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao obter o model pai por conexão lazy. A operação foi abortada.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> ex<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Bastante simples. Agora alteramos os <em>getters</em> em questão de Pessoa para verificar a <a title="Nullable Type" href="http://en.wikipedia.org/wiki/Nullable_Types" target="_blank">nulabilidade</a> dos pais e buscar por eles caso afirmativo.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> Pessoa getMae<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>mae <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">id</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            BasicDao basicDao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BasicDao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            mae <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span> basicDao.<span style="color: #006633;">getLazyBasicModel</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>, Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;">&quot;mae&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> mae<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Pessoa getPai<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>pai <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">id</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            BasicDao basicDao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BasicDao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            pai <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span> basicDao.<span style="color: #006633;">getLazyBasicModel</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>, Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;">&quot;pai&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> pai<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Temos, é claro, que testar! Então adicionemos o seguinte teste ao BasicDaoTest:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testGetLazyModel<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        Pessoa pai <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pai.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pai.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Pai&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa filho <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Filho&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho.<span style="color: #006633;">setPai</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>filho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa filhoTest <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span> basicDao.<span style="color: #006633;">findByPk</span><span style="color: #009900;">&#40;</span>Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, filho.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertNotNull<span style="color: #009900;">&#40;</span>filhoTest.<span style="color: #006633;">getPai</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertEquals<span style="color: #009900;">&#40;</span>pai.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, filhoTest.<span style="color: #006633;">getPai</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertNull<span style="color: #009900;">&#40;</span>filhoTest.<span style="color: #006633;">getMae</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Se tudo ocorrer bem, podemos avançar para a próxima e um pouco mais complexa parte.</p>
<h2>Lazy getFilhos()</h2>
<p>Antes de mais de nada, existe uma observação que deve ser feita com relação ao modelo de dados utilizado aqui.</p>
<p>Como esse projeto tem uma função apenas didática e como estamos construindo cada um dos SQLs de interação com o banco, podemos nos dar a liberdade de realizar escolhas visando a facilidade de implementação. Mas nem sempre essas escolhas poderão ser feitas.</p>
<p>Por exemplo, no BasicModel implementado, cada pessoa possui pai, mae e filhos de maneira direta. Entretando, se fôssemos utilizar um framework de persistência como o Hibernate, teríamos que estudar um pouco melhor esses relacionamentos.</p>
<p>No momento de mapear a coleção de filhos, precisamos informar qual o atributo do outro lado que comanda o relacionamento. Por exemplo, num relacionamento <em>Estado-Cidade</em>, um <em>Estado </em>possui um conjunto de cidades, e o atributo que comanda esse relacionamento é <em>Cidade.estado</em>. Entretanto, no relacionamento de <em>Pai-Filho</em>, temos mais de um atributo que pode comandar (<em>pai </em>e <em>mae</em>). Por isso, utilizando o Hibernate teríamos que alterar o modelo, talvez criando uma tabela intermediária com o tipo de relacionamento.</p>
<p><a class="shutterset_" href="http://blog.jesjobom.com/wp-content/gallery/java/relacionamento_pessoa.jpg"><img class="ngg-singlepic ngg-center" src="http://blog.jesjobom.com/wp-content/gallery/java/thumbs/thumbs_relacionamento_pessoa.jpg" alt="relacionamento_pessoa.jpg" /></a></p>
<p>Mas voltando à nossa realidade, podemos criar um SQL como &#8220;<em>SELECT * FROM Pessoa WHERE pai = 1 OR mae = 1</em>&#8220;. Então mãos à obra!</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Obtem uma lista de filhos a partir de um model pai
     *
     * @param parent
     * @param childClazz
     * @param fieldNames
     * @return {@link List} de {@link BasicModel}
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> Set<span style="color: #339933;">&lt;</span>BasicModel<span style="color: #339933;">&gt;</span> getLazyBasicModelCollection<span style="color: #009900;">&#40;</span>BasicModel parent, <span style="color: #000000; font-weight: bold;">Class</span> childClazz, <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> fieldNames<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">String</span> select <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT id, &quot;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> from <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; FROM &quot;</span> <span style="color: #339933;">+</span> childClazz.<span style="color: #006633;">getSimpleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> where <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; WHERE &quot;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">boolean</span> primeiro <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Field</span> field <span style="color: #339933;">:</span> childClazz.<span style="color: #006633;">getDeclaredFields</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">//Se o campo for uma coleção de objetos ou um basic model</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span>.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span>
                    BasicModel.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">isAssignableFrom</span><span style="color: #009900;">&#40;</span>field.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">//DO NOTHING</span>
                <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>primeiro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    primeiro <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                    select <span style="color: #339933;">+=</span> <span style="color: #0000ff;">&quot;, &quot;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
            select <span style="color: #339933;">+=</span> field.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        primeiro <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> fieldName <span style="color: #339933;">:</span> fieldNames<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>primeiro<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                primeiro <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                where <span style="color: #339933;">+=</span> <span style="color: #0000ff;">&quot; OR &quot;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            where <span style="color: #339933;">+=</span> fieldName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; = &quot;</span> <span style="color: #339933;">+</span> parent.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Connection</span> conn <span style="color: #339933;">=</span> getConnection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">PreparedStatement</span> pstmt <span style="color: #339933;">=</span> conn.<span style="color: #006633;">prepareStatement</span><span style="color: #009900;">&#40;</span>select <span style="color: #339933;">+</span> from <span style="color: #339933;">+</span> where<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            pstmt.<span style="color: #006633;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            Set<span style="color: #339933;">&lt;</span>BasicModel<span style="color: #339933;">&gt;</span> filhos <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>BasicModel<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">ResultSet</span> keys <span style="color: #339933;">=</span> pstmt.<span style="color: #006633;">getResultSet</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>keys.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                filhos.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>ResultSet2BasicModel<span style="color: #009900;">&#40;</span>keys, childClazz<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">return</span> filhos<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> ex<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao obter uma coleção de models por conexão lazy. A operação foi abortada.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> ex<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>A implementação não ficou muito complicada. Apenas obtemos todas as pessoas cujo pai ou mãe é a pessoa base (atenção&#8230; nós não restringimos que uma pessoa pode ser apenas pai ou mãe!) e retornamos uma lista com essas pessoas.</p>
<p>Em Pessoa temos que alterar o <em>getFilhos():</em></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Set</span> getFilhos<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>filhos <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">id</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            BasicDao basicDao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BasicDao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">Set</span> set <span style="color: #339933;">=</span> basicDao.<span style="color: #006633;">getLazyBasicModelCollection</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>, Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #0000ff;">&quot;pai&quot;</span>,<span style="color: #0000ff;">&quot;mae&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            filhos <span style="color: #339933;">=</span> set<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">return</span> filhos<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>E então, podemos testar!</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testGetLazyCollection<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        Pessoa pai <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pai.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pai.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Pai&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa filho <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Filho&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho.<span style="color: #006633;">setPai</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>filho<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa paiTest <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span> basicDao.<span style="color: #006633;">findByPk</span><span style="color: #009900;">&#40;</span>Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, pai.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertNotNull<span style="color: #009900;">&#40;</span>paiTest.<span style="color: #006633;">getFilhos</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>, paiTest.<span style="color: #006633;">getFilhos</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testGetLazyCollection2<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        Pessoa pai <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pai.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        pai.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Pai&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa filho1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho1.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Filho 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho1.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho1.<span style="color: #006633;">setPai</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>filho1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa filho2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho2.<span style="color: #006633;">setNome</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pessoa Filho 2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho2.<span style="color: #006633;">setDataNascimento</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Date</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        filho2.<span style="color: #006633;">setMae</span><span style="color: #009900;">&#40;</span>pai<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicDao.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>filho2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Pessoa paiTest <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span> basicDao.<span style="color: #006633;">findByPk</span><span style="color: #009900;">&#40;</span>Pessoa.<span style="color: #000000; font-weight: bold;">class</span>, pai.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertNotNull<span style="color: #009900;">&#40;</span>paiTest.<span style="color: #006633;">getFilhos</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        assertEquals<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span>, paiTest.<span style="color: #006633;">getFilhos</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Se tudo deu certo os testes deverão estar 100% e estamos prontos para começar, efetivamente, a camada web!&#8230; Outro dia, claro&#8230;</p>
<p>(Bruno! Agora é com você!)</p>
<p>Baixe aqui o código fonte do core com o que foi visto até agora: <a href="http://blog.jesjobom.com/wp-content/uploads/2009/04/arvore-ginecologica.rar">arvore-ginecologica</a>. (Obs: necessita o <a title="PostgreSQL Driver Download" href="http://jdbc.postgresql.org/download.html" target="_blank">driver do pgsql</a> e não notem o nome &#8220;zuado&#8221; do projeto ^^)</p>
<p>WARNING! POST EXTENSO DETECTADO! o_O</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2009%2F04%2Fbasico-de-java-para-web-parte-3%2F&amp;title=B%C3%A1sico%20de%20Java%20para%20Web%20%26%238211%3B%20parte%203" id="wpa2a_12"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/k2FrUxbyY7wKitAwa0yIehssr4w/0/da"><img src="http://feedads.g.doubleclick.net/~a/k2FrUxbyY7wKitAwa0yIehssr4w/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/k2FrUxbyY7wKitAwa0yIehssr4w/1/da"><img src="http://feedads.g.doubleclick.net/~a/k2FrUxbyY7wKitAwa0yIehssr4w/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2009/04/basico-de-java-para-web-parte-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Como alterar o idioma base do NetBeans</title>
		<link>http://blog.jesjobom.com/2009/04/como-alterar-o-idioma-base-do-netbeans/</link>
		<comments>http://blog.jesjobom.com/2009/04/como-alterar-o-idioma-base-do-netbeans/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 17:40:00 +0000</pubDate>
		<dc:creator>jesjobom</dc:creator>
				<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Ferramenta]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[Idioma Padrão]]></category>
		<category><![CDATA[MacOS]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.jesjobom.com/?p=77</guid>
		<description><![CDATA[Peguei esta dica com alguns amigos usuários de Mac que não suportaram a tradução da interface do NetBeans (bem, convenhamos que &#8220;Deburar&#8221; é realmente insuportável&#8230;). A partir da versão 6.5 o NetBeans define o idioma padrão automaticamente de acordo com as configurações regionais do sistema em questão. E, até onde sei, não existe uma forma [...]]]></description>
			<content:encoded><![CDATA[<p>Peguei esta dica com alguns amigos usuários de Mac que não suportaram a tradução da interface do NetBeans (bem, convenhamos que &#8220;Deburar&#8221; é realmente insuportável&#8230;).<span id="more-77"></span></p>
<p>A partir da versão 6.5 o NetBeans define o idioma padrão automaticamente de acordo com as configurações regionais do sistema em questão. E, até onde sei, <strong>não existe </strong>uma forma elegante para alterar isso (imagino que não seja complicado adicionar um menu para esta função).</p>
<p>Por isso, segue uma forma mais bruta:</p>
<p>Localize o arquivo &#8220;netbeans.conf&#8221;, na pasta onde a IDE está instalada. Provavelmente em um caminho como:</p>
<ul>
<li><span style="color: #000000; font-family: Segoe UI;">&#8220;<strong>/Applications/NetBeans/NetBeans\  6.5.app/Contents/Resources/NetBeans/etc/netbeans.conf</strong>&#8220;</span> para MacOS;</li>
<li><span style="color: #000000; font-family: Segoe UI;">&#8220;<strong>C:\Arquivos de programas\NetBeans 6.5.1\etc\netbeans.conf</strong>&#8220;</span> para Windows.</li>
</ul>
<p>Abra-o com o bloco de notas e no final da string referente ao atributo &#8220;<strong>netbeans_default_options</strong>&#8220;, adicione as opções &#8220;<strong>-J-Duser.language=en -J-Duser.region=US</strong>&#8220;.</p>
<p>O arquivo deverá ficar como <a href="http://blog.jesjobom.com/wp-content/uploads/2009/04/netbeans.conf">netbeans.conf</a>.</p>
<p>Salve, abra ou reinicie o NetBeans e verifique a alteração do idioma.</p>
<p>Fonte: <a title="Algumas Idéias" href="http://algumasideias.net/2008/02/22/netbeans-interface-language/" target="_blank">Algumas Idéias</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.jesjobom.com%2F2009%2F04%2Fcomo-alterar-o-idioma-base-do-netbeans%2F&amp;title=Como%20alterar%20o%20idioma%20base%20do%20NetBeans" id="wpa2a_14"><img src="http://blog.jesjobom.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/ZowfxbT9nI-1JlLdWER3gDEPolA/0/da"><img src="http://feedads.g.doubleclick.net/~a/ZowfxbT9nI-1JlLdWER3gDEPolA/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ZowfxbT9nI-1JlLdWER3gDEPolA/1/da"><img src="http://feedads.g.doubleclick.net/~a/ZowfxbT9nI-1JlLdWER3gDEPolA/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.jesjobom.com/2009/04/como-alterar-o-idioma-base-do-netbeans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

