001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.configuration2; 018 019import java.io.IOException; 020import java.io.Reader; 021import java.io.Writer; 022import java.net.URL; 023import java.util.ArrayDeque; 024import java.util.LinkedHashMap; 025import java.util.List; 026import java.util.Map; 027import java.util.Objects; 028import java.util.Set; 029import java.util.concurrent.atomic.AtomicInteger; 030 031import org.apache.commons.configuration2.event.ConfigurationEvent; 032import org.apache.commons.configuration2.event.EventListener; 033import org.apache.commons.configuration2.ex.ConfigurationException; 034import org.apache.commons.configuration2.ex.ConfigurationRuntimeException; 035import org.apache.commons.lang3.StringUtils; 036 037/** 038 * <p> 039 * A helper class used by {@link PropertiesConfiguration} to keep the layout of a properties file. 040 * </p> 041 * <p> 042 * Instances of this class are associated with a {@code PropertiesConfiguration} object. They are responsible for 043 * analyzing properties files and for extracting as much information about the file layout (e.g. empty lines, comments) 044 * as possible. When the properties file is written back again it should be close to the original. 045 * </p> 046 * <p> 047 * The {@code PropertiesConfigurationLayout} object associated with a {@code PropertiesConfiguration} object can be 048 * obtained using the {@code getLayout()} method of the configuration. Then the methods provided by this class can be 049 * used to alter the properties file's layout. 050 * </p> 051 * <p> 052 * Implementation note: This is a very simple implementation, which is far away from being perfect, i.e. the original 053 * layout of a properties file won't be reproduced in all cases. One limitation is that comments for multi-valued 054 * property keys are concatenated. Maybe this implementation can later be improved. 055 * </p> 056 * <p> 057 * To get an impression how this class works consider the following properties file: 058 * </p> 059 * 060 * <pre> 061 * # A demo configuration file 062 * # for Demo App 1.42 063 * 064 * # Application name 065 * AppName=Demo App 066 * 067 * # Application vendor 068 * AppVendor=DemoSoft 069 * 070 * 071 * # GUI properties 072 * # Window Color 073 * windowColors=0xFFFFFF,0x000000 074 * 075 * # Include some setting 076 * include=settings.properties 077 * # Another vendor 078 * AppVendor=TestSoft 079 * </pre> 080 * 081 * <p> 082 * For this example the following points are relevant: 083 * </p> 084 * <ul> 085 * <li>The first two lines are set as header comment. The header comment is determined by the last blank line before the 086 * first property definition.</li> 087 * <li>For the property {@code AppName} one comment line and one leading blank line is stored.</li> 088 * <li>For the property {@code windowColors} two comment lines and two leading blank lines are stored.</li> 089 * <li>Include files is something this class cannot deal with well. When saving the properties configuration back, the 090 * included properties are simply contained in the original file. The comment before the include property is 091 * skipped.</li> 092 * <li>For all properties except for {@code AppVendor} the "single line" flag is set. This is relevant only 093 * for {@code windowColors}, which has multiple values defined in one line using the separator character.</li> 094 * <li>The {@code AppVendor} property appears twice. The comment lines are concatenated, so that 095 * {@code layout.getComment("AppVendor");} will result in {@code Application vendor<CR>Another vendor}, with 096 * {@code <CR>} meaning the line separator. In addition the "single line" flag is set to <b>false</b> 097 * for this property. When the file is saved, two property definitions will be written (in series).</li> 098 * </ul> 099 * 100 * @since 1.3 101 */ 102public class PropertiesConfigurationLayout implements EventListener<ConfigurationEvent> { 103 /** Constant for the line break character. */ 104 private static final String CR = "\n"; 105 106 /** Constant for the default comment prefix. */ 107 private static final String COMMENT_PREFIX = "# "; 108 109 /** Stores a map with the contained layout information. */ 110 private final Map<String, PropertyLayoutData> layoutData; 111 112 /** Stores the header comment. */ 113 private String headerComment; 114 115 /** Stores the footer comment. */ 116 private String footerComment; 117 118 /** The global separator that will be used for all properties. */ 119 private String globalSeparator; 120 121 /** The line separator. */ 122 private String lineSeparator; 123 124 /** A counter for determining nested load calls. */ 125 private final AtomicInteger loadCounter; 126 127 /** Stores the force single line flag. */ 128 private boolean forceSingleLine; 129 130 /** Seen includes. */ 131 private final ArrayDeque<URL> seenStack = new ArrayDeque<>(); 132 133 /** 134 * Creates a new, empty instance of {@code PropertiesConfigurationLayout}. 135 */ 136 public PropertiesConfigurationLayout() { 137 this(null); 138 } 139 140 /** 141 * Creates a new instance of {@code PropertiesConfigurationLayout} and copies the data of the specified layout object. 142 * 143 * @param c the layout object to be copied 144 */ 145 public PropertiesConfigurationLayout(final PropertiesConfigurationLayout c) { 146 loadCounter = new AtomicInteger(); 147 layoutData = new LinkedHashMap<>(); 148 149 if (c != null) { 150 copyFrom(c); 151 } 152 } 153 154 /** 155 * Gets the comment for the specified property key in a canonical form. "Canonical" means that either all 156 * lines start with a comment character or none. If the {@code commentChar} parameter is <b>false</b>, all comment 157 * characters are removed, so that the result is only the plain text of the comment. Otherwise it is ensured that each 158 * line of the comment starts with a comment character. Also, line breaks in the comment are normalized to the line 159 * separator "\n". 160 * 161 * @param key the key of the property 162 * @param commentChar determines whether all lines should start with comment characters or not 163 * @return the canonical comment for this key (can be <b>null</b>) 164 */ 165 public String getCanonicalComment(final String key, final boolean commentChar) { 166 return constructCanonicalComment(getComment(key), commentChar); 167 } 168 169 /** 170 * Gets the comment for the specified property key. The comment is returned as it was set (either manually by calling 171 * {@code setComment()} or when it was loaded from a properties file). No modifications are performed. 172 * 173 * @param key the key of the property 174 * @return the comment for this key (can be <b>null</b>) 175 */ 176 public String getComment(final String key) { 177 return fetchLayoutData(key).getComment(); 178 } 179 180 /** 181 * Sets the comment for the specified property key. The comment (or its single lines if it is a multi-line comment) can 182 * start with a comment character. If this is the case, it will be written without changes. Otherwise a default comment 183 * character is added automatically. 184 * 185 * @param key the key of the property 186 * @param comment the comment for this key (can be <b>null</b>, then the comment will be removed) 187 */ 188 public void setComment(final String key, final String comment) { 189 fetchLayoutData(key).setComment(comment); 190 } 191 192 /** 193 * Gets the number of blank lines before this property key. If this key does not exist, 0 will be returned. 194 * 195 * @param key the property key 196 * @return the number of blank lines before the property definition for this key 197 * @deprecated Use {@link #getBlankLinesBefore(String)}. 198 */ 199 @Deprecated 200 public int getBlancLinesBefore(final String key) { 201 return getBlankLinesBefore(key); 202 } 203 204 /** 205 * Gets the number of blank lines before this property key. If this key does not exist, 0 will be returned. 206 * 207 * @param key the property key 208 * @return the number of blank lines before the property definition for this key 209 */ 210 public int getBlankLinesBefore(final String key) { 211 return fetchLayoutData(key).getBlankLines(); 212 } 213 214 /** 215 * Sets the number of blank lines before the given property key. This can be used for a logical grouping of properties. 216 * 217 * @param key the property key 218 * @param number the number of blank lines to add before this property definition 219 * @deprecated use {@link PropertiesConfigurationLayout#setBlankLinesBefore(String, int)}. 220 */ 221 @Deprecated 222 public void setBlancLinesBefore(final String key, final int number) { 223 setBlankLinesBefore(key, number); 224 } 225 226 /** 227 * Sets the number of blank lines before the given property key. This can be used for a logical grouping of properties. 228 * 229 * @param key the property key 230 * @param number the number of blank lines to add before this property definition 231 * @since 2.8.0 232 */ 233 public void setBlankLinesBefore(final String key, final int number) { 234 fetchLayoutData(key).setBlankLines(number); 235 } 236 237 /** 238 * Gets the header comment of the represented properties file in a canonical form. With the {@code commentChar} 239 * parameter it can be specified whether comment characters should be stripped or be always present. 240 * 241 * @param commentChar determines the presence of comment characters 242 * @return the header comment (can be <b>null</b>) 243 */ 244 public String getCanonicalHeaderComment(final boolean commentChar) { 245 return constructCanonicalComment(getHeaderComment(), commentChar); 246 } 247 248 /** 249 * Gets the header comment of the represented properties file. This method returns the header comment exactly as it 250 * was set using {@code setHeaderComment()} or extracted from the loaded properties file. 251 * 252 * @return the header comment (can be <b>null</b>) 253 */ 254 public String getHeaderComment() { 255 return headerComment; 256 } 257 258 /** 259 * Sets the header comment for the represented properties file. This comment will be output on top of the file. 260 * 261 * @param comment the comment 262 */ 263 public void setHeaderComment(final String comment) { 264 headerComment = comment; 265 } 266 267 /** 268 * Gets the footer comment of the represented properties file in a canonical form. This method works like 269 * {@code getCanonicalHeaderComment()}, but reads the footer comment. 270 * 271 * @param commentChar determines the presence of comment characters 272 * @return the footer comment (can be <b>null</b>) 273 * @see #getCanonicalHeaderComment(boolean) 274 * @since 2.0 275 */ 276 public String getCanonicalFooterCooment(final boolean commentChar) { 277 return constructCanonicalComment(getFooterComment(), commentChar); 278 } 279 280 /** 281 * Gets the footer comment of the represented properties file. This method returns the footer comment exactly as it 282 * was set using {@code setFooterComment()} or extracted from the loaded properties file. 283 * 284 * @return the footer comment (can be <b>null</b>) 285 * @since 2.0 286 */ 287 public String getFooterComment() { 288 return footerComment; 289 } 290 291 /** 292 * Sets the footer comment for the represented properties file. This comment will be output at the bottom of the file. 293 * 294 * @param footerComment the footer comment 295 * @since 2.0 296 */ 297 public void setFooterComment(final String footerComment) { 298 this.footerComment = footerComment; 299 } 300 301 /** 302 * Returns a flag whether the specified property is defined on a single line. This is meaningful only if this property 303 * has multiple values. 304 * 305 * @param key the property key 306 * @return a flag if this property is defined on a single line 307 */ 308 public boolean isSingleLine(final String key) { 309 return fetchLayoutData(key).isSingleLine(); 310 } 311 312 /** 313 * Sets the "single line flag" for the specified property key. This flag is evaluated if the property has 314 * multiple values (i.e. if it is a list property). In this case, if the flag is set, all values will be written in a 315 * single property definition using the list delimiter as separator. Otherwise multiple lines will be written for this 316 * property, each line containing one property value. 317 * 318 * @param key the property key 319 * @param f the single line flag 320 */ 321 public void setSingleLine(final String key, final boolean f) { 322 fetchLayoutData(key).setSingleLine(f); 323 } 324 325 /** 326 * Returns the "force single line" flag. 327 * 328 * @return the force single line flag 329 * @see #setForceSingleLine(boolean) 330 */ 331 public boolean isForceSingleLine() { 332 return forceSingleLine; 333 } 334 335 /** 336 * Sets the "force single line" flag. If this flag is set, all properties with multiple values are written on 337 * single lines. This mode provides more compatibility with {@code java.lang.Properties}, which cannot deal with 338 * multiple definitions of a single property. This mode has no effect if the list delimiter parsing is disabled. 339 * 340 * @param f the force single line flag 341 */ 342 public void setForceSingleLine(final boolean f) { 343 forceSingleLine = f; 344 } 345 346 /** 347 * Gets the separator for the property with the given key. 348 * 349 * @param key the property key 350 * @return the property separator for this property 351 * @since 1.7 352 */ 353 public String getSeparator(final String key) { 354 return fetchLayoutData(key).getSeparator(); 355 } 356 357 /** 358 * Sets the separator to be used for the property with the given key. The separator is the string between the property 359 * key and its value. For new properties " = " is used. When a properties file is read, the layout tries to 360 * determine the separator for each property. With this method the separator can be changed. To be compatible with the 361 * properties format only the characters {@code =} and {@code :} (with or without whitespace) should be used, but this 362 * method does not enforce this - it accepts arbitrary strings. If the key refers to a property with multiple values 363 * that are written on multiple lines, this separator will be used on all lines. 364 * 365 * @param key the key for the property 366 * @param sep the separator to be used for this property 367 * @since 1.7 368 */ 369 public void setSeparator(final String key, final String sep) { 370 fetchLayoutData(key).setSeparator(sep); 371 } 372 373 /** 374 * Gets the global separator. 375 * 376 * @return the global properties separator 377 * @since 1.7 378 */ 379 public String getGlobalSeparator() { 380 return globalSeparator; 381 } 382 383 /** 384 * Sets the global separator for properties. With this method a separator can be set that will be used for all 385 * properties when writing the configuration. This is an easy way of determining the properties separator globally. To 386 * be compatible with the properties format only the characters {@code =} and {@code :} (with or without whitespace) 387 * should be used, but this method does not enforce this - it accepts arbitrary strings. If the global separator is set 388 * to <b>null</b>, property separators are not changed. This is the default behavior as it produces results that are 389 * closer to the original properties file. 390 * 391 * @param globalSeparator the separator to be used for all properties 392 * @since 1.7 393 */ 394 public void setGlobalSeparator(final String globalSeparator) { 395 this.globalSeparator = globalSeparator; 396 } 397 398 /** 399 * Gets the line separator. 400 * 401 * @return the line separator 402 * @since 1.7 403 */ 404 public String getLineSeparator() { 405 return lineSeparator; 406 } 407 408 /** 409 * Sets the line separator. When writing the properties configuration, all lines are terminated with this separator. If 410 * no separator was set, the platform-specific default line separator is used. 411 * 412 * @param lineSeparator the line separator 413 * @since 1.7 414 */ 415 public void setLineSeparator(final String lineSeparator) { 416 this.lineSeparator = lineSeparator; 417 } 418 419 /** 420 * Gets a set with all property keys managed by this object. 421 * 422 * @return a set with all contained property keys 423 */ 424 public Set<String> getKeys() { 425 return layoutData.keySet(); 426 } 427 428 /** 429 * Reads a properties file and stores its internal structure. The found properties will be added to the specified 430 * configuration object. 431 * 432 * @param config the associated configuration object 433 * @param reader the reader to the properties file 434 * @throws ConfigurationException if an error occurs 435 */ 436 public void load(final PropertiesConfiguration config, final Reader reader) throws ConfigurationException { 437 loadCounter.incrementAndGet(); 438 @SuppressWarnings("resource") // createPropertiesReader wraps the reader. 439 final PropertiesConfiguration.PropertiesReader pReader = config.getIOFactory().createPropertiesReader(reader); 440 441 try { 442 while (pReader.nextProperty()) { 443 if (config.propertyLoaded(pReader.getPropertyName(), pReader.getPropertyValue(), seenStack)) { 444 final boolean contained = layoutData.containsKey(pReader.getPropertyName()); 445 int blankLines = 0; 446 int idx = checkHeaderComment(pReader.getCommentLines()); 447 while (idx < pReader.getCommentLines().size() && StringUtils.isEmpty(pReader.getCommentLines().get(idx))) { 448 idx++; 449 blankLines++; 450 } 451 final String comment = extractComment(pReader.getCommentLines(), idx, pReader.getCommentLines().size() - 1); 452 final PropertyLayoutData data = fetchLayoutData(pReader.getPropertyName()); 453 if (contained) { 454 data.addComment(comment); 455 data.setSingleLine(false); 456 } else { 457 data.setComment(comment); 458 data.setBlankLines(blankLines); 459 data.setSeparator(pReader.getPropertySeparator()); 460 } 461 } 462 } 463 464 setFooterComment(extractComment(pReader.getCommentLines(), 0, pReader.getCommentLines().size() - 1)); 465 } catch (final IOException ioex) { 466 throw new ConfigurationException(ioex); 467 } finally { 468 loadCounter.decrementAndGet(); 469 } 470 } 471 472 /** 473 * Writes the properties file to the given writer, preserving as much of its structure as possible. 474 * 475 * @param config the associated configuration object 476 * @param writer the writer 477 * @throws ConfigurationException if an error occurs 478 */ 479 public void save(final PropertiesConfiguration config, final Writer writer) throws ConfigurationException { 480 try { 481 @SuppressWarnings("resource") // createPropertiesReader wraps the writer. 482 final PropertiesConfiguration.PropertiesWriter pWriter = config.getIOFactory().createPropertiesWriter(writer, config.getListDelimiterHandler()); 483 pWriter.setGlobalSeparator(getGlobalSeparator()); 484 if (getLineSeparator() != null) { 485 pWriter.setLineSeparator(getLineSeparator()); 486 } 487 488 if (headerComment != null) { 489 writeComment(pWriter, getCanonicalHeaderComment(true)); 490 } 491 492 boolean firstKey = true; 493 for (final String key : getKeys()) { 494 if (config.containsKeyInternal(key)) { 495 // preset header comment needs to be separated from key 496 if (firstKey && headerComment != null && getBlankLinesBefore(key) == 0) { 497 pWriter.writeln(null); 498 } 499 500 // Output blank lines before property 501 for (int i = 0; i < getBlankLinesBefore(key); i++) { 502 pWriter.writeln(null); 503 } 504 505 // Output the comment 506 writeComment(pWriter, getCanonicalComment(key, true)); 507 508 // Output the property and its value 509 final boolean singleLine = isForceSingleLine() || isSingleLine(key); 510 pWriter.setCurrentSeparator(getSeparator(key)); 511 pWriter.writeProperty(key, config.getPropertyInternal(key), singleLine); 512 } 513 firstKey = false; 514 } 515 516 writeComment(pWriter, getCanonicalFooterCooment(true)); 517 pWriter.flush(); 518 } catch (final IOException ioex) { 519 throw new ConfigurationException(ioex); 520 } 521 } 522 523 /** 524 * The event listener callback. Here event notifications of the configuration object are processed to update the layout 525 * object properly. 526 * 527 * @param event the event object 528 */ 529 @Override 530 public void onEvent(final ConfigurationEvent event) { 531 if (!event.isBeforeUpdate() && loadCounter.get() == 0) { 532 if (ConfigurationEvent.ADD_PROPERTY.equals(event.getEventType())) { 533 final boolean contained = layoutData.containsKey(event.getPropertyName()); 534 final PropertyLayoutData data = fetchLayoutData(event.getPropertyName()); 535 data.setSingleLine(!contained); 536 } else if (ConfigurationEvent.CLEAR_PROPERTY.equals(event.getEventType())) { 537 layoutData.remove(event.getPropertyName()); 538 } else if (ConfigurationEvent.CLEAR.equals(event.getEventType())) { 539 clear(); 540 } else if (ConfigurationEvent.SET_PROPERTY.equals(event.getEventType())) { 541 fetchLayoutData(event.getPropertyName()); 542 } 543 } 544 } 545 546 /** 547 * Returns a layout data object for the specified key. If this is a new key, a new object is created and initialized 548 * with default values. 549 * 550 * @param key the key 551 * @return the corresponding layout data object 552 */ 553 private PropertyLayoutData fetchLayoutData(final String key) { 554 if (key == null) { 555 throw new IllegalArgumentException("Property key must not be null!"); 556 } 557 558 PropertyLayoutData data = layoutData.get(key); 559 if (data == null) { 560 data = new PropertyLayoutData(); 561 data.setSingleLine(true); 562 layoutData.put(key, data); 563 } 564 565 return data; 566 } 567 568 /** 569 * Removes all content from this layout object. 570 */ 571 private void clear() { 572 seenStack.clear(); 573 layoutData.clear(); 574 setHeaderComment(null); 575 setFooterComment(null); 576 } 577 578 /** 579 * Tests whether a line is a comment, i.e. whether it starts with a comment character. 580 * 581 * @param line the line 582 * @return a flag if this is a comment line 583 */ 584 static boolean isCommentLine(final String line) { 585 return PropertiesConfiguration.isCommentLine(line); 586 } 587 588 /** 589 * Trims a comment. This method either removes all comment characters from the given string, leaving only the plain 590 * comment text or ensures that every line starts with a valid comment character. 591 * 592 * @param s the string to be processed 593 * @param comment if <b>true</b>, a comment character will always be enforced; if <b>false</b>, it will be removed 594 * @return the trimmed comment 595 */ 596 static String trimComment(final String s, final boolean comment) { 597 final StringBuilder buf = new StringBuilder(s.length()); 598 int lastPos = 0; 599 int pos; 600 601 do { 602 pos = s.indexOf(CR, lastPos); 603 if (pos >= 0) { 604 final String line = s.substring(lastPos, pos); 605 buf.append(stripCommentChar(line, comment)).append(CR); 606 lastPos = pos + CR.length(); 607 } 608 } while (pos >= 0); 609 610 if (lastPos < s.length()) { 611 buf.append(stripCommentChar(s.substring(lastPos), comment)); 612 } 613 return buf.toString(); 614 } 615 616 /** 617 * Either removes the comment character from the given comment line or ensures that the line starts with a comment 618 * character. 619 * 620 * @param s the comment line 621 * @param comment if <b>true</b>, a comment character will always be enforced; if <b>false</b>, it will be removed 622 * @return the line without comment character 623 */ 624 static String stripCommentChar(final String s, final boolean comment) { 625 if (StringUtils.isBlank(s) || isCommentLine(s) == comment) { 626 return s; 627 } 628 if (!comment) { 629 int pos = 0; 630 // find first comment character 631 while (PropertiesConfiguration.COMMENT_CHARS.indexOf(s.charAt(pos)) < 0) { 632 pos++; 633 } 634 635 // Remove leading spaces 636 pos++; 637 while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) { 638 pos++; 639 } 640 641 return pos < s.length() ? s.substring(pos) : StringUtils.EMPTY; 642 } 643 return COMMENT_PREFIX + s; 644 } 645 646 /** 647 * Extracts a comment string from the given range of the specified comment lines. The single lines are added using a 648 * line feed as separator. 649 * 650 * @param commentLines a list with comment lines 651 * @param from the start index 652 * @param to the end index (inclusive) 653 * @return the comment string (<b>null</b> if it is undefined) 654 */ 655 private String extractComment(final List<String> commentLines, final int from, final int to) { 656 if (to < from) { 657 return null; 658 } 659 final StringBuilder buf = new StringBuilder(commentLines.get(from)); 660 for (int i = from + 1; i <= to; i++) { 661 buf.append(CR); 662 buf.append(commentLines.get(i)); 663 } 664 return buf.toString(); 665 } 666 667 /** 668 * Checks if parts of the passed in comment can be used as header comment. This method checks whether a header comment 669 * can be defined (i.e. whether this is the first comment in the loaded file). If this is the case, it is searched for 670 * the latest blank line. This line will mark the end of the header comment. The return value is the index of the first 671 * line in the passed in list, which does not belong to the header comment. 672 * 673 * @param commentLines the comment lines 674 * @return the index of the next line after the header comment 675 */ 676 private int checkHeaderComment(final List<String> commentLines) { 677 if (loadCounter.get() == 1 && layoutData.isEmpty()) { 678 int index = commentLines.size() - 1; 679 // strip comments that belong to first key 680 while (index >= 0 && StringUtils.isNotEmpty(commentLines.get(index))) { 681 index--; 682 } 683 // strip blank lines 684 while (index >= 0 && StringUtils.isEmpty(commentLines.get(index))) { 685 index--; 686 } 687 if (getHeaderComment() == null) { 688 setHeaderComment(extractComment(commentLines, 0, index)); 689 } 690 return index + 1; 691 } 692 return 0; 693 } 694 695 /** 696 * Copies the data from the given layout object. 697 * 698 * @param c the layout object to copy 699 */ 700 private void copyFrom(final PropertiesConfigurationLayout c) { 701 c.getKeys().forEach(key -> layoutData.put(key, c.layoutData.get(key).clone())); 702 703 setHeaderComment(c.getHeaderComment()); 704 setFooterComment(c.getFooterComment()); 705 } 706 707 /** 708 * Helper method for writing a comment line. This method ensures that the correct line separator is used if the comment 709 * spans multiple lines. 710 * 711 * @param writer the writer 712 * @param comment the comment to write 713 * @throws IOException if an IO error occurs 714 */ 715 private static void writeComment(final PropertiesConfiguration.PropertiesWriter writer, final String comment) throws IOException { 716 if (comment != null) { 717 writer.writeln(StringUtils.replace(comment, CR, writer.getLineSeparator())); 718 } 719 } 720 721 /** 722 * Helper method for generating a comment string. Depending on the boolean argument the resulting string either has no 723 * comment characters or a leading comment character at each line. 724 * 725 * @param comment the comment string to be processed 726 * @param commentChar determines the presence of comment characters 727 * @return the canonical comment string (can be <b>null</b>) 728 */ 729 private static String constructCanonicalComment(final String comment, final boolean commentChar) { 730 return comment == null ? null : trimComment(comment, commentChar); 731 } 732 733 /** 734 * A helper class for storing all layout related information for a configuration property. 735 */ 736 static class PropertyLayoutData implements Cloneable { 737 /** Stores the comment for the property. */ 738 private StringBuffer comment; 739 740 /** The separator to be used for this property. */ 741 private String separator; 742 743 /** Stores the number of blank lines before this property. */ 744 private int blankLines; 745 746 /** Stores the single line property. */ 747 private boolean singleLine; 748 749 /** 750 * Creates a new instance of {@code PropertyLayoutData}. 751 */ 752 public PropertyLayoutData() { 753 singleLine = true; 754 separator = PropertiesConfiguration.DEFAULT_SEPARATOR; 755 } 756 757 /** 758 * Gets the number of blank lines before this property. 759 * 760 * @return the number of blank lines before this property 761 * @deprecated Use {#link {@link #getBlankLines()}}. 762 */ 763 @Deprecated 764 public int getBlancLines() { 765 return getBlankLines(); 766 } 767 768 /** 769 * Gets the number of blank lines before this property. 770 * 771 * @return the number of blank lines before this property 772 * @since 2.8.0 773 */ 774 public int getBlankLines() { 775 return blankLines; 776 } 777 778 /** 779 * Sets the number of properties before this property. 780 * 781 * @param blankLines the number of properties before this property 782 * @deprecated Use {@link #setBlankLines(int)}. 783 */ 784 @Deprecated 785 public void setBlancLines(final int blankLines) { 786 setBlankLines(blankLines); 787 } 788 789 /** 790 * Sets the number of properties before this property. 791 * 792 * @param blankLines the number of properties before this property 793 * @since 2.8.0 794 */ 795 public void setBlankLines(final int blankLines) { 796 this.blankLines = blankLines; 797 } 798 799 /** 800 * Returns the single line flag. 801 * 802 * @return the single line flag 803 */ 804 public boolean isSingleLine() { 805 return singleLine; 806 } 807 808 /** 809 * Sets the single line flag. 810 * 811 * @param singleLine the single line flag 812 */ 813 public void setSingleLine(final boolean singleLine) { 814 this.singleLine = singleLine; 815 } 816 817 /** 818 * Adds a comment for this property. If already a comment exists, the new comment is added (separated by a newline). 819 * 820 * @param s the comment to add 821 */ 822 public void addComment(final String s) { 823 if (s != null) { 824 if (comment == null) { 825 comment = new StringBuffer(s); 826 } else { 827 comment.append(CR).append(s); 828 } 829 } 830 } 831 832 /** 833 * Sets the comment for this property. 834 * 835 * @param s the new comment (can be <b>null</b>) 836 */ 837 public void setComment(final String s) { 838 if (s == null) { 839 comment = null; 840 } else { 841 comment = new StringBuffer(s); 842 } 843 } 844 845 /** 846 * Gets the comment for this property. The comment is returned as it is, without processing of comment characters. 847 * 848 * @return the comment (can be <b>null</b>) 849 */ 850 public String getComment() { 851 return Objects.toString(comment, null); 852 } 853 854 /** 855 * Gets the separator that was used for this property. 856 * 857 * @return the property separator 858 */ 859 public String getSeparator() { 860 return separator; 861 } 862 863 /** 864 * Sets the separator to be used for the represented property. 865 * 866 * @param separator the property separator 867 */ 868 public void setSeparator(final String separator) { 869 this.separator = separator; 870 } 871 872 /** 873 * Creates a copy of this object. 874 * 875 * @return the copy 876 */ 877 @Override 878 public PropertyLayoutData clone() { 879 try { 880 final PropertyLayoutData copy = (PropertyLayoutData) super.clone(); 881 if (comment != null) { 882 // must copy string buffer, too 883 copy.comment = new StringBuffer(getComment()); 884 } 885 return copy; 886 } catch (final CloneNotSupportedException cnex) { 887 // This cannot happen! 888 throw new ConfigurationRuntimeException(cnex); 889 } 890 } 891 } 892}