aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/taskdefs/optional/PropertyFile.java
blob: 162cab1a440443a17a071ccd9cbfd9a7f573d1b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.tools.ant.taskdefs.optional;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.LayoutPreservingProperties;

/**
 * Modifies settings in a property file.
 *
 * <p>The following is an example of its usage:</p>
 * <pre>
 *    &lt;target name="setState"&gt;
 *      &lt;property
 *        name="header"
 *        value="##Generated file - do not modify!"/&gt;
 *      &lt;propertyfile file="apropfile.properties" comment="${header}"&gt;
 *        &lt;entry key="product.version.major" type="int"  value="5"/&gt;
 *        &lt;entry key="product.version.minor" type="int"  value="0"/&gt;
 *        &lt;entry key="product.build.major"   type="int"  value="0" /&gt;
 *        &lt;entry key="product.build.minor"   type="int"  operation="+" /&gt;
 *        &lt;entry key="product.build.date"    type="date" value="now" /&gt;
 *        &lt;entry key="intSet" type="int" operation="=" value="681"/&gt;
 *        &lt;entry key="intDec" type="int" operation="-"/&gt;
 *        &lt;entry key="StringEquals" type="string" value="testValue"/&gt;
 *     &lt;/propertyfile&gt;
 *   &lt;/target&gt;
 * </pre>
 *
 * The &lt;propertyfile&gt; task must have:
 * <ul>
 *   <li>file</li>
 * </ul>
 * Other parameters are:
 * <ul>
 *   <li>comment</li>
 *   <li>key</li>
 *   <li>operation</li>
 *   <li>type</li>
 *   <li>value (the final four being eliminated shortly)</li>
 * </ul>
 *
 * The &lt;entry&gt; task must have:
 * <ul>
 *   <li>key</li>
 * </ul>
 * Other parameters are:
 * <ul>
 *   <li>operation</li>
 *   <li>type</li>
 *   <li>value</li>
 *   <li>default</li>
 *   <li>unit</li>
 * </ul>
 *
 * If type is unspecified, it defaults to string.
 *
 * Parameter values:
 * <ul>
 *   <li>operation:</li>
 *   <ul>
 *     <li>"=" (set -- default)</li>
 *     <li>"-" (dec)</li>
 *     <li>"+" (inc)</li>
 *   </ul>
 *   <li>type:</li>
 *   <ul>
 *     <li>"int"</li>
 *     <li>"date"</li>
 *     <li>"string"</li>
 *   </ul>
 *   <li>value:</li>
 *   <ul>
 *     <li>holds the default value, if the property
 *              was not found in property file</li>
 *     <li>"now" In case of type "date", the
 *              value "now" will be replaced by the current
 *              date/time and used even if a valid date was
 *              found in the property file.</li>
 *   </ul>
 * </ul>
 *
 * <p>String property types can only use the "=" operation.
 * Int property types can only use the "=", "-" or "+" operations.<p>
 *
 * The message property is used for the property file header, with "\\" being
 * a newline delimiter character.
 *
 */
public class PropertyFile extends Task {

    /* ========================================================================
     *
     * Instance variables.
     */

    // Use this to prepend a message to the properties file
    private String              comment;

    private Properties          properties;
    private File                propertyfile;
    private boolean             useJDKProperties;

    private Vector entries = new Vector();

    /* ========================================================================
     *
     * Constructors
     */

    /* ========================================================================
     *
     * Methods
     */

    /**
     * Execute the task.
     * @throws BuildException on error.
     */
    @Override
    public void execute() throws BuildException {
        checkParameters();
        readFile();
        executeOperation();
        writeFile();
    }

    /**
     * The entry nested element.
     * @return an entry nested element to be configured.
     */
    public Entry createEntry() {
        Entry e = new Entry();
        entries.addElement(e);
        return e;
    }

    private void executeOperation() throws BuildException {
        for (Enumeration e = entries.elements(); e.hasMoreElements();) {
            Entry entry = (Entry) e.nextElement();
            entry.executeOn(properties);
        }
    }

    private void readFile() throws BuildException {
        if (useJDKProperties) {
            // user chose to use standard Java properties, which loose
            // comments and layout
            properties = new Properties();
        } else {
            properties = new LayoutPreservingProperties();
        }
        try {
            if (propertyfile.exists()) {
                log("Updating property file: "
                    + propertyfile.getAbsolutePath());
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertyfile);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    properties.load(bis);
                } finally {
                    if (fis != null) {
                        fis.close();
                    }
                }
            } else {
                log("Creating new property file: "
                    + propertyfile.getAbsolutePath());
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(propertyfile.getAbsolutePath());
                    out.flush();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }
        } catch (IOException ioe) {
            throw new BuildException(ioe.toString());
        }
    }

    private void checkParameters() throws BuildException {
        if (!checkParam(propertyfile)) {
            throw new BuildException("file token must not be null.",
                                     getLocation());
        }
    }

    /**
     * Location of the property file to be edited; required.
     * @param file the property file.
     */
    public void setFile(File file) {
        propertyfile = file;
    }

    /**
     * optional header comment for the file
     * @param hdr the string to use for the comment.
     */
    public void setComment(String hdr) {
        comment = hdr;
    }

    /**
     * optional flag to use original Java properties (as opposed to
     * layout preserving properties)
     */
    public void setJDKProperties(boolean val) {
        useJDKProperties = val;
    }

    private void writeFile() throws BuildException {
        // Write to RAM first, as an OOME could otherwise produce a truncated file:
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            properties.store(baos, comment);
        } catch (IOException x) { // should not happen
            throw new BuildException(x, getLocation());
        }
        try {
            OutputStream os = new FileOutputStream(propertyfile);
            try {
                try {
                    os.write(baos.toByteArray());
                } finally {
                    os.close();
                }
            } catch (IOException x) { // possibly corrupt
                FileUtils.getFileUtils().tryHardToDelete(propertyfile);
                throw x;
            }
        } catch (IOException x) { // opening, writing, or closing
            throw new BuildException(x, getLocation());
        }
    }

    private boolean checkParam(File param) {
        return !(param == null);
    }

    /**
     * Instance of this class represents nested elements of
     * a task propertyfile.
     */
    public static class Entry {
        private static final int DEFAULT_INT_VALUE = 0;
        private static final String DEFAULT_DATE_VALUE = "now";
        private static final String DEFAULT_STRING_VALUE = "";

        private String              key = null;
        private int                 type = Type.STRING_TYPE;
        private int                 operation = Operation.EQUALS_OPER;
        private String              value = null;
        private String              defaultValue = null;
        private String              newValue = null;
        private String              pattern = null;
        private int                 field = Calendar.DATE;

        /**
         * Name of the property name/value pair
         * @param value the key.
         */
        public void setKey(String value) {
            this.key = value;
        }

        /**
         * Value to set (=), to add (+) or subtract (-)
         * @param value the value.
         */
        public void setValue(String value) {
            this.value = value;
        }

        /**
         * operation to apply.
         * &quot;+&quot; or &quot;=&quot;
         *(default) for all datatypes; &quot;-&quot; for date and int only)\.
         * @param value the operation enumerated value.
         */
        public void setOperation(Operation value) {
            this.operation = Operation.toOperation(value.getValue());
        }

        /**
         * Regard the value as : int, date or string (default)
         * @param value the type enumerated value.
         */
        public void setType(Type value) {
            this.type = Type.toType(value.getValue());
        }

        /**
         * Initial value to set for a property if it is not
         * already defined in the property file.
         * For type date, an additional keyword is allowed: &quot;now&quot;
         * @param value the default value.
         */
        public void setDefault(String value) {
            this.defaultValue = value;
        }

        /**
         * For int and date type only. If present, Values will
         * be parsed and formatted accordingly.
         * @param value the pattern to use.
         */
        public void setPattern(String value) {
            this.pattern = value;
        }

        /**
         * The unit of the value to be applied to date +/- operations.
         *            Valid Values are:
         *            <ul>
         *               <li>millisecond</li>
         *               <li>second</li>
         *               <li>minute</li>
         *               <li>hour</li>
         *               <li>day (default)</li>
         *               <li>week</li>
         *               <li>month</li>
         *               <li>year</li>
         *            </ul>
         *            This only applies to date types using a +/- operation.
         * @param unit the unit enumerated value.
         * @since Ant 1.5
         */
        public void setUnit(PropertyFile.Unit unit) {
            field = unit.getCalendarField();
        }

        /**
         * Apply the nested element to the properties.
         * @param props the properties to apply the entry on.
         * @throws BuildException if there is an error.
         */
        protected void executeOn(Properties props) throws BuildException {
            checkParameters();

            if (operation == Operation.DELETE_OPER) {
                props.remove(key);
                return;
            }

            // type may be null because it wasn't set
            String oldValue = (String) props.get(key);
            try {
                if (type == Type.INTEGER_TYPE) {
                    executeInteger(oldValue);
                } else if (type == Type.DATE_TYPE) {
                    executeDate(oldValue);
                } else if (type == Type.STRING_TYPE) {
                    executeString(oldValue);
                } else {
                    throw new BuildException("Unknown operation type: "
                                             + type);
                }
            } catch (NullPointerException npe) {
                // Default to string type
                // which means do nothing
                npe.printStackTrace();
            }

            if (newValue == null) {
                newValue = "";
            }

            // Insert as a string by default
            props.put(key, newValue);
        }

        /**
         * Handle operations for type <code>date</code>.
         *
         * @param oldValue the current value read from the property file or
         *                 <code>null</code> if the <code>key</code> was
         *                 not contained in the property file.
         */
        private void executeDate(String oldValue) throws BuildException {
            Calendar currentValue = Calendar.getInstance();

            if (pattern == null) {
                pattern = "yyyy/MM/dd HH:mm";
            }
            DateFormat fmt = new SimpleDateFormat(pattern);

            String currentStringValue = getCurrentValue(oldValue);
            if (currentStringValue == null) {
                currentStringValue = DEFAULT_DATE_VALUE;
            }

            if ("now".equals(currentStringValue)) {
                currentValue.setTime(new Date());
            } else {
                try {
                    currentValue.setTime(fmt.parse(currentStringValue));
                } catch (ParseException pe)  {
                    // swallow
                }
            }

            if (operation != Operation.EQUALS_OPER) {
                int offset = 0;
                try {
                    offset = Integer.parseInt(value);
                    if (operation == Operation.DECREMENT_OPER) {
                        offset = -1 * offset;
                    }
                } catch (NumberFormatException e) {
                    throw new BuildException("Value not an integer on " + key);
                }
                currentValue.add(field, offset);
            }

            newValue = fmt.format(currentValue.getTime());
        }


        /**
         * Handle operations for type <code>int</code>.
         *
         * @param oldValue the current value read from the property file or
         *                 <code>null</code> if the <code>key</code> was
         *                 not contained in the property file.
         */
        private void executeInteger(String oldValue) throws BuildException {
            int currentValue = DEFAULT_INT_VALUE;
            int newV  = DEFAULT_INT_VALUE;


            DecimalFormat fmt = (pattern != null) ? new DecimalFormat(pattern)
                : new DecimalFormat();
            try {
                String curval = getCurrentValue(oldValue);
                if (curval != null) {
                    currentValue = fmt.parse(curval).intValue();
                } else {
                    currentValue = 0;
                }
            } catch (NumberFormatException nfe) {
                // swallow
            } catch (ParseException pe)  {
                // swallow
            }

            if (operation == Operation.EQUALS_OPER) {
                newV = currentValue;
            } else {
                int operationValue = 1;
                if (value != null) {
                    try {
                        operationValue = fmt.parse(value).intValue();
                    } catch (NumberFormatException nfe) {
                        // swallow
                    } catch (ParseException pe)  {
                        // swallow
                    }
                }

                if (operation == Operation.INCREMENT_OPER) {
                    newV = currentValue + operationValue;
                } else if (operation == Operation.DECREMENT_OPER) {
                    newV = currentValue - operationValue;
                }
            }

            this.newValue = fmt.format(newV);
        }

        /**
         * Handle operations for type <code>string</code>.
         *
         * @param oldValue the current value read from the property file or
         *                 <code>null</code> if the <code>key</code> was
         *                 not contained in the property file.
         */
        private void executeString(String oldValue) throws BuildException {
            String newV  = DEFAULT_STRING_VALUE;

            String currentValue = getCurrentValue(oldValue);

            if (currentValue == null) {
                currentValue = DEFAULT_STRING_VALUE;
            }

            if (operation == Operation.EQUALS_OPER) {
                newV = currentValue;
            } else if (operation == Operation.INCREMENT_OPER) {
                newV = currentValue + value;
            }
            this.newValue = newV;
        }

        /**
         * Check if parameter combinations can be supported
         * @todo make sure the 'unit' attribute is only specified on date
         *      fields
         */
        private void checkParameters() throws BuildException {
            if (type == Type.STRING_TYPE
                && operation == Operation.DECREMENT_OPER) {
                throw new BuildException("- is not supported for string "
                                         + "properties (key:" + key + ")");
            }
            if (value == null && defaultValue == null  && operation != Operation.DELETE_OPER) {
                throw new BuildException("\"value\" and/or \"default\" "
                                         + "attribute must be specified (key:" + key + ")");
            }
            if (key == null) {
                throw new BuildException("key is mandatory");
            }
            if (type == Type.STRING_TYPE && pattern != null) {
                throw new BuildException("pattern is not supported for string "
                                         + "properties (key:" + key + ")");
            }
        }

        private String getCurrentValue(String oldValue) {
            String ret = null;
            if (operation == Operation.EQUALS_OPER) {
                // If only value is specified, the property is set to it
                // regardless of its previous value.
                if (value != null && defaultValue == null) {
                    ret = value;
                }

                // If only default is specified and the property previously
                // existed in the property file, it is unchanged.
                if (value == null && defaultValue != null && oldValue != null) {
                    ret = oldValue;
                }

                // If only default is specified and the property did not
                // exist in the property file, the property is set to default.
                if (value == null && defaultValue != null && oldValue == null) {
                    ret = defaultValue;
                }

                // If value and default are both specified and the property
                // previously existed in the property file, the property
                // is set to value.
                if (value != null && defaultValue != null && oldValue != null) {
                    ret = value;
                }

                // If value and default are both specified and the property
                // did not exist in the property file, the property is set
                // to default.
                if (value != null && defaultValue != null && oldValue == null) {
                    ret = defaultValue;
                }
            } else {
                ret = (oldValue == null) ? defaultValue : oldValue;
            }

            return ret;
        }

        /**
         * Enumerated attribute with the values "+", "-", "="
         */
        public static class Operation extends EnumeratedAttribute {

            // Property type operations
            /** + */
            public static final int INCREMENT_OPER =   0;
            /** - */
            public static final int DECREMENT_OPER =   1;
            /** = */
            public static final int EQUALS_OPER =      2;
            /** del */
            public static final int DELETE_OPER =      3;

            /** {@inheritDoc}. */
            @Override
            public String[] getValues() {
                return new String[] {"+", "-", "=", "del"};
            }

            /**
             * Convert string to index.
             * @param oper the string to convert.
             * @return the index.
             */
            public static int toOperation(String oper) {
                if ("+".equals(oper)) {
                    return INCREMENT_OPER;
                } else if ("-".equals(oper)) {
                    return DECREMENT_OPER;
                } else if ("del".equals(oper)) {
                    return DELETE_OPER;
                }
                return EQUALS_OPER;
            }
        }

        /**
         * Enumerated attribute with the values "int", "date" and "string".
         */
        public static class Type extends EnumeratedAttribute {

            // Property types
            /** int */
            public static final int INTEGER_TYPE =     0;
            /** date */
            public static final int DATE_TYPE =        1;
            /** string */
            public static final int STRING_TYPE =      2;

            /** {@inheritDoc} */
            @Override
            public String[] getValues() {
                return new String[] {"int", "date", "string"};
            }

            /**
             * Convert string to index.
             * @param type the string to convert.
             * @return the index.
             */
            public static int toType(String type) {
                if ("int".equals(type)) {
                    return INTEGER_TYPE;
                } else if ("date".equals(type)) {
                    return DATE_TYPE;
                }
                return STRING_TYPE;
            }
        }
    }

    /**
     * Borrowed from Tstamp
     * @todo share all this time stuff across many tasks as a datetime datatype
     * @since Ant 1.5
     */
    public static class Unit extends EnumeratedAttribute {

        private static final String MILLISECOND = "millisecond";
        private static final String SECOND = "second";
        private static final String MINUTE = "minute";
        private static final String HOUR = "hour";
        private static final String DAY = "day";
        private static final String WEEK = "week";
        private static final String MONTH = "month";
        private static final String YEAR = "year";

        private static final String[] UNITS
            = {MILLISECOND, SECOND, MINUTE, HOUR,
               DAY, WEEK, MONTH, YEAR };

        private Map calendarFields = new HashMap();

        /** no arg constructor */
        public Unit() {
            calendarFields.put(MILLISECOND,
                               new Integer(Calendar.MILLISECOND));
            calendarFields.put(SECOND, new Integer(Calendar.SECOND));
            calendarFields.put(MINUTE, new Integer(Calendar.MINUTE));
            calendarFields.put(HOUR, new Integer(Calendar.HOUR_OF_DAY));
            calendarFields.put(DAY, new Integer(Calendar.DATE));
            calendarFields.put(WEEK, new Integer(Calendar.WEEK_OF_YEAR));
            calendarFields.put(MONTH, new Integer(Calendar.MONTH));
            calendarFields.put(YEAR, new Integer(Calendar.YEAR));
        }

        /**
         * Convert the value to a Calendar field index.
         * @return the calendar value.
         */
        public int getCalendarField() {
            String key = getValue().toLowerCase();
            Integer i = (Integer) calendarFields.get(key);
            return i.intValue();
        }

        /** {@inheritDoc}. */
        @Override
        public String[] getValues() {
            return UNITS;
        }
    }
}