1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18 package org.apache.tools.ant;
19
20 import java.io.File;
21 import java.util.Hashtable;
22 import java.util.LinkedList;
23 import java.util.List;
24 import java.util.Locale;
25 import java.util.Vector;
26
27 import org.apache.tools.ant.types.Resource;
28 import org.apache.tools.ant.types.resources.FileResource;
29 import org.apache.tools.ant.util.LoaderUtils;
30 import org.xml.sax.AttributeList;
31
32 /**
33 * Configures a Project (complete with Targets and Tasks) based on
34 * a build file. It'll rely on a plugin to do the actual processing
35 * of the file.
36 * <p>
37 * This class also provide static wrappers for common introspection.
38 */
39 public class ProjectHelper {
40 /** The URI for ant name space */
41 public static final String ANT_CORE_URI = "antlib:org.apache.tools.ant";
42
43 /** The URI for antlib current definitions */
44 public static final String ANT_CURRENT_URI = "ant:current";
45
46 /** The URI for defined types/tasks - the format is antlib:<package> */
47 public static final String ANTLIB_URI = "antlib:";
48
49 /** Polymorphic attribute */
50 public static final String ANT_TYPE = "ant-type";
51
52 /**
53 * Name of JVM system property which provides the name of the
54 * ProjectHelper class to use.
55 */
56 public static final String HELPER_PROPERTY = MagicNames.PROJECT_HELPER_CLASS;
57
58 /**
59 * The service identifier in jars which provide Project Helper
60 * implementations.
61 */
62 public static final String SERVICE_ID = MagicNames.PROJECT_HELPER_SERVICE;
63
64 /**
65 * name of project helper reference that we add to a project
66 */
67 public static final String PROJECTHELPER_REFERENCE = MagicNames.REFID_PROJECT_HELPER;
68
69 /**
70 * Configures the project with the contents of the specified build file.
71 *
72 * @param project The project to configure. Must not be <code>null</code>.
73 * @param buildFile A build file giving the project's configuration.
74 * Must not be <code>null</code>.
75 *
76 * @exception BuildException if the configuration is invalid or cannot be read
77 */
78 public static void configureProject(Project project, File buildFile) throws BuildException {
79 FileResource resource = new FileResource(buildFile);
80 ProjectHelper helper = ProjectHelperRepository.getInstance().getProjectHelperForBuildFile(resource);
81 project.addReference(PROJECTHELPER_REFERENCE, helper);
82 helper.parse(project, buildFile);
83 }
84
85 /** Default constructor */
86 public ProjectHelper() {
87 }
88
89 // -------------------- Common properties --------------------
90 // The following properties are required by import ( and other tasks
91 // that read build files using ProjectHelper ).
92
93 private Vector importStack = new Vector();
94 private List extensionStack = new LinkedList();
95
96 /**
97 * Import stack.
98 * Used to keep track of imported files. Error reporting should
99 * display the import path.
100 *
101 * @return the stack of import source objects.
102 */
103 public Vector getImportStack() {
104 return importStack;
105 }
106
107 /**
108 * Extension stack.
109 * Used to keep track of targets that extend extension points.
110 *
111 * @return a list of two element string arrays where the first
112 * element is the name of the extensionpoint and the second the
113 * name of the target
114 */
115 public List getExtensionStack() {
116 return extensionStack;
117 }
118
119 private final static ThreadLocal targetPrefix = new ThreadLocal() {
120 protected Object initialValue() {
121 return (String) null;
122 }
123 };
124
125 /**
126 * The prefix to prepend to imported target names.
127 *
128 * <p>May be set by <import>'s as attribute.</p>
129 *
130 * @return the configured prefix or null
131 *
132 * @since Ant 1.8.0
133 */
134 public static String getCurrentTargetPrefix() {
135 return (String) targetPrefix.get();
136 }
137
138 /**
139 * Sets the prefix to prepend to imported target names.
140 *
141 * @since Ant 1.8.0
142 */
143 public static void setCurrentTargetPrefix(String prefix) {
144 targetPrefix.set(prefix);
145 }
146
147 private final static ThreadLocal prefixSeparator = new ThreadLocal() {
148 protected Object initialValue() {
149 return ".";
150 }
151 };
152
153 /**
154 * The separator between the prefix and the target name.
155 *
156 * <p>May be set by <import>'s prefixSeperator attribute.</p>
157 *
158 * @since Ant 1.8.0
159 */
160 public static String getCurrentPrefixSeparator() {
161 return (String) prefixSeparator.get();
162 }
163
164 /**
165 * Sets the separator between the prefix and the target name.
166 *
167 * @since Ant 1.8.0
168 */
169 public static void setCurrentPrefixSeparator(String sep) {
170 prefixSeparator.set(sep);
171 }
172
173 private final static ThreadLocal inIncludeMode = new ThreadLocal() {
174 protected Object initialValue() {
175 return Boolean.FALSE;
176 }
177 };
178
179 /**
180 * Whether the current file should be read in include as opposed
181 * to import mode.
182 *
183 * <p>In include mode included targets are only known by their
184 * prefixed names and their depends lists get rewritten so that
185 * all dependencies get the prefix as well.</p>
186 *
187 * <p>In import mode imported targets are known by an adorned as
188 * well as a prefixed name and the unadorned target may be
189 * overwritten in the importing build file. The depends list of
190 * the imported targets is not modified at all.</p>
191 *
192 * @since Ant 1.8.0
193 */
194 public static boolean isInIncludeMode() {
195 return inIncludeMode.get() == Boolean.TRUE;
196 }
197
198 /**
199 * Sets whether the current file should be read in include as
200 * opposed to import mode.
201 *
202 * @since Ant 1.8.0
203 */
204 public static void setInIncludeMode(boolean includeMode) {
205 inIncludeMode.set(includeMode ? Boolean.TRUE : Boolean.FALSE);
206 }
207
208 // -------------------- Parse method --------------------
209 /**
210 * Parses the project file, configuring the project as it goes.
211 *
212 * @param project The project for the resulting ProjectHelper to configure.
213 * Must not be <code>null</code>.
214 * @param source The source for XML configuration. A helper must support
215 * at least File, for backward compatibility. Helpers may
216 * support URL, InputStream, etc or specialized types.
217 *
218 * @since Ant1.5
219 * @exception BuildException if the configuration is invalid or cannot
220 * be read
221 */
222 public void parse(Project project, Object source) throws BuildException {
223 throw new BuildException("ProjectHelper.parse() must be implemented "
224 + "in a helper plugin " + this.getClass().getName());
225 }
226
227 /**
228 * Get the first project helper found in the classpath
229 *
230 * @return an project helper, never <code>null</code>
231 * @see org.apache.tools.ant.ProjectHelperRepository#getHelpers()
232 */
233 public static ProjectHelper getProjectHelper() {
234 return (ProjectHelper) ProjectHelperRepository.getInstance().getHelpers().next();
235 }
236
237 /**
238 * JDK1.1 compatible access to the context class loader. Cut & paste from JAXP.
239 *
240 * @deprecated since 1.6.x.
241 * Use LoaderUtils.getContextClassLoader()
242 *
243 * @return the current context class loader, or <code>null</code>
244 * if the context class loader is unavailable.
245 */
246 public static ClassLoader getContextClassLoader() {
247 return LoaderUtils.isContextLoaderAvailable() ? LoaderUtils.getContextClassLoader() : null;
248 }
249
250 // -------------------- Static utils, used by most helpers ----------------
251
252 /**
253 * Configures an object using an introspection handler.
254 *
255 * @param target The target object to be configured.
256 * Must not be <code>null</code>.
257 * @param attrs A list of attributes to configure within the target.
258 * Must not be <code>null</code>.
259 * @param project The project containing the target.
260 * Must not be <code>null</code>.
261 *
262 * @deprecated since 1.6.x.
263 * Use IntrospectionHelper for each property.
264 *
265 * @exception BuildException if any of the attributes can't be handled by
266 * the target
267 */
268 public static void configure(Object target, AttributeList attrs,
269 Project project) throws BuildException {
270 if (target instanceof TypeAdapter) {
271 target = ((TypeAdapter) target).getProxy();
272 }
273 IntrospectionHelper ih = IntrospectionHelper.getHelper(project, target.getClass());
274
275 for (int i = 0, length = attrs.getLength(); i < length; i++) {
276 // reflect these into the target
277 String value = replaceProperties(project, attrs.getValue(i), project.getProperties());
278 try {
279 ih.setAttribute(project, target, attrs.getName(i).toLowerCase(Locale.ENGLISH), value);
280 } catch (BuildException be) {
281 // id attribute must be set externally
282 if (!attrs.getName(i).equals("id")) {
283 throw be;
284 }
285 }
286 }
287 }
288
289 /**
290 * Adds the content of #PCDATA sections to an element.
291 *
292 * @param project The project containing the target.
293 * Must not be <code>null</code>.
294 * @param target The target object to be configured.
295 * Must not be <code>null</code>.
296 * @param buf A character array of the text within the element.
297 * Will not be <code>null</code>.
298 * @param start The start element in the array.
299 * @param count The number of characters to read from the array.
300 *
301 * @exception BuildException if the target object doesn't accept text
302 */
303 public static void addText(Project project, Object target, char[] buf,
304 int start, int count) throws BuildException {
305 addText(project, target, new String(buf, start, count));
306 }
307
308 /**
309 * Adds the content of #PCDATA sections to an element.
310 *
311 * @param project The project containing the target.
312 * Must not be <code>null</code>.
313 * @param target The target object to be configured.
314 * Must not be <code>null</code>.
315 * @param text Text to add to the target.
316 * May be <code>null</code>, in which case this
317 * method call is a no-op.
318 *
319 * @exception BuildException if the target object doesn't accept text
320 */
321 public static void addText(Project project, Object target, String text)
322 throws BuildException {
323
324 if (text == null) {
325 return;
326 }
327 if (target instanceof TypeAdapter) {
328 target = ((TypeAdapter) target).getProxy();
329 }
330 IntrospectionHelper.getHelper(project, target.getClass()).addText(project, target, text);
331 }
332
333 /**
334 * Stores a configured child element within its parent object.
335 *
336 * @param project Project containing the objects.
337 * May be <code>null</code>.
338 * @param parent Parent object to add child to.
339 * Must not be <code>null</code>.
340 * @param child Child object to store in parent.
341 * Should not be <code>null</code>.
342 * @param tag Name of element which generated the child.
343 * May be <code>null</code>, in which case
344 * the child is not stored.
345 */
346 public static void storeChild(Project project, Object parent, Object child, String tag) {
347 IntrospectionHelper ih = IntrospectionHelper.getHelper(project, parent.getClass());
348 ih.storeElement(project, parent, child, tag);
349 }
350
351 /**
352 * Replaces <code>${xxx}</code> style constructions in the given value with
353 * the string value of the corresponding properties.
354 *
355 * @param project The project containing the properties to replace.
356 * Must not be <code>null</code>.
357 *
358 * @param value The string to be scanned for property references.
359 * May be <code>null</code>.
360 *
361 * @exception BuildException if the string contains an opening
362 * <code>${</code> without a closing
363 * <code>}</code>
364 * @return the original string with the properties replaced, or
365 * <code>null</code> if the original string is <code>null</code>.
366 *
367 * @deprecated since 1.6.x.
368 * Use project.replaceProperties().
369 * @since 1.5
370 */
371 public static String replaceProperties(Project project, String value) throws BuildException {
372 // needed since project properties are not accessible
373 return project.replaceProperties(value);
374 }
375
376 /**
377 * Replaces <code>${xxx}</code> style constructions in the given value
378 * with the string value of the corresponding data types.
379 *
380 * @param project The container project. This is used solely for
381 * logging purposes. Must not be <code>null</code>.
382 * @param value The string to be scanned for property references.
383 * May be <code>null</code>, in which case this
384 * method returns immediately with no effect.
385 * @param keys Mapping (String to String) of property names to their
386 * values. Must not be <code>null</code>.
387 *
388 * @exception BuildException if the string contains an opening
389 * <code>${</code> without a closing
390 * <code>}</code>
391 * @return the original string with the properties replaced, or
392 * <code>null</code> if the original string is <code>null</code>.
393 * @deprecated since 1.6.x.
394 * Use PropertyHelper.
395 */
396 public static String replaceProperties(Project project, String value, Hashtable keys)
397 throws BuildException {
398 PropertyHelper ph = PropertyHelper.getPropertyHelper(project);
399 return ph.replaceProperties(null, value, keys);
400 }
401
402 /**
403 * Parses a string containing <code>${xxx}</code> style property
404 * references into two lists. The first list is a collection
405 * of text fragments, while the other is a set of string property names.
406 * <code>null</code> entries in the first list indicate a property
407 * reference from the second list.
408 *
409 * <p>As of Ant 1.8.0 this method is never invoked by any code
410 * inside of Ant itself.</p>
411 *
412 * @param value Text to parse. Must not be <code>null</code>.
413 * @param fragments List to add text fragments to.
414 * Must not be <code>null</code>.
415 * @param propertyRefs List to add property names to.
416 * Must not be <code>null</code>.
417 *
418 * @deprecated since 1.6.x.
419 * Use PropertyHelper.
420 * @exception BuildException if the string contains an opening
421 * <code>${</code> without a closing <code>}</code>
422 */
423 public static void parsePropertyString(String value, Vector fragments, Vector propertyRefs)
424 throws BuildException {
425 PropertyHelper.parsePropertyStringDefault(value, fragments, propertyRefs);
426 }
427
428 /**
429 * Map a namespaced {uri,name} to an internal string format.
430 * For BC purposes the names from the ant core uri will be
431 * mapped to "name", other names will be mapped to
432 * uri + ":" + name.
433 * @param uri The namepace URI
434 * @param name The localname
435 * @return The stringified form of the ns name
436 */
437 public static String genComponentName(String uri, String name) {
438 if (uri == null || uri.equals("") || uri.equals(ANT_CORE_URI)) {
439 return name;
440 }
441 return uri + ":" + name;
442 }
443
444 /**
445 * extract a uri from a component name
446 *
447 * @param componentName The stringified form for {uri, name}
448 * @return The uri or "" if not present
449 */
450 public static String extractUriFromComponentName(String componentName) {
451 if (componentName == null) {
452 return "";
453 }
454 int index = componentName.lastIndexOf(':');
455 if (index == -1) {
456 return "";
457 }
458 return componentName.substring(0, index);
459 }
460
461 /**
462 * extract the element name from a component name
463 *
464 * @param componentName The stringified form for {uri, name}
465 * @return The element name of the component
466 */
467 public static String extractNameFromComponentName(String componentName) {
468 int index = componentName.lastIndexOf(':');
469 if (index == -1) {
470 return componentName;
471 }
472 return componentName.substring(index + 1);
473 }
474
475 /**
476 * Add location to build exception.
477 * @param ex the build exception, if the build exception
478 * does not include
479 * @param newLocation the location of the calling task (may be null)
480 * @return a new build exception based in the build exception with
481 * location set to newLocation. If the original exception
482 * did not have a location, just return the build exception
483 */
484 public static BuildException addLocationToBuildException(
485 BuildException ex, Location newLocation) {
486 if (ex.getLocation() == null || ex.getMessage() == null) {
487 return ex;
488 }
489 String errorMessage
490 = "The following error occurred while executing this line:"
491 + System.getProperty("line.separator")
492 + ex.getLocation().toString()
493 + ex.getMessage();
494 if (newLocation == null) {
495 return new BuildException(errorMessage, ex);
496 }
497 return new BuildException(errorMessage, ex, newLocation);
498 }
499
500 /**
501 * Whether this instance of ProjectHelper can parse an Antlib
502 * descriptor given by the URL and return its content as an
503 * UnknownElement ready to be turned into an Antlib task.
504 *
505 * <p>This method should not try to parse the content of the
506 * descriptor, the URL is only given as an argument to allow
507 * subclasses to decide whether they can support a given URL
508 * scheme or not.</p>
509 *
510 * <p>Subclasses that return true in this method must also
511 * override {@link #parseAntlibDescriptor
512 * parseAntlibDescriptor}.</p>
513 *
514 * <p>This implementation returns false.</p>
515 *
516 * @since Ant 1.8.0
517 */
518 public boolean canParseAntlibDescriptor(Resource r) {
519 return false;
520 }
521
522 /**
523 * Parse the given URL as an antlib descriptor and return the
524 * content as something that can be turned into an Antlib task.
525 *
526 * @since ant 1.8.0
527 */
528 public UnknownElement parseAntlibDescriptor(Project containingProject,
529 Resource source) {
530 throw new BuildException("can't parse antlib descriptors");
531 }
532
533 /**
534 * Check if the helper supports the kind of file. Some basic check on the
535 * extension's file should be done here.
536 *
537 * @param buildFile
538 * the file expected to be parsed (never <code>null</code>)
539 * @return true if the helper supports it
540 * @since Ant 1.8.0
541 */
542 public boolean canParseBuildFile(Resource buildFile) {
543 return true;
544 }
545
546 /**
547 * The file name of the build script to be parsed if none specified on the command line
548 *
549 * @return the name of the default file (never <code>null</code>)
550 * @since Ant 1.8.0
551 */
552 public String getDefaultBuildFile() {
553 return Main.DEFAULT_BUILD_FILENAME;
554 }
555 }