Implemented an URL-to-String converter
authorKai Moritz <kai@juplo.de>
Mon, 21 Dec 2015 19:54:48 +0000 (20:54 +0100)
committerKai Moritz <kai@juplo.de>
Mon, 21 Dec 2015 19:54:48 +0000 (20:54 +0100)
src/main/java/de/juplo/jpa/converters/URLConverter.java [new file with mode: 0644]

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 (file)
index 0000000..9fe0c0e
--- /dev/null
@@ -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}.
+ * <p>
+ * 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<URL, String>
+{
+  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);
+    }
+  }
+}