1 24 package org.ofbiz.base.util; 25 26 import java.io.File ; 27 import java.net.MalformedURLException ; 28 import java.net.URL ; 29 30 37 public class UtilURL { 38 39 public static final String module = UtilURL.class.getName(); 40 41 public static URL fromClass(Class contextClass) { 42 String resourceName = contextClass.getName(); 43 int dotIndex = resourceName.lastIndexOf('.'); 44 45 if (dotIndex != -1) resourceName = resourceName.substring(0, dotIndex); 46 resourceName += ".properties"; 47 48 return fromResource(contextClass, resourceName); 49 } 50 51 public static URL fromResource(String resourceName) { 52 return fromResource(resourceName, null); 53 } 54 55 public static URL fromResource(Class contextClass, String resourceName) { 56 if (contextClass == null) 57 return fromResource(resourceName, null); 58 else 59 return fromResource(resourceName, contextClass.getClassLoader()); 60 } 61 62 public static URL fromResource(String resourceName, ClassLoader loader) { 63 URL url = null; 64 65 if (loader != null && url == null) url = loader.getResource(resourceName); 66 if (loader != null && url == null) url = loader.getResource(resourceName + ".properties"); 67 68 if (loader == null && url == null) { 69 try { 70 loader = Thread.currentThread().getContextClassLoader(); 71 } catch (SecurityException e) { 72 UtilURL utilURL = new UtilURL(); 73 loader = utilURL.getClass().getClassLoader(); 74 } 75 } 76 77 if (url == null) url = loader.getResource(resourceName); 78 if (url == null) url = loader.getResource(resourceName + ".properties"); 79 80 if (url == null) url = ClassLoader.getSystemResource(resourceName); 81 if (url == null) url = ClassLoader.getSystemResource(resourceName + ".properties"); 82 83 if (url == null) url = fromFilename(resourceName); 84 if (url == null) url = fromOfbizHomePath(resourceName); 85 if (url == null) url = fromUrlString(resourceName); 86 87 return url; 89 } 90 91 public static URL fromFilename(String filename) { 92 if (filename == null) return null; 93 File file = new File (filename); 94 URL url = null; 95 96 try { 97 if (file.exists()) url = file.toURL(); 98 } catch (java.net.MalformedURLException e) { 99 e.printStackTrace(); 100 url = null; 101 } 102 return url; 103 } 104 105 public static URL fromUrlString(String urlString) { 106 URL url = null; 107 try { 108 url = new URL (urlString); 109 } catch (MalformedURLException e) { 110 } 111 112 return url; 113 } 114 115 public static URL fromOfbizHomePath(String filename) { 116 String ofbizHome = System.getProperty("ofbiz.home"); 117 if (ofbizHome == null) { 118 Debug.logWarning("No ofbiz.home property set in environment", module); 119 return null; 120 } 121 String newFilename = ofbizHome; 122 if (!newFilename.endsWith("/") && !filename.startsWith("/")) { 123 newFilename = newFilename + "/"; 124 } 125 newFilename = newFilename + filename; 126 return fromFilename(newFilename); 127 } 128 } 129 | Popular Tags |