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

View file

@ -21,7 +21,8 @@ public class PropertyFileBuild extends Project {
javadocOptions
.docLint(NO_MISSING)
.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()
.groupId("com.uwyn.rife2")
.artifactId("bld-property-file")
@ -45,7 +46,7 @@ public class PropertyFileBuild extends Project {
repositories = List.of(MAVEN_CENTRAL, RIFE2);
scope(compile)
.include(dependency("com.uwyn.rife2", "rife2", version(1, 5, 16)));
.include(dependency("com.uwyn.rife2", "rife2", version(1, 5, 17)));
scope(test)
.include(dependency("org.jsoup", "jsoup", version(1, 15, 4)))
.include(dependency("org.junit.jupiter", "junit-jupiter", version(5, 9, 2)))

View file

@ -17,7 +17,6 @@
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.
@ -26,67 +25,30 @@ import java.util.function.IntFunction;
* @author <a href="https://github.com/gbevin">Geert Bevin</a>
* @since 1.0
*/
public class Entry {
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 class Entry extends EntryBase {
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 type the value {@link Types Type}
* @param s The new value
*/
public Entry(String key, Types type) {
this.key = key;
this.type = type;
public Entry set(Object s) {
setNewValue(s);
return this;
}
/**
* Returns the value to be used in the {@link #modify} function.
*/
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.
* <p>Sets the initial value to set the {@link java.util.Properties property} to, if not already defined.</p>
*
* @param value the value to perform a modification with
* @param defaultValue the default value
*/
public void setModify(String value, BiFunction<String, String, String> modify) {
this.modifyValue = value;
this.modify = modify;
@SuppressWarnings("unused")
public Entry defaultValue(Object defaultValue) {
setDefaultValue(defaultValue);
return this;
}
/**
@ -96,7 +58,7 @@ public class Entry {
* @param modify the modification function
*/
public Entry modify(String value, BiFunction<String, String, String> modify) {
modifyValue = value;
setModifyValue(value);
setModify(modify);
return this;
}
@ -111,251 +73,11 @@ public class Entry {
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.
*/
public Entry delete() {
isDelete = true;
setDelete(true);
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 java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@ -32,7 +31,7 @@ import java.util.Properties;
* @since 1.0
*/
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 File file;
private String comment = "";
@ -49,7 +48,7 @@ public class PropertyFileOperation extends AbstractOperation<PropertyFileOperati
* @param entry the {@link Entry entry}
*/
@SuppressWarnings("unused")
public PropertyFileOperation entry(Entry entry) {
public PropertyFileOperation entry(EntryBase entry) {
entries.add(entry);
return this;
}
@ -103,45 +102,44 @@ public class PropertyFileOperation extends AbstractOperation<PropertyFileOperati
*/
@Override
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 success = false;
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) {
for (var entry : entries) {
if (entry.getKey().isBlank()) {
PropertyFileUtils.warn(commandName, "At least one entry key must specified.");
success = false;
PropertyFileUtils.warn(commandName, "An entry key must specified.");
} else {
var key = entry.getKey();
var value = entry.getNewValue();
var defaultValue = entry.getDefaultValue();
Object value = entry.getNewValue();
Object defaultValue = entry.getDefaultValue();
var p = properties.getProperty(key);
if (entry.isDelete()) {
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);
success = false;
} else {
switch (entry.getType()) {
case DATE ->
success = PropertyFileUtils.processDate(commandName, properties, entry, failOnWarning);
case INT ->
success = PropertyFileUtils.processInt(commandName, properties, entry, failOnWarning);
default -> success = PropertyFileUtils.processString(properties, entry);
}
if (entry instanceof EntryDate)
success = PropertyFileUtils.processDate(commandName, properties, (EntryDate) entry, failOnWarning);
else if (entry instanceof EntryInt)
success = PropertyFileUtils.processInt(commandName, properties, (EntryInt) entry, failOnWarning);
else
success = PropertyFileUtils.processString(properties, (Entry) entry);
}
}
}
}
if (failOnWarning && !success) {
throw new RuntimeException("Properties file configuration failed: " + file);
} else if (success) {
if (success) {
PropertyFileUtils.saveProperties(file, comment, properties);
}
}

View file

@ -16,9 +16,6 @@
package rife.bld.extension.propertyfile;
import rife.bld.extension.propertyfile.Entry.Units;
import rife.tools.Localization;
import javax.imageio.IIOException;
import java.io.File;
import java.io.IOException;
@ -26,10 +23,11 @@ import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.DecimalFormat;
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.Date;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -44,16 +42,6 @@ import java.util.logging.Logger;
public final class PropertyFileUtils {
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() {
// no-op
}
@ -66,43 +54,97 @@ public final class PropertyFileUtils {
* @param entry the {@link Entry} containing the {@link Properties property} edits
* @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 cal = Calendar.getInstance();
String value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(),
var value = PropertyFileUtils.currentValue(null, entry.getDefaultValue(),
entry.getNewValue());
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()) {
cal.setTime(new Date());
} else {
String parsedValue = String.valueOf(value);
if (pattern != null && !pattern.isBlank()) {
var offset = 0;
if (entry.getCalc() != null) {
offset = entry.getCalc().apply(offset);
}
var dtf = DateTimeFormatter.ofPattern(pattern);
var unit = entry.getUnit();
try {
cal.setTime(fmt.parse(value));
} catch (ParseException pe) {
warn(command, "Non-date value for \"" + entry.getKey() + "\" --> " + pe.getMessage(),
pe, failOnWarning);
if (value instanceof String) {
if ("now".equalsIgnoreCase((String) value)) {
value = ZonedDateTime.now();
} 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;
}
}
var offset = 0;
if (entry.getCalc() != null) {
offset = entry.getCalc().apply(offset);
if (success) {
p.setProperty(entry.getKey(), parsedValue);
}
//noinspection MagicConstant
cal.add(CALENDAR_FIELDS.getOrDefault(entry.getUnit(), Calendar.DATE), offset);
p.setProperty(entry.getKey(), fmt.format(cal.getTime()));
return success;
}
@ -114,7 +156,7 @@ public final class PropertyFileUtils {
* @param defaultValue the default 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) {
return newValue;
} else if (value == null) {
@ -132,16 +174,17 @@ public final class PropertyFileUtils {
* @param entry the {@link Entry} containing the {@link Properties property} edits
* @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;
int intValue = 0;
try {
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());
if (value != null) {
intValue = fmt.parse(value).intValue();
intValue = fmt.parse(String.valueOf(value)).intValue();
}
if (entry.getCalc() != null) {
@ -168,7 +211,7 @@ public final class PropertyFileUtils {
var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getDefaultValue(),
entry.getNewValue());
p.setProperty(entry.getKey(), value);
p.setProperty(entry.getKey(), String.valueOf(value));
if (entry.getModify() != null && entry.getModifyValue() != null) {
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 failOnWarning skips logging the exception if set to {@code false}
*/
static void warn(String command, String message, Exception e, boolean failOnWarning) {
if (LOGGER.isLoggable(Level.WARNING)) {
if (failOnWarning) {
LOGGER.log(Level.WARNING, '[' + command + "] " + message, e);
} else {
LOGGER.warning('[' + command + "] " + message);
}
static void warn(String command, String message, Exception e, boolean failOnWarning) throws Exception {
if (failOnWarning) {
LOGGER.log(Level.SEVERE, '[' + command + "] " + message, e);
throw e;
} else {
warn(command, message);
}
}
@ -215,7 +257,7 @@ public final class PropertyFileUtils {
* @param p the {@link Properties properties} to load into.
* @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;
if (file != null) {
if (file.exists()) {

View file

@ -21,7 +21,8 @@ import rife.tools.Localization;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
@ -38,12 +39,14 @@ import static rife.bld.extension.propertyfile.Calc.SUB;
*/
class PropertyFileUtilsTest {
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";
@Test
void processStringTest() {
var entry = new Entry("version.major").set("1");
PropertyFileUtils.processString(p, entry);
assertThat(entry.getNewValue()).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue()))
@ -52,106 +55,158 @@ class PropertyFileUtilsTest {
entry.setKey("version.minor");
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()));
}
// 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));
assertThat(p.getProperty(entry.getKey())).as(String.format("processString(%s, %s)", entry.getKey(), entry.getNewValue()))
.isEqualTo("0-foo");
assertThat(p.getProperty(entry.getKey())).as(String.format("processString(%s, %s)", entry.getKey(),
entry.getNewValue())).isEqualTo("1-foo");
}
// PREPEND
@Test
void parseStringPrepend() {
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()))
.isEqualTo("foo-0");
// CAP
PropertyFileUtils.processString(p, entry.set(t).modify((v, s) -> v.toUpperCase(Localization.getLocale())));
.isEqualTo("foo-1");
}
@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()));
// REPLACE
}
@Test
void parseStringReplace() {
entry.set(t).setModify("T", (v, s) -> v.replace("t", s));
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);
assertThat(p.getProperty(entry.getKey())).as("substring").isEqualTo(t.substring(1));
assertThat(p.getProperty(entry.getKey())).as("replace").isEqualTo(t + "-foo");
}
@Test
void processIntTest() {
var entry = new Entry("version.patch").type(Entry.Types.INT);
// 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");
void parseStringSub() {
PropertyFileUtils.processString(p, entry.set(t).modify((v, s) -> v.substring(1)));
assertThat(p.getProperty(entry.getKey())).as("substring(1)").isEqualTo(t.substring(1));
}
@Test
void processDateTest() {
var entry = new Entry("adate", Entry.Types.DATE).pattern("D");
var day = new SimpleDateFormat(entry.getPattern(), Localization.getLocale()).format(new Date());
var dayInt = Integer.parseInt(day);
void processIntAddTest() throws Exception {
entryInt.calc(ADD);
entryInt.setDefaultValue("-1");
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);
assertThat(p.getProperty(entry.getKey())).as("processDate(99)").isEqualTo("99");
entryInt.setKey("formatted.int");
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);
assertThat(p.getProperty(entry.getKey())).as("processDate(now)").isEqualTo(day);
entryInt.calc(v -> v + 2);
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);
PropertyFileUtils.processDate(t, p, entry.set(dayInt), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now+1)").isEqualTo(String.valueOf(dayInt + 1));
PropertyFileUtils.processDate(t, p, entry.set(time).unit(EntryDate.Units.MINUTE), true);
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);
PropertyFileUtils.processDate(t, p, entry.set(dayInt), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now-3)").isEqualTo(String.valueOf(dayInt - 1));
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));
PropertyFileUtils.processDate(t, p, entry.set(time).unit(EntryDate.Units.HOUR).pattern("H"), true);
assertThat(p.getProperty(entry.getKey())).as("processDate(now+1)")
.isEqualTo(String.valueOf(time.minusHours(1).getHour()));
}
@Test
@ -168,7 +223,7 @@ class PropertyFileUtilsTest {
}
@Test
void savePropertiesTest() throws IOException {
void savePropertiesTest() throws Exception {
var p = new Properties();
var test = "test";