Transcript
Bizus em JavaBibliotecas que todos devem saber
Rodrigo Barbosa - Desenvolvedor líder no Guichê VirtualTwitter: @digao_barbosaEmail: 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-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(); }
}}
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(); } }}
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"); }
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 - 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 }
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");
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
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. CacheProblema 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 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());
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());
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?@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; }}
Cansei de getters e setters - Lombok
● @Data● @Getter● @Setter● @ToString● @EqualsAndHashC
ode
Lombok
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/
Referências● A fonte principal: http://pt.scribd.
com/doc/16065335/The-Common-Java-Cookbook
● Guava https://code.google.com/p/guava-libraries/
top related