user710818
user710818

Reputation: 24248

How to validate properties/custom configuration files?

My application has many properties/text configuration files. Is there a common way to validate these kind of files? May be some tools or something like xsd? The files are large (more 1000 rows), so I frequently make mistake. Information in file in majority of cases - is path to different directories. So it will be good if they exist and are consistent. E.g. if I have

mydata.root="c:\data"

and after I have:

myreports=${mydata.root}/reports

that will be good check that c:\data and c:\data\report exist

and not written (some hundreds rows down) e.g.

myreports=${mdata.root}/reports

Upvotes: 4

Views: 6590

Answers (2)

Ciaran McHale
Ciaran McHale

Reputation: 2234

I once offered a bounty for information on configuration languages other than XML that provide schema validation. Unfortunately, such configuration languages are few and far between.

Here is a link to the bountied question, in case you want to see the sparseness of the responses.

Upvotes: 1

ewan.chalmers
ewan.chalmers

Reputation: 16235

You could do this validation in your build file.

For example, the following build file defines a macrodef validate-file-property which validates that a specified property is defined and that it exists as a file or dir in the file system.

<project default="init">

  <property file="test.properties"/>

  <target name="init">
    <validate-file-property property="program.files" type="dir"/>
    <validate-file-property property="mydata.root" type="dir"/>
    <validate-file-property property="foo"/>
  </target>

  <macrodef name="validate-file-property">
    <attribute name="property"/>
    <attribute name="type" default="file"/>
    <sequential>
      <fail unless="@{property}" message="The property '@{property}' is undefinded."/>
      <available file="${@{property}}" property="@{property}.exists" type="@{type}"/>
      <fail unless="@{property}.exists" message="The @{type} '@{property}' with value '${@{property}}' does not exist."/>
    </sequential>
  </macrodef>

</project>

You need to decide when to validate the properties, and you need to validate them explicitly - as shown in the init target in this example.

BTW, if you used a standardized pattern to name properties which refer to files or directories - e.g. my.special.file, my.build.dir - then you could use a shell script to discover all relevant properties and write all your validate-file-property elements . Something like this:

awk -F= '/\.(file|dir)/{ printf "<validate-file-property property=\"%s\" type=\"%s\"/>\n", $1, gensub(/.*\.(file|dir)/, "\\1", "g", $1) }' *.properties

You could paste the output into your build file.

Upvotes: 5

Related Questions