Implemented an URL-to-String converter
[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     try
31     {
32       return url.toURI().toASCIIString();
33     }
34     catch (URISyntaxException e)
35     {
36       log.error("Cannot convert invalid URL \"{}\" to ASCII-string: {}", url, e.getMessage());
37       throw new IllegalArgumentException(e);
38     }
39   }
40
41   @Override
42   public URL convertToEntityAttribute(String string)
43   {
44     try
45     {
46       return URI.create(string).toURL();
47     }
48     catch (MalformedURLException e)
49     {
50       log.error("Cannot convert invalid string \"{}\" to URL: {}", string, e.getMessage());
51       throw new IllegalArgumentException(e);
52     }
53   }
54 }