PropertyFile task uses java.util.Properties to modify integer, String and
Date settings in a property file.
The following is an example of it's usage:
<target name="testPropertyFiles">
<property
name="COPYRIGHT_MESSAGE"
value="Copyright 2000 Coporation inc\\This file does some of
this\\and some of that" />
<propertyFile key="Int" type="int" operation="=" value="681"
file="test.txt" />
<propertyFile key="IntInc" type="int" operation="+" file="test.txt" />
<propertyFile key="IntDec" type="int" operation="-" file="test.txt" />
<propertyFile key="NeverDate" type="date" operation="never"
file="test.txt" />
<propertyFile key="StringEquals" type="string" value="testValue"
file="test.txt" />
<propertyFile key="NowDate" type="date" operation="now"
file="test.txt" message ="${COPYRIGHT_MESSAGE}" />
</target>
The propertyFile task must have:
key, type, file
Other parameters are:
operation, value, message
Parameter values:
operation:
"=" (set -- default)
"-" (dec)
"+" (inc)
"now" (date and time)
"never" (empty string)
type:
"int"
"date"
"string"
String property types can only use the "=" operation
Date property types can only use the "never" or "now" operations
Int property types can only use the "=", "-" or "+" operations
The message property is used for the property file header, with "\\" being
a newline delimiter charater. (This should be '\n' but I couldn't quite get
it right).
Source attached.
Jeremy/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.*;
import java.io.*;
import java.util.*;
/**
* <code>PropertyFile</code> provides a mechanism for updating a
* java.util.Properties object via Ant.
* @author Jeremy Mawson <[EMAIL PROTECTED]>
*/
public class PropertyFile extends Task {
/* ========================================================================
*
* Static variables.
*/
// Property types
private static final String INTEGER_TYPE = "int";
private static final String DATE_TYPE = "date";
private static final String STRING_TYPE = "string";
// Property type operations
private static final String INCREMENT_OPER = "+";
private static final String DECREMENT_OPER = "-";
private static final String EQUALS_OPER = "=";
// Special values
private static final String NOW_VALUE = "now";
private static final String NULL_VALUE = "never";
private static final int DEFAULT_INT_VALUE = 1;
private static final GregorianCalendar
DEFAULT_DATE_VALUE = new GregorianCalendar();
private static final String NEWLINE = System.getProperty("line.separator");
/* ========================================================================
*
* Instance variables.
*/
// Copyright message. Use this to prepend a copyright message to the
// Properties file
private String m_copyrightMessage;
private String m_key;
private String m_type = null;
private String m_operation = null;
private String m_value;
private int m_intValue = DEFAULT_INT_VALUE;
private GregorianCalendar m_dateValue = DEFAULT_DATE_VALUE;
private Properties m_properties;
private File m_propertyFile;
/* ========================================================================
*
* Constructors
*/
/* ========================================================================
*
* Methods
*/
public void execute() throws BuildException {
if (!checkParam(m_type)) {
throw new BuildException("type token must not be null.", location);
}
if (!checkParam(m_operation)) {
m_operation = EQUALS_OPER;
}
if (!checkParam(m_propertyFile)) {
throw new BuildException("file token must not be null.", location);
}
if (!checkParam(m_key)) {
throw new BuildException("key token must not be null.", location);
}
if ((!checkParam(m_value)) && (m_operation.equals(EQUALS_OPER))) {
throw new BuildException("key token must not be null when the "+
"operation token is either \""+EQUALS_OPER+"\" or undefined.",
location);
}
// Create the PropertyFile
m_properties = new Properties();
try {
if (m_propertyFile.exists()) {
log("Updating property file:
"+m_propertyFile.getAbsolutePath());
m_properties.load(new BufferedInputStream(
new FileInputStream(m_propertyFile)));
} else {
log("Creating new property file: "+
m_propertyFile.getAbsolutePath());
m_propertyFile.createNewFile();
}
} catch(IOException ioe) {
throw new BuildException(ioe.toString());
}
// Fork off process per the operation type requested
if (m_type.equals(INTEGER_TYPE)) {
executeInteger();
} else if (m_type.equals(DATE_TYPE)) {
executeDate();
} else if (m_type.equals(STRING_TYPE)) {
executeString();
} else {
throw new BuildException("Operation type "+m_type+" is not known.",
location);
}
}
/*
* Continue execution for Date values
* TODO: Modify for different locales and formats
*/
private void executeDate() throws BuildException {
StringBuffer dateString = new StringBuffer();
// If value is defined then interpret what's given
if (m_operation.equals(NULL_VALUE)) {
m_dateValue = null;
} else {
Date now = new Date();
m_dateValue.setTime(now);
dateString.append(m_dateValue.get(Calendar.YEAR));
dateString.append("/");
dateString.append((m_dateValue.get(Calendar.MONTH) < 10) ? "0" :
"");
dateString.append(m_dateValue.get(Calendar.MONTH));
dateString.append("/");
dateString.append((m_dateValue.get(Calendar.DATE) < 10) ? "0" : "");
dateString.append(m_dateValue.get(Calendar.DATE));
dateString.append(" ");
dateString.append((m_dateValue.get(Calendar.HOUR_OF_DAY) < 10) ?
"0" : "");
dateString.append(m_dateValue.get(Calendar.HOUR_OF_DAY));
dateString.append(":");
dateString.append((m_dateValue.get(Calendar.MINUTE) < 10) ? "0" :
"");
dateString.append(m_dateValue.get(Calendar.MINUTE));
}
setValue(m_key, dateString.toString());
}
/*
* Continue execution for int values
*/
private void executeInteger() throws BuildException {
int currentValue = 0;
try {
currentValue =
(new Integer((String)m_properties.get(m_key))).intValue();
} catch (NumberFormatException nfe) {
// Do nothing
}
if (m_operation.equals(EQUALS_OPER)) {
setValue(m_key, m_value);
} else if (m_operation.equals(INCREMENT_OPER)) {
currentValue++;
setValue(m_key, new String(""+currentValue));
} else if (m_operation.equals(DECREMENT_OPER)) {
currentValue--;
setValue(m_key, new String(""+currentValue));
}
}
/*
* Continue execution for String values
*/
private void executeString() throws BuildException {
setValue(m_key, m_value);
}
public void setOperation(String op) {
m_operation = op;
}
public void setType(String type) {
m_type = type;
}
public void setValue(String value) {
m_value = value;
}
public void setKey(String key) {
m_key = key;
}
public void setFile(String file) {
m_propertyFile = new File(file);
}
public void setMessage(String msg) {
m_copyrightMessage = msg;
}
/*
* Sets the value in the property file
*/
private void setValue(String key, String value) throws BuildException {
log("Setting: "+key+EQUALS_OPER+value);
m_properties.put(key, value);
try {
writeFile();
} catch (IOException ioe) {
throw new BuildException(ioe.toString());
}
}
/*
* Writes the properties to a file. Writes the file manually, rather than
* using Properties.store method, so that special characters are not
escaped.
*/
private void writeFile() throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(m_propertyFile));
// Write the copyright message if we have one.
if (m_copyrightMessage != null) {
// FIXME: would like to use \n as the newline token rather than \\.
StringTokenizer tok = new StringTokenizer(m_copyrightMessage, "\\");
while (tok.hasMoreTokens()) {
bos.write("# ".getBytes());
bos.write(((String)tok.nextToken()).getBytes());
bos.write(NEWLINE.getBytes());
}
bos.write(NEWLINE.getBytes());
bos.flush();
}
Enumeration enumValues = m_properties.elements();
Enumeration enumKeys = m_properties.keys();
while (enumKeys.hasMoreElements()) {
bos.write(((String)enumKeys.nextElement()).getBytes());
bos.write("=".getBytes());
bos.write(((String)enumValues.nextElement()).getBytes());
bos.write(NEWLINE.getBytes());
bos.flush();
}
bos.close();
}
/*
* Returns whether the given parameter has been defined.
*/
private boolean checkParam(String param) {
return !((param == null) || (param.equals("null")));
}
private boolean checkParam(File param) {
return !(param == null);
}
}
=========================================
Jeremy Mawson
E-Commerce Consultant
QSI Payments, Inc
Phone (07) +617 3224 9886
Fax (07) +617 3210 2566
Email [EMAIL PROTECTED]
URL http://www.qsipayments.com/
This message or any part of it is intended solely for the named addressee
and contains privileged and confidential information. If you receive this
message in error please notify QSI Payments, Inc by replying to the sender
and removing the message from your computer.