2
* Licensed to the Apache Software Foundation (ASF) under one or more
3
* contributor license agreements. See the NOTICE file distributed with
4
* this work for additional information regarding copyright ownership.
5
* The ASF licenses this file to You under the Apache License, Version 2.0
6
* (the "License"); you may not use this file except in compliance with
7
* the License. You may obtain a copy of the License at
9
* http://www.apache.org/licenses/LICENSE-2.0
11
* Unless required by applicable law or agreed to in writing, software
12
* distributed under the License is distributed on an "AS IS" BASIS,
13
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
* See the License for the specific language governing permissions and
15
* limitations under the License.
17
package org.apache.commons.configuration;
19
import java.io.IOException;
20
import java.io.Reader;
21
import java.io.Writer;
22
import java.util.LinkedHashMap;
23
import java.util.List;
27
import org.apache.commons.configuration.event.ConfigurationEvent;
28
import org.apache.commons.configuration.event.ConfigurationListener;
29
import org.apache.commons.lang.StringUtils;
33
* A helper class used by {@link PropertiesConfiguration} to keep
34
* the layout of a properties file.
37
* Instances of this class are associated with a
38
* {@code PropertiesConfiguration} object. They are responsible for
39
* analyzing properties files and for extracting as much information about the
40
* file layout (e.g. empty lines, comments) as possible. When the properties
41
* file is written back again it should be close to the original.
44
* The {@code PropertiesConfigurationLayout} object associated with a
45
* {@code PropertiesConfiguration} object can be obtained using the
46
* {@code getLayout()} method of the configuration. Then the methods
47
* provided by this class can be used to alter the properties file's layout.
50
* Implementation note: This is a very simple implementation, which is far away
51
* from being perfect, i.e. the original layout of a properties file won't be
52
* reproduced in all cases. One limitation is that comments for multi-valued
53
* property keys are concatenated. Maybe this implementation can later be
57
* To get an impression how this class works consider the following properties
63
* # A demo configuration file
69
* # Application vendor
75
* windowColors=0xFFFFFF,0x000000
77
* # Include some setting
78
* include=settings.properties
85
* For this example the following points are relevant:
89
* <li>The first two lines are set as header comment. The header comment is
90
* determined by the last blanc line before the first property definition.</li>
91
* <li>For the property {@code AppName} one comment line and one
92
* leading blanc line is stored.</li>
93
* <li>For the property {@code windowColors} two comment lines and two
94
* leading blanc lines are stored.</li>
95
* <li>Include files is something this class cannot deal with well. When saving
96
* the properties configuration back, the included properties are simply
97
* contained in the original file. The comment before the include property is
99
* <li>For all properties except for {@code AppVendor} the "single
100
* line" flag is set. This is relevant only for {@code windowColors},
101
* which has multiple values defined in one line using the separator character.</li>
102
* <li>The {@code AppVendor} property appears twice. The comment lines
103
* are concatenated, so that {@code layout.getComment("AppVendor");} will
104
* result in <code>Application vendor<CR>Another vendor</code>, with
105
* <code><CR></code> meaning the line separator. In addition the
106
* "single line" flag is set to <b>false</b> for this property. When
107
* the file is saved, two property definitions will be written (in series).</li>
112
* href="http://commons.apache.org/configuration/team-list.html">Commons
113
* Configuration team</a>
114
* @version $Id: PropertiesConfigurationLayout.java 1301991 2012-03-17 20:18:02Z sebb $
117
public class PropertiesConfigurationLayout implements ConfigurationListener
119
/** Constant for the line break character. */
120
private static final String CR = "\n";
122
/** Constant for the default comment prefix. */
123
private static final String COMMENT_PREFIX = "# ";
125
/** Stores the associated configuration object. */
126
private PropertiesConfiguration configuration;
128
/** Stores a map with the contained layout information. */
129
private Map<String, PropertyLayoutData> layoutData;
131
/** Stores the header comment. */
132
private String headerComment;
134
/** The global separator that will be used for all properties. */
135
private String globalSeparator;
137
/** The line separator.*/
138
private String lineSeparator;
140
/** A counter for determining nested load calls. */
141
private int loadCounter;
143
/** Stores the force single line flag. */
144
private boolean forceSingleLine;
147
* Creates a new instance of {@code PropertiesConfigurationLayout}
148
* and initializes it with the associated configuration object.
150
* @param config the configuration (must not be <b>null</b>)
152
public PropertiesConfigurationLayout(PropertiesConfiguration config)
158
* Creates a new instance of {@code PropertiesConfigurationLayout}
159
* and initializes it with the given configuration object. The data of the
160
* specified layout object is copied.
162
* @param config the configuration (must not be <b>null</b>)
163
* @param c the layout object to be copied
165
public PropertiesConfigurationLayout(PropertiesConfiguration config,
166
PropertiesConfigurationLayout c)
170
throw new IllegalArgumentException(
171
"Configuration must not be null!");
173
configuration = config;
174
layoutData = new LinkedHashMap<String, PropertyLayoutData>();
175
config.addConfigurationListener(this);
184
* Returns the associated configuration object.
186
* @return the associated configuration
188
public PropertiesConfiguration getConfiguration()
190
return configuration;
194
* Returns the comment for the specified property key in a canonical form.
195
* "Canonical" means that either all lines start with a comment
196
* character or none. If the {@code commentChar} parameter is <b>false</b>,
197
* all comment characters are removed, so that the result is only the plain
198
* text of the comment. Otherwise it is ensured that each line of the
199
* comment starts with a comment character. Also, line breaks in the comment
200
* are normalized to the line separator "\n".
202
* @param key the key of the property
203
* @param commentChar determines whether all lines should start with comment
205
* @return the canonical comment for this key (can be <b>null</b>)
207
public String getCanonicalComment(String key, boolean commentChar)
209
String comment = getComment(key);
216
return trimComment(comment, commentChar);
221
* Returns the comment for the specified property key. The comment is
222
* returned as it was set (either manually by calling
223
* {@code setComment()} or when it was loaded from a properties
224
* file). No modifications are performed.
226
* @param key the key of the property
227
* @return the comment for this key (can be <b>null</b>)
229
public String getComment(String key)
231
return fetchLayoutData(key).getComment();
235
* Sets the comment for the specified property key. The comment (or its
236
* single lines if it is a multi-line comment) can start with a comment
237
* character. If this is the case, it will be written without changes.
238
* Otherwise a default comment character is added automatically.
240
* @param key the key of the property
241
* @param comment the comment for this key (can be <b>null</b>, then the
242
* comment will be removed)
244
public void setComment(String key, String comment)
246
fetchLayoutData(key).setComment(comment);
250
* Returns the number of blanc lines before this property key. If this key
251
* does not exist, 0 will be returned.
253
* @param key the property key
254
* @return the number of blanc lines before the property definition for this
257
public int getBlancLinesBefore(String key)
259
return fetchLayoutData(key).getBlancLines();
263
* Sets the number of blanc lines before the given property key. This can be
264
* used for a logical grouping of properties.
266
* @param key the property key
267
* @param number the number of blanc lines to add before this property
270
public void setBlancLinesBefore(String key, int number)
272
fetchLayoutData(key).setBlancLines(number);
276
* Returns the header comment of the represented properties file in a
277
* canonical form. With the {@code commentChar} parameter it can be
278
* specified whether comment characters should be stripped or be always
281
* @param commentChar determines the presence of comment characters
282
* @return the header comment (can be <b>null</b>)
284
public String getCanonicalHeaderComment(boolean commentChar)
286
return (getHeaderComment() == null) ? null : trimComment(
287
getHeaderComment(), commentChar);
291
* Returns the header comment of the represented properties file. This
292
* method returns the header comment exactly as it was set using
293
* {@code setHeaderComment()} or extracted from the loaded properties
296
* @return the header comment (can be <b>null</b>)
298
public String getHeaderComment()
300
return headerComment;
304
* Sets the header comment for the represented properties file. This comment
305
* will be output on top of the file.
307
* @param comment the comment
309
public void setHeaderComment(String comment)
311
headerComment = comment;
315
* Returns a flag whether the specified property is defined on a single
316
* line. This is meaningful only if this property has multiple values.
318
* @param key the property key
319
* @return a flag if this property is defined on a single line
321
public boolean isSingleLine(String key)
323
return fetchLayoutData(key).isSingleLine();
327
* Sets the "single line flag" for the specified property key.
328
* This flag is evaluated if the property has multiple values (i.e. if it is
329
* a list property). In this case, if the flag is set, all values will be
330
* written in a single property definition using the list delimiter as
331
* separator. Otherwise multiple lines will be written for this property,
332
* each line containing one property value.
334
* @param key the property key
335
* @param f the single line flag
337
public void setSingleLine(String key, boolean f)
339
fetchLayoutData(key).setSingleLine(f);
343
* Returns the "force single line" flag.
345
* @return the force single line flag
346
* @see #setForceSingleLine(boolean)
348
public boolean isForceSingleLine()
350
return forceSingleLine;
354
* Sets the "force single line" flag. If this flag is set, all
355
* properties with multiple values are written on single lines. This mode
356
* provides more compatibility with {@code java.lang.Properties},
357
* which cannot deal with multiple definitions of a single property. This
358
* mode has no effect if the list delimiter parsing is disabled.
360
* @param f the force single line flag
362
public void setForceSingleLine(boolean f)
368
* Returns the separator for the property with the given key.
370
* @param key the property key
371
* @return the property separator for this property
374
public String getSeparator(String key)
376
return fetchLayoutData(key).getSeparator();
380
* Sets the separator to be used for the property with the given key. The
381
* separator is the string between the property key and its value. For new
382
* properties " = " is used. When a properties file is read, the
383
* layout tries to determine the separator for each property. With this
384
* method the separator can be changed. To be compatible with the properties
385
* format only the characters {@code =} and {@code :} (with or
386
* without whitespace) should be used, but this method does not enforce this
387
* - it accepts arbitrary strings. If the key refers to a property with
388
* multiple values that are written on multiple lines, this separator will
389
* be used on all lines.
391
* @param key the key for the property
392
* @param sep the separator to be used for this property
395
public void setSeparator(String key, String sep)
397
fetchLayoutData(key).setSeparator(sep);
401
* Returns the global separator.
403
* @return the global properties separator
406
public String getGlobalSeparator()
408
return globalSeparator;
412
* Sets the global separator for properties. With this method a separator
413
* can be set that will be used for all properties when writing the
414
* configuration. This is an easy way of determining the properties
415
* separator globally. To be compatible with the properties format only the
416
* characters {@code =} and {@code :} (with or without whitespace)
417
* should be used, but this method does not enforce this - it accepts
418
* arbitrary strings. If the global separator is set to <b>null</b>,
419
* property separators are not changed. This is the default behavior as it
420
* produces results that are closer to the original properties file.
422
* @param globalSeparator the separator to be used for all properties
425
public void setGlobalSeparator(String globalSeparator)
427
this.globalSeparator = globalSeparator;
431
* Returns the line separator.
433
* @return the line separator
436
public String getLineSeparator()
438
return lineSeparator;
442
* Sets the line separator. When writing the properties configuration, all
443
* lines are terminated with this separator. If no separator was set, the
444
* platform-specific default line separator is used.
446
* @param lineSeparator the line separator
449
public void setLineSeparator(String lineSeparator)
451
this.lineSeparator = lineSeparator;
455
* Returns a set with all property keys managed by this object.
457
* @return a set with all contained property keys
459
public Set<String> getKeys()
461
return layoutData.keySet();
465
* Reads a properties file and stores its internal structure. The found
466
* properties will be added to the associated configuration object.
468
* @param in the reader to the properties file
469
* @throws ConfigurationException if an error occurs
471
public void load(Reader in) throws ConfigurationException
473
if (++loadCounter == 1)
475
getConfiguration().removeConfigurationListener(this);
477
PropertiesConfiguration.PropertiesReader reader = getConfiguration()
478
.getIOFactory().createPropertiesReader(in,
479
getConfiguration().getListDelimiter());
483
while (reader.nextProperty())
485
if (getConfiguration().propertyLoaded(reader.getPropertyName(),
486
reader.getPropertyValue()))
488
boolean contained = layoutData.containsKey(reader
491
int idx = checkHeaderComment(reader.getCommentLines());
492
while (idx < reader.getCommentLines().size()
493
&& reader.getCommentLines().get(idx).length() < 1)
498
String comment = extractComment(reader.getCommentLines(),
499
idx, reader.getCommentLines().size() - 1);
500
PropertyLayoutData data = fetchLayoutData(reader
504
data.addComment(comment);
505
data.setSingleLine(false);
509
data.setComment(comment);
510
data.setBlancLines(blancLines);
511
data.setSeparator(reader.getPropertySeparator());
516
catch (IOException ioex)
518
throw new ConfigurationException(ioex);
522
if (--loadCounter == 0)
524
getConfiguration().addConfigurationListener(this);
530
* Writes the properties file to the given writer, preserving as much of its
531
* structure as possible.
533
* @param out the writer
534
* @throws ConfigurationException if an error occurs
536
public void save(Writer out) throws ConfigurationException
540
char delimiter = getConfiguration().isDelimiterParsingDisabled() ? 0
541
: getConfiguration().getListDelimiter();
542
PropertiesConfiguration.PropertiesWriter writer = getConfiguration()
543
.getIOFactory().createPropertiesWriter(out, delimiter);
544
writer.setGlobalSeparator(getGlobalSeparator());
545
if (getLineSeparator() != null)
547
writer.setLineSeparator(getLineSeparator());
550
if (headerComment != null)
552
writeComment(writer, getCanonicalHeaderComment(true));
553
writer.writeln(null);
556
for (String key : layoutData.keySet())
558
if (getConfiguration().containsKey(key))
561
// Output blank lines before property
562
for (int i = 0; i < getBlancLinesBefore(key); i++)
564
writer.writeln(null);
567
// Output the comment
568
writeComment(writer, getCanonicalComment(key, true));
570
// Output the property and its value
571
boolean singleLine = (isForceSingleLine() || isSingleLine(key))
572
&& !getConfiguration().isDelimiterParsingDisabled();
573
writer.setCurrentSeparator(getSeparator(key));
574
writer.writeProperty(key, getConfiguration().getProperty(
580
catch (IOException ioex)
582
throw new ConfigurationException(ioex);
587
* The event listener callback. Here event notifications of the
588
* configuration object are processed to update the layout object properly.
590
* @param event the event object
592
public void configurationChanged(ConfigurationEvent event)
594
if (event.isBeforeUpdate())
596
if (AbstractFileConfiguration.EVENT_RELOAD == event.getType())
604
switch (event.getType())
606
case AbstractConfiguration.EVENT_ADD_PROPERTY:
607
boolean contained = layoutData.containsKey(event
609
PropertyLayoutData data = fetchLayoutData(event
611
data.setSingleLine(!contained);
613
case AbstractConfiguration.EVENT_CLEAR_PROPERTY:
614
layoutData.remove(event.getPropertyName());
616
case AbstractConfiguration.EVENT_CLEAR:
619
case AbstractConfiguration.EVENT_SET_PROPERTY:
620
fetchLayoutData(event.getPropertyName());
627
* Returns a layout data object for the specified key. If this is a new key,
628
* a new object is created and initialized with default values.
631
* @return the corresponding layout data object
633
private PropertyLayoutData fetchLayoutData(String key)
637
throw new IllegalArgumentException("Property key must not be null!");
640
PropertyLayoutData data = layoutData.get(key);
643
data = new PropertyLayoutData();
644
data.setSingleLine(true);
645
layoutData.put(key, data);
652
* Removes all content from this layout object.
657
setHeaderComment(null);
661
* Tests whether a line is a comment, i.e. whether it starts with a comment
664
* @param line the line
665
* @return a flag if this is a comment line
667
static boolean isCommentLine(String line)
669
return PropertiesConfiguration.isCommentLine(line);
673
* Trims a comment. This method either removes all comment characters from
674
* the given string, leaving only the plain comment text or ensures that
675
* every line starts with a valid comment character.
677
* @param s the string to be processed
678
* @param comment if <b>true</b>, a comment character will always be
679
* enforced; if <b>false</b>, it will be removed
680
* @return the trimmed comment
682
static String trimComment(String s, boolean comment)
684
StringBuilder buf = new StringBuilder(s.length());
690
pos = s.indexOf(CR, lastPos);
693
String line = s.substring(lastPos, pos);
694
buf.append(stripCommentChar(line, comment)).append(CR);
695
lastPos = pos + CR.length();
699
if (lastPos < s.length())
701
buf.append(stripCommentChar(s.substring(lastPos), comment));
703
return buf.toString();
707
* Either removes the comment character from the given comment line or
708
* ensures that the line starts with a comment character.
710
* @param s the comment line
711
* @param comment if <b>true</b>, a comment character will always be
712
* enforced; if <b>false</b>, it will be removed
713
* @return the line without comment character
715
static String stripCommentChar(String s, boolean comment)
717
if (s.length() < 1 || (isCommentLine(s) == comment))
727
// find first comment character
728
while (PropertiesConfiguration.COMMENT_CHARS.indexOf(s
734
// Remove leading spaces
736
while (pos < s.length()
737
&& Character.isWhitespace(s.charAt(pos)))
742
return (pos < s.length()) ? s.substring(pos)
747
return COMMENT_PREFIX + s;
753
* Extracts a comment string from the given range of the specified comment
754
* lines. The single lines are added using a line feed as separator.
756
* @param commentLines a list with comment lines
757
* @param from the start index
758
* @param to the end index (inclusive)
759
* @return the comment string (<b>null</b> if it is undefined)
761
private String extractComment(List<String> commentLines, int from, int to)
770
StringBuilder buf = new StringBuilder(commentLines.get(from));
771
for (int i = from + 1; i <= to; i++)
774
buf.append(commentLines.get(i));
776
return buf.toString();
781
* Checks if parts of the passed in comment can be used as header comment.
782
* This method checks whether a header comment can be defined (i.e. whether
783
* this is the first comment in the loaded file). If this is the case, it is
784
* searched for the latest blanc line. This line will mark the end of the
785
* header comment. The return value is the index of the first line in the
786
* passed in list, which does not belong to the header comment.
788
* @param commentLines the comment lines
789
* @return the index of the next line after the header comment
791
private int checkHeaderComment(List<String> commentLines)
793
if (loadCounter == 1 && getHeaderComment() == null
794
&& layoutData.isEmpty())
796
// This is the first comment. Search for blanc lines.
797
int index = commentLines.size() - 1;
799
&& commentLines.get(index).length() > 0)
803
setHeaderComment(extractComment(commentLines, 0, index - 1));
813
* Copies the data from the given layout object.
815
* @param c the layout object to copy
817
private void copyFrom(PropertiesConfigurationLayout c)
819
for (String key : c.getKeys())
821
PropertyLayoutData data = c.layoutData.get(key);
822
layoutData.put(key, data.clone());
827
* Helper method for writing a comment line. This method ensures that the
828
* correct line separator is used if the comment spans multiple lines.
830
* @param writer the writer
831
* @param comment the comment to write
832
* @throws IOException if an IO error occurs
834
private static void writeComment(
835
PropertiesConfiguration.PropertiesWriter writer, String comment)
840
writer.writeln(StringUtils.replace(comment, CR, writer
841
.getLineSeparator()));
846
* A helper class for storing all layout related information for a
847
* configuration property.
849
static class PropertyLayoutData implements Cloneable
851
/** Stores the comment for the property. */
852
private StringBuffer comment;
854
/** The separator to be used for this property. */
855
private String separator;
857
/** Stores the number of blanc lines before this property. */
858
private int blancLines;
860
/** Stores the single line property. */
861
private boolean singleLine;
864
* Creates a new instance of {@code PropertyLayoutData}.
866
public PropertyLayoutData()
869
separator = PropertiesConfiguration.DEFAULT_SEPARATOR;
873
* Returns the number of blanc lines before this property.
875
* @return the number of blanc lines before this property
877
public int getBlancLines()
883
* Sets the number of properties before this property.
885
* @param blancLines the number of properties before this property
887
public void setBlancLines(int blancLines)
889
this.blancLines = blancLines;
893
* Returns the single line flag.
895
* @return the single line flag
897
public boolean isSingleLine()
903
* Sets the single line flag.
905
* @param singleLine the single line flag
907
public void setSingleLine(boolean singleLine)
909
this.singleLine = singleLine;
913
* Adds a comment for this property. If already a comment exists, the
914
* new comment is added (separated by a newline).
916
* @param s the comment to add
918
public void addComment(String s)
924
comment = new StringBuffer(s);
928
comment.append(CR).append(s);
934
* Sets the comment for this property.
936
* @param s the new comment (can be <b>null</b>)
938
public void setComment(String s)
946
comment = new StringBuffer(s);
951
* Returns the comment for this property. The comment is returned as it
952
* is, without processing of comment characters.
954
* @return the comment (can be <b>null</b>)
956
public String getComment()
958
return (comment == null) ? null : comment.toString();
962
* Returns the separator that was used for this property.
964
* @return the property separator
966
public String getSeparator()
972
* Sets the separator to be used for the represented property.
974
* @param separator the property separator
976
public void setSeparator(String separator)
978
this.separator = separator;
982
* Creates a copy of this object.
987
public PropertyLayoutData clone()
991
PropertyLayoutData copy = (PropertyLayoutData) super.clone();
994
// must copy string buffer, too
995
copy.comment = new StringBuffer(getComment());
999
catch (CloneNotSupportedException cnex)
1001
// This cannot happen!
1002
throw new ConfigurationRuntimeException(cnex);