Added EntryBase, EntryDate and EntryInt

This commit is contained in:
Erik C. Thauvin 2023-04-06 03:43:09 -07:00
parent 99c3774227
commit 473a70329e
13 changed files with 794 additions and 497 deletions

3
.idea/misc.xml generated
View file

@ -9,6 +9,9 @@
<pattern value="rife.bld.extension.propertyfile.Entry" method="delete" /> <pattern value="rife.bld.extension.propertyfile.Entry" method="delete" />
<pattern value="rife.bld.extension.propertyfile.Entry" /> <pattern value="rife.bld.extension.propertyfile.Entry" />
<pattern value="rife.bld.extension.propertyfile.Entry" method="setDelete" /> <pattern value="rife.bld.extension.propertyfile.Entry" method="setDelete" />
<pattern value="rife.bld.extension.propertyfile.EntryDate" method="delete" />
<pattern value="rife.bld.extension.propertyfile.EntryDate" />
<pattern value="rife.bld.extension.propertyfile.EntryInt" method="delete" />
</component> </component>
<component name="PDMPlugin"> <component name="PDMPlugin">
<option name="skipTestSources" value="false" /> <option name="skipTestSources" value="false" />

View file

@ -13,10 +13,10 @@ An extension for creating or modifying [property files](https://docs.oracle.com/
public void updateMajor() throws Exception { public void updateMajor() throws Exception {
new PropertyFileOperation(this) new PropertyFileOperation(this)
.file("version.properties") .file("version.properties")
.entry(new Entry("version.major", Types.INT).defaultValue(0).calc(ADD)) .entry(new EntryInt("version.major").defaultValue(0).calc(ADD))
.entry(new Entry("version.minor").set(0)) .entry(new EntryInt("version.minor").set(0))
.entry(new Entry("version.patch").set(0)) .entry(new EntryInt("version.patch").set(0))
.entry(new Entry("build.date", Types.DATE).set("now").pattern("yyyy-MM-dd")) .entry(new EntryDate("build.date").now().pattern("yyyy-MM-dd"))
.execute(); .execute();
} }
``` ```
@ -62,33 +62,33 @@ The [PropertyFileOperation](https://rife2.github.io/bld-property-file/rife/bld/e
## Entry ## Entry
The [Entry](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.html) class is used to specify modifications to be made to the [properties file](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html). The [Entry](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.html) class is used to specify modifications to a [String property](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html).
| Function | Description | | Function | Description/Example |
|:-----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |:-----------------|:--------------------------------------------------------------------------------------------------------|
| `key()` | The name of the property name/value pair. | | `defaultValue()` | The value to be used if the property doesn't exist. |
| `set()` | The value to set the property to, regardless of its previous value. | | `delete()` | Delete the property. |
| `type()` | The value datatype, either [Types.INT](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html), [Types.DATE](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html), or [Types.STRING](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html). If none specified, [Types.STRING](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html) is assumed. | | `modify()` | `modify("-foo", String::concat)`<br/>`modify("-foo", (v, s) -> v + s)`<br/>`modify((v, s) -> v.trim())` | Modify an entry value. |
| `pattern()` | For [Types.INT](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html) and [Types.DATE](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html) only. If present, will parse the value as [DecimalFormat](https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) or [SimpleDateFormat](https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) patterns, respectively. | | `set()` | The value to set the property to, regardless of its previous value. |
| `unit()` | The unit value to be used with [Types.DATE](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html) calculations. See [Units](#units). |
- For convenience the `key` (and optional `type`) is first set in the constructor. ## EntryDate
- The `key` is required.
- A `set` value or `defaultValue` are required except when deleting.
- For [Types.DATE](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html), the `now` keyword can be used as the property value.
## Functions The [Entry](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/EntryDate.html) class is used to specify modifications to a [date property](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html).
The following function are available: | Function | Description/Example |
|:-----------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `calc()` | `calc(ADD)`<br/>`calc(v -> v + 1)`<br/>`calc(SUB)`<br/>`calc(v -> v - 1)` |
| `delete()` | Delete the property. |
| `now()` | Set the entry to the current date/time. |
| `pattern()` | If present, will parse the value as a [DateTimeFormatter](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) pattern. |
| `set()` | The [Calendar](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Calendar.html), [Date](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Date.html), or [java.time](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/package-summary.html) value to set the property to, regardless of its previous value. |
| `unit()` | The unit to be used calculations. See [Units](#units). |
| Function | Example | Description | - `set` or `now` are required.
|:-----------|:--------------------------------------------------------------------------------------------------------|:-------------------------------------------|
| `calc()` | `calc(ADD)`<br/>`calc(v -> v + 1)`<br/>`calc(SUB)`<br/>`calc(v -> v - 1)` | Perform a calculation with an entry value. |
| `modify()` | `modify("-foo", String::concat)`<br/>`modify("-foo", (v, s) -> v + s)`<br/>`modify((v, s) -> v.trim())` | Modify an entry value. |
| `delete()` | `delete()` | Delete an entry. |
## Units
The following [Units](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Units.html) are available for [Types.DATE](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html): ### Units
The following [Units](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/EntryDate.Units.html) are available:
* `Units.MILLISECOND` * `Units.MILLISECOND`
* `Units.SECOND` * `Units.SECOND`
@ -99,8 +99,14 @@ The following [Units](https://rife2.github.io/bld-property-file/rife/bld/extensi
* `Units.MONTH` * `Units.MONTH`
* `Units.YEAR` * `Units.YEAR`
## Differences with the [ant PropertyFile task](https://ant.apache.org/manual/Tasks/propertyfile.html) ## EntryInt
* The comments and layout of the original property file will not be preserved. The [Entry](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/EntryInt.html) class is used to specify modifications to a [integer property](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html).
* The `jdkproperties` parameter is not implemented.
* The default [Types.DATE](https://rife2.github.io/bld-property-file/rife/bld/extension/propertyfile/Entry.Types.html) pattern is `yyyy-MM-dd HH:mm` and not `yyyy/MM/dd HH:mm`. | Function | Description/Example |
|:-----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `defaultValue()` | The value to be used if the property doesn't exist. |
| `calc()` | `calc(ADD)`<br/>`calc(v -> v + 1)`<br/>`calc(SUB)`<br/>`calc(v -> v - 1)` |
| `delete()` | Delete the property. |
| `pattern()` | If present, will parse the value as a [DecimalFormat](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/DecimalFormat.html) pattern. |
| `set()` | The [integer value](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Integer.html) to set the property to, regardless of its previous value. |

View file

@ -15,6 +15,7 @@ To run the examples, issue one of the following command or combination there off
./bld updateMajor run ./bld updateMajor run
./bld updateMinor run ./bld updateMinor run
./bld updatePatch run ./bld updatePatch run
./bld updateRelease run
``` ```
Upon execution, the `version.properties` file will be created and displayed: Upon execution, the `version.properties` file will be created and displayed:

View file

@ -1,5 +1,5 @@
#Sun Apr 02 10:32:44 PDT 2023 #Sun Apr 02 10:32:44 PDT 2023
bld.extension=com.uwyn.rife2:bld-property-file:0.9.0 bld.extension=com.uwyn.rife2:bld-property-file:0.9.1-SNAPSHOT
bld.repositories=MAVEN_LOCAL,RIFE2 bld.repositories=MAVEN_LOCAL,RIFE2
bld.downloadExtensionSources=true bld.downloadExtensionSources=true
rife2.downloadLocation= rife2.downloadLocation=

View file

@ -3,18 +3,18 @@ package com.example;
import rife.bld.BuildCommand; import rife.bld.BuildCommand;
import rife.bld.Project; import rife.bld.Project;
import rife.bld.extension.propertyfile.Entry; import rife.bld.extension.propertyfile.Entry;
import rife.bld.extension.propertyfile.Entry.Types; import rife.bld.extension.propertyfile.EntryDate;
import rife.bld.extension.propertyfile.EntryInt;
import rife.bld.extension.propertyfile.PropertyFileOperation; import rife.bld.extension.propertyfile.PropertyFileOperation;
import java.util.List; import java.util.List;
import static rife.bld.dependencies.Repository.MAVEN_CENTRAL; import static rife.bld.dependencies.Repository.MAVEN_CENTRAL;
import static rife.bld.dependencies.Repository.SONATYPE_SNAPSHOTS;
import static rife.bld.dependencies.Scope.test; import static rife.bld.dependencies.Scope.test;
import static rife.bld.extension.propertyfile.Calc.ADD; import static rife.bld.extension.propertyfile.Calc.ADD;
public class PropertyFileExampleBuild extends Project { public class PropertyFileExampleBuild extends Project {
final Entry buildDateEntry = new Entry("build.date").set("now").pattern("yyyy-MM-dd").type(Types.DATE); final EntryDate buildDateEntry = new EntryDate("build.date").now().pattern("yyyy-MM-dd");
public PropertyFileExampleBuild() { public PropertyFileExampleBuild() {
pkg = "com.example"; pkg = "com.example";
@ -23,7 +23,7 @@ public class PropertyFileExampleBuild extends Project {
version = version(0, 1, 0); version = version(0, 1, 0);
downloadSources = true; downloadSources = true;
repositories = List.of(MAVEN_CENTRAL, SONATYPE_SNAPSHOTS); repositories = List.of(MAVEN_CENTRAL);
scope(test) scope(test)
.include(dependency("org.junit.jupiter", "junit-jupiter", version(5, 9, 2))) .include(dependency("org.junit.jupiter", "junit-jupiter", version(5, 9, 2)))
.include(dependency("org.junit.platform", "junit-platform-console-standalone", version(1, 9, 2))); .include(dependency("org.junit.platform", "junit-platform-console-standalone", version(1, 9, 2)));
@ -38,11 +38,11 @@ public class PropertyFileExampleBuild extends Project {
new PropertyFileOperation(this) new PropertyFileOperation(this)
.file("version.properties") .file("version.properties")
// set the major version to 1 if it doesn't exist, increase by 1 // set the major version to 1 if it doesn't exist, increase by 1
.entry(new Entry("version.major").defaultValue(0).type(Types.INT).calc(ADD)) .entry(new EntryInt("version.major").defaultValue(0).calc(ADD))
// set the minor version to 0 // set the minor version to 0
.entry(new Entry("version.minor").set(0)) .entry(new EntryInt("version.minor").set(0))
// set the patch version to 0 // set the patch version to 0
.entry(new Entry("version.patch").set(0)) .entry(new EntryInt("version.patch").set(0))
// set the build date to the current date // set the build date to the current date
.entry(buildDateEntry) .entry(buildDateEntry)
.execute(); .execute();
@ -53,11 +53,11 @@ public class PropertyFileExampleBuild extends Project {
new PropertyFileOperation(this) new PropertyFileOperation(this)
.file("version.properties") .file("version.properties")
// set the major version to 1 if it doesn't exist // set the major version to 1 if it doesn't exist
.entry(new Entry("version.major").defaultValue(1)) .entry(new EntryInt("version.major").defaultValue(1))
// set the minor version to 0 if it doesn't exist, increase by 1 // set the minor version to 0 if it doesn't exist, increase by 1
.entry(new Entry("version.minor").defaultValue(-1).type(Types.INT).calc(ADD)) .entry(new EntryInt("version.minor").defaultValue(-1).calc(ADD))
// set the patch version to 0 // set the patch version to 0
.entry(new Entry("version.patch").set(0)) .entry(new EntryInt("version.patch").set(0))
// set the build date to the current date // set the build date to the current date
.entry(buildDateEntry) .entry(buildDateEntry)
.execute(); .execute();
@ -68,16 +68,27 @@ public class PropertyFileExampleBuild extends Project {
new PropertyFileOperation(this) new PropertyFileOperation(this)
.file("version.properties") .file("version.properties")
// set the major version to 1 if it doesn't exist // set the major version to 1 if it doesn't exist
.entry(new Entry("version.major").defaultValue(1)) .entry(new EntryInt("version.major").defaultValue(1))
// set the minor version to 0 if it doesn't exist // set the minor version to 0 if it doesn't exist
.entry(new Entry("version.minor").defaultValue(0)) .entry(new EntryInt("version.minor").defaultValue(0))
// set the patch version to 10 if it doesn't exist, increase by 10 // set the patch version to 10 if it doesn't exist, increase by 10
.entry(new Entry("version.patch").defaultValue(0).type(Types.INT).calc(v -> v + 10)) .entry(new EntryInt("version.patch").defaultValue(0).calc(v -> v + 10))
// set the build date to the current date // set the build date to the current date
.entry(buildDateEntry) .entry(buildDateEntry)
.execute(); .execute();
} }
@BuildCommand(summary = "Updates the release")
public void updateRelease() throws Exception {
new PropertyFileOperation(this)
.file("version.properties")
// set the release to current date/time
.entry(new EntryDate("release").now().pattern("yyyyMMddHHmmss"))
// prepend 'beta.' to the release
.entry(new Entry("release").modify("beta.", (v, s) -> s + v))
.execute();
}
@BuildCommand(summary = "Delete version properties") @BuildCommand(summary = "Delete version properties")
public void deleteVersion() throws Exception { public void deleteVersion() throws Exception {
new PropertyFileOperation(this) new PropertyFileOperation(this)
@ -85,6 +96,7 @@ public class PropertyFileExampleBuild extends Project {
.entry(new Entry("version.major").delete()) .entry(new Entry("version.major").delete())
.entry(new Entry("version.minor").delete()) .entry(new Entry("version.minor").delete())
.entry(new Entry("version.patch").delete()) .entry(new Entry("version.patch").delete())
.entry(new Entry("release").delete())
.entry(buildDateEntry.delete()) .entry(buildDateEntry.delete())
.execute(); .execute();
} }

View file

@ -21,7 +21,8 @@ public class PropertyFileBuild extends Project {
javadocOptions javadocOptions
.docLint(NO_MISSING) .docLint(NO_MISSING)
.link("https://rife2.github.io/rife2/"); .link("https://rife2.github.io/rife2/");
publishRepository = version.isSnapshot() ? repository("rife2-snapshot") : repository("rife2"); // publishRepository = version.isSnapshot() ? repository("rife2-snapshot") : repository("rife2");
publishRepository = MAVEN_LOCAL;
publishInfo = new PublishInfo() publishInfo = new PublishInfo()
.groupId("com.uwyn.rife2") .groupId("com.uwyn.rife2")
.artifactId("bld-property-file") .artifactId("bld-property-file")
@ -45,7 +46,7 @@ public class PropertyFileBuild extends Project {
repositories = List.of(MAVEN_CENTRAL, RIFE2); repositories = List.of(MAVEN_CENTRAL, RIFE2);
scope(compile) scope(compile)
.include(dependency("com.uwyn.rife2", "rife2", version(1, 5, 16))); .include(dependency("com.uwyn.rife2", "rife2", version(1, 5, 17)));
scope(test) scope(test)
.include(dependency("org.jsoup", "jsoup", version(1, 15, 4))) .include(dependency("org.jsoup", "jsoup", version(1, 15, 4)))
.include(dependency("org.junit.jupiter", "junit-jupiter", version(5, 9, 2))) .include(dependency("org.junit.jupiter", "junit-jupiter", version(5, 9, 2)))

View file

@ -17,7 +17,6 @@
package rife.bld.extension.propertyfile; package rife.bld.extension.propertyfile;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.IntFunction;
/** /**
* Declares the modifications to be made to a {@link java.util.Properties Properties} file. * Declares the modifications to be made to a {@link java.util.Properties Properties} file.
@ -26,67 +25,30 @@ import java.util.function.IntFunction;
* @author <a href="https://github.com/gbevin">Geert Bevin</a> * @author <a href="https://github.com/gbevin">Geert Bevin</a>
* @since 1.0 * @since 1.0
*/ */
public class Entry { public class Entry extends EntryBase {
private String key;
private String defaultValue;
private String newValue;
private String modifyValue;
private boolean isDelete;
private Types type = Types.STRING;
private String pattern = "";
private Units unit = Units.DAY;
private IntFunction<Integer> calc;
private BiFunction<String, String, String> modify;
/**
* Creates a new {@link Entry entry}.
*
* @param key the required property key
*/
public Entry(String key) { public Entry(String key) {
this.key = key; super(key);
} }
/** /**
* Creates a new {@link Entry entry}. * Set the new {@link java.util.Properties property} value.
* *
* @param key the required property key * @param s The new value
* @param type the value {@link Types Type}
*/ */
public Entry(String key, Types type) { public Entry set(Object s) {
this.key = key; setNewValue(s);
this.type = type; return this;
} }
/** /**
* Returns the value to be used in the {@link #modify} function. * <p>Sets the initial value to set the {@link java.util.Properties property} to, if not already defined.</p>
*/
public String getModifyValue() {
return modifyValue;
}
/**
* Returns the modify function.
*/
public BiFunction<String, String, String> getModify() {
return modify;
}
/**
* Set the modify function.
*/
public void setModify(BiFunction<String, String, String> modify) {
this.modify = modify;
}
/**
* Set the modify function.
* *
* @param value the value to perform a modification with * @param defaultValue the default value
*/ */
public void setModify(String value, BiFunction<String, String, String> modify) { @SuppressWarnings("unused")
this.modifyValue = value; public Entry defaultValue(Object defaultValue) {
this.modify = modify; setDefaultValue(defaultValue);
return this;
} }
/** /**
@ -96,7 +58,7 @@ public class Entry {
* @param modify the modification function * @param modify the modification function
*/ */
public Entry modify(String value, BiFunction<String, String, String> modify) { public Entry modify(String value, BiFunction<String, String, String> modify) {
modifyValue = value; setModifyValue(value);
setModify(modify); setModify(modify);
return this; return this;
} }
@ -111,251 +73,11 @@ public class Entry {
return this; return this;
} }
/**
* Returns {@code true} if the {@link Entry} is to be deleted.
*/
public boolean isDelete() {
return isDelete;
}
/**
* Sets whether the {@link Entry} should be deleted.
*/
public void setDelete(boolean delete) {
isDelete = delete;
}
/**
* Returns the calculation function.
*/
public IntFunction<Integer> getCalc() {
return calc;
}
/**
* Sets the calculation function.
*/
public void setCalc(IntFunction<Integer> calc) {
this.calc = calc;
}
/**
* Creates a new {@link Entry entry}.
*
* @param calc the calculation function.
*/
public Entry calc(IntFunction<Integer> calc) {
setCalc(calc);
return this;
}
/**
* Returns the key of the {@link java.util.Properties property}.
*/
public String getKey() {
return key;
}
/**
* Sets the key of the {@link java.util.Properties property}.
*
* @param key the {@link java.util.Properties property} key
*/
public void setKey(String key) {
this.key = key;
}
/**
* Returns the default value.
*/
public String getDefaultValue() {
return defaultValue;
}
/**
* <p>Sets the initial value to set the {@link java.util.Properties property} to, if not already defined.</p>
*
* <p>The {@code now} keyword can be used for {@link Types#DATE Types.DATE}</p>
*
* @param defaultValue the default value
*/
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Return the value {@link Types Type}.
*/
public Types getType() {
return type;
}
/**
* Sets the value {@link Types Type}, if none is specified {@link Types#STRING Types.STRING} is assumed.
*
* @param type the value {@link Types Type}
*/
public void setType(Types type) {
this.type = type;
}
/**
* Returns the pattern.
*/
public String getPattern() {
return pattern;
}
/**
* Sets the {@link java.text.DecimalFormat DecimalFormat} or {@link java.text.SimpleDateFormat SimpleDateFormat}
* pattern to be used with {@link Types#INT Types.INT} or {@link Types#DATE Types.DATE} respectively.
*
* @param pattern the pattern
*/
public void setPattern(String pattern) {
this.pattern = pattern;
}
/**
* Return the {@link Units unit}.
*/
public Units getUnit() {
return unit;
}
/**
* Sets the {@link Units unit} value to apply to {@link Calc#ADD add} and {@link Calc#SUB subtract} calculations
* for {@link Types#DATE Types.DATE}.
*
* @param unit the {@link Units unit}
*/
public void setUnit(Units unit) {
this.unit = unit;
}
/**
* Sets the key of the {@link java.util.Properties property}.
*
* @param key the {@link java.util.Properties property} key
*/
@SuppressWarnings("unused")
public Entry key(String key) {
setKey(key);
return this;
}
/**
* Returns the new value to set the {@link java.util.Properties property)} to.
*/
public String getNewValue() {
return newValue;
}
/**
* Sets a new value to set the {@link java.util.Properties property} to, regardless of its previous value.
*
* <p>The {@code now} keyword can be used for {@link Types#DATE Types.DATE}</p>
*
* @param newValue the {@link java.util.Properties property} new value
*/
@SuppressWarnings("unused")
public Entry set(Object newValue) {
if (newValue != null) {
this.newValue = String.valueOf(newValue);
} else {
this.newValue = null;
}
return this;
}
/**
* <p>Sets the initial value to set the {@link java.util.Properties property} to, if not already defined.</p>
*
* <p>The {@code now} keyword can be used for {@link Types#DATE Types.DATE}</p>
*
* @param defaultValue the default value
*/
@SuppressWarnings("unused")
public Entry defaultValue(Object defaultValue) {
if (defaultValue != null) {
setDefaultValue(String.valueOf(defaultValue));
} else {
setDefaultValue(null);
}
return this;
}
/**
* Sets the value {@link Types Type}, if none is specified {@link Types#STRING Types.STRING} is assumed.
*
* @param type the value {@link Types Type}
*/
public Entry type(Types type) {
setType(type);
return this;
}
/**
* <p>Sets the pattern for {@link Types#INT Types.INT} and {@link Types#DATE Types.DATE} to
* {@link java.text.DecimalFormat DecimalFormat} and {@link java.text.SimpleDateFormat SimpleDateFormat}
* respectively.</p>
*
* @param pattern the pattern
*/
public Entry pattern(String pattern) {
setPattern(pattern);
return this;
}
/**
* Sets the {@link Units unit} value to apply to {@link Calc#ADD add} and {@link Calc#SUB subtract} calculations
* for {@link Types#DATE Types.DATE}.
*
* @param unit the {@link Units unit}
*/
@SuppressWarnings("unused")
public Entry unit(Units unit) {
setUnit(unit);
return this;
}
/** /**
* Sets the {@link Entry entry} up for deletion. * Sets the {@link Entry entry} up for deletion.
*/ */
public Entry delete() { public Entry delete() {
isDelete = true; setDelete(true);
return this; return this;
} }
/**
* The available datatypes.
*
* <uL>
* <li>{@link Types#DATE DATE}</li>
* <li>{@link Types#INT INT}</li>
* <li>{@link Types#STRING STRING}</li>
* </uL>
*/
public enum Types {
DATE, INT, STRING
}
/**
* The units available for {@link Types#DATE Type.DATE} {@link Calc#ADD add}
* and {@link Calc#SUB subtract} calculations.
*
* <uL>
* <li>{@link Units#SECOND SECOND}</li>
* <li>{@link Units#MINUTE MINUTE}</li>
* <li>{@link Units#MILLISECOND MILLISECOND}</li>
* <li>{@link Units#HOUR HOUR}</li>
* <li>{@link Units#DAY DAY}</li>
* <li>{@link Units#WEEK WEEK}</li>
* <li>{@link Units#MONTH MONTH}</li>
* <li>{@link Units#YEAR YEAR}</li>
* </uL>
*/
public enum Units {
MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
}
} }

View file

@ -0,0 +1,208 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed 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
*
* https://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 rife.bld.extension.propertyfile;
import java.util.function.BiFunction;
import java.util.function.IntFunction;
/**
* Declares the modifications to be made to a {@link java.util.Properties Properties} file.
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @author <a href="https://github.com/gbevin">Geert Bevin</a>
* @since 1.0
*/
public class EntryBase {
private String key;
private Object defaultValue;
private Object newValue;
private String modifyValue = "";
private boolean isDelete;
private String pattern = "";
private EntryDate.Units unit = EntryDate.Units.DAY;
private IntFunction<Integer> calc;
private BiFunction<String, String, String> modify;
/**
* Creates a new {@link EntryBase entry}.
*
* @param key the required property key
*/
public EntryBase(String key) {
this.key = key;
}
/**
* Returns the value to be used in the {@link #modify} function.
*/
protected String getModifyValue() {
return modifyValue;
}
/**
* Sets the modify value.
*
* @param value the modify value.
*/
protected void setModifyValue(String value) {
this.modifyValue = value;
}
/**
* Returns the modify function.
*/
protected BiFunction<String, String, String> getModify() {
return modify;
}
/**
* Set the modify function.
*/
protected void setModify(BiFunction<String, String, String> modify) {
this.modify = modify;
}
/**
* Set the modify function.
*
* @param value the value to perform a modification with
*/
protected void setModify(String value, BiFunction<String, String, String> modify) {
this.modifyValue = value;
this.modify = modify;
}
/**
* Returns {@code true} if the {@link EntryBase} is to be deleted.
*/
protected boolean isDelete() {
return isDelete;
}
/**
* Sets whether the {@link EntryBase} should be deleted.
*/
protected void setDelete(boolean delete) {
isDelete = delete;
}
/**
* Returns the calculation function.
*/
protected IntFunction<Integer> getCalc() {
return calc;
}
/**
* Sets the calculation function.
*/
protected void setCalc(IntFunction<Integer> calc) {
this.calc = calc;
}
/**
* Returns the key of the {@link java.util.Properties property}.
*/
protected String getKey() {
return key;
}
/**
* Sets the key of the {@link java.util.Properties property}.
*
* @param key the {@link java.util.Properties property} key
*/
protected void setKey(String key) {
this.key = key;
}
/**
* Returns the default value.
*/
protected Object getDefaultValue() {
return defaultValue;
}
/**
* <p>Sets the initial value to set the {@link java.util.Properties property} to, if not already defined.</p>
*
* @param defaultValue the default value
*/
protected void setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Returns the pattern.
*/
protected String getPattern() {
return pattern;
}
/**
* Sets the {@link java.text.DecimalFormat DecimalFormat} or {@link java.time.format.DateTimeFormatter DateTimeFormatter}
* pattern to be used with {@link EntryDate} or {@link EntryInt} respectively.
*
* @param pattern the pattern
*/
protected void setPattern(String pattern) {
this.pattern = pattern;
}
/**
* Return the {@link EntryDate.Units unit}.
*/
protected EntryDate.Units getUnit() {
return unit;
}
/**
* Sets the {@link EntryDate.Units unit} value to apply to calculations for {@link EntryDate}.
*
* @param unit the {@link EntryDate.Units unit}
*/
protected void setUnit(EntryDate.Units unit) {
this.unit = unit;
}
/**
* Sets the key of the {@link java.util.Properties property}.
*
* @param key the {@link java.util.Properties property} key
*/
@SuppressWarnings("unused")
public EntryBase key(String key) {
setKey(key);
return this;
}
/**
* Returns the new value to set the {@link java.util.Properties property)} to.
*/
public Object getNewValue() {
return newValue;
}
/**
* Set a new value for {@link java.util.Properties property}.
*
* @param newValue the new value
*/
public void setNewValue(Object newValue) {
this.newValue = newValue;
}
}

View file

@ -0,0 +1,174 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed 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
*
* https://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 rife.bld.extension.propertyfile;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.function.IntFunction;
/**
* Declares the modifications to be made to a {@link java.util.Properties Properties} file.
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @since 1.0
*/
public class EntryDate extends EntryBase {
/**
* Creates a new date {@link Entry entry}.
*
* @param key the required property key
*/
public EntryDate(String key) {
super(key);
}
/**
* Set the new {@link java.util.Properties property} value to an {@link Instant}
*
* @param instant the {@link Instant} to set the value to.
*/
public EntryDate set(Instant instant) {
setNewValue(instant);
return this;
}
/**
* Set the new {@link java.util.Properties property} value to an {@link LocalDate}
*
* @param date the {@link LocalDate} to set the value to.
*/
public EntryDate set(LocalDate date) {
setNewValue(date);
return this;
}
/**
* Set the new {@link java.util.Properties property} value to an {@link LocalDateTime}
*
* @param date the {@link LocalDateTime} to set the value to.
*/
public EntryDate set(LocalDateTime date) {
setNewValue(date);
return this;
}
/**
* Set the new {@link java.util.Properties property} value to an {@link ZonedDateTime}
*
* @param date the {@link ZonedDateTime} to set the value to.
*/
public EntryDate set(ZonedDateTime date) {
setNewValue(date);
return this;
}
/**
* Set the new {@link java.util.Properties property} value to an {@link LocalTime}
*
* @param time the {@link LocalTime} to set the value to.
*/
public EntryDate set(LocalTime time) {
setNewValue(time);
return this;
}
/**
* Set the new {@link java.util.Properties property} value to an {@link Calendar}
*
* @param cal the {@link Calendar} to set the value to.
*/
public EntryDate set(Calendar cal) {
setNewValue(cal);
return this;
}
/**
* Set the new {@link java.util.Properties property} value to an {@link Date}
*
* @param date the {@link Date} to set the value to.
*/
public EntryDate set(Date date) {
setNewValue(date);
return this;
}
/**
* Sets the new value to now.
*/
public EntryDate now() {
setNewValue("now");
return this;
}
/**
* Creates a new {@link EntryDate entry}.
*
* @param calc the calculation function.
*/
public EntryDate calc(IntFunction<Integer> calc) {
setCalc(calc);
return this;
}
/**
* <p>Sets the pattern for {@link EntryInt} and {@link EntryDate} to
* {@link java.text.DecimalFormat DecimalFormat} and {@link java.time.format.DateTimeFormatter DateTimeFormatter}
* respectively.</p>
*
* @param pattern the pattern
*/
public EntryDate pattern(String pattern) {
setPattern(pattern);
return this;
}
/**
* Sets the {@link Units unit} value to apply to calculations for {@link EntryDate}.
*
* @param unit the {@link Units unit}
*/
public EntryDate unit(Units unit) {
setUnit(unit);
return this;
}
/**
* Sets the {@link EntryDate entry} up for deletion.
*/
public EntryDate delete() {
setDelete(true);
return this;
}
/**
* The units available for {@link EntryDate} calculations.
*
* <uL>
* <li>{@link Units#SECOND SECOND}</li>
* <li>{@link Units#MINUTE MINUTE}</li>
* <li>{@link Units#HOUR HOUR}</li>
* <li>{@link Units#DAY DAY}</li>
* <li>{@link Units#WEEK WEEK}</li>
* <li>{@link Units#MONTH MONTH}</li>
* <li>{@link Units#YEAR YEAR}</li>
* </uL>
*/
public enum Units {
SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed 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
*
* https://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 rife.bld.extension.propertyfile;
import java.util.function.IntFunction;
/**
* Declares the modifications to be made to a {@link java.util.Properties Properties} file.
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @since 1.0
*/
public class EntryInt extends EntryBase {
/**
* Creates a new date {@link Entry entry}.
*
* @param key the required property key
*/
public EntryInt(String key) {
super(key);
}
/**
* Set the new {@link java.util.Properties property} value to an integer.
*
* @param i The integer to set the value to.
*/
public EntryInt set(int i) {
setNewValue(i);
return this;
}
/**
* <p>Sets the initial value to set the {@link java.util.Properties property} to, if not already defined.</p>
*
* @param defaultValue the default value
*/
@SuppressWarnings("unused")
public EntryInt defaultValue(Object defaultValue) {
setDefaultValue(defaultValue);
return this;
}
/**
* Creates a new {@link EntryInt entry}.
*
* @param calc the calculation function.
*/
public EntryInt calc(IntFunction<Integer> calc) {
setCalc(calc);
return this;
}
/**
* Sets the {@link EntryInt entry} up for deletion.
*/
public EntryInt delete() {
setDelete(true);
return this;
}
}

View file

@ -20,7 +20,6 @@ import rife.bld.Project;
import rife.bld.operations.AbstractOperation; import rife.bld.operations.AbstractOperation;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
@ -32,7 +31,7 @@ import java.util.Properties;
* @since 1.0 * @since 1.0
*/ */
public class PropertyFileOperation extends AbstractOperation<PropertyFileOperation> { public class PropertyFileOperation extends AbstractOperation<PropertyFileOperation> {
private final List<Entry> entries = new ArrayList<>(); private final List<EntryBase> entries = new ArrayList<>();
private final Project project; private final Project project;
private File file; private File file;
private String comment = ""; private String comment = "";
@ -49,7 +48,7 @@ public class PropertyFileOperation extends AbstractOperation<PropertyFileOperati
* @param entry the {@link Entry entry} * @param entry the {@link Entry entry}
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public PropertyFileOperation entry(Entry entry) { public PropertyFileOperation entry(EntryBase entry) {
entries.add(entry); entries.add(entry);
return this; return this;
} }
@ -103,45 +102,44 @@ public class PropertyFileOperation extends AbstractOperation<PropertyFileOperati
*/ */
@Override @Override
public void execute() throws Exception { public void execute() throws Exception {
if (project == null) {
throw new IOException("A project must be specified.");
}
if (file == null) {
throw new IOException("A properties file location must be specified.");
}
var commandName = project.getCurrentCommandName(); var commandName = project.getCurrentCommandName();
var success = false;
var properties = new Properties(); var properties = new Properties();
success = PropertyFileUtils.loadProperties(commandName, file, properties); var success = false;
if (file == null) {
PropertyFileUtils.warn(commandName, "A properties file must be specified.");
} else {
success = PropertyFileUtils.loadProperties(commandName, file, properties);
}
if (success) { if (success) {
for (var entry : entries) { for (var entry : entries) {
if (entry.getKey().isBlank()) { if (entry.getKey().isBlank()) {
PropertyFileUtils.warn(commandName, "At least one entry key must specified."); PropertyFileUtils.warn(commandName, "An entry key must specified.");
success = false;
} else { } else {
var key = entry.getKey(); var key = entry.getKey();
var value = entry.getNewValue(); Object value = entry.getNewValue();
var defaultValue = entry.getDefaultValue(); Object defaultValue = entry.getDefaultValue();
var p = properties.getProperty(key);
if (entry.isDelete()) { if (entry.isDelete()) {
properties.remove(key); properties.remove(key);
} else if ((value == null || value.isBlank()) && (defaultValue == null || defaultValue.isBlank())) { } else if ((value == null || String.valueOf(value).isBlank())
&& (defaultValue == null || String.valueOf(defaultValue).isBlank())
&& (p == null || p.isBlank())) {
PropertyFileUtils.warn(commandName, "An entry must be set or have a default value: " + key); PropertyFileUtils.warn(commandName, "An entry must be set or have a default value: " + key);
success = false;
} else { } else {
switch (entry.getType()) { if (entry instanceof EntryDate)
case DATE -> success = PropertyFileUtils.processDate(commandName, properties, (EntryDate) entry, failOnWarning);
success = PropertyFileUtils.processDate(commandName, properties, entry, failOnWarning); else if (entry instanceof EntryInt)
case INT -> success = PropertyFileUtils.processInt(commandName, properties, (EntryInt) entry, failOnWarning);
success = PropertyFileUtils.processInt(commandName, properties, entry, failOnWarning); else
default -> success = PropertyFileUtils.processString(properties, entry); success = PropertyFileUtils.processString(properties, (Entry) entry);
}
} }
} }
} }
} }
if (failOnWarning && !success) {
throw new RuntimeException("Properties file configuration failed: " + file); if (success) {
} else if (success) {
PropertyFileUtils.saveProperties(file, comment, properties); PropertyFileUtils.saveProperties(file, comment, properties);
} }
} }

View file

@ -16,9 +16,6 @@
package rife.bld.extension.propertyfile; package rife.bld.extension.propertyfile;
import rife.bld.extension.propertyfile.Entry.Units;
import rife.tools.Localization;
import javax.imageio.IIOException; import javax.imageio.IIOException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -26,10 +23,11 @@ import java.nio.file.Files;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -44,16 +42,6 @@ import java.util.logging.Logger;
public final class PropertyFileUtils { public final class PropertyFileUtils {
private final static Logger LOGGER = Logger.getLogger(PropertyFileUtils.class.getName()); private final static Logger LOGGER = Logger.getLogger(PropertyFileUtils.class.getName());
private final static Map<Units, Integer> CALENDAR_FIELDS =
Map.of(Units.MILLISECOND, Calendar.MILLISECOND,
Units.SECOND, Calendar.SECOND,
Units.MINUTE, Calendar.MINUTE,
Units.HOUR, Calendar.HOUR_OF_DAY,
Units.DAY, Calendar.DATE,
Units.WEEK, Calendar.WEEK_OF_YEAR,
Units.MONTH, Calendar.MONTH,
Units.YEAR, Calendar.YEAR);
private PropertyFileUtils() { private PropertyFileUtils() {
// no-op // no-op
} }
@ -66,43 +54,97 @@ public final class PropertyFileUtils {
* @param entry the {@link Entry} containing the {@link Properties property} edits * @param entry the {@link Entry} containing the {@link Properties property} edits
* @return {@code true} if successful * @return {@code true} if successful
*/ */
public static boolean processDate(String command, Properties p, Entry entry, boolean failOnWarning) { public static boolean processDate(String command, Properties p, EntryDate entry, boolean failOnWarning)
throws Exception {
var success = true; var success = true;
var cal = Calendar.getInstance(); var value = PropertyFileUtils.currentValue(null, entry.getDefaultValue(),
String value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(),
entry.getNewValue()); entry.getNewValue());
var pattern = entry.getPattern(); var pattern = entry.getPattern();
SimpleDateFormat fmt;
if (pattern.isBlank()) {
fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm", Localization.getLocale());
} else {
fmt = new SimpleDateFormat(entry.getPattern(), Localization.getLocale());
}
if ("now".equalsIgnoreCase(value) || value.isBlank()) { String parsedValue = String.valueOf(value);
cal.setTime(new Date()); if (pattern != null && !pattern.isBlank()) {
} else { var offset = 0;
if (entry.getCalc() != null) {
offset = entry.getCalc().apply(offset);
}
var dtf = DateTimeFormatter.ofPattern(pattern);
var unit = entry.getUnit();
try { try {
cal.setTime(fmt.parse(value)); if (value instanceof String) {
} catch (ParseException pe) { if ("now".equalsIgnoreCase((String) value)) {
warn(command, "Non-date value for \"" + entry.getKey() + "\" --> " + pe.getMessage(), value = ZonedDateTime.now();
pe, failOnWarning); } else {
throw new DateTimeException("Excepted: Calendar, Date or java.time.");
}
} else if (value instanceof LocalDateTime) {
value = ((LocalDateTime) value).atZone(ZoneId.systemDefault());
} else if (value instanceof Date) {
value = ((Date) value).toInstant().atZone(ZoneId.systemDefault());
} else if (value instanceof Calendar) {
value = ((Calendar) value).toInstant().atZone(ZoneId.systemDefault());
} else if (value instanceof Instant) {
value = ((Instant) value).atZone(ZoneId.systemDefault());
}
if (value instanceof LocalDate) {
if (offset != 0) {
if (unit == EntryDate.Units.DAY) {
value = ((LocalDate) value).plusDays(offset);
} else if (unit == EntryDate.Units.MONTH) {
value = ((LocalDate) value).plusMonths(offset);
} else if (unit == EntryDate.Units.WEEK) {
value = ((LocalDate) value).plusWeeks(offset);
} else if (unit == EntryDate.Units.YEAR) {
value = ((LocalDate) value).plusYears(offset);
}
}
parsedValue = dtf.format((LocalDate) value);
} else if (value instanceof LocalTime) {
if (offset != 0) {
if (unit == EntryDate.Units.SECOND) {
value = ((LocalTime) value).plusSeconds(offset);
} else if (unit == EntryDate.Units.MINUTE) {
value = ((LocalTime) value).plusMinutes(offset);
} else if (unit == EntryDate.Units.HOUR) {
value = ((LocalTime) value).plusHours(offset);
}
}
parsedValue = dtf.format((LocalTime) value);
} else if (value instanceof ZonedDateTime) {
if (offset != 0) {
if (unit == EntryDate.Units.DAY) {
value = ((ZonedDateTime) value).plus(offset, ChronoUnit.DAYS);
} else if (unit == EntryDate.Units.MONTH) {
value = ((ZonedDateTime) value).plus(offset, ChronoUnit.MONTHS);
} else if (unit == EntryDate.Units.WEEK) {
value = ((ZonedDateTime) value).plus(offset, ChronoUnit.WEEKS);
} else if (unit == EntryDate.Units.YEAR) {
value = ((ZonedDateTime) value).plus(offset, ChronoUnit.YEARS);
} else if (unit == EntryDate.Units.SECOND) {
value = ((ZonedDateTime) value).plusSeconds(offset);
} else if (unit == EntryDate.Units.MINUTE) {
value = ((ZonedDateTime) value).plus(offset, ChronoUnit.MINUTES);
} else if (unit == EntryDate.Units.HOUR) {
value = ((ZonedDateTime) value).plus(offset, ChronoUnit.HOURS);
}
}
parsedValue = dtf.format((ZonedDateTime) value);
}
} catch (DateTimeException dte) {
warn(command, "Non-date value for \"" + entry.getKey() + "\" --> " + dte.getMessage(),
dte, failOnWarning);
success = false; success = false;
} }
} }
var offset = 0; if (success) {
p.setProperty(entry.getKey(), parsedValue);
if (entry.getCalc() != null) {
offset = entry.getCalc().apply(offset);
} }
//noinspection MagicConstant
cal.add(CALENDAR_FIELDS.getOrDefault(entry.getUnit(), Calendar.DATE), offset);
p.setProperty(entry.getKey(), fmt.format(cal.getTime()));
return success; return success;
} }
@ -114,7 +156,7 @@ public final class PropertyFileUtils {
* @param defaultValue the default value * @param defaultValue the default value
* @return the current value * @return the current value
*/ */
public static String currentValue(String value, String defaultValue, String newValue) { public static Object currentValue(String value, Object defaultValue, Object newValue) {
if (newValue != null) { if (newValue != null) {
return newValue; return newValue;
} else if (value == null) { } else if (value == null) {
@ -132,16 +174,17 @@ public final class PropertyFileUtils {
* @param entry the {@link Entry} containing the {@link Properties property} edits * @param entry the {@link Entry} containing the {@link Properties property} edits
* @return {@code true} if successful * @return {@code true} if successful
*/ */
public static boolean processInt(String command, Properties p, Entry entry, boolean failOnWarning) { public static boolean processInt(String command, Properties p, EntryInt entry, boolean failOnWarning)
throws Exception {
var success = true; var success = true;
int intValue = 0; int intValue = 0;
try { try {
var fmt = new DecimalFormat(entry.getPattern()); var fmt = new DecimalFormat(entry.getPattern());
String value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(), var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(),
entry.getNewValue()); entry.getNewValue());
if (value != null) { if (value != null) {
intValue = fmt.parse(value).intValue(); intValue = fmt.parse(String.valueOf(value)).intValue();
} }
if (entry.getCalc() != null) { if (entry.getCalc() != null) {
@ -168,7 +211,7 @@ public final class PropertyFileUtils {
var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(), var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(),
entry.getNewValue()); entry.getNewValue());
p.setProperty(entry.getKey(), value); p.setProperty(entry.getKey(), String.valueOf(value));
if (entry.getModify() != null && entry.getModifyValue() != null) { if (entry.getModify() != null && entry.getModifyValue() != null) {
p.setProperty(entry.getKey(), entry.getModify().apply(p.getProperty(entry.getKey()), entry.getModifyValue())); p.setProperty(entry.getKey(), entry.getModify().apply(p.getProperty(entry.getKey()), entry.getModifyValue()));
@ -197,13 +240,12 @@ public final class PropertyFileUtils {
* @param e the related exception * @param e the related exception
* @param failOnWarning skips logging the exception if set to {@code false} * @param failOnWarning skips logging the exception if set to {@code false}
*/ */
static void warn(String command, String message, Exception e, boolean failOnWarning) { static void warn(String command, String message, Exception e, boolean failOnWarning) throws Exception {
if (LOGGER.isLoggable(Level.WARNING)) { if (failOnWarning) {
if (failOnWarning) { LOGGER.log(Level.SEVERE, '[' + command + "] " + message, e);
LOGGER.log(Level.WARNING, '[' + command + "] " + message, e); throw e;
} else { } else {
LOGGER.warning('[' + command + "] " + message); warn(command, message);
}
} }
} }
@ -215,7 +257,7 @@ public final class PropertyFileUtils {
* @param p the {@link Properties properties} to load into. * @param p the {@link Properties properties} to load into.
* @return {@code true} if successful * @return {@code true} if successful
*/ */
public static boolean loadProperties(String command, File file, Properties p) { public static boolean loadProperties(String command, File file, Properties p) throws Exception {
boolean success = true; boolean success = true;
if (file != null) { if (file != null) {
if (file.exists()) { if (file.exists()) {

View file

@ -21,7 +21,8 @@ import rife.tools.Localization;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.text.SimpleDateFormat; import java.time.*;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.Properties; import java.util.Properties;
@ -38,12 +39,14 @@ import static rife.bld.extension.propertyfile.Calc.SUB;
*/ */
class PropertyFileUtilsTest { class PropertyFileUtilsTest {
final Properties p = new Properties(); final Properties p = new Properties();
final Entry entry = new Entry("version.major").set("1");
final EntryDate entryDate = new EntryDate("adate").pattern("D");
final EntryInt entryInt = new EntryInt("version.patch");
final int dayOfYear = LocalDate.now().getDayOfYear();
final String t = "test"; final String t = "test";
@Test @Test
void processStringTest() { void processStringTest() {
var entry = new Entry("version.major").set("1");
PropertyFileUtils.processString(p, entry); PropertyFileUtils.processString(p, entry);
assertThat(entry.getNewValue()).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue())) assertThat(entry.getNewValue()).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue()))
@ -52,106 +55,158 @@ class PropertyFileUtilsTest {
entry.setKey("version.minor"); entry.setKey("version.minor");
PropertyFileUtils.processString(p, entry.set(0)); PropertyFileUtils.processString(p, entry.set(0));
assertThat(entry.getNewValue()).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue())) assertThat(entry.getNewValue().toString()).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue()))
.isEqualTo(p.getProperty(entry.getKey())); .isEqualTo(p.getProperty(entry.getKey()));
}
// APPEND @Test
void testWarn() {
assertThatCode(() -> PropertyFileUtils.warn("command", "message", new IOException(t), true))
.hasMessage(t).isInstanceOf(IOException.class);
assertThatCode(() -> PropertyFileUtils.warn("command", t, new Exception(t), false))
.as("failOnWarning = false").doesNotThrowAnyException();
}
@Test
void parseStringAppend() {
PropertyFileUtils.processString(p, entry.modify("-foo", String::concat)); PropertyFileUtils.processString(p, entry.modify("-foo", String::concat));
assertThat(p.getProperty(entry.getKey())).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue())) assertThat(p.getProperty(entry.getKey())).as(String.format("processString(%s, %s)", entry.getKey(),
.isEqualTo("0-foo"); entry.getNewValue())).isEqualTo("1-foo");
}
// PREPEND @Test
void parseStringPrepend() {
PropertyFileUtils.processString(p, entry.modify("foo-", (v, s) -> s + v)); PropertyFileUtils.processString(p, entry.modify("foo-", (v, s) -> s + v));
assertThat(p.getProperty(entry.getKey())).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue())) assertThat(p.getProperty(entry.getKey())).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue()))
.isEqualTo("foo-0"); .isEqualTo("foo-1");
// CAP }
PropertyFileUtils.processString(p, entry.set(t).modify((v, s) -> v.toUpperCase(Localization.getLocale())));
@Test
void parseStringCap() {
PropertyFileUtils.processString(p, entry.set(t).modify("", (v, s) -> v.toUpperCase(Localization.getLocale())));
assertThat(p.getProperty(entry.getKey())).as("capitalize").isEqualTo(t.toUpperCase(Localization.getLocale())); assertThat(p.getProperty(entry.getKey())).as("capitalize").isEqualTo(t.toUpperCase(Localization.getLocale()));
// REPLACE }
@Test
void parseStringReplace() {
entry.set(t).setModify("T", (v, s) -> v.replace("t", s)); entry.set(t).setModify("T", (v, s) -> v.replace("t", s));
PropertyFileUtils.processString(p, entry); PropertyFileUtils.processString(p, entry);
assertThat(p.getProperty(entry.getKey())).as("replace").isEqualTo("TesT"); assertThat(p.getProperty(entry.getKey())).as("replace(t -> T)").isEqualTo("TesT");
// SUBSTRING }
entry.set(t).setModify((v, s) -> v.substring(1));
@Test
void parseStringCat() {
entry.set(t).setModify("-foo", String::concat);
PropertyFileUtils.processString(p, entry); PropertyFileUtils.processString(p, entry);
assertThat(p.getProperty(entry.getKey())).as("substring").isEqualTo(t.substring(1)); assertThat(p.getProperty(entry.getKey())).as("replace").isEqualTo(t + "-foo");
} }
@Test @Test
void processIntTest() { void parseStringSub() {
var entry = new Entry("version.patch").type(Entry.Types.INT); PropertyFileUtils.processString(p, entry.set(t).modify((v, s) -> v.substring(1)));
assertThat(p.getProperty(entry.getKey())).as("substring(1)").isEqualTo(t.substring(1));
// ADD
entry.calc(ADD);
entry.setDefaultValue("-1");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("add(-1)").isEqualTo("0");
entry.setKey("anint");
entry.setDefaultValue("0");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("add(0)").isEqualTo("1");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("add(1)").isEqualTo("2");
entry.setKey("formated.int");
entry.setDefaultValue("0013");
entry.setPattern("0000");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("add(0013)").isEqualTo("0014");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("add(0014)").isEqualTo("0015");
entry.setKey("formated.int");
entry.calc(v -> v + 2);
entry.setDefaultValue("0013");
entry.setPattern("0000");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("add(0013)+2").isEqualTo("0017");
// SUBTRACT
entry.calc(SUB);
entry.setPattern("0000");
PropertyFileUtils.processInt(t, p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("sub(0017)").isEqualTo("0016");
PropertyFileUtils.processInt(t, p, entry.calc(v -> v - 3), true);
assertThat(p.getProperty(entry.getKey())).as("sub(0017)-3").isEqualTo("0013");
} }
@Test @Test
void processDateTest() { void processIntAddTest() throws Exception {
var entry = new Entry("adate", Entry.Types.DATE).pattern("D"); entryInt.calc(ADD);
var day = new SimpleDateFormat(entry.getPattern(), Localization.getLocale()).format(new Date()); entryInt.setDefaultValue("-1");
var dayInt = Integer.parseInt(day); PropertyFileUtils.processInt(t, p, entryInt, true);
assertThat(p.getProperty(entryInt.getKey())).as("add(-1)").isEqualTo("0");
assertThat(PropertyFileUtils.processDate(t, p, entry.set("a"), false)).as("processDate(a)").isFalse(); entryInt.setKey("anint");
entryInt.setDefaultValue("0");
PropertyFileUtils.processInt(t, p, entryInt, true);
assertThat(p.getProperty(entryInt.getKey())).as("add(0)").isEqualTo("1");
PropertyFileUtils.processInt(t, p, entryInt, true);
assertThat(p.getProperty(entryInt.getKey())).as("add(1)").isEqualTo("2");
PropertyFileUtils.processDate(t, p, entry.set("99"), true); entryInt.setKey("formatted.int");
assertThat(p.getProperty(entry.getKey())).as("processDate(99)").isEqualTo("99"); entryInt.setDefaultValue("0013");
entryInt.setPattern("0000");
PropertyFileUtils.processInt(t, p, entryInt, true);
assertThat(p.getProperty(entryInt.getKey())).as("add(0013)").isEqualTo("0014");
PropertyFileUtils.processInt(t, p, entryInt, true);
assertThat(p.getProperty(entryInt.getKey())).as("add(0014)").isEqualTo("0015");
PropertyFileUtils.processDate(t, p, entry.set("noew"), true); entryInt.calc(v -> v + 2);
assertThat(p.getProperty(entry.getKey())).as("processDate(now)").isEqualTo(day); PropertyFileUtils.processInt(t, p, entryInt, true);
assertThat(p.getProperty(entryInt.getKey())).as("add(0015)+2").isEqualTo("0017");
}
@Test
void parseIntSubTest() throws Exception {
entryInt.calc(SUB);
entryInt.setPattern("0000");
PropertyFileUtils.processInt(t, p, entryInt.defaultValue("0017"), true);
assertThat(p.getProperty(entryInt.getKey())).as("sub(0017)").isEqualTo("0016");
PropertyFileUtils.processInt(t, p, entryInt.set(16).calc(v -> v - 3), true);
assertThat(p.getProperty(entryInt.getKey())).as("sub(16)-3").isEqualTo("0013");
}
@Test
void processDateAddTest() throws Exception {
entryDate.setCalc(ADD);
PropertyFileUtils.processDate(t, p, entryDate.now(), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(now+1)").isEqualTo(String.valueOf(dayOfYear + 1));
PropertyFileUtils.processDate(t, p, entryDate.now().calc(v -> v + 3), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(now+3)").isEqualTo(String.valueOf(dayOfYear + 3));
entryDate.setCalc(ADD);
PropertyFileUtils.processDate(t, p, entryDate.set(ZonedDateTime.now()), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(ZonedDateTime+1)")
.isEqualTo(String.valueOf(dayOfYear + 1));
PropertyFileUtils.processDate(t, p, entryDate.set(Instant.now()).calc(v -> v + 2), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(Instant+2)").isEqualTo(String.valueOf(dayOfYear + 2));
entryDate.setCalc(v -> v + 3);
PropertyFileUtils.processDate(t, p, entryDate.set(LocalDateTime.now()), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(LocalDteTime+2)").isEqualTo(String.valueOf(dayOfYear + 3));
}
@Test
void parseDateSub() throws Exception {
entryDate.setCalc(SUB);
PropertyFileUtils.processDate(t, p, entryDate.now(), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(now-3)").isEqualTo(String.valueOf(dayOfYear - 1));
entryDate.setCalc(v -> v - 2);
PropertyFileUtils.processDate(t, p, entryDate.now(), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(now-2)").isEqualTo(String.valueOf(dayOfYear - 2));
entryDate.setCalc(SUB);
PropertyFileUtils.processDate(t, p, entryDate.set(new Date()), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(date-1)").isEqualTo(String.valueOf(dayOfYear - 1));
entryDate.setCalc(v -> v - 2);
PropertyFileUtils.processDate(t, p, entryDate.set(Calendar.getInstance()), true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(cal-2)").isEqualTo(String.valueOf(dayOfYear - 2));
entryDate.setCalc(v -> v - 3);
PropertyFileUtils.processDate(t, p, entryDate.set(LocalDate.now()),
true);
assertThat(p.getProperty(entryDate.getKey())).as("processDate(LocalDate-3)").isEqualTo(String.valueOf(dayOfYear - 3));
}
@Test
void parseTimeTest() throws Exception {
var entry = new EntryDate("time").pattern("m");
var time = LocalTime.now();
// ADD
entry.setCalc(ADD); entry.setCalc(ADD);
PropertyFileUtils.processDate(t, p, entry.set(dayInt), true); PropertyFileUtils.processDate(t, p, entry.set(time).unit(EntryDate.Units.MINUTE), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now+1)").isEqualTo(String.valueOf(dayInt + 1)); assertThat(p.getProperty(entry.getKey())).as("processDate(now+1)")
.isEqualTo(String.valueOf(time.plusMinutes(1).getMinute()));
entry.setCalc(v -> v + 3);
PropertyFileUtils.processDate(t, p, entry.set(dayInt), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now+3)").isEqualTo(String.valueOf(dayInt + 3));
// SUBTRACT
entry.setCalc(SUB); entry.setCalc(SUB);
PropertyFileUtils.processDate(t, p, entry.set(dayInt), true); PropertyFileUtils.processDate(t, p, entry.set(time).unit(EntryDate.Units.HOUR).pattern("H"), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now-3)").isEqualTo(String.valueOf(dayInt - 1)); assertThat(p.getProperty(entry.getKey())).as("processDate(now+1)")
.isEqualTo(String.valueOf(time.minusHours(1).getHour()));
entry.setCalc(v -> v - 2);
PropertyFileUtils.processDate(t, p, entry.set(dayInt), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now-2)").isEqualTo(String.valueOf(dayInt - 2));
} }
@Test @Test
@ -168,7 +223,7 @@ class PropertyFileUtilsTest {
} }
@Test @Test
void savePropertiesTest() throws IOException { void savePropertiesTest() throws Exception {
var p = new Properties(); var p = new Properties();
var test = "test"; var test = "test";