26
Bizus em Java Bibliotecas que todos devem saber Rodrigo Barbosa - Desenvolvedor líder no Guichê Virtual Twitter: @digao_barbosa Email: [email protected]

Jug bizus

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Jug   bizus

Bizus em JavaBibliotecas que todos devem saber

Rodrigo Barbosa - Desenvolvedor líder no Guichê VirtualTwitter: @digao_barbosaEmail: [email protected]

Page 2: Jug   bizus

Objetivo● Público iniciante

● Aumentar produtividade

● Evitar duplicação de código

● Solução de Problemas comuns

Page 3: Jug   bizus

Fonte

Page 4: Jug   bizus

1. Lendo arquivo - commons-iopublic 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(); }

}}

Page 5: Jug   bizus

Lendo arquivo commons-io para o resgatepublic 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(); } }}

Page 6: Jug   bizus

Outras utilidadesIOUtils.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"); }

Page 7: Jug   bizus

commons-io ... e ainda tem● FileUtils.copyDirectory● FileUtils.copyFile● IOUtils.copyLarge● IOUtils.readLines● FileUtils.checksum● FileUtils.contentEquals

Page 8: Jug   bizus

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);}

Page 9: Jug   bizus

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'); }

Page 10: Jug   bizus

3. Lidando com Strings - apache-common-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 }

Page 11: Jug   bizus

4. Trabalhando com Reflection - bean-utils● Lendo uma propriedade simplesString value = (String) PropertyUtils.getSimpleProperty(person, "name");

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

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

● Todas as anterioresString java2 = (String) PropertyUtils.getProperty(person,"skill.name");

Page 12: Jug   bizus

bean-utils mais exemplos● Escrevendo uma propriedadePropertyUtils.setProperty(person,"skill.name","java");

● Copiando propriedadesPropertyUtils.copyProperties(copia,original);

● Mapa a partir de objeto Map personMap = PropertyUtils.describe(person);// gera um mapa

Page 13: Jug   bizus

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

Page 14: Jug   bizus

Trabalhando com Datas - commons-lang● DateUtils

○ isSameDay

○ addDays, addHours, addMinutes

○ parseDate

● DateFormatUtils○ format

Page 15: Jug   bizus

Trabalhando com Datas - joda time● Biblioteca completa de datas

● Será nativa do Java 8

● Novos conceitos: Data, horário, intervalo○ LocalTime, LocalDate,LocalDateTime, Interval

Page 16: Jug   bizus

6. CacheProblema de performance - que tal um cache?

Page 17: Jug   bizus

Eu quero também

● Para hibernate, pode usar ehcache

● Para Spring, alguns XMLs de configuração e @Cacheable

● Para outros casos, Guava pode ajudar

Page 18: Jug   bizus

Guava● Collections● Strings● Concorrencia● E cache

Page 19: Jug   bizus

Guava - cache● Simples de fazer

● Evita erros comuns

● Dá estatísticas do cache

● Diversas modalidades

Page 20: Jug   bizus

Cache como um mapaConstruindo 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());

Page 21: Jug   bizus

Cache com LoaderConstruindo um CacheCache<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); } });

UtilizandoPerson papito = cache.get("papito");

System.out.println(cache.stats().hitRate());

Page 22: Jug   bizus

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

Page 23: Jug   bizus

Cansei de getters e setters - Qual o melhor?@Datapublic 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; }

public Date getBirthDate() { return birthDate; }

public void setBirthDate(Date birthDate) { this.birthDate = birthDate; }}

Page 24: Jug   bizus

Cansei de getters e setters - Lombok

● @Data● @Getter● @Setter● @ToString● @EqualsAndHashC

ode

Lombok

Page 25: Jug   bizus

Outros bizús● imgscalr - Resize fácil (e rápido) de imagenshttps://github.com/thebuzzmedia/imgscalr● granule - minimização de css/jshttps://code.google.com/p/granule/● XStream - Serialização e deserialização de

XML fácilhttp://xstream.codehaus.org/