From: Kai Moritz Date: Mon, 21 Dec 2015 19:54:48 +0000 (+0100) Subject: Implemented an URL-to-String converter X-Git-Tag: jpa-converters-1.0.0~30 X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=5e61f8949e63fb35ad7de8e927600ffaf0b617c8;p=jpa-converters Implemented an URL-to-String converter --- 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); + } + } +}