<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Pobre Computeiro</title>
	<atom:link href="http://pobrecomputeiro.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://pobrecomputeiro.wordpress.com</link>
	<description>Por computadores nunca dantes navegados - Declare variáveis, não guerra</description>
	<lastBuildDate>Thu, 19 Jan 2012 20:33:45 +0000</lastBuildDate>
	<language>pt-br</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='pobrecomputeiro.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Pobre Computeiro</title>
		<link>http://pobrecomputeiro.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://pobrecomputeiro.wordpress.com/osd.xml" title="Pobre Computeiro" />
	<atom:link rel='hub' href='http://pobrecomputeiro.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Java + Spring + LDAP + Active Directory Windows</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/12/14/java-spring-ldap-active-directory-windows/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/12/14/java-spring-ldap-active-directory-windows/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 23:17:47 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[ad]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[ldap]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=521</guid>
		<description><![CDATA[Por diversos momentos na vida de arquitetos/desenvolvedores de software recebemos o bendito requisito vindo do usuário de que o seu sistema web precisa desesperadamente conversar com o Microsoft Active Directory. Desde que me conheço no desenvolvimento vejo isso acontecendo e vejo diversos desenvolvedores sentindo um frio na espinha neste momento. Creio que tenha sido com [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=521&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Por diversos momentos na vida de arquitetos/desenvolvedores de software recebemos o bendito requisito vindo do usuário de que o seu sistema web precisa desesperadamente conversar com o Microsoft Active Directory. Desde que me conheço no desenvolvimento vejo isso acontecendo e vejo diversos desenvolvedores sentindo um frio na espinha neste momento.</p>
<p>Creio que tenha sido com o intuíto de ajudar estes pobres é que os geniais lá do Spring resolveram quebrar mais uma. É o Spring LDAP.</p>
<p>Não vou colocar o projeto inteiro aqui, o foco deste post não é ensinar a criar um projeto jsf + spring, mas vou tentar detalhar legal a parte do ldap que tanto nos aflige.</p>
<p>Inicialmente vou colocar o meu pom.xml com todas as dependências, creio que este arquivo seja o mais importante e ao mesmo tempo o mais problematico.</p>
<p><pre class="brush: plain;">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.app&lt;/groupId&gt;
&lt;artifactId&gt;App&lt;/artifactId&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;ISO-8859-1&lt;/project.build.sourceEncoding&gt;
&lt;/properties&gt;

&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;servlet-api&lt;/artifactId&gt;
&lt;version&gt;2.5&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
&lt;artifactId&gt;jsp-api&lt;/artifactId&gt;
&lt;version&gt;2.1&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.faces&lt;/groupId&gt;
&lt;artifactId&gt;jsf-api&lt;/artifactId&gt;
&lt;version&gt;1.2_08&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.faces&lt;/groupId&gt;
&lt;artifactId&gt;jsf-impl&lt;/artifactId&gt;
&lt;version&gt;1.2_08&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;log4j&lt;/groupId&gt;
&lt;artifactId&gt;log4j&lt;/artifactId&gt;
&lt;version&gt;1.2.14&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.8.2&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.facelets&lt;/groupId&gt;
&lt;artifactId&gt;jsf-facelets&lt;/artifactId&gt;
&lt;version&gt;1.1.15&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.richfaces.ui&lt;/groupId&gt;
&lt;artifactId&gt;richfaces-ui&lt;/artifactId&gt;
&lt;version&gt;3.3.1.GA&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-web&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt;
&lt;artifactId&gt;ehcache-core&lt;/artifactId&gt;
&lt;version&gt;2.3.2&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;cglib&lt;/groupId&gt;
&lt;artifactId&gt;cglib-nodep&lt;/artifactId&gt;
&lt;version&gt;2.1_3&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.webflow&lt;/groupId&gt;
&lt;artifactId&gt;spring-faces&lt;/artifactId&gt;
&lt;version&gt;2.3.0.RELEASE&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.mail&lt;/groupId&gt;
&lt;artifactId&gt;mail&lt;/artifactId&gt;
&lt;version&gt;1.4&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;artifactId&gt;activation&lt;/artifactId&gt;
&lt;groupId&gt;javax.activation&lt;/groupId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
&lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
&lt;version&gt;3.4.0.GA&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.jboss.snowdrop&lt;/groupId&gt;
&lt;artifactId&gt;snowdrop-vfs&lt;/artifactId&gt;
&lt;version&gt;1.0.1.GA&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.xml.messaging.saaj&lt;/groupId&gt;
&lt;artifactId&gt;saaj-impl&lt;/artifactId&gt;
&lt;version&gt;1.3&lt;/version&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;artifactId&gt;activation&lt;/artifactId&gt;
&lt;groupId&gt;javax.activation&lt;/groupId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.ws&lt;/groupId&gt;
&lt;artifactId&gt;spring-ws&lt;/artifactId&gt;
&lt;version&gt;1.5.8&lt;/version&gt;
&lt;classifier&gt;all&lt;/classifier&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
&lt;groupId&gt;org.easymock&lt;/groupId&gt;
&lt;artifactId&gt;easymock&lt;/artifactId&gt;
&lt;version&gt;3.0&lt;/version&gt;
&lt;type&gt;jar&lt;/type&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-core&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-taglibs&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.integration&lt;/groupId&gt;
&lt;artifactId&gt;spring-integration-rmi&lt;/artifactId&gt;
&lt;version&gt;2.0.4.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-ldap&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.quartz-scheduler&lt;/groupId&gt;
&lt;artifactId&gt;quartz&lt;/artifactId&gt;
&lt;version&gt;2.0.0&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.quartz-scheduler&lt;/groupId&gt;
&lt;artifactId&gt;quartz-jboss&lt;/artifactId&gt;
&lt;version&gt;2.0.0&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;finalName&gt;${project.artifactId}-${project.version}&lt;/finalName&gt;
&lt;directory&gt;${basedir}/target&lt;/directory&gt;
&lt;outputDirectory&gt;${basedir}/target/classes&lt;/outputDirectory&gt;
&lt;testOutputDirectory&gt;${basedir}/target/test-classes&lt;/testOutputDirectory&gt;
&lt;sourceDirectory&gt;${basedir}/src/main/java&lt;/sourceDirectory&gt;
&lt;scriptSourceDirectory&gt;${basedir}/src/main/scripts&lt;/scriptSourceDirectory&gt;
&lt;testSourceDirectory&gt;${basedir}/src/test/java&lt;/testSourceDirectory&gt;
&lt;resources&gt;
&lt;resource&gt;
&lt;directory&gt;${basedir}/src/main/resources&lt;/directory&gt;
&lt;/resource&gt;
&lt;/resources&gt;
&lt;testResources&gt;
&lt;testResource&gt;
&lt;directory&gt;${basedir}/src/test/resources&lt;/directory&gt;
&lt;/testResource&gt;
&lt;/testResources&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;2.3.2&lt;/version&gt;
&lt;configuration&gt;
&lt;source&gt;1.6&lt;/source&gt;
&lt;target&gt;1.6&lt;/target&gt;
&lt;executable&gt;${env.JAVA_HOME}/bin/javac&lt;/executable&gt;
&lt;showDeprecation&gt;true&lt;/showDeprecation&gt;
&lt;showWarnings&gt;true&lt;/showWarnings&gt;
&lt;optimize&gt;true&lt;/optimize&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
&lt;version&gt;2.6&lt;/version&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;

</pre></p>
<p>Por cima você já consegue ver que é um projeto JSF 1.2, Spring e um pouco de Hibernate, como eu disse, o que não se aplica a sua aplicação deve ser simplesmente ignorado. Tomei a decisão de colocar todo o pom aqui, pois é muito comum ficarmos presos no famoso dependency-hell do Java, mas a única dependência que de fato faz a diferença neste post é spring-security-ldap.</p>
<p>A primeira coisa é criar o bean de ldapTemplate dentro do seu contexto do Spring, é através deste bean que você se comunicará com o AD e ele é a principal figura deste projeto.</p>
<p>Vamos lá:</p>
<p><pre class="brush: plain;">

&lt;bean id=&quot;properties&quot;&gt;
&lt;property name=&quot;locations&quot;&gt;
&lt;list&gt;
&lt;value&gt;/WEB-INF/classes/com/app/app/resources/ldap.properties&lt;/value&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;

&lt;bean id=&quot;contextSource&quot;&gt;
&lt;property name=&quot;url&quot; value=&quot;${ldap.url}&quot; /&gt;
&lt;property name=&quot;userDn&quot; value=&quot;${ldap.userName}&quot; /&gt;
&lt;property name=&quot;password&quot; value=&quot;${ldap.password}&quot; /&gt;
&lt;property name=&quot;pooled&quot; value=&quot;${ldap.pooled}&quot;/&gt;
&lt;property name=&quot;referral&quot; value=&quot;${ldap.referral}&quot;/&gt;
&lt;/bean&gt;

&lt;bean id=&quot;ldapTemplate&quot;&gt;
&lt;constructor-arg ref=&quot;contextSource&quot; /&gt;
&lt;property name=&quot;ignorePartialResultException&quot; value=&quot;${ldap.ignore}&quot;/&gt;
&lt;/bean&gt;

</pre></p>
<p>Nas linhas de código acima criarmos três beans bem simplezinhos. O primeiro properties, apenas carregamos o arquivo especificado (o seu arquivo pode estar em qualquer lugar, ou mesmo não existir) para que possamos parametrizar os valores do servidor ldap de fora do arquivo xml do Spring.</p>
<p>Olha o meu arquivo properties aí:</p>
<p><pre class="brush: plain;">

ldap.url=ldap://dominio.com.br/DC=dominio,DC=com,DC=br
ldap.userName=leonardo.moreira@dominio.com.br
ldap.password=senha
ldap.userPrincipalPath=(userPrincipalName={0})
ldap.pooled=true
ldap.referral=follow
ldap.ignore=true

</pre></p>
<p>Vou frisar que o endereço da propriedade ldap.url varia de acordo com suas configurações de ldap. Veja, em geral é sempre o nome do seu domínio seguido pelos sufixos definidos pela galera da sua Infra-estrutura.<br />
Uma dica para ver alguns destes dados é aquela busca avançada de usuários do windows, sabe? Você pode adicionar diversos campos e valores que constituem o domínio e outras informações úteis.</p>
<p>Uma vez com o properties em mãos o aplicamos ao conector do ldap, no caso o bean contextSource. Este bean irá criar a comunicação com o ldap e lhe passar o contexto do mesmo para que você trabalhe livremente utilizando o ldapTemplate. Falando em ldapTemplate o criamos no bean seguinte passando o contextSource no construtor.</p>
<p>Bom, uma vez que nossa aplicação esteja subindo no web-server com os beans descritos acima vem a parte mais fácil que é lidar com o contexto do Ldap.</p>
<p>Aqui na minha aplicação eu criei um serviço simples que apenas faz a busca dos usuários no AD com o critério LIKE (Do SQL lembra? <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
<p>Bom, a primeira coisa de tudo aqui é definir as nossas interfaces, afinal, desacoplamento nunca é ruim, correto?</p>
<p>A interface User descreve os campos que a nossa classe concreta de usuário deverá ter. Esta interface é bem pessoal, tem gente que gosta de criar e tem gente que não vê a necessidade. Em todo caso está aí.</p>
<p><pre class="brush: plain;">


package com.app.app.ldap;

/**
* @author Leonardo Machado Moreira
* @version 1.0 04/11/2011
*/
public interface User {

public String getUserName();

public void setUserName(String userName);

public String getFirstName();

public void setFirstName(String firstName);

public String getLastName();

public void setLastName(String lastName);

public String getEmail();

public void setEmail(String email);

public String getPassword();

public void setPassword(String password);

public String getDepartment();

public void setDepartment(String departement);

public String getLogin();

public void setLogin(String login);

public String [] getGroups();

public void setGroups(String [] groups);
}

</pre></p>
<p>A interface User será implementada pela classe DefaultUser, que terá o papel de mapear de fato um usuário do ldap.</p>
<p><pre class="brush: plain;">

/*
* @(#)DefaultUser.java 1.0 04/11/2011
*
* Copyright (c) 2011, GSW Software Ltda. Todos os direitos reservados.
* Propriedade particular/confidencial da GSW. Uso sujeito a termos de licença.
*/

package com.app.app.ldap;

/**
* @author Leonardo Machado Moreira
* @version 1.0 04/11/2011
*/
public class DefaultUser implements User {

private String userName;
private String firstName;
private String lastName;
private String email;
private String password;
private String department;
private String login;
private String groups[];

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

public String [] getGroups() {
return groups;
}

public void setGroups(String [] groups) {
this.groups = groups;
}

@Override
public String getLogin() {
return login;
}

@Override
public void setLogin(String login) {
this.login = login;
}

public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(&quot;UserImpl[&quot;);
buffer.append(&quot; userName = &quot;).append(userName);
buffer.append(&quot; email = &quot;).append(email);
buffer.append(&quot; firstName = &quot;).append(firstName);
buffer.append(&quot; lastName = &quot;).append(lastName);
buffer.append(&quot; password = &quot;).append(password);
buffer.append(&quot;]&quot;);
return buffer.toString();
}

}

</pre></p>
<p>Agora mapearemos o serviço em sí, e lá vai mais uma interface.</p>
<p>Segue:</p>
<p><pre class="brush: plain;">

package com.app.app.ldap;

import java.util.List;

/**
* @author Leonardo Machado Moreira
* @version 1.0 04/11/2011
*/
public interface UserService {

User getUser(final String userName);

List&lt;User&gt; getUsers(final String pattern);

}

</pre></p>
<p>Dois métodos simples de tudo, um retorna um usuário específico através da busca pelo nome e o outro retornará uma lista de usuários a partir de uma String qualquer, onde será feito o like.</p>
<p><pre class="brush: plain;">


package com.app.app.ldap;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.filter.LikeFilter;
import org.springframework.ldap.filter.OrFilter;
import org.springframework.stereotype.Service;

/**
* @author Leonardo Machado Moreira
* @version 1.0 04/11/2011
*/
@Service
public class DefaultUserService implements UserService {

@Autowired
private LdapTemplate ldapTemplate;

public User getUser(final String userName) {
OrFilter filter = new OrFilter();
filter.or(new EqualsFilter(&quot;givenName&quot;, userName));

@SuppressWarnings(&quot;unchecked&quot;)
List&lt;User&gt; users = getLdapTemplate().search(DistinguishedName.EMPTY_PATH, filter.encode(), new UserAttributesMapper());

if (!users.isEmpty()) {
return users.get(0);
}

return null;
}

@SuppressWarnings(&quot;unchecked&quot;)
public List&lt;User&gt; getUsers(final String pattern) {

OrFilter filter = new OrFilter();

if (pattern != null) {
filter.or(new LikeFilter(&quot;givenName&quot;, pattern));
}

List&lt;User&gt; users = new ArrayList&lt;User&gt;();

users.addAll(getLdapTemplate().search(DistinguishedName.EMPTY_PATH, filter.encode(), new UserAttributesMapper()));
return users;

}

public LdapTemplate getLdapTemplate() {
return ldapTemplate;
}

}

</pre></p>
<p>É na classe acima que toda a mágica acontece. Ela é que será chamada nos outros locais da sua aplicação (controladores) e ela que encapsulará toda a complexidade da comunicação com o AD.</p>
<p>A classe é tão simples e tão descritiva que tenho até preguiça de explicar.</p>
<p>Fiz o Autowired do ldapTemplate que nós criamos lá no XML um pouco para trás e então é só utiliza-lo a-la-vonte.</p>
<p>A linha mais importante desta classe é obviamente a linha a seguir.</p>
<p><pre class="brush: plain;">
List&lt;User&gt; users = getLdapTemplate().search(DistinguishedName.EMPTY_PATH, filter.encode(), new UserAttributesMapper());
</pre></p>
<p>Aqui listamos o filtro e a classe de mapeamento onde a string retornada pelo ldap será convertida na nossa entidade.</p>
<p>Vejam:</p>
<p><pre class="brush: plain;">

public class UserAttributesMapper implements AttributesMapper {

@Override
public Object mapFromAttributes(Attributes attrs) throws NamingException {
DefaultUser user = new DefaultUser();

if (attrs.get(&quot;cn&quot;) != null) {
user.setUserName((String) attrs.get(&quot;cn&quot;).get());
}

if (attrs.get(&quot;cn&quot;) != null)
user.setFirstName((String) attrs.get(&quot;cn&quot;).get());

if (attrs.get(&quot;sn&quot;) != null)
user.setLastName((String) attrs.get(&quot;sn&quot;).get());

if (attrs.get(&quot;mail&quot;) != null)
user.setEmail((String) attrs.get(&quot;mail&quot;).get());

if (attrs.get(&quot;sAMAccountName&quot;) != null)
user.setLogin((String) attrs.get(&quot;sAMAccountName&quot;).get());

return user;
}

}

</pre></p>
<p>É importante ressaltar que não fui eu que inventei estas constantes (sn, cn e etc), também as abomino, mas é a forma que a Microsoft gerencia os dados de seus usuáriso no AD.</p>
<p>Com uma googlada simples eu encontrei o descritivo de todos os atributos, tá no link:</p>
<p>http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm</p>
<p>Bom, creio que agora temos 99% do trabalho pronto, vou só mostrar como ficou a chamada lá no controller do meu jsf, onde eu populo um autocomplete o Richfaces, conforme o usuário vai digitando eu vou listando todos os usuários do AD a partir do nome.</p>
<p><pre class="brush: plain;">

@Autowired
private UserService defaultUserService;

public List&lt;com.embraer.icm.ldap.User&gt; autocomplete(Object suggest) {
try {
List&lt;com.embraer.icm.ldap.User&gt; users = new ArrayList&lt;com.embraer.icm.ldap.User&gt;();
users.addAll(defaultUserService.getUsers(suggest + &quot;*&quot;));
return users;
} catch (Exception e) {
return new ArrayList&lt;com.embraer.icm.ldap.User&gt;();
}
}


&lt;h:inputText id=&quot;name&quot; value=&quot;#{userController.entity.name}&quot;
required=&quot;true&quot;
requiredMessage=&quot;#{labels['user.labels.required.name']}&quot;
disabled=&quot;#{userController.rendered}&quot; style=&quot;width:300px;&quot; /&gt;

&lt;rich:suggestionbox for=&quot;name&quot; var=&quot;result&quot;
suggestionAction=&quot;#{userController.autocomplete}&quot;&gt;
&lt;h:column&gt;
&lt;h:outputText value=&quot;#{result.userName}&quot; /&gt;
&lt;/h:column&gt;
&lt;a4j:support event=&quot;onselect&quot; reRender=&quot;login, email&quot;&gt;
&lt;f:setPropertyActionListener value=&quot;#{result.email}&quot;
target=&quot;#{userController.entity.email}&quot; /&gt;
&lt;f:setPropertyActionListener value=&quot;#{result.login}&quot;
target=&quot;#{userController.entity.login}&quot; /&gt;
&lt;/a4j:support&gt;
&lt;/rich:suggestionbox&gt;

</pre></p>
<p>Pronto, agora sim, tudo que precisamos para nos comunicar com o LDAP e ainda mostrar em um auto complete do Richfaces. É óbvio que não coloquei as configurações básicas de framework, afinal, perderia toda a graça de programar, não é?</p>
<p>Mas quem realmente tiver dificuldade em uma configuração simples de JSF + Spring e etc, pode comentar ai que eu dou uma força, mas dê uma boa googlada antes, tá?</p>
<p>Ah, outra coisa que esqueci de comentar, o ldapTemplate não faz apenas pesquisa, ele chega ao cúmulo de modificar usuários e até cria-los dentro do AD, é só questão de brincar melhor com a sua API e com os seus atributos.</p>
<p>É isso aí, até a próxima.</p>
<p>Leonardo</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/521/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/521/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/521/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=521&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/12/14/java-spring-ldap-active-directory-windows/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Java RMI fácil utilizando o Spring &#8211; Cliente</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/07/16/java-rmi-facil-utilizando-o-spring-cliente/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/07/16/java-rmi-facil-utilizando-o-spring-cliente/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 03:24:13 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cliente]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[rmi]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=518</guid>
		<description><![CDATA[Esta é a continuação do post anterior. Uma vez que já criamos o servidor RMI basta consumi-lo. Vou mostrar de duas formas para ficar bem entendido. A primeira é já na sua aplicação web, maneira mais simples de todas. No seu application context .xml ou arquivo que o valha adicione o seguinte bean: Neste bean [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=518&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Esta é a continuação do post anterior.</p>
<p>Uma vez que já criamos o servidor RMI basta consumi-lo. Vou mostrar de duas formas para ficar bem entendido.</p>
<p>A primeira é já na sua aplicação web, maneira mais simples de todas. No seu application context .xml ou arquivo que o valha adicione o seguinte bean:</p>
<p><pre class="brush: plain;">

&lt;bean id=&quot;rmiService&quot;&gt;
&lt;property name=&quot;serviceUrl&quot; value=&quot;rmi://192.168.224.75:1099/rmi-service&quot;/&gt;
&lt;property name=&quot;serviceInterface&quot; value=&quot;com.app.sys.rmiclient.FileManagement&quot;/&gt;
&lt;/bean&gt;

</pre></p>
<p>Neste bean podemos notar algums coisinhas simples. Ele cria um bean chamado rmiService e configura-o para o endereço onde o nosso servidor RMI está rodando, no meu caso é<br />
este IP configurado aí.</p>
<p>Este codigo especifica uma interface também, para o Spring saber exatamente o que está criando. Note que nossa interface é exatamente a mesma interface que criamos no servidor RMI. DEVE ser a mesma interface<br />
se puder copiar e colar melhor ainda.</p>
<p>Creio que tenha ficado bem claro que nosso cliente deve ter uma versão da Interface do RMI, né?</p>
<p>Agora que o bean está no seu application context, sempre que sua aplicação &#8220;subir&#8221; vai tentar fazer a conexão e se o RMI não estiver rodando no servidor vai retornar um erro.</p>
<p>Quando a aplicação subir é só fazer o @Autowired utilizando o rmiService do tipo FileManagement e usar os métodos da interface.</p>
<p>Simples, simples.</p>
<p>Para quem quer um pouco mais de detalhes eu criei um outro JAR chamado client-rmi, o contrário do server-rmi que criei no post anterior, mas volta lá e pegue a definição do POM<br />
e pegue também a estrutura de pastas do resources por exemplo.</p>
<p><pre class="brush: plain;">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd&quot;&gt;
&lt;bean id=&quot;rmiService&quot;&gt;
&lt;property name=&quot;serviceUrl&quot; value=&quot;rmi://192.168.224.75:1099/rmi-service&quot;/&gt;
&lt;property name=&quot;serviceInterface&quot; value=&quot;com.app.sys.rmiclient.FileManagement&quot;/&gt;
&lt;/bean&gt;

&lt;/beans&gt;


</pre></p>
<p>Veja que a criação do bean aqui é exatamente a mesma que usamos no nosso container web, isto mostra legal o quão parrudo o Spring é para criar o seu próprio contexto.</p>
<p>Como já descrevi você cola a interface FileManagement no seu client.</p>
<p>E agora o simples e fácil Main.</p>
<p><pre class="brush: plain;">


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
public static void main(String[] args) throws IOException {
ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;com/app/sys/rmiclient/rmi-server-context.xml&quot;);
FileManagement management = (FileManagement) ctx.getBean(&quot;rmiService&quot;);

System.out.println(&quot;Digite o arquivo:&quot;);

java.util.Scanner s = new Scanner(System.in);

String arquivo = s.next();

byte[] file = management.getFile(arquivo);

InputStream is = new ByteArrayInputStream(file);

System.out.println(file.length);

if (is != null) {
Writer writer = new StringWriter();

char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
&quot;UTF-8&quot;));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
System.out.println(writer.toString());
}

System.out.println(&quot;Deseja excluir: (s/n)&quot;);

if(s.next().equals(&quot;s&quot;))
System.out.println(management.deleteFile(arquivo));

System.out.println(&quot;FIM EXEC&quot;);
}
}

</pre></p>
<p>Veja que carregamos o contexto do Spring mostrando o endereço do arquivo e deste contexto apenas pegamos o bean que ele mesmo criou.</p>
<p>A partir daí é só rodar nosso métodos e é o nosso bom e velho código Java.</p>
<p>Simples assim.</p>
<p>Qualquer dúvida é só escrever.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/518/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=518&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/07/16/java-rmi-facil-utilizando-o-spring-cliente/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Java RMI fácil utilizando o Spring</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/07/15/java-rmi-facil-utilizando-o-spring/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/07/15/java-rmi-facil-utilizando-o-spring/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 02:52:17 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[arquivos]]></category>
		<category><![CDATA[deletar]]></category>
		<category><![CDATA[pegar]]></category>
		<category><![CDATA[remoto]]></category>
		<category><![CDATA[rmi]]></category>
		<category><![CDATA[servidor]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=511</guid>
		<description><![CDATA[Qualquer um que já precisou rodar alguma de suas classes Java remotamente já precisou fazer um servidor RMI. Para quem não conhece vai um resumão BEM básico. O RMI no Java, do Inglês, Remote Method Invocation é exatamente o que o seu nome diz, uma chamada de métodos de uma classe de forma remota. Imagine [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=511&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Qualquer um que já precisou rodar alguma de suas classes Java remotamente já precisou fazer um servidor RMI.</p>
<p>Para quem não conhece vai um resumão BEM básico.</p>
<p>O RMI no Java, do Inglês, Remote Method Invocation é exatamente o que o seu nome diz, uma chamada de métodos de uma classe de forma remota.</p>
<p>Imagine que por algum motivo você está em uma máquina e precisa executar operações em outra máquina, apagar um arquivo, recuperar outro arquivo, tanto faz, a questão é que você precisa executar um comando na outra máquina. O que você faz?</p>
<p>Ou cria um container web todo ferrado na máquina e apela para um web-service ou faz um bom e velho RMI.</p>
<p>Até um tempo atrás fazer um servidor RMI era um trampo danado para falar a verdade, e até assustava um pouco os desenvolvedores para esta simples solução. A questão é que o Spring veio com tudo e resolveu toda esta complexidade.</p>
<p>Vamos lá.</p>
<p>Lá no meu trabalho me deparei com a seguinte situação:</p>
<p>Temos uma aplicação web com mensagens (parecido com uma mensagem de e-mail) salvas em um banco de dados. Estas mensagens vieram de um web-service, que salvou as mesmas no banco com o endereço dos anexos de um outro servidor, o repositório do cliente.</p>
<p>A questão é que este servidor não tem acesso ao mundo lá fora, portanto não dá pra fazer acesso direto de jeito nenhum.</p>
<p>O que precisamos fazer?</p>
<p>Montamos um servidor RMI nesta máquina repositório, este servidor RMI tem dois papéis, retornar um Array de Byte com o arquivo da máquina e excluir um arquivo passado.</p>
<p>Então nossa aplicação web simplesmente consome este servidor RMI, e passa um Path para pegar os arquivos, excluí-los e ser feliz para sempre.</p>
<p>Vamos lá para a criação do SERVIDOR RMI:</p>
<p>A primeira coisa que fiz foi um novo projeto Maven simples do eclipse.</p>
<p>Meu pom ficou com as seguintes dependências:</p>
<p><pre class="brush: plain;">

&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.integration&lt;/groupId&gt;
&lt;artifactId&gt;spring-integration-rmi&lt;/artifactId&gt;
&lt;version&gt;2.0.4.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-beans&lt;/artifactId&gt;
&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;3.8.1&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;

</pre></p>
<p>Não podemos esquecer que iremos empacotar esta aplicação em um jar executável com as dependências já resolvidas, portanto, os seguintes plugins serão necessários no Maven:</p>
<p><pre class="brush: plain;">

&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
&lt;version&gt;2.2-beta-5&lt;/version&gt;
&lt;configuration&gt;
&lt;descriptorRefs&gt;
&lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;
&lt;/descriptorRefs&gt;
&lt;archive&gt;
&lt;manifest&gt;
&lt;mainClass&gt;com.sys.app.rmiserver.Main&lt;/mainClass&gt;
&lt;/manifest&gt;
&lt;/archive&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;id&gt;make-assembly&lt;/id&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;single&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;

</pre></p>
<p>Feito isto podemos partir para o código de verdade. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>A primeira coisa é a nossa classe Main, executável, meio que um EntryPoint do programa, como qualquer iniciante Java conhece nos seus sistemas de console.</p>
<p><pre class="brush: plain;">

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* A classe &lt;code&gt;Main&lt;/code&gt; inicia o serviço RMI ao carregar o Spring Application Context
*
* @author Leonardo Machado Moreira
*/

public class Main
{
public static void main( String[] args )
{
new ClassPathXmlApplicationContext(&quot;com/app/sys/rmiserver/rmi-server-context.xml&quot;);
}
}

</pre></p>
<p>Como podemos ver esta classe Main é ridícula. Na iremos apenas iniciar um contexto simples do Spring utilizando como configuração padrão o arquivo passado.</p>
<p>Esta localização é dentro da pasta resouces como qualquer recurso do Java, então, dentro de /src/main/resources/com/app/sys/rmiserver/rmi-server-context.xml</p>
<p>Este arquivo contém o seguinte conteúdo:</p>
<p><pre class="brush: plain;">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd&quot;&gt;
&lt;bean id=&quot;rmiService&quot; class=&quot;com.app.sys.rmiserver.DefaultFileManagement&quot;/&gt;
&lt;bean&gt;
&lt;property name=&quot;serviceName&quot; value=&quot;rmi-service&quot;/&gt;
&lt;property name=&quot;service&quot; ref=&quot;rmiService&quot;/&gt;
&lt;property name=&quot;serviceInterface&quot; value=&quot;com.app.sys.rmiserver.FileManagement&quot;/&gt;
&lt;property name=&quot;registryPort&quot; value=&quot;1099&quot;/&gt;
&lt;/bean&gt;
&lt;/beans&gt;

</pre></p>
<p>A primeira coisa que este arquivo faz é criar um bean chamado rmiService baseado na nossa classe DefaultFileManagement, que abordaremos daqui a pouco.</p>
<p>Na linha de baixo criamos outro bean da classe RmiServiceExporter responsável por abrir a porta de comunicação com o mundo e nomear um label do serviço.</p>
<p>Nossa codificação agora é bem simples.</p>
<p>Primeiro criamos uma Interface com todos os métodos que serão consumidos pelos clientes. Esta interface é a porta com o mundo, portanto deve ser exatamente o que você<br />
implementou. No meu caso a interface FileManagement ficou assim:</p>
<p><pre class="brush: plain;">

/**
* A interface &lt;code&gt;FileManagement&lt;/code&gt; é utilizada pelo Spring RMI para acesso remoto
*
* @author Leonardo Machado Moreira
*/

public interface FileManagement {

byte[] getFile(String path);
boolean deleteFile(String path);

}

</pre></p>
<p>Tão simples quanto poderia ser.</p>
<p>Agora é que vem onde a magia acontece. A implementação desta classe é exatamente o que nosso servidor fará e exatamente o que o Spring utilizou para criar o bean.</p>
<p>A classe DefaultFileManagement está desta forma:</p>
<p><pre class="brush: plain;">

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
* A classe &lt;code&gt;DefaultFileManagement&lt;/code&gt; implementa FileManagement e
* realiza as ações de arquivo no servidor
*
* @author Leonardo Machado Moreira
*
* Retornado em Byte array para que a referencia exata seja passada, caso contrário o java não encontra o arquivo
*/
public class DefaultFileManagement implements FileManagement {

public byte[] getFile(String path) {
try {

File file = new File(path);
InputStream is = new FileInputStream(file);
long length = file.length();

if (length &gt; Integer.MAX_VALUE)
throw new IllegalArgumentException(&quot;Arquivo muito grande&quot;);

byte[] bytes = new byte[(int) length];

int offset = 0;
int numRead = 0;

while (offset &lt; bytes.length &amp;&amp; (numRead = is.read(bytes, offset, bytes.length - offset)) &gt;= 0) {
offset += numRead;
}

if (offset &lt; bytes.length)
throw new IllegalArgumentException(&quot;Erro ao ler o arquivo&quot;);

is.close();

return bytes;

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

public boolean deleteFile(String path) {
return new File(path).delete();
}

}

</pre></p>
<p>De RMI mesmo esta classe não tem absolutamente nada, veja o método delefeFile por exemplo, tão ridículo quanto nosso Java IO permite ser.</p>
<p>Agora é a parte mais simples.</p>
<p>Utilizando o Maven faça um build.</p>
<p>Em pacote rodando um mvn package na pasta e pegue o jar com todas as dependências.</p>
<p>Cole-o na pasta do servidor e rode-o utilizando o comando</p>
<p>java -jar rmi-service.jar</p>
<p>Pronto, seu servidor RMI está criado.</p>
<p>No próximo posto mostro como consumir.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/511/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/511/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/511/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/511/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/511/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/511/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/511/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/511/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=511&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/07/15/java-rmi-facil-utilizando-o-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Maven 2 e a criação de projetos</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/06/19/maven-2-e-a-criacao-de-projetos/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/06/19/maven-2-e-a-criacao-de-projetos/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 23:31:01 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[criação]]></category>
		<category><![CDATA[criação de projetos]]></category>
		<category><![CDATA[maven 2]]></category>
		<category><![CDATA[maven2]]></category>
		<category><![CDATA[projetos]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=502</guid>
		<description><![CDATA[Não me lembro se já falei do Maven 2 para desenvolvimento Java, mas caso já tenha falado me repito: É uma ferramenta incrível para gerenciamento de estrutura de projetos e de dependências. Quantas vezes você já não se pegou fazendo um control+c e control+v em um projeto, deletando as classes na mão e aí começando [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=502&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Não me lembro se já falei do Maven 2 para desenvolvimento Java, mas caso já tenha falado me repito: É uma ferramenta incrível para gerenciamento de estrutura de projetos e de dependências.</p>
<p>Quantas vezes você já não se pegou fazendo um control+c e control+v em um projeto, deletando as classes na mão e aí começando outro depois de renomear tudo que tem que renomear? Então, com o maven e um comando você poderia simplesmente através de uma estrutura pré-definida criar um projeto inteiro.</p>
<p>Onde trabalho temos um cliente relativamente chato que define os frameworks que devemos utilizar, a estrutura que o nosso projeto deve ter, em qual lugar a camada de serviço deve se encontrar e tudo mais&#8230; Então ao invez de ele mandar uma pasta inteira com o projeto e tudo mais ele simplesmente manda um Archetype do Maven 2 e através de um comando agente gera o projeto de onde quer que esteja.</p>
<p>Bom, instalar o Maven é simplão você só baixa, descompacta e adiciona ele a seu Path.</p>
<p>Criação de um projeto simples a partir de um archetype-quickstart é efetuada utilizando um comando como o seguinte:</p>
<p><pre class="brush: plain;">

mvn archetype:generate -DgroupId=br.eximia -DartifactId=simple -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

</pre></p>
<p>Você percebe que os parâmetros são bastante auto-explicativos. Grupo, artefato e o nome do archetype do Maven.</p>
<p>Ao rodar o comando a seguir você só assiste o Maven criando uma pasta com toda a estrutura do seu projeto para você, até com um Hello World inclusive.</p>
<p>Lembrando que o Maven 2 não escolhe IDE e nem nada então uma coisa interessante após criar o seu projeto é destinar o mesmo ao Eclipse. Isto é feito através do comando:</p>
<p><pre class="brush: plain;">

mvn eclipse:eclipse

</pre></p>
<p>Aí você simplesmente importa este arquivo no Eclipse como um projeto Maven já existente. Para te ajudar neste projeto é bastante interessante que você instale o plugin m2Eclipse adicionando <strong><a href="http://m2eclipse.sonatype.org/sites/m2e">este</a></strong> repositorio aos seus updates e fazendo um next, next, next básico.</p>
<p>Note pela estrutura do projeto criado pelo Maven que este é um projeto de Console, então para a criação de um projeto web basta alterar o archetype, veja o comando:</p>
<p><pre class="brush: plain;">

mvn archetype:generate -DgroupId=br.eximia -DartifactId=simpleWeb -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

</pre></p>
<p>Note que o comando é exatamente o mesmo, eu só alterei o achetype, e aí temos um diretório chamado webapp e tudo mais que um projeto web precisa.</p>
<p>Como não é só porque um projeto é Web que ele tem código Java escrito o archetype não gera para você a pasta src/main/java, então você abre a sua estrutura e cria manualmente dentro de main a pasta java. Logo dentro de main haverão as pastas java, resources e webapp. De quebra eu já crio dentro de /src o diretório test e dentro deste o diretório java para abrigar os testes unitários. Então esta parte ficou com /src/test/java.</p>
<p>Agora um detalhe MUITO importante, da mesma forma que o comando para criar o projeto Console e o projeto web é diferente, o comando para fazer sua aplicação web suportar o Eclipse também é um pouco diferente.</p>
<p>Veja:</p>
<p><pre class="brush: plain;">

mvn eclipse:eclipse -Dwtpversion=2.0

</pre></p>
<p>Na verdade o comando é exatamente o mesmo, mas adicionamos um parametro que configura a versão do WTP, que é um plugin do Maven e do Eclipse para a configuração de aplicações web.</p>
<p>Após rodar este comando e importar o projeto no Eclipse verá que entenderá a estrutura do projeto com mais assertividade, verá também que ele gera os arquivos .classpath e .project do Eclipse.</p>
<p>Simples assim, agora é só colocar todas as dependencias do Maven dentro do seu POM que o Eclipse automaticamente baixará para o seu repositório local.</p>
<p>O legal que a partir de agora você já pode criar um servidor no seu eclipse, adicionar o projeto a ele e simplesmente iniciar o projeto, no meu caso o link http://localhost:8080/simpleWeb/, já estava funcionando com um Hello World.</p>
<p>Agora vem o motivador deste post. O site <a href="http://www.springfuse.com/">http://www.springfuse.com/</a>, criar através de um archetype maven um projeto inteiro baseado em Spring, Spring WF, Primefaces e JPA, com um ótima estrutura que vale pena dar uma estudada.</p>
<p>É fantástico.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/502/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/502/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/502/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=502&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/06/19/maven-2-e-a-criacao-de-projetos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Absolutamente tudo (mínimo) sobre Charsets</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/05/10/absolutamente-tudo-sobre-charsets/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/05/10/absolutamente-tudo-sobre-charsets/#comments</comments>
		<pubDate>Tue, 10 May 2011 11:18:35 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[charset]]></category>
		<category><![CDATA[tudo sobre]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=498</guid>
		<description><![CDATA[Charsets são um assunto um pouco místico para diversos desenvolvedores. Encontrei um artigo na internet de 2003, mas é relevante para muita gente. Com os devidos créditos, absolutamente tudo sobre charsets. Ever wonder about that mysterious Content-Type tag? You know, the one you&#8217;re supposed to put in HTML and you never quite know what it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=498&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Charsets são um assunto um pouco místico para diversos desenvolvedores. Encontrei um artigo na internet de 2003, mas é relevante para muita gente. Com os devidos <a href="http://www.joelonsoftware.com/articles/Unicode.html">créditos</a>, absolutamente tudo sobre charsets.</p>
<p>Ever wonder about that mysterious Content-Type tag? You know, the one you&#8217;re supposed to put in HTML and you never quite know what it should be?</p>
<p>Did you ever get an email from your friends in Bulgaria with the subject line &#8220;???? ?????? ??? ????&#8221;?</p>
<p><img src="http://www.joelonsoftware.com/pictures/unicode/ibm.jpg" alt="" width="150" height="143" align="right" border="0" />I&#8217;ve been dismayed to discover just how many software developers aren&#8217;t really completely up to speed on the mysterious world of character sets, encodings, Unicode, all that stuff. A couple of years ago, a beta tester for <a href="http://www.fogcreek.com/FogBUGZ">FogBUGZ</a> was wondering whether it could handle incoming email in Japanese. Japanese? They have email in Japanese? I had no idea. When I looked closely at the commercial ActiveX control we were using to parse MIME email messages, we discovered it was doing exactly the wrong thing with character sets, so we actually had to write heroic code to undo the wrong conversion it had done and redo it correctly. When I looked into another commercial library, it, too, had a completely broken character code implementation. I corresponded with the developer of that package and he sort of thought they &#8220;couldn&#8217;t do anything about it.&#8221; Like many programmers, he just wished it would all blow over somehow.</p>
<p>But it won&#8217;t. When I discovered that the popular web development tool PHP has almost <a href="http://ca3.php.net/manual/en/language.types.string.php">complete ignorance of character encoding issues</a>, blithely using 8 bits for characters, making it darn near impossible to develop good international web applications, I thought, <em>enough is enough</em>.</p>
<p>So I have an announcement to make: if you are a programmer working in 2003 and you don&#8217;t know the basics of characters, character sets, encodings, and Unicode, and I <em>catch</em> you, I&#8217;m going to punish you by making you peel onions for 6 months in a submarine. I swear I will.</p>
<p>And one more thing:</p>
<p align="center"><strong>IT&#8217;S NOT THAT HARD.</strong></p>
<p align="left">In this article I&#8217;ll fill you in on exactly what <em>every working programmer</em> should know. All that stuff about &#8220;plain text = ascii = characters are 8 bits&#8221; is not only wrong, it&#8217;s hopelessly wrong, and if you&#8217;re still programming that way, you&#8217;re not much better than a medical doctor who doesn&#8217;t believe in germs. Please do not write another line of code until you finish reading this article.</p>
<p align="left">Before I get started, I should warn you that if you are one of those rare people who knows about internationalization, you are going to find my entire discussion a little bit oversimplified. I&#8217;m really just trying to set a minimum bar here so that everyone can understand what&#8217;s going on and can write code that has a <em>hope</em> of working with text in any language other than the subset of English that doesn&#8217;t include words with accents. And I should warn you that character handling is only a tiny portion of what it takes to create software that works internationally, but I can only write about one thing at a time so today it&#8217;s character sets.</p>
<p><strong><span style="font-size:medium;">A Historical Perspective</span></strong></p>
<p>The easiest way to understand this stuff is to go chronologically.</p>
<p>You probably think I&#8217;m going to talk about very old character sets like EBCDIC here. Well, I won&#8217;t. EBCDIC is not relevant to your life. We don&#8217;t have to go that far back in time.</p>
<p><img src="http://www.joelonsoftware.com/pictures/unicode/ascii.png" alt="ASCII table" width="274" height="146" align="right" border="0" />Back in the semi-olden days, when Unix was being invented and K&amp;R were writing <a href="http://cm.bell-labs.com/cm/cs/cbook/">The C Programming Language</a>, everything was very simple. EBCDIC was on its way out. The only characters that mattered were good old unaccented English letters, and we had a code for them called <a href="http://www.robelle.com/library/smugbook/ascii.html">ASCII</a> which was able to represent every character using a number between 32 and 127. Space was 32, the letter &#8220;A&#8221; was 65, etc. This could conveniently be stored in 7 bits. Most computers in those days were using 8-bit bytes, so not only could you store every possible ASCII character, but you had a whole bit to spare, which, if you were wicked, you could use for your own devious purposes: the dim bulbs at WordStar actually turned on the high bit to indicate the last letter in a word, condemning WordStar to English text only. Codes below 32 were called <em>unprintable</em> and were used for cussing. Just kidding. They were used for control characters, like 7 which made your computer beep and 12 which caused the current page of paper to go flying out of the printer and a new one to be fed in.</p>
<p>And all was good, assuming you were an English speaker.</p>
<p><img src="http://www.joelonsoftware.com/pictures/unicode/oem.png" alt="" width="271" height="209" align="right" border="0" />Because bytes have room for up to eight bits, lots of people got to thinking, &#8220;gosh, we can use the codes 128-255 for our own purposes.&#8221; The trouble was, <em>lots</em> of people had this idea at the same time, and they had their own ideas of what should go where in the space from 128 to 255. The IBM-PC had something that came to be known as the OEM character set which provided some accented characters for European languages and <a href="http://www.jimprice.com/ascii-dos.gif">a bunch of line drawing characters</a>&#8230; horizontal bars, vertical bars, horizontal bars with little dingle-dangles dangling off the right side, etc., and you could use these line drawing characters to make spiffy boxes and lines on the screen, which you can still see running on the 8088 computer at your dry cleaners&#8217;. In fact  as soon as people started buying PCs outside of America all kinds of different OEM character sets were dreamed up, which all used the top 128 characters for their own purposes. For example on some PCs the character code 130 would display as é, but on computers sold in Israel it was the Hebrew letter Gimel (<img src="http://www.joelonsoftware.com/pictures/unicode/gimel.png" alt="ג" width="5" height="9" border="0" />), so when Americans would send their résumés to Israel they would arrive as r<img src="http://www.joelonsoftware.com/pictures/unicode/gimel.png" alt="ג" width="5" height="9" border="0" />sum<img src="http://www.joelonsoftware.com/pictures/unicode/gimel.png" alt="ג" width="5" height="9" border="0" />s. In many cases, such as Russian, there were lots of different ideas of what to do with the upper-128 characters, so you couldn&#8217;t even reliably interchange Russian documents.</p>
<p>Eventually this OEM free-for-all got codified in the ANSI standard. In the ANSI standard, everybody agreed on what to do below 128, which was pretty much the same as ASCII, but there were lots of different ways to handle the characters from 128 and on up, depending on where you lived. These different systems were called <em><a href="http://www.i18nguy.com/unicode/codepages.html#msftdos">code pages</a></em>. So for example in Israel DOS used a code page called 862, while Greek users used 737. They were the same below 128 but different from 128 up, where all the funny letters resided. The national versions of MS-DOS had dozens of these code pages, handling everything from English to Icelandic and they even had a few &#8220;multilingual&#8221; code pages that could do Esperanto and Galician <em>on the same computer! Wow!</em> But getting, say, Hebrew and Greek on the same computer was a complete impossibility unless you wrote your own custom program that displayed everything using bitmapped graphics, because Hebrew and Greek required different code pages with different interpretations of the high numbers.</p>
<p>Meanwhile, in Asia, even more crazy things were going on to take into account the fact that Asian alphabets have thousands of letters, which were never going to fit into 8 bits. This was usually solved by the messy system called DBCS, the &#8220;double byte character set&#8221; in which <em>some</em> letters were stored in one byte and others took two. It was easy to move forward in a string, but dang near impossible to move backwards. Programmers were encouraged not to use s++ and s&#8211; to move backwards and forwards, but instead to call functions such as Windows&#8217; AnsiNext and AnsiPrev which knew how to deal with the whole mess.</p>
<p>But still, most people just pretended that a byte was a character and a character was 8 bits and as long as you never moved a string from one computer to another, or spoke more than one language, it would sort of always work. But of course, as soon as the Internet happened, it became quite commonplace to move strings from one computer to another, and the whole mess came tumbling down. Luckily, Unicode had been invented.</p>
<p><strong><span style="font-size:medium;">Unicode</span></strong></p>
<p>Unicode was a brave effort to create a single character set that included every reasonable writing system on the planet and some make-believe ones like Klingon, too. Some people are under the misconception that Unicode is simply a 16-bit code where each character takes 16 bits and therefore there are 65,536 possible characters. <strong>This is not, actually, correct.</strong> It is the single most common myth about Unicode, so if you thought that, don&#8217;t feel bad.</p>
<p>In fact, Unicode has a different way of thinking about characters, and you have to understand the Unicode way of thinking of things or nothing will make sense.</p>
<p>Until now, we&#8217;ve assumed that a letter maps to some bits which you can store on disk or in memory:</p>
<p>A -&gt; 0100 0001</p>
<p>In Unicode, a letter maps to something called a <em>code point</em> which is still just a theoretical concept. How that code point is represented in memory or on disk is a whole nuther story.</p>
<p>In Unicode, the letter A is a platonic ideal. It&#8217;s just floating in heaven:</p>
<p align="center"><span style="font-size:x-large;">A</span></p>
<p>This platonic <span style="font-size:x-large;">A</span> is different than <span style="font-size:x-large;">B</span>, and different from <span style="font-size:x-large;">a</span>, but the same as <span style="font-family:arial,helvetica,sans serif;font-size:x-large;">A</span> and <em><strong><span style="font-size:x-large;">A</span></strong></em> and A. The idea that A in a Times New Roman font is the same character as the A in a Helvetica font, but <em>different</em> from &#8220;a&#8221; in lower case, does not seem very controversial, but in some languages just figuring out what a letter <em>is</em> can cause controversy. Is the German letter ß a real letter or just a fancy way of writing ss? If a letter&#8217;s shape changes at the end of the word, is that a different letter? Hebrew says yes, Arabic says no. Anyway, the smart people at the Unicode consortium have been figuring this out for the last decade or so, accompanied by a great deal of highly political debate, and you don&#8217;t have to worry about it. They&#8217;ve figured it all out already.</p>
<p>Every platonic letter in every alphabet is assigned a magic number by the Unicode consortium which is written like this: <strong>U+0639</strong>.  This magic number is called a <em>code point</em>. The U+ means &#8220;Unicode&#8221; and the numbers are hexadecimal. <strong>U+0639</strong> is the Arabic letter Ain. The English letter A would be <strong>U+0041</strong>. You can find them all using the <strong>charmap</strong> utility on Windows 2000/XP or visiting <a href="http://www.unicode.org/">the Unicode web site</a>.</p>
<p>There is no real limit on the number of letters that Unicode can define and in fact they have gone beyond 65,536 so not every unicode letter can really be squeezed into two bytes, but that was a myth anyway.</p>
<p>OK, so say we have a string:</p>
<p align="center"><strong>Hello</strong></p>
<p>which, in Unicode, corresponds to these five code points:</p>
<p align="center">U+0048 U+0065 U+006C U+006C U+006F.</p>
<p>Just a bunch of code points. Numbers, really. We haven&#8217;t yet said anything about how to store this in memory or represent it in an email message.</p>
<p><strong><span style="font-size:medium;">Encodings</span></strong></p>
<p>That&#8217;s where <em>encodings</em> come in.</p>
<p>The earliest idea for Unicode encoding, which led to the myth about the two bytes, was, hey, let&#8217;s just store those numbers in two bytes each. So Hello becomes</p>
<p align="center">00 48 00 65 00 6C 00 6C 00 6F</p>
<p>Right? Not so fast! Couldn&#8217;t it also be:</p>
<p align="center">48 00 65 00 6C 00 6C 00 6F 00 ?</p>
<p>Well, technically, yes, I do believe it could, and, in fact, early implementors wanted to be able to store their Unicode code points in high-endian or low-endian mode, whichever their particular CPU was fastest at, and lo, it was evening and it was morning and there were already <em>two</em> ways to store Unicode. So the people were forced to come up with the bizarre convention of storing a FE FF at the beginning of every Unicode string; this is called a <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/unicode_42jv.asp">Unicode Byte Order Mark</a> and if you are swapping your high and low bytes it will look like a FF FE and the person reading your string will know that they have to swap every other byte. Phew. Not every Unicode string in the wild has a byte order mark at the beginning.</p>
<p align="center"><img src="http://www.joelonsoftware.com/pictures/unicode/hummers.jpg" alt="" width="390" height="61" border="0" /></p>
<p>For a while it seemed like that might be good enough, but programmers were complaining. &#8220;Look at all those zeros!&#8221; they said, since they were Americans and they were looking at English text which rarely used code points above U+00FF. Also they were liberal hippies in California who wanted to <em>conserve (sneer)</em>. If they were Texans they wouldn&#8217;t have minded guzzling twice the number of bytes. But those Californian wimps couldn&#8217;t bear the idea of <em>doubling</em> the amount of storage it took for strings, and anyway, there were already all these doggone documents out there using various ANSI and DBCS character sets and who&#8217;s going to convert them all? <em>Moi?</em> For this reason alone most people decided to ignore Unicode for several years and in the meantime things got worse.</p>
<p>Thus was <a href="http://www.cl.cam.ac.uk/%7Emgk25/ucs/utf-8-history.txt">invented</a> the brilliant concept of <a href="http://www.utf-8.com/">UTF-8</a>. UTF-8 was another system for storing your string of Unicode code points, those magic U+ numbers, in memory using 8 bit bytes. In UTF-8, every code point from 0-127 is stored <em>in a single byte</em>. Only code points 128 and above are stored using 2, 3, in fact, up to 6 bytes.</p>
<p align="center"><img src="http://www.joelonsoftware.com/pictures/unicode/utf8.png" alt="How UTF-8 works" width="400" height="63" border="1" /></p>
<p>This has the neat side effect that English text looks <em>exactly the same in UTF-8 as it did in ASCII,</em> so Americans don&#8217;t even notice anything wrong. Only the rest of the world has to jump through hoops. Specifically, <strong>Hello</strong>, which was U+0048 U+0065 U+006C U+006C U+006F, will be stored as 48 65 6C 6C 6F, which, behold! is the same as it was stored in ASCII, and ANSI, and every OEM character set on the planet. Now, if you are so bold as to use accented letters or Greek letters or Klingon letters, you&#8217;ll have to use several bytes to store a single code point, but the Americans will never notice. (UTF-8 also has the nice property that ignorant old string-processing code that wants to use a single 0 byte as the null-terminator will not truncate strings).</p>
<p>So far I&#8217;ve told you <em>three</em> ways of encoding Unicode. The traditional store-it-in-two-byte methods are called UCS-2 (because it has two bytes) or UTF-16 (because it has 16 bits), and you still have to figure out if it&#8217;s high-endian UCS-2 or low-endian UCS-2. And there&#8217;s the popular new UTF-8 <a href="http://www.zvon.org/tmRFC/RFC2279/Output/chapter2.html">standard</a> which has the nice property of also working respectably if you have the happy coincidence of English text and braindead programs that are completely unaware that there is anything other than ASCII.</p>
<p>There are actually a bunch of other ways of encoding Unicode. There&#8217;s something called UTF-7, which is a lot like UTF-8 but guarantees that the high bit will always be zero, so that if you have to pass Unicode through some kind of draconian police-state email system that thinks 7 bits are <em>quite enough, thank you</em> it can still squeeze through unscathed. There&#8217;s UCS-4, which stores each code point in 4 bytes, which has the nice property that every single code point can be stored in the same number of bytes, but, golly, even the Texans wouldn&#8217;t be so bold as to waste <em>that</em> much memory.</p>
<p>And in fact now that you&#8217;re thinking of things in terms of platonic ideal letters which are represented by Unicode code points, those unicode code points can be encoded in any old-school encoding scheme, too! For example, you could encode the Unicode string for Hello (U+0048 U+0065 U+006C U+006C U+006F) in ASCII, or the old OEM Greek Encoding, or the Hebrew ANSI Encoding, or any of several hundred encodings that have been invented so far, <em>with one catch:</em> some of the letters might not show up! If there&#8217;s no equivalent for the Unicode code point you&#8217;re trying to represent in the encoding you&#8217;re trying to represent it in, you usually get a little question mark: ? or, if you&#8217;re <em>really</em> good, a box. Which did you get? -&gt; �</p>
<p>There are hundreds of traditional encodings which can only store <em>some</em> code points correctly and change all the other code points into question marks. Some popular encodings of English text are Windows-1252 (the Windows 9x standard for Western European languages) and <a href="http://www.htmlhelp.com/reference/charset/">ISO-8859-1</a>, aka Latin-1 (also useful for any Western European language). But try to store Russian or Hebrew letters in these encodings and you get a bunch of question marks. UTF 7, 8, 16, and 32 all have the nice property of being able to store <em>any</em> code point correctly.</p>
<p><strong><span style="font-size:medium;">The Single Most Important Fact About Encodings</span></strong></p>
<p>If you completely forget everything I just explained, please remember one extremely important fact. <strong>It does not make sense to have a string without knowing what encoding it uses</strong>. You can no longer stick your head in the sand and pretend that &#8220;plain&#8221; text is ASCII.</p>
<p align="center"><strong><span style="text-decoration:underline;">There Ain&#8217;t No Such Thing As Plain Text.</span></strong></p>
<p>If you have a string, in memory, in a file, or in an email message, you have to know what encoding it is in or you cannot interpret it or display it to users correctly.</p>
<p>Almost every stupid &#8220;my website looks like gibberish&#8221; or &#8220;she can&#8217;t read my emails when I use accents&#8221; problem comes down to one naive programmer who didn&#8217;t understand the simple fact that if you don&#8217;t tell me whether a particular string is encoded using UTF-8 or ASCII or ISO 8859-1 (Latin 1) or Windows 1252 (Western European), you simply cannot display it correctly or even figure out where it ends. There are over a hundred encodings and above code point 127, all bets are off.</p>
<p>How do we preserve this information about what encoding a string uses? Well, there are standard ways to do this. For an email message, you are expected to have a string in the header of the form</p>
<blockquote><p><strong>Content-Type: text/plain; charset=&#8221;UTF-8&#8243;</strong></p></blockquote>
<p>For a web page, the original idea was that the web server would return a similar <strong>Content-Type</strong> http header along with the web page itself &#8212; not in the HTML itself, but as one of the response headers that are sent before the HTML page.</p>
<p>This causes problems. Suppose you have a big web server with lots of sites and hundreds of pages contributed by lots of people in lots of different languages and all using whatever encoding their copy of Microsoft FrontPage saw fit to generate. The web server itself wouldn&#8217;t really <em>know</em> what encoding each file was written in, so it couldn&#8217;t send the Content-Type header.</p>
<p>It would be convenient if you could put the Content-Type of the HTML file right in the HTML file itself, using some kind of special tag. Of course this drove purists crazy&#8230; how can you <em>read</em> the HTML file until you know what encoding it&#8217;s in?! Luckily, almost every encoding in common use does the same thing with characters between 32 and 127, so you can always get this far on the HTML page without starting to use funny letters:</p>
<blockquote><p><strong>&lt;html&gt;<br />
&lt;head&gt;<br />
</strong><strong>&lt;meta http-equiv=&#8221;Content-Type&#8221; content=&#8221;text/html; charset=utf-8&#8243;&gt;</strong></p></blockquote>
<p>But that meta tag really has to be the very first thing in the &lt;head&gt; section because as soon as the web browser sees this tag it&#8217;s going to stop parsing the page and start over after reinterpreting the whole page using the encoding you specified.</p>
<p>What do web browsers do if they don&#8217;t find any Content-Type, either in the http headers or the meta tag? Internet Explorer actually does something quite interesting: it tries to guess, based on the frequency in which various bytes appear in typical text in typical encodings of various languages, what language and encoding was used. Because the various old 8 bit code pages tended to put their national letters in different ranges between 128 and 255, and because every human language has a different characteristic histogram of letter usage, this actually has a chance of working. It&#8217;s truly weird, but it does seem to work often enough that naïve web-page writers who never knew they needed a Content-Type header look at their page in a web browser and it <em>looks ok</em>, until one day, they write something that doesn&#8217;t exactly conform to the letter-frequency-distribution of their native language, and Internet Explorer decides it&#8217;s Korean and displays it thusly, proving, I think, the point that Postel&#8217;s Law about being &#8220;conservative in what you emit and liberal in what you accept&#8221; is quite frankly not a good engineering principle. Anyway, what does the poor reader of this website, which was written in Bulgarian but appears to be Korean (and not even cohesive Korean), do? He uses the View | Encoding menu and tries a bunch of different encodings (there are at least a dozen for Eastern European languages) until the picture comes in clearer. If he knew to do that, which most people don&#8217;t.</p>
<p align="center"><img src="http://www.joelonsoftware.com/pictures/unicode/rose.jpg" alt="" width="300" height="225" border="0" /></p>
<p>For the latest version of <a href="http://www.fogcreek.com/CityDesk">CityDesk</a>, the web site management software published by <a href="http://www.fogcreek.com/">my company</a>, we decided to do everything internally in UCS-2 (two byte) Unicode, which is what Visual Basic, COM, and Windows NT/2000/XP use as their native string type. In C++ code we just declare strings as <strong>wchar_t</strong> (&#8220;wide char&#8221;) instead of <strong>char</strong> and use the <strong>wcs</strong> functions instead of the <strong>str</strong> functions (for example <strong>wcscat</strong> and <strong>wcslen</strong> instead of <strong>strcat</strong> and <strong>strlen</strong>). To create a literal UCS-2 string in C code you just put an L before it as so: <strong>L&#8221;Hello&#8221;</strong>.</p>
<p>When CityDesk publishes the web page, it converts it to UTF-8 encoding, which has been well supported by web browsers for many years. That&#8217;s the way all <a href="http://www.joelonsoftware.com/navLinks/OtherLanguages.html">29 language versions</a> of <em>Joel on Software</em> are encoded and I have not yet heard a single person who has had any trouble viewing them.</p>
<p>This article is getting rather long, and I can&#8217;t possibly cover everything there is to know about character encodings and Unicode, but I hope that if you&#8217;ve read this far, you know enough to go back to programming, using antibiotics instead of leeches and spells, a task to which I will leave you now.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/498/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=498&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/05/10/absolutamente-tudo-sobre-charsets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/ibm.jpg" medium="image" />

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/ascii.png" medium="image">
			<media:title type="html">ASCII table</media:title>
		</media:content>

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/oem.png" medium="image" />

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/gimel.png" medium="image">
			<media:title type="html">ג</media:title>
		</media:content>

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/gimel.png" medium="image">
			<media:title type="html">ג</media:title>
		</media:content>

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/gimel.png" medium="image">
			<media:title type="html">ג</media:title>
		</media:content>

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/hummers.jpg" medium="image" />

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/utf8.png" medium="image">
			<media:title type="html">How UTF-8 works</media:title>
		</media:content>

		<media:content url="http://www.joelonsoftware.com/pictures/unicode/rose.jpg" medium="image" />
	</item>
		<item>
		<title>Ubuntu + Totem + MP3</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/05/04/ubuntu-totem-mp3/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/05/04/ubuntu-totem-mp3/#comments</comments>
		<pubDate>Thu, 05 May 2011 00:05:17 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[adiantar]]></category>
		<category><![CDATA[mp3]]></category>
		<category><![CDATA[retroceder]]></category>
		<category><![CDATA[totem]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=495</guid>
		<description><![CDATA[Assim que atualizei muito notebook para o Ubuntu 11.04 notei que somente no Totem, minhas músicas não avançavam e nem retrocediam na linha do tempo do tocador. Busquei suas propriedades e tudo mais e nada. Dei uma pesquisada e ví que o novo Ubuntu na sua atualização acaba apagando uns pacotes que ele diz ser [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=495&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Assim que atualizei muito notebook para o Ubuntu 11.04 notei que somente no Totem, minhas músicas não avançavam e nem retrocediam na linha do tempo do tocador.</p>
<p>Busquei suas propriedades e tudo mais e nada.</p>
<p>Dei uma pesquisada e ví que o novo Ubuntu na sua atualização acaba apagando uns pacotes que ele diz ser inúteis, mas são bem úteis sim.</p>
<p>Vá no menu de aplicativos -&gt; Central de Programas do Ubuntu</p>
<p>Lá em cima no canto superior direito na busca você digita apenas &#8220;Ubuntu&#8221;, estamos procurando por &#8220;Ubuntu restricted extras&#8221; que não passa de um monte de pacotes de compotentes protegidos por direitos autorais.</p>
<p>Assim que instalar você já consegue avançar e retroceder suas músicas.</p>
<p>Até mais.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/495/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/495/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/495/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/495/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/495/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/495/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/495/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/495/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=495&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/05/04/ubuntu-totem-mp3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Diquinhas bestas no Ubuntu &#8211; Numlock e Correção de Bateria</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/04/27/diquinhas-besta-no-ubuntu-numlock-e-correcao-de-bateria/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/04/27/diquinhas-besta-no-ubuntu-numlock-e-correcao-de-bateria/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 23:15:29 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Arch Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Slackware]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[bateria]]></category>
		<category><![CDATA[ligado]]></category>
		<category><![CDATA[notebook]]></category>
		<category><![CDATA[numlock]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=489</guid>
		<description><![CDATA[Estas duas dicas são muito bestas e nem compensa falar muito sobre elas, mas vamos lá. A primeira é o problema que 90% dos notebooks com Ubuntu instalado apresentem: quando você desconecta a bateria ele na hora fala que a energia está critica, que vai desligar e aí fica enxendo o saco também. E fica [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=489&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Estas duas dicas são muito bestas e nem compensa falar muito sobre elas, mas vamos lá.</p>
<p>A primeira é o problema que 90% dos notebooks com Ubuntu instalado apresentem: quando você desconecta a bateria ele na hora fala que a energia está critica, que vai desligar e aí fica enxendo o saco também. E fica desligando sua tela.</p>
<p>Essa é bem simples, no terminal digite</p>
<p><pre class="brush: plain;">

gconftool-2 --type bool --set /apps/gnome-power-manager/general/use_time_for_policy false

</pre></p>
<p>Bem simples, agora é capaz que esteja corrigido o problema.</p>
<p>O segundo parece beta, mas é a melhor. Estava de saco cheio de ligar o NumLock toda vez que o sistema reiniciava.</p>
<p>Então um simples</p>
<p><pre class="brush: plain;">

sudo apt-get install numlockx

</pre></p>
<p>Funciona</p>
<p>Para preguiçoso mesmo, né.</p>
<p>Ta aí.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/489/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/489/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/489/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/489/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/489/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/489/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/489/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/489/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=489&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/04/27/diquinhas-besta-no-ubuntu-numlock-e-correcao-de-bateria/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Remapeamento de Teclas no Ubuntu</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/04/24/remapeamento-de-teclas-no-ubuntu/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/04/24/remapeamento-de-teclas-no-ubuntu/#comments</comments>
		<pubDate>Sun, 24 Apr 2011 21:04:35 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Arch Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Slackware]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[apóstrofo]]></category>
		<category><![CDATA[aspas]]></category>
		<category><![CDATA[remapeamento]]></category>
		<category><![CDATA[teclas]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=486</guid>
		<description><![CDATA[Há um tempo instalei o Ubuntu 10.10 no meu notebook Toshiba Satellite A665 e há um tempo convivo com um problema safado no Layout do teclado. É um notebook americano, logo, sem o cedilha (ç), manja? Aí naquela seleção de padrão de teclado que o Ubuntu faz ele me deu o &#8220;EUA Internacional alternativo (antigo [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=486&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Há um tempo instalei o Ubuntu 10.10 no meu notebook Toshiba Satellite A665 e há um tempo convivo com um problema safado no Layout do teclado. É um notebook americano, logo, sem o cedilha (ç), manja?</p>
<p>Aí naquela seleção de padrão de teclado que o Ubuntu faz ele me deu o &#8220;EUA Internacional alternativo (antigo us_intl)&#8221;.</p>
<p>Beleza tudo bem com o cedilha, e tals, só que na tecla de acento, onde deveria ter a aspas duplas ele me dava uma aspinha pequena, meio feia, não sei exatamente o nome dela. Mas é bem simples distinguir, pois nos programas Java o compilador reclama.</p>
<p>Com este problema fui procurar um outro layout de teclado que resolvesse o meu problema, então encontrei o &#8220;EUA Internacional tecla morta (Alt GR)&#8221;. Este layout resolveu o problema da aspas duplas, só que ferrou com o cedilha que parou de funcionar. Fiquei um tempo convivendo com esta porcaria, só trocando de teclado quando eu ia desenvolver, até que enxeu o saco e daí saiu este post.</p>
<p>O Linux tem uma interessante função de mapeamento das teclas. Você pode fazer com que qualquer tecla do teclado tenha uma função definida por você, mesmo que não tenha nenhum sentido no layout padrão do teclado. Basta que utilize o comando <strong>xmodmap</strong>.</p>
<p>Vamos lá usar o meu problema como exemplo.</p>
<p>A primeira coisa a fazer é identificar o código da tecla que você está pressionando, para isto existe o programa <strong>xev</strong>. Abra o terminal e digite xev. Vai abrir um quadradinho preto e diversos códigos ficarão rolando na tela do terminal conforme você digita.</p>
<p>Veja:</p>
<p><pre class="brush: plain;">

KeyRelease event, serial 36, synthetic NO, window 0x4a00001,
root 0x15d, subw 0x0, time 1090414, (-410,293), root:(254,453),
state 0x10, &lt;strong&gt;keycode 36&lt;/strong&gt; (keysym 0xff0d, &lt;strong&gt;Return&lt;/strong&gt;), same_screen YES,
&quot;   XLookupString gives 1 bytes: (0d) &quot;
XFilterEvent returns: False

</pre></p>
<p>Atente para códigos com este padrão. Este código foi gerado ao pressionar a tecla <strong>enter</strong>. Em negrito os pontos importantes.</p>
<p>keycode 36: Representa o código da tecla pressionada</p>
<p>Return: Representa a função da tecla pressionada</p>
<p>Como eu disse no meu caso eu queria na mesma tecla (48, tecla da aspas e do acento agudo) adicionar funções de dois layouts diferentes do Ubuntu. Então eu mudeu para o layout de tecla morta (que possuí as aspas duplas) e usando o xev obtive os códigos abaixo descritos ao pressionar shift e aspas duplas.</p>
<p>Código: <strong>keycode 48</strong></p>
<p>Função: <strong>quotedbl</strong></p>
<p>Voltei o layout do teclado do Ubuntu para o que possuí o cedilha e obtive este código ao pressionar o botão do acento agudo (sem o shift)</p>
<p>Código: <strong>keycode 48</strong></p>
<p>Função: <strong>dead_acute</strong></p>
<p>Agora vem a parte simples, é só rodar o seguinte comando:</p>
<p><strong>xmodmap -e &#8220;keycode 48 = dead_acute quotedbl&#8221;</strong></p>
<p>Entre as aspas duplas é onde está a parte importante.</p>
<p>Você indica para a tecla número 48 as funções de dead_acute, que seria o meu acento agudo, e o quotedbl que seria as aspas duplas. Esta sequencia é importante, pois a primeira função indica o que eu quero que a tecla faça quando pressionada sem o shift, a segunda é ao pressionar com o shift.</p>
<p>Sacou?</p>
<p>Simples assim.</p>
<p>É só executar este comando que já está tudo legal, só tem um problema, ao reiniciar a máquina para de funcionar. Então dentro da sua pasta home você cria um arquivo chamado <strong>.xmodmaprc</strong>, com o seguinte conteúdo:</p>
<p>keycode 48 = dead_acute quotedbl</p>
<p>Simples assim.</p>
<p>Ao reiniciar o gnome, vai perguntar se você deseja carregar este arquivo, você diz que sim e já era, agora suas teclas estão mapeadas do jeito que você deseja.</p>
<p>Até mais</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/486/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/486/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/486/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/486/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/486/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/486/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/486/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/486/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=486&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/04/24/remapeamento-de-teclas-no-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Dropbox e Linux &#8211; Can´t Sync Permission Denied</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/03/13/dropbox-e-linux-can%c2%b4t-sync-permission-denied/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/03/13/dropbox-e-linux-can%c2%b4t-sync-permission-denied/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 00:16:33 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Arch Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Slackware]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[cant]]></category>
		<category><![CDATA[denied]]></category>
		<category><![CDATA[dropbox]]></category>
		<category><![CDATA[permission]]></category>
		<category><![CDATA[sync]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=483</guid>
		<description><![CDATA[Rapidamente aos que não conhecem o Drobox lhes adianto que é uma fantástica ferramente FREE para sincronização de dados na Web entre as diversos computadores que você tem contato. Apenas para lhes contextualizar tenho o Drobox no trabalho em um Windows 7 e em casa em um Ubuntu 10.10. Importante lembrar que o Drobox de [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=483&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Rapidamente aos que não conhecem o Drobox lhes adianto que é uma fantástica ferramente FREE para sincronização de dados na Web entre as diversos computadores que você tem contato.</p>
<p>Apenas para lhes contextualizar tenho o Drobox no trabalho em um Windows 7 e em casa em um Ubuntu 10.10.</p>
<p>Importante lembrar que o Drobox de casa está em uma partição diferente da do sistema, partição esta que é NTFS. Isto é assim por que também tenho um Windows 7 em casa que nunca utilizo.</p>
<p>Recentemente formatei meu Ubuntu e ao instalar o Drobox recebi a fatídica mensagem de Can`t Sync, Permission Denied. Aí fiz o básico, um simples e irresponsável: chmod ugo=rwx -R /Dropbox</p>
<p>É eu liberei todos os direitos porque estava com pressa <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>E o pior é que não funcionou, aí dei uma pesquisada na internet e ví que no próprio forum da Dropbox o pessoal não entrava em um consenso. Teve gente mando desinstalar e instalar novamente, fazer um chown da pasta para o nome do seu usuário e outros disseram para colocar a pasta do Dropbox dentro da sua home.</p>
<p>Tirando a última gambiarra&#8230;ops solução, as outras não funcionavam mesmo, o pior é que o pessoal não lembrou do mais simples.</p>
<p>Uma partição NTFS no ambiente Linux dependendo da forma e dos direitos que é montada no fstab não permite chmod nem chown, aí não funciona mesmo e o pior dependendo dos direitos não permite que o daemon Dropbox coloque seus arquivos lá.</p>
<p>Então simples assim você vai em /etc/fstab e monta a sua partição NTFS com direitos de edição assim:</p>
<p>/dev/sda5     /media/Volume     ntfs-3g defaults,locale=pt_BR.utf8 0 0</p>
<p>Reinicia e vai estar lá um Dropbox novinho em folha.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/483/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/483/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/483/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/483/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/483/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/483/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/483/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/483/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=483&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/03/13/dropbox-e-linux-can%c2%b4t-sync-permission-denied/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
		<item>
		<title>Problemas com Encoding, Maven e Netbeans</title>
		<link>http://pobrecomputeiro.wordpress.com/2011/02/23/problemas-com-encoding-maven-e-netbeans/</link>
		<comments>http://pobrecomputeiro.wordpress.com/2011/02/23/problemas-com-encoding-maven-e-netbeans/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 01:14:01 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[encoding]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[problemas]]></category>

		<guid isPermaLink="false">http://pobrecomputeiro.wordpress.com/?p=480</guid>
		<description><![CDATA[Encoding é uma zica que atormenta todo e qualquer desenvolvedor. Se ele ainda tenta desenvolver em dois ambientes, Windows e Linux aí que o desespero aumenta. Meu cenário é que no trabalho desenvolvo em Windows, codificação ISO-8859-1. Em casa tenho o Ubuntu e o UTF-8. Então começa a briga. Desenvolvo no trabalho, chego em casa [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=480&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Encoding é uma zica que atormenta todo e qualquer desenvolvedor. Se ele ainda tenta desenvolver em dois ambientes, Windows e Linux aí que o desespero aumenta.</p>
<p>Meu cenário é que no trabalho desenvolvo em Windows, codificação ISO-8859-1.</p>
<p>Em casa tenho o Ubuntu e o UTF-8.</p>
<p>Então começa a briga. Desenvolvo no trabalho, chego em casa e recebo o fatídico:<strong> unmappable character for encoding UTF8</strong>. Além de é claro todos os acentos estarem completamente destruídos. A primeira coisa para corrigir o projeto inteiro é alterar a codificação em que o mesmo está sendo desenvolvido, e isto fazemos no Maven, é claro.</p>
<p>No pom, é legal que sua área de properties fique mais ou menos desta forma</p>
<p><pre class="brush: plain;">

&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;ISO-8859-1&lt;/project.build.sourceEncoding&gt;
&lt;project.reporting.outputEncoding&gt;ISO-8859-1&lt;/project.reporting.outputEncoding&gt;
&lt;/properties&gt;

</pre></p>
<p>A partir deste momento os arquivos de fonte do seu projeto no netbeans estarão corrigidos, mas é provável que  após uma limpeza e construção você veja que o problema de <strong>unmappable character for encoding UTF8</strong> continua.</p>
<p>Isto é por que seu netbeans por default compila os arquivos em UTF-8, e você acabou de configurar seu projeto para ISO-8859-1.</p>
<p>Então vá onde seu netbeans está instalado, no arquivo <strong>/etc/netbeans.conf</strong> e adicione o código <strong>&#8220;-J-Dfile.encoding=UTF-8&#8243; </strong>dentro da opção <strong>netbeans_default_options</strong>.</p>
<p>Então é só abrir e fechar o netbeans e está tudo ao normal.</p>
<p>O meu ficou assim:</p>
<p><strong>netbeans_default_options=&#8221;-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dfile.encoding=UTF-8&#8243;</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pobrecomputeiro.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pobrecomputeiro.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pobrecomputeiro.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pobrecomputeiro.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pobrecomputeiro.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pobrecomputeiro.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pobrecomputeiro.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pobrecomputeiro.wordpress.com/480/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pobrecomputeiro.wordpress.com&amp;blog=4959545&amp;post=480&amp;subd=pobrecomputeiro&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pobrecomputeiro.wordpress.com/2011/02/23/problemas-com-encoding-maven-e-netbeans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Leonardo</media:title>
		</media:content>
	</item>
	</channel>
</rss>
