O documento apresenta 6 bibliotecas Java úteis: 1) commons-io para leitura e escrita de arquivos, 2) apache-commons-lang para geração de tokens e manipulação de strings, 3) bean-utils para reflexão em objetos, 4) joda-time para trabalhar com datas, 5) Guava para implementar cache e 6) Lombok para gerar automaticamente getters e setters.
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 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();
}
}
}
6. 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");
}
7. commons-io ... e ainda 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 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');
}
10. 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
}
11. 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");
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 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
14. Trabalhando com Datas commons-lang
● DateUtils
○ isSameDay
○ addDays, addHours, addMinutes
○ parseDate
● DateFormatUtils
○ format
15. Trabalhando com Datas joda time
● Biblioteca completa de datas
● Será nativa do Java 8
● Novos conceitos: Data, horário, intervalo
○ LocalTime, LocalDate,LocalDateTime, Interval
19. Guava - cache
● Simples de fazer
● Evita erros comuns
● Dá estatísticas do cache
● Diversas modalidades
20. 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());
21. 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());
22. 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
23. 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;
24. Cansei de getters e 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/