1 14 package com.sun.facelets.util; 15 16 import java.io.FileNotFoundException ; 17 import java.io.IOException ; 18 import java.io.InputStream ; 19 import java.net.MalformedURLException ; 20 import java.net.URL ; 21 import java.net.URLConnection ; 22 import java.net.URLStreamHandler ; 23 import java.util.logging.Level ; 24 import java.util.logging.Logger ; 25 26 import javax.faces.context.ExternalContext; 27 import javax.faces.context.FacesContext; 28 import javax.servlet.ServletContext ; 29 30 34 public final class Resource { 35 36 protected final static Logger log = Logger.getLogger("facelets.factory"); 37 38 57 public static URL getResourceUrl(FacesContext ctx, String path) 58 throws MalformedURLException { 59 final ExternalContext externalContext = ctx.getExternalContext(); 60 URL url = externalContext.getResource(path); 61 if (log.isLoggable(Level.FINE)) { 62 log.fine("Resource-Url from external context: " + url); 63 } 64 if (url == null) { 65 if (resourceExist(externalContext, path)) { 73 url = getUrlForResourceAsStream(externalContext, path); 74 } 75 } 76 return url; 77 } 78 79 private static boolean resourceExist(ExternalContext externalContext, 83 String path) { 84 if ("/".equals(path)) { 85 return true; 87 } 88 Object ctx = externalContext.getContext(); 89 if (ctx instanceof ServletContext ) { 90 ServletContext servletContext = (ServletContext ) ctx; 91 InputStream stream = servletContext.getResourceAsStream(path); 92 if (stream != null) { 93 try { 94 stream.close(); 95 } catch (IOException e) { 96 } 99 return true; 100 } 101 } 102 return false; 103 } 104 105 private static URL getUrlForResourceAsStream( 108 final ExternalContext externalContext, String path) 109 throws MalformedURLException { 110 URLStreamHandler handler = new URLStreamHandler () { 111 protected URLConnection openConnection(URL u) throws IOException { 112 final String file = u.getFile(); 113 return new URLConnection (u) { 114 public void connect() throws IOException { 115 } 116 117 public InputStream getInputStream() throws IOException { 118 if (log.isLoggable(Level.FINE)) { 119 log.fine("Opening internal url to " + file); 120 } 121 Object ctx = externalContext.getContext(); 122 126 if (ctx instanceof ServletContext ) { 127 ServletContext servletContext = (ServletContext ) ctx; 128 InputStream stream = servletContext 129 .getResourceAsStream(file); 130 if (stream == null) { 131 throw new FileNotFoundException ( 132 "Cannot open resource " + file); 133 } 134 return stream; 135 } else { 136 throw new IOException ( 137 "Cannot open resource for an context of " 138 + (ctx != null ? ctx.getClass() 139 : null)); 140 } 141 } 142 }; 143 } 144 }; 145 return new URL ("internal", null, 0, path, handler); 146 } 147 } 148 | Popular Tags |