techjourneyman
techjourneyman

Reputation: 1813

Ant job adding escape character for String Password field

I have an Ant build that I am invoking from Jenkins. The Jenkins job has parameters, one of which is a password string ("Password Parameter" in Jenkins).

The Ant target that writes the password in the properties file is specified as:

<target name="pwd-properties">
        <echo>Password is: ${password}</echo>   
       <propertyfile file="data.properties" comment="property file">
          <entry key="Pwd" value="${password}" />                 
       </propertyfile>
    </target>

The password is

I am password!

However, in the build machine it shows as

I am password\!

in the properties file. The echo however shows it correctly.

Can someone tell how it is getting that extra escape character in the password string?

Upvotes: 0

Views: 972

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

It's got nothing to do with Ant - this is just the documented behaviour of Properties.store:

Then every entry in this Properties table is written out, one per line. For each entry the key string is written, then an ASCII =, then the associated element string. For the key, all space characters are written with a preceding \ character. For the element, leading space characters, but not embedded or trailing space characters, are written with a preceding \ character. The key and element characters #, !, =, and : are written with a preceding backslash to ensure that they are properly loaded.

Sample code:

import java.io.*;
import java.util.*;

public class Test {
    public static void main(String[] args) throws Exception {
        StringWriter writer = new StringWriter();
        Properties props = new Properties();
        props.setProperty("key", "value!");
        props.store(writer, "Demo");
        System.out.println(writer);
    }
}

Output:

#Demo
#Wed Feb 04 22:38:55 GMT 2015
key=value\!

In other words, all is well.

The reason for the escaping is because ! is used for comments. From Properties.load:

A comment line has an ASCII '#' or '!' as its first non-white space character; comment lines are also ignored and do not encode key-element information.

Now it could be conditionally escaped - in other words, only if it would otherwise act as a comment character - but it's simplest to just escape it all the time.

Upvotes: 1

Related Questions