FileDocCategorySizeDatePackage
EchoProperties.javaAPI DocApache Ant 1.7018368Wed Dec 13 06:16:18 GMT 2006org.apache.tools.ant.taskdefs.optional

EchoProperties

public class EchoProperties extends org.apache.tools.ant.Task
Displays all the current properties in the build. The output can be sent to a file if desired.

Attribute "destfile" defines a file to send the properties to. This can be processed as a standard property file later.

Attribute "prefix" defines a prefix which is used to filter the properties only those properties starting with this prefix will be echoed.

By default, the "failonerror" attribute is enabled. If an error occurs while writing the properties to a file, and this attribute is enabled, then a BuildException will be thrown. If disabled, then IO errors will be reported as a log statement, but no error will be thrown.

Examples:

<echoproperties />
Report the current properties to the log.

<echoproperties destfile="my.properties" />
Report the current properties to the file "my.properties", and will fail the build if the file could not be created or written to.

<echoproperties destfile="my.properties" failonerror="false"
prefix="ant" />
Report all properties beginning with 'ant' to the file "my.properties", and will log a message if the file could not be created or written to, but will still allow the build to continue.
since
Ant 1.5

Fields Summary
private static final String
PROPERTIES
the properties element.
private static final String
PROPERTY
the property element.
private static final String
ATTR_NAME
name attribute for property, testcase and testsuite elements.
private static final String
ATTR_VALUE
value attribute for property elements.
private File
inFile
the input file.
private File
destfile
File object pointing to the output file. If this is null, then we output to the project log, not to a file.
private boolean
failonerror
If this is true, then errors generated during file output will become build errors, and if false, then such errors will be logged, but not thrown.
private Vector
propertySets
private String
format
private String
prefix
private String
regex
Constructors Summary
Methods Summary
public voidaddPropertyset(org.apache.tools.ant.types.PropertySet ps)
A set of properties to write.

param
ps the property set to write
since
Ant 1.6

        propertySets.addElement(ps);
    
public voidexecute()
Run the task.

exception
BuildException trouble, probably file IO

        if (prefix != null && regex != null) {
            throw new BuildException("Please specify either prefix"
                    + " or regex, but not both", getLocation());
        }
        //copy the properties file
        Hashtable allProps = new Hashtable();

        /* load properties from file if specified, otherwise
        use Ant's properties */
        if (inFile == null && propertySets.size() == 0) {
            // add ant properties
            allProps.putAll(getProject().getProperties());
        } else if (inFile != null) {
            if (inFile.exists() && inFile.isDirectory()) {
                String message = "srcfile is a directory!";
                if (failonerror) {
                    throw new BuildException(message, getLocation());
                } else {
                    log(message, Project.MSG_ERR);
                }
                return;
            }

            if (inFile.exists() && !inFile.canRead()) {
                String message = "Can not read from the specified srcfile!";
                if (failonerror) {
                    throw new BuildException(message, getLocation());
                } else {
                    log(message, Project.MSG_ERR);
                }
                return;
            }

            FileInputStream in = null;
            try {
                in = new FileInputStream(inFile);
                Properties props = new Properties();
                props.load(in);
                allProps.putAll(props);
            } catch (FileNotFoundException fnfe) {
                String message =
                    "Could not find file " + inFile.getAbsolutePath();
                if (failonerror) {
                    throw new BuildException(message, fnfe, getLocation());
                } else {
                    log(message, Project.MSG_WARN);
                }
                return;
            } catch (IOException ioe) {
                String message =
                    "Could not read file " + inFile.getAbsolutePath();
                if (failonerror) {
                    throw new BuildException(message, ioe, getLocation());
                } else {
                    log(message, Project.MSG_WARN);
                }
                return;
            } finally {
                FileUtils.close(in);
            }
        }

        Enumeration e = propertySets.elements();
        while (e.hasMoreElements()) {
            PropertySet ps = (PropertySet) e.nextElement();
            allProps.putAll(ps.getProperties());
        }

        OutputStream os = null;
        try {
            if (destfile == null) {
                os = new ByteArrayOutputStream();
                saveProperties(allProps, os);
                log(os.toString(), Project.MSG_INFO);
            } else {
                if (destfile.exists() && destfile.isDirectory()) {
                    String message = "destfile is a directory!";
                    if (failonerror) {
                        throw new BuildException(message, getLocation());
                    } else {
                        log(message, Project.MSG_ERR);
                    }
                    return;
                }

                if (destfile.exists() && !destfile.canWrite()) {
                    String message =
                        "Can not write to the specified destfile!";
                    if (failonerror) {
                        throw new BuildException(message, getLocation());
                    } else {
                        log(message, Project.MSG_ERR);
                    }
                    return;
                }
                os = new FileOutputStream(this.destfile);
                saveProperties(allProps, os);
            }
        } catch (IOException ioe) {
            if (failonerror) {
                throw new BuildException(ioe, getLocation());
            } else {
                log(ioe.getMessage(), Project.MSG_INFO);
            }
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                    //ignore
                }
            }
        }
    
private static javax.xml.parsers.DocumentBuildergetDocumentBuilder()
Uses the DocumentBuilderFactory to get a DocumentBuilder instance.

return
The DocumentBuilder instance

        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    
protected voidjdkSaveProperties(java.util.Properties props, java.io.OutputStream os, java.lang.String header)
JDK 1.2 allows for the safer method Properties.store(OutputStream, String), which throws an IOException on an output error.

param
props the properties to record
param
os record the properties to this output stream
param
header prepend this header to the property output
exception
IOException on an I/O error during a write.

       try {
           props.store(os, header);

       } catch (IOException ioe) {
           throw new BuildException(ioe, getLocation());
       } finally {
           if (os != null) {
               try {
                   os.close();
               } catch (IOException ioex) {
                   log("Failed to close output stream");
               }
           }
       }
    
protected voidsaveProperties(java.util.Hashtable allProps, java.io.OutputStream os)
Send the key/value pairs in the hashtable to the given output stream. Only those properties matching the prefix constraint will be sent to the output stream. The output stream will be closed when this method returns.

param
allProps propfile to save
param
os output stream
throws
IOException on output errors
throws
BuildException on other errors

        final List keyList = new ArrayList(allProps.keySet());
        Collections.sort(keyList);
        Properties props = new Properties() {
            public Enumeration keys() {
                return CollectionUtils.asEnumeration(keyList.iterator());
            }
            public Set entrySet() {
                Set result = super.entrySet();
                if (JavaEnvUtils.isKaffe()) {
                    TreeSet t = new TreeSet(new Comparator() {
                        public int compare(Object o1, Object o2) {
                            String key1 = (String) ((Map.Entry) o1).getKey();
                            String key2 = (String) ((Map.Entry) o2).getKey();
                            return key1.compareTo(key2);
                        }
                    });
                    t.addAll(result);
                    result = t;
                }
                return result;
            }
        };
        for (int i = 0; i < keyList.size(); i++) {
            String name = keyList.get(i).toString();
            String value = allProps.get(name).toString();
            props.setProperty(name, value);
        }
        if ("text".equals(format)) {
            jdkSaveProperties(props, os, "Ant properties");
        } else if ("xml".equals(format)) {
            xmlSaveProperties(props, os);
        }
    
public voidsetDestfile(java.io.File destfile)
Set a file to store the property output. If this is never specified, then the output will be sent to the Ant log.

param
destfile file to store the property output

        this.destfile = destfile;
    
public voidsetFailOnError(boolean failonerror)
If true, the task will fail if an error occurs writing the properties file, otherwise errors are just logged.

param
failonerror true if IO exceptions are reported as build exceptions, or false if IO exceptions are ignored.

        this.failonerror = failonerror;
    
public voidsetFormat(org.apache.tools.ant.taskdefs.optional.EchoProperties$FormatAttribute ea)
Set the output format - xml or text.

param
ea an enumerated FormatAttribute value

        format = ea.getValue();
    
public voidsetPrefix(java.lang.String prefix)
If the prefix is set, then only properties which start with this prefix string will be recorded. If regex is not set and if this is never set, or it is set to an empty string or null, then all properties will be recorded.

For example, if the attribute is set as:

<echoproperties prefix="ant." />
then the property "ant.home" will be recorded, but "ant-example" will not.

param
prefix The new prefix value

        if (prefix != null && prefix.length() != 0) {
            this.prefix = prefix;
            PropertySet ps = new PropertySet();
            ps.setProject(getProject());
            ps.appendPrefix(prefix);
            addPropertyset(ps);
        }
    
public voidsetRegex(java.lang.String regex)
If the regex is set, then only properties whose names match it will be recorded. If prefix is not set and if this is never set, or it is set to an empty string or null, then all properties will be recorded.

For example, if the attribute is set as:

<echoproperties prefix=".*ant.*" />
then the properties "ant.home" and "user.variant" will be recorded, but "ant-example" will not.

param
regex The new regex value
since
Ant 1.7

        if (regex != null && regex.length() != 0) {
            this.regex = regex;
            PropertySet ps = new PropertySet();
            ps.setProject(getProject());
            ps.appendRegex(regex);
            addPropertyset(ps);
        }
    
public voidsetSrcfile(java.io.File file)
Sets the input file.

param
file the input file


                   
        
        inFile = file;
    
private java.util.ListsortProperties(java.util.Properties props)

        //sort the list. Makes SCM and manual diffs easier.
        List sorted = new ArrayList(props.size());
        Enumeration e = props.propertyNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            sorted.add(new Tuple(name, props.getProperty(name)));
        }
        Collections.sort(sorted);
        return sorted;
    
protected voidxmlSaveProperties(java.util.Properties props, java.io.OutputStream os)
Output the properties as xml output.

param
props the properties to save
param
os the output stream to write to (Note this gets closed)
throws
IOException on error in writing to the stream

        // create XML document
        Document doc = getDocumentBuilder().newDocument();
        Element rootElement = doc.createElement(PROPERTIES);

        List sorted = sortProperties(props);


        // output properties
        Iterator iten = sorted.iterator();
        while (iten.hasNext()) {
            Tuple tuple = (Tuple) iten.next();
            Element propElement = doc.createElement(PROPERTY);
            propElement.setAttribute(ATTR_NAME, tuple.key);
            propElement.setAttribute(ATTR_VALUE, tuple.value);
            rootElement.appendChild(propElement);
        }

        Writer wri = null;
        try {
            wri = new OutputStreamWriter(os, "UTF8");
            wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            (new DOMElementWriter()).write(rootElement, wri, 0, "\t");
            wri.flush();
        } catch (IOException ioe) {
            throw new BuildException("Unable to write XML file", ioe);
        } finally {
            FileUtils.close(wri);
        }