Prevented possible NullPointerException's
[jpa-converters] / src / main / java / de / juplo / jpa / converters / URLConverter.java
1 package de.juplo.jpa.converters;
2
3 import java.net.MalformedURLException;
4 import java.net.URI;
5 import java.net.URISyntaxException;
6 import java.net.URL;
7 import javax.persistence.AttributeConverter;
8 import javax.persistence.Converter;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11
12
13 /**
14  * Converts an {@link URL} to an ASCII-representation using the class
15  * {@link URI}.
16  * <p>
17  * If the {@link URL} cannot be converted to an {@link URI}, an
18  * {@link IllegalArgumentException} is thrown.
19  * @author Kai Moritz
20  */
21 @Converter(autoApply = true)
22 public class URLConverter implements AttributeConverter<URL, String>
23 {
24   private final static Logger log = LoggerFactory.getLogger(URLConverter.class);
25
26
27   @Override
28   public String convertToDatabaseColumn(URL url)
29   {
30     if (url == null)
31       return null;
32     try
33     {
34       return url.toURI().toASCIIString();
35     }
36     catch (URISyntaxException e)
37     {
38       log.error("Cannot convert invalid URL \"{}\" to ASCII-string: {}", url, e.getMessage());
39       throw new IllegalArgumentException(e);
40     }
41   }
42
43   @Override
44   public URL convertToEntityAttribute(String string)
45   {
46     if (string == null)
47       return null;
48     try
49     {
50       return URI.create(string).toURL();
51     }
52     catch (MalformedURLException e)
53     {
54       log.error("Cannot convert invalid string \"{}\" to URL: {}", string, e.getMessage());
55       throw new IllegalArgumentException(e);
56     }
57   }
58 }