You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide utility for writing Properties to a file in a repeatable manner #23018
Instances of java.util.Properties are typically written to file using Properties#store. Since this method also writes a timestamp in a comment, its use is problematic in projects that need to have reproducible builds.
If Spring Framework could provide utility for writing Properties to a file in a repeatable manner, this would IMO be of great benefit to all Spring projects. There are already several issues/PRs that are blocked due to the shortcomings of Properties#store:
As @jhoeller mentioned elsewhere, Spring already has a PropertiesPersister interface and DefaultPropertiesPersister implementation.
So, we'll look into providing support to filter out comment lines from the output (likely enabled via a new boolean flag in DefaultPropertiesPersister), which should take care of the timestamp comment.
I'm not sure that filtering comments alone is sufficient. To be guaranteed to be repeatable I believe it's also necessary to order the keys. Without ordering the keys, you are reliant on repeatable hashing of the keys which may not hold true under all circumstances.
Gradle contains some code for writing properties in a repeatable manner which could serve as inspiration.
I'm not sure that filtering comments alone is sufficient. To be guaranteed to be repeatable I believe it's also necessary to order the keys. Without ordering the keys, you are reliant on repeatable hashing of the keys which may not hold true under all circumstances.
OK. Thanks for bringing that up. We'll then have to take the order into account as well.
Can you please confirm that you do not need this support for the storeToXML(...) variants?
Is it acceptable to ignore (i.e., filter out) any user-supplied comments (provided via the String comment argument to store(OutputStream, String) or store(Writer, String))?
Regarding PropertiesPersister itself, it seems a bit obscure as code search doesn't reveal any (production) uses even in Framework's codebase - Properties#store is actually used in all places that write Properties instances.
To me PropertiesPersister looks like an overhead for this, as simple property writing helper with two variants (one accepting OutputStream the other Writer) of static store method would be much simpler to consume across the Spring portfolio. Both load and XML related parts of the API don't seem particularly relevant to the core problem being discussed here.
I am actually considering only a custom subclass of Properties. If I get that to work, I don't think there will be a need to implement a custom PropertiesPersister, modify DefaultPropertiesPersister, or introduce a new helper class.
OK, this feature is basically done, but I'd like to share it with you here first to see if it meets your needs.
New method in org.springframework.core.CollectionFactory (per recommendation by @jhoeller):
/** * Create a variant of {@code java.util.Properties} that sorts properties * alphanumerically based on their keys. * * <p>This can be useful when storing the {@link Properties} instance in a * properties file, since it allows such files to be generated in a repeatable * manner with consistent ordering of properties. Comments in generated * properties files can also be optionally omitted. * * @param omitComments {@code true} if comments should be omitted when * storing properties in a file * @return a new {@code Properties} instance * @since 5.2 */publicstaticPropertiescreateSortedProperties(booleanomitComments) {
returnnewSortedProperties(omitComments);
}
Implementation of SortedProperties:
/** * Specialization of {@link Properties} that sorts properties alphanumerically * based on their keys. * * <p>This can be useful when storing the {@link Properties} instance in a * properties file, since it allows such files to be generated in a repeatable * manner with consistent ordering of properties. * * <p>Comments in generated properties files can also be optionally omitted * (see {@link SortedProperties#SortedProperties(boolean)}). * * @author Sam Brannen * @since 5.2 * @see java.util.Properties */classSortedPropertiesextendsProperties {
privatestaticfinalStringEOL = System.getProperty("line.separator");
privatestaticfinalComparator<Entry<Object, Object>> entryComparator = //
(entry1, entry2) -> String.valueOf(entry1.getKey()).compareTo(String.valueOf(entry2.getKey()));
privatefinalbooleanomitComments;
/** * Construct a new {@code SortedProperties} instance that honors the supplied * {@code omitComments} flag. * * @param omitComments {@code true} if comments should be omitted when * storing properties in a file */SortedProperties(booleanomitComments) {
this.omitComments = omitComments;
}
@Overridepublicvoidstore(OutputStreamout, Stringcomments) throwsIOException {
ByteArrayOutputStreambaos = newByteArrayOutputStream();
super.store(baos, (this.omitComments ? null : comments));
Stringcontents = newString(baos.toByteArray(), StandardCharsets.ISO_8859_1);
for (Stringline : StringUtils.tokenizeToStringArray(contents, EOL)) {
if (!omitComments || !line.startsWith("#")) {
out.write((line + EOL).getBytes(StandardCharsets.ISO_8859_1));
}
}
}
@Overridepublicvoidstore(Writerwriter, Stringcomments) throwsIOException {
StringWriterstringWriter = newStringWriter();
super.store(stringWriter, (this.omitComments ? null : comments));
Stringcontents = stringWriter.toString();
for (Stringline : StringUtils.tokenizeToStringArray(contents, EOL)) {
if (!omitComments || !line.startsWith("#")) {
writer.write(line + EOL);
}
}
}
@OverridepublicvoidstoreToXML(OutputStreamout, Stringcomments) throwsIOException {
super.storeToXML(out, (this.omitComments ? null : comments));
}
@OverridepublicvoidstoreToXML(OutputStreamout, Stringcomments, Stringencoding) throwsIOException {
super.storeToXML(out, (this.omitComments ? null : comments), encoding);
}
/** * Return a sorted enumeration of the keys in this {@link Properties} object. * <p>The keys will be converted to strings if necessary using * {@link String#valueOf(Object)} and sorted alphanumerically according to * the natural order of strings. */@OverridepublicsynchronizedEnumeration<Object> keys() {
Set<Object> sortedKeys = newTreeSet<>();
for (Objectkey : super.keySet()) {
sortedKeys.add(String.valueOf(key));
}
returnCollections.enumeration(sortedKeys);
}
/** * Return a sorted set of the entries in this {@link Properties} object. * <p>The entries will be sorted based on their keys, and the keys will be * converted to strings if necessary using {@link String#valueOf(Object)} * and compared alphanumerically according to the natural order of strings. */@OverridepublicSet<Entry<Object, Object>> entrySet() {
Set<Entry<Object, Object>> sortedEntries = newTreeSet<>(entryComparator);
sortedEntries.addAll(super.entrySet());
returnCollections.synchronizedSet(sortedEntries);
}
}
My only concern is that this basically limits the use to SortedProperties instances, meaning you'd have to be control of both creation and persistence of properties. It would be nice if SortedProperties could wrap regular Properies instance so that we're be able to write it repeatable manner even when we're not in control of creation.
It would be nice if SortedProperties could wrap regular Properies instance so that we're be able to write it repeatable manner even when we're not in control of creation.
OK. I just added that locally. The additional factory method looks like this:
/** * Create a variant of {@link java.util.Properties} that sorts properties * alphanumerically based on their keys. * * <p>This can be useful when storing the {@code Properties} instance in a * properties file, since it allows such files to be generated in a repeatable * manner with consistent ordering of properties. Comments in generated * properties files can also be optionally omitted. * * <p>The returned {@code Properties} instance will be populated with * properties from the supplied {@code properties} object, but default * properties from the supplied {@code properties} object will not be copied. * * @param properties the {@code Properties} object from which to copy the * initial properties * @param omitComments {@code true} if comments should be omitted when * storing properties in a file * @return a new {@code Properties} instance * @since 5.2 * @see #createSortedProperties(boolean) */publicstaticPropertiescreateSortedProperties(Propertiesproperties, booleanomitComments) {
returnnewSortedProperties(properties, omitComments);
}
The new createSortedProperties(...) factory methods in CollectionFactory are now in place. See c39c421 for details, and feel free to try it out in an upcoming snapshot build.
Activity
sbrannen commentedon May 23, 2019
As @jhoeller mentioned elsewhere, Spring already has a
PropertiesPersisterinterface andDefaultPropertiesPersisterimplementation.So, we'll look into providing support to filter out comment lines from the output (likely enabled via a new
booleanflag inDefaultPropertiesPersister), which should take care of the timestamp comment.@vpavic, would that meet your needs?
wilkinsona commentedon May 23, 2019
I'm not sure that filtering comments alone is sufficient. To be guaranteed to be repeatable I believe it's also necessary to order the keys. Without ordering the keys, you are reliant on repeatable hashing of the keys which may not hold true under all circumstances.
Gradle contains some code for writing properties in a repeatable manner which could serve as inspiration.
vpavic commentedon May 23, 2019
Thanks for the feedback @sbrannen, I wasn't aware of
PropertiesPersister- a custom implementation would probably do.Thanks @wilkinsona, I forgot to mention there's also an ordering aspect to this.
sbrannen commentedon May 26, 2019
OK. Thanks for bringing that up. We'll then have to take the order into account as well.
sbrannen commentedon May 26, 2019
Design Notes
It will likely be easiest to support consistent ordering by extending
Propertiesand overriding the implementation ofkeys().To remove the comments, we will likely need to override
store(OutputStream, String)andstore(Writer, String)to filter out all comments.Open Issues
@vpavic, @dsyer, @wilkinsona:
storeToXML(...)variants?String commentargument tostore(OutputStream, String)orstore(Writer, String))?vpavic commentedon May 27, 2019
I believe XML variants aren't needed.
Regarding
PropertiesPersisteritself, it seems a bit obscure as code search doesn't reveal any (production) uses even in Framework's codebase -Properties#storeis actually used in all places that writePropertiesinstances.To me
PropertiesPersisterlooks like an overhead for this, as simple property writing helper with two variants (one acceptingOutputStreamthe otherWriter) of staticstoremethod would be much simpler to consume across the Spring portfolio. Both load and XML related parts of the API don't seem particularly relevant to the core problem being discussed here.sbrannen commentedon May 27, 2019
Thanks for the feedback, @vpavic.
I am actually considering only a custom subclass of
Properties. If I get that to work, I don't think there will be a need to implement a customPropertiesPersister, modifyDefaultPropertiesPersister, or introduce a new helper class.sbrannen commentedon May 27, 2019
OK, this feature is basically done, but I'd like to share it with you here first to see if it meets your needs.
New method in
org.springframework.core.CollectionFactory(per recommendation by @jhoeller):Implementation of
SortedProperties:@vpavic, @dsyer, @wilkinsona, please let me know your thoughts.
Cheers,
Sam
vpavic commentedon May 27, 2019
Thanks @sbrannen, looks good at first glance.
My only concern is that this basically limits the use to
SortedPropertiesinstances, meaning you'd have to be control of both creation and persistence of properties. It would be nice ifSortedPropertiescould wrap regularProperiesinstance so that we're be able to write it repeatable manner even when we're not in control of creation.sbrannen commentedon May 28, 2019
OK. I just added that locally. The additional factory method looks like this:
So, I hope that meets all of your needs now.
vpavic commentedon May 28, 2019
Looks good, thanks Sam! 👍
wilkinsona commentedon May 28, 2019
Thanks, @sbrannen. I can confirm that we have no need for storing to XML in a repeatable manner.
sbrannen commentedon May 28, 2019
Oh... well... it turns out that my implementation fully supports XML as well. 😇
sbrannen commentedon May 28, 2019
The new
createSortedProperties(...)factory methods inCollectionFactoryare now in place. See c39c421 for details, and feel free to try it out in an upcoming snapshot build.Polishing
Remove dependency on StringUtils in SortedProperties
Introduce support for sorted Properties