1 16 package scriptella.configuration; 17 18 import scriptella.spi.Resource; 19 import scriptella.util.IOUtils; 20 21 import java.io.IOException ; 22 import java.io.Reader ; 23 import java.net.MalformedURLException ; 24 import java.net.URL ; 25 import java.nio.charset.Charset ; 26 import java.util.logging.Level ; 27 import java.util.logging.Logger ; 28 29 30 36 public class IncludeEl extends XmlConfigurableBase implements Resource { 37 private URL url; 38 private String href; 39 private String charset; 40 private static final Logger LOG = Logger.getLogger(IncludeEl.class.getName()); 41 private FallbackEl fallbackEl; 42 43 public IncludeEl(XmlElement element) { 44 configure(element); 45 } 46 47 public String getHref() { 48 return href; 49 } 50 51 public void setHref(final String href) { 52 this.href = href; 53 } 54 55 public String getCharset() { 56 return charset; 57 } 58 59 public void setCharset(final String charset) { 60 this.charset = charset; 61 } 62 63 public FallbackEl getFallbackEl() { 64 return fallbackEl; 65 } 66 67 public void setFallbackEl(FallbackEl fallbackEl) { 68 this.fallbackEl = fallbackEl; 69 } 70 71 public void configure(final XmlElement element) { 72 url = element.getDocumentUrl(); 73 setRequiredProperty(element, "href"); 74 75 String enc = element.getAttribute("encoding"); 76 if (enc != null && !Charset.isSupported(enc)) { 77 throw new ConfigurationException("Encoding " + enc + " is not supported", element); 78 } 79 charset = enc; 80 final XmlElement fallbackElement = element.getChild("fallback"); 81 if (fallbackElement != null) { 82 fallbackEl = new FallbackEl(fallbackElement); 83 } 84 } 85 86 public Reader open() throws IOException { 87 try { 88 URL u = new URL (url, href); 89 return IOUtils.getReader(u.openStream(), charset); 90 } catch (MalformedURLException e) { 91 throw (IOException ) new IOException ("Malformed include url: " + href).initCause(e); 92 } catch (IOException e) { 93 if (fallbackEl != null) { 94 LOG.log(Level.FINE, e.getMessage()); 95 return fallbackEl.open(); 96 } else { 97 throw e; 98 } 99 } 100 } 101 } 102 | Popular Tags |