Skip to content

Commit 8ffb86d

Browse files
PropertiesFilesImporter.writeValueAsString does not escape special characters
1 parent 19cf32b commit 8ffb86d

2 files changed

Lines changed: 16 additions & 11 deletions

File tree

consul-populate-core/src/main/java/com/frogdevelopment/consul/populate/files/PropertiesFilesImporter.java

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.io.File;
44
import java.io.IOException;
5+
import java.io.StringWriter;
56
import java.nio.file.Files;
67
import java.nio.file.Path;
78
import java.util.LinkedHashMap;
@@ -54,13 +55,18 @@ protected SequencedMap<String, Object> readFile(@NonNull final File file) throws
5455

5556
@NonNull
5657
@Override
57-
protected String writeValueAsString(@NonNull final Map<String, Object> map) {
58-
if (map == null || map.isEmpty()) {
58+
protected String writeValueAsString(@NonNull final Map<String, Object> map) throws IOException {
59+
if (map.isEmpty()) {
5960
return "";
6061
}
61-
return map.entrySet()
62-
.stream()
63-
.map(entry -> entry.getKey() + "=" + entry.getValue())
64-
.collect(Collectors.joining("\n"));
62+
final var properties = new Properties();
63+
map.forEach((k, v) -> properties.setProperty(k, v.toString()));
64+
final var sw = new StringWriter();
65+
properties.store(sw, null);
66+
// Properties.store() prepends a "#<timestamp>" comment line and a blank line — strip both
67+
return sw.toString().lines()
68+
.filter(line -> !line.startsWith("#"))
69+
.collect(Collectors.joining("\n"))
70+
.strip();
6571
}
6672
}

consul-populate-core/src/test/java/com/frogdevelopment/consul/populate/files/PropertiesFilesImporterTest.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ class PropertiesFilesImporterTest extends BaseFilesImporterTest {
1919
@Language("PROPERTIES")
2020
private static final String EXPECTED = """
2121
collection.items=item_C
22-
very.deep.nested.field.that.will.but.not=here
23-
very.deep.nested.field.that.will.be.overridden=salut
2422
foo.bar=new_value
2523
foo.baz=to_keep
2624
simple-value=kept
27-
something.new=true""";
25+
something.new=true
26+
very.deep.nested.field.that.will.be.overridden=salut
27+
very.deep.nested.field.that.will.but.not=here""";
2828

2929
@Inject
3030
private PropertiesFilesImporter filesImporter;
@@ -56,8 +56,7 @@ void should_mergeProperties() {
5656
}
5757

5858
@Test
59-
void should_handle_empty() {
60-
// given
59+
void should_handle_empty() throws Exception {
6160
// when
6261
final var value = filesImporter.writeValueAsString(new TreeMap<>());
6362

0 commit comments

Comments
 (0)