From 5e61f8949e63fb35ad7de8e927600ffaf0b617c8 Mon Sep 17 00:00:00 2001 From: Kai Moritz Date: Mon, 21 Dec 2015 20:54:48 +0100 Subject: [PATCH] Implemented an URL-to-String converter --- .../de/juplo/jpa/converters/URLConverter.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/de/juplo/jpa/converters/URLConverter.java diff --git a/src/main/java/de/juplo/jpa/converters/URLConverter.java b/src/main/java/de/juplo/jpa/converters/URLConverter.java new file mode 100644 index 0000000..9fe0c0e --- /dev/null +++ b/src/main/java/de/juplo/jpa/converters/URLConverter.java @@ -0,0 +1,54 @@ +package de.juplo.jpa.converters; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Converts an {@link URL} to an ASCII-representation using the class + * {@link URI}. + *

+ * If the {@link URL} cannot be converted to an {@link URI}, an + * {@link IllegalArgumentException} is thrown. + * @author Kai Moritz + */ +@Converter(autoApply = true) +public class URLConverter implements AttributeConverter +{ + private final static Logger log = LoggerFactory.getLogger(URLConverter.class); + + + @Override + public String convertToDatabaseColumn(URL url) + { + try + { + return url.toURI().toASCIIString(); + } + catch (URISyntaxException e) + { + log.error("Cannot convert invalid URL \"{}\" to ASCII-string: {}", url, e.getMessage()); + throw new IllegalArgumentException(e); + } + } + + @Override + public URL convertToEntityAttribute(String string) + { + try + { + return URI.create(string).toURL(); + } + catch (MalformedURLException e) + { + log.error("Cannot convert invalid string \"{}\" to URL: {}", string, e.getMessage()); + throw new IllegalArgumentException(e); + } + } +} -- 2.20.1