Bizus em Java
Bibliotecas que todos devem saber
Rodrigo Barbosa - Desenvolvedor líder no Guichê Virtual
Twitter: @digao_barbosa
Email: rodrigo@guichevirtual.com.br
Objetivo
● Público iniciante
● Aumentar produtividade
● Evitar duplicação de código
● Solução de Problemas comuns
Fonte
1. Lendo arquivo - commons-io
public class ReadFile {
public static void main(String [] a) throws IOException {
BufferedReader br=null;
try{
br= new BufferedReader(new FileReader("test.txt"));
String currentLine =null;
while((currentLine=br.readLine())!=null){
System.out.println(currentLine);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(br!=null)
br.close();
}

}
}
Lendo arquivo
commons-io para o resgate
public class ReadFileUtil {
public static void main(String[] a) {
try {
String s = FileUtils.readFileToString(new File("test.txt"));
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Outras utilidades
IOUtils.toString
public static void main(String[] a) throws IOException, URISyntaxException {
String text = IOUtils.toString(new FileInputStream("test.txt"));
String text2 = IOUtils.toString(new URI("http://www.guichevirtual.com.br"));
byte[] bytes = IOUtils.toByteArray(new FileInputStream("test.jug"));
}

FileUtils.write
public static void main(String[] a) throws IOException, URISyntaxException {
FileUtils.write(new File("test.txt"),"Bem vindos ao JUG Vale");
}
commons-io ... e ainda tem
●
●
●
●
●
●

FileUtils.copyDirectory
FileUtils.copyFile
IOUtils.copyLarge
IOUtils.readLines
FileUtils.checksum
FileUtils.contentEquals
2. Gerando tokens - apache-commons-lang
●

Usando API da JDK

public static String generateString(Random rng, String characters,
int length)
{
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
De novo a apache nos ajuda
RandomStringUtils - apache commons lang
public static void main(String[] a) throws IOException, URISyntaxException {
String random = RandomStringUtils.random(10, true, true);
String random2 = RandomStringUtils.random(10, 'a', 'b', 'c', 'd', 'e');
}
3. Lidando com Strings - apachecommon-lang
Pra variar, apache commons lang
public static void main(String [] a){
String str="jug vale ";
StringUtils.isBlank(str);//false
StringUtils.abbreviate(str,6);//jug...
StringUtils.capitalize(str);//Jug vale
StringUtils.trim(" abc ");//"abc"
StringUtils.difference("abc","abcde");//"de"
StringUtils.getLevenshteinDistance("abc","abcde");//2
StringUtils.getLevenshteinDistance("abc","abc");//0
StringUtils.getLevenshteinDistance("frog","fog");//1
StringUtils.getLevenshteinDistance("frog","flog");//1
}
4. Trabalhando com Reflection bean-utils
● Lendo uma propriedade simples
String value = (String) PropertyUtils.getSimpleProperty(person, "name");

● Lendo uma propriedade aninhada
String java1 = (String) PropertyUtils.getNestedProperty(person,"skill.name");

● Lendo uma propriedade indexada
String telepone = (String) PropertyUtils.getIndexedProperty(person,"telephones",0);

● Todas as anteriores
String java2 = (String) PropertyUtils.getProperty(person,"skill.name");
bean-utils mais exemplos
● Escrevendo uma propriedade
PropertyUtils.setProperty(person,"skill.name","java");

● Copiando propriedades
PropertyUtils.copyProperties(copia,original);

● Mapa a partir de objeto
Map personMap = PropertyUtils.describe(person);// gera um mapa
5. Trabalhando com Datas
● java.util.Date é zoado
● java.util.Calendar é um pouco menos zoado
● Date é mutável, pode causar problemas
● Difícil de fazer operações
Trabalhando com Datas commons-lang
● DateUtils
○ isSameDay
○ addDays, addHours, addMinutes
○ parseDate

● DateFormatUtils
○ format
Trabalhando com Datas joda time
● Biblioteca completa de datas
● Será nativa do Java 8
● Novos conceitos: Data, horário, intervalo
○ LocalTime, LocalDate,LocalDateTime, Interval
6. Cache
Problema de performance - que tal um cache?
Eu quero também
● Para hibernate, pode usar ehcache
● Para Spring, alguns XMLs de configuração e
@Cacheable
● Para outros casos, Guava pode ajudar
Guava
●
●
●
●

Collections
Strings
Concorrencia
E cache
Guava - cache
● Simples de fazer
● Evita erros comuns
● Dá estatísticas do cache
● Diversas modalidades
Cache como um mapa
Construindo um
Cache
Cache<String,Person> cache = CacheBuilder.
newBuilder()
.maximumSize(1000)
.expireAfterWrite(5,TimeUnit.MINUTES)
.build();

Utilizando (como um
mapa)

cache.put("papito",findByName("supla"));
cache.put("raulzito",findByName("Raul Seixas"));
Person papito = cache.get("papito");
System.out.println(cache.stats().hitRate());
System.out.println(cache.stats().hitCount());
Cache com Loader
Construindo um Cache
Cache<String,Person> autoCache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build(new CacheLoader<String, Person>() {
@Override
public Person load(String key) throws Exception {
return findByName(key);
}
});

Utilizando
Person papito = cache.get("papito");
System.out.println(cache.stats().hitRate());
7. Cansei de getters e setters
● Muito código sem importância
● Difícil achar o que realmente importa
● Dá trabalho, mesmo com generate do
eclipse
● Possível de erros
Cansei de getters e setters - Qual o melhor?
@Data
public class Person {
private Long id;
private String name;
private String address;
private String telephone;
private String email;
private Date birthDate;
}

public class Person {
private Long id;
private String name;
private String address;
private String telephone;
private String email;
private Date birthDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
Cansei de getters e setters - Lombok
●
●
●
●
●

@Data
Lombok
@Getter
@Setter
@ToString
@EqualsAndHashC
ode
Outros bizús
● imgscalr - Resize fácil (e rápido) de imagens
https://github.com/thebuzzmedia/imgscalr
● granule - minimização de css/js
https://code.google.com/p/granule/
● XStream - Serialização e deserialização de
XML fácil
http://xstream.codehaus.org/
Referências
● A fonte principal: http://pt.scribd.
com/doc/16065335/The-Common-JavaCookbook
● Guava https://code.google.com/p/guavalibraries/

Jug bizus (4)

  • 1.
    Bizus em Java Bibliotecasque todos devem saber Rodrigo Barbosa - Desenvolvedor líder no Guichê Virtual Twitter: @digao_barbosa Email: [email protected]
  • 2.
    Objetivo ● Público iniciante ●Aumentar produtividade ● Evitar duplicação de código ● Solução de Problemas comuns
  • 3.
  • 4.
    1. Lendo arquivo- commons-io public class ReadFile { public static void main(String [] a) throws IOException { BufferedReader br=null; try{ br= new BufferedReader(new FileReader("test.txt")); String currentLine =null; while((currentLine=br.readLine())!=null){ System.out.println(currentLine); } }catch (Exception e){ e.printStackTrace(); }finally { if(br!=null) br.close(); } } }
  • 5.
    Lendo arquivo commons-io parao resgate public class ReadFileUtil { public static void main(String[] a) { try { String s = FileUtils.readFileToString(new File("test.txt")); System.out.println(s); } catch (IOException e) { e.printStackTrace(); } } }
  • 6.
    Outras utilidades IOUtils.toString public staticvoid main(String[] a) throws IOException, URISyntaxException { String text = IOUtils.toString(new FileInputStream("test.txt")); String text2 = IOUtils.toString(new URI("http://www.guichevirtual.com.br")); byte[] bytes = IOUtils.toByteArray(new FileInputStream("test.jug")); } FileUtils.write public static void main(String[] a) throws IOException, URISyntaxException { FileUtils.write(new File("test.txt"),"Bem vindos ao JUG Vale"); }
  • 7.
    commons-io ... eainda tem ● ● ● ● ● ● FileUtils.copyDirectory FileUtils.copyFile IOUtils.copyLarge IOUtils.readLines FileUtils.checksum FileUtils.contentEquals
  • 8.
    2. Gerando tokens- apache-commons-lang ● Usando API da JDK public static String generateString(Random rng, String characters, int length) { char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); }
  • 9.
    De novo aapache nos ajuda RandomStringUtils - apache commons lang public static void main(String[] a) throws IOException, URISyntaxException { String random = RandomStringUtils.random(10, true, true); String random2 = RandomStringUtils.random(10, 'a', 'b', 'c', 'd', 'e'); }
  • 10.
    3. Lidando comStrings - apachecommon-lang Pra variar, apache commons lang public static void main(String [] a){ String str="jug vale "; StringUtils.isBlank(str);//false StringUtils.abbreviate(str,6);//jug... StringUtils.capitalize(str);//Jug vale StringUtils.trim(" abc ");//"abc" StringUtils.difference("abc","abcde");//"de" StringUtils.getLevenshteinDistance("abc","abcde");//2 StringUtils.getLevenshteinDistance("abc","abc");//0 StringUtils.getLevenshteinDistance("frog","fog");//1 StringUtils.getLevenshteinDistance("frog","flog");//1 }
  • 11.
    4. Trabalhando comReflection bean-utils ● Lendo uma propriedade simples String value = (String) PropertyUtils.getSimpleProperty(person, "name"); ● Lendo uma propriedade aninhada String java1 = (String) PropertyUtils.getNestedProperty(person,"skill.name"); ● Lendo uma propriedade indexada String telepone = (String) PropertyUtils.getIndexedProperty(person,"telephones",0); ● Todas as anteriores String java2 = (String) PropertyUtils.getProperty(person,"skill.name");
  • 12.
    bean-utils mais exemplos ●Escrevendo uma propriedade PropertyUtils.setProperty(person,"skill.name","java"); ● Copiando propriedades PropertyUtils.copyProperties(copia,original); ● Mapa a partir de objeto Map personMap = PropertyUtils.describe(person);// gera um mapa
  • 13.
    5. Trabalhando comDatas ● java.util.Date é zoado ● java.util.Calendar é um pouco menos zoado ● Date é mutável, pode causar problemas ● Difícil de fazer operações
  • 14.
    Trabalhando com Datascommons-lang ● DateUtils ○ isSameDay ○ addDays, addHours, addMinutes ○ parseDate ● DateFormatUtils ○ format
  • 15.
    Trabalhando com Datasjoda time ● Biblioteca completa de datas ● Será nativa do Java 8 ● Novos conceitos: Data, horário, intervalo ○ LocalTime, LocalDate,LocalDateTime, Interval
  • 16.
    6. Cache Problema deperformance - que tal um cache?
  • 17.
    Eu quero também ●Para hibernate, pode usar ehcache ● Para Spring, alguns XMLs de configuração e @Cacheable ● Para outros casos, Guava pode ajudar
  • 18.
  • 19.
    Guava - cache ●Simples de fazer ● Evita erros comuns ● Dá estatísticas do cache ● Diversas modalidades
  • 20.
    Cache como ummapa Construindo um Cache Cache<String,Person> cache = CacheBuilder. newBuilder() .maximumSize(1000) .expireAfterWrite(5,TimeUnit.MINUTES) .build(); Utilizando (como um mapa) cache.put("papito",findByName("supla")); cache.put("raulzito",findByName("Raul Seixas")); Person papito = cache.get("papito"); System.out.println(cache.stats().hitRate()); System.out.println(cache.stats().hitCount());
  • 21.
    Cache com Loader Construindoum Cache Cache<String,Person> autoCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(5, TimeUnit.MINUTES) .build(new CacheLoader<String, Person>() { @Override public Person load(String key) throws Exception { return findByName(key); } }); Utilizando Person papito = cache.get("papito"); System.out.println(cache.stats().hitRate());
  • 22.
    7. Cansei degetters e setters ● Muito código sem importância ● Difícil achar o que realmente importa ● Dá trabalho, mesmo com generate do eclipse ● Possível de erros
  • 23.
    Cansei de getterse setters - Qual o melhor? @Data public class Person { private Long id; private String name; private String address; private String telephone; private String email; private Date birthDate; } public class Person { private Long id; private String name; private String address; private String telephone; private String email; private Date birthDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email;
  • 24.
    Cansei de getterse setters - Lombok ● ● ● ● ● @Data Lombok @Getter @Setter @ToString @EqualsAndHashC ode
  • 25.
    Outros bizús ● imgscalr- Resize fácil (e rápido) de imagens https://github.com/thebuzzmedia/imgscalr ● granule - minimização de css/js https://code.google.com/p/granule/ ● XStream - Serialização e deserialização de XML fácil http://xstream.codehaus.org/
  • 26.
    Referências ● A fonteprincipal: http://pt.scribd. com/doc/16065335/The-Common-JavaCookbook ● Guava https://code.google.com/p/guavalibraries/