1 18 19 package org.apache.tools.ant.taskdefs; 20 21 import org.apache.tools.ant.types.Path; 22 import org.apache.tools.ant.Task; 23 import org.apache.tools.ant.BuildException; 24 import org.apache.tools.ant.Project; 25 import org.apache.tools.ant.AntClassLoader; 26 27 import java.net.URL ; 28 29 40 public class WhichResource extends Task { 41 44 private Path classpath; 45 46 49 private String classname; 50 51 54 private String resource; 55 56 59 private String property; 60 61 62 66 public void setClasspath(Path cp) { 67 if (classpath == null) { 68 classpath = cp; 69 } else { 70 classpath.append(cp); 71 } 72 } 73 74 78 public Path createClasspath() { 79 if (classpath == null) { 80 classpath = new Path(getProject()); 81 } 82 return classpath.createPath(); 83 } 84 85 86 89 private void validate() { 90 int setcount = 0; 91 if (classname != null) { 92 setcount++; 93 } 94 if (resource != null) { 95 setcount++; 96 } 97 98 99 if (setcount == 0) { 100 throw new BuildException( 101 "One of classname or resource must be specified"); 102 } 103 if (setcount > 1) { 104 throw new BuildException( 105 "Only one of classname or resource can be specified"); 106 } 107 if (property == null) { 108 throw new BuildException("No property defined"); 109 } 110 } 111 112 116 public void execute() throws BuildException { 117 validate(); 118 if (classpath != null) { 119 getProject().log("using user supplied classpath: " + classpath, 120 Project.MSG_DEBUG); 121 classpath = classpath.concatSystemClasspath("ignore"); 122 } else { 123 classpath = new Path(getProject()); 124 classpath = classpath.concatSystemClasspath("only"); 125 getProject().log("using system classpath: " + classpath, Project.MSG_DEBUG); 126 } 127 AntClassLoader loader; 128 loader = new AntClassLoader(getProject().getCoreLoader(), 129 getProject(), 130 classpath, false); 131 String loc = null; 132 if (classname != null) { 133 resource = classname.replace('.', '/') + ".class"; 135 } 136 137 if (resource == null) { 138 throw new BuildException("One of class or resource is required"); 139 } 140 141 if (resource.startsWith("/")) { 142 resource = resource.substring(1); 143 } 144 145 log("Searching for " + resource, Project.MSG_VERBOSE); 146 URL url; 147 url = loader.getResource(resource); 148 if (url != null) { 149 loc = url.toExternalForm(); 151 getProject().setNewProperty(property, loc); 152 } 153 } 154 155 160 public void setResource(String resource) { 161 this.resource = resource; 162 } 163 164 169 public void setClass(String classname) { 170 this.classname = classname; 171 } 172 173 178 public void setProperty(String property) { 179 this.property = property; 180 } 181 182 } 183 | Popular Tags |