Initial commit

This commit is contained in:
Erik C. Thauvin 2023-04-02 15:29:27 -07:00
commit 387d1a93e7
52 changed files with 1917 additions and 0 deletions

View file

@ -0,0 +1,301 @@
/*
* 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;
/**
* <p>Declares the edits to be made to a {@link java.util.Properties Properties} file.</p>
*
* <p>The rules used when setting a {@link java.util.Properties property} value are:</p>
*
* <ul>
* <li>If only value is specified, the property is set to it regardless of its previous value.</li>
* <li>If only default value is specified and the property previously existed, it is unchanged.</li>
* <li>If only default value is specified and the property did not exist, the property is set to the default value.</li>
* <li>If value and default value are both specified and the property previously existed, the property is set to value.</li>
* <li>If value and default value are both specified and the property did not exist, the property is set to the default value.</li>
* </ul>
*
* <p>{@link Operations Operations} occur after the rules are evaluated.</p>
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @since 1.0
*/
public class Entry {
private String key;
private String value;
private String defaultValue;
private Types type = Types.STRING;
private Operations operation = Operations.SET;
private String pattern = "";
private Units unit = Units.DAY;
/**
* Creates a new {@link Entry entry} Entry.
*
* @param key the required property key
*/
public Entry(String key) {
this.key = key;
}
/**
* Returns the name of the {@link java.util.Properties property} name/value pair.
*/
public String getKey() {
return key;
}
/**
* Sets the name of the {@link java.util.Properties property} name/value pair.
*
* @param key the {@link java.util.Properties property} key
*/
public void setKey(String key) {
this.key = key;
}
/**
* Returns the value of the {@link java.util.Properties property}.
*/
public String getValue() {
return value;
}
/**
* Sets the value of the {@link java.util.Properties property}.
*
* @param value the {@link java.util.Properties property} value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Returns the default value.
*/
public String getDefaultValue() {
return defaultValue;
}
/**
* <p>Sets the initial value to set for the {@link java.util.Properties property} 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;
}
/**
* Return the {@link Operations Operation}.
*/
public Operations getOperation() {
return operation;
}
/**
* Sets the {@link Operations Operation} to be performed on the {@link java.util.Properties property} value,
*
* @param operation the entry {@link Operations Operation}
*/
public void setOperation(Operations operation) {
this.operation = operation;
}
/**
* Returns the pattern.
*/
public String getPattern() {
return pattern;
}
/**
* <p>Parses the value of {@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 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 Operations#ADD Operations.ADD}
* and {@link Operations#SUBTRACT Operations.SUBTRACT} for {@link Types#DATE Types.DATE}.
*
* @param unit the {@link Units unit}
*/
public void setUnit(Units unit) {
this.unit = unit;
}
/**
* Sets the name of the {@link java.util.Properties property} name/value pair.
*
* @param key the {@link java.util.Properties property} key
*/
public Entry key(String key) {
setKey(key);
return this;
}
/**
* Sets the value of the {@link java.util.Properties property}.
*
* @param value the {@link java.util.Properties property} value
*/
public Entry value(Object value) {
if (value != null) {
setValue(String.valueOf(value));
} else {
setValue(null);
}
return this;
}
/**
* <p>Sets the initial value to set for the {@link java.util.Properties property} 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 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;
}
/**
* Sets the {@link Operations Operation} to be performed on the {@link java.util.Properties property} value,
*
* @param operation the entry {@link Operations Operation}
*/
public Entry operation(Operations operation) {
setOperation(operation);
return this;
}
/**
* <p>Parses the value of {@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 Operations#ADD Operations.ADD}
* and {@link Operations#SUBTRACT Operations.SUBTRACT} for {@link Types#DATE Types.DATE}.
*
* @param unit the {@link Units unit}
*/
public Entry unit(Units unit) {
setUnit(unit);
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 operations available for all {@link Types Types}.
*
* <uL>
* <li>{@link Operations#ADD ADD} adds a value to an {@link Entry entry}</li>
* <li>{@link Operations#DELETE DELETE} deletes an entry</li>
* <li>{@link Operations#SET SET} sets the entry value. This is the default operation</li>
* <li>{@link Operations#SUBTRACT SUBTRACT} subtracts a value from the {@link Entry entry}.
* For {@link Types#INT Types.INT} and {@link Types#DATE Types.DATE} only.</li>
* </uL>
*/
public enum Operations {
ADD, DELETE, SET, SUBTRACT
}
/**
* The units available for {@link Types#DATE Type.DATE} with {@link Operations#ADD Operations>ADD}
* and {@link Operations#SUBTRACT Operations.SUBTRACT}.
*
* <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,145 @@
/*
* 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 rife.bld.Project;
import rife.bld.extension.propertyFile.Entry.Operations;
import rife.bld.extension.propertyFile.Entry.Types;
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;
/**
* Creates or applies edits to a {@link Properties Properties} file.
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @since 1.0
*/
public class PropertyFileOperation extends AbstractOperation<PropertyFileOperation> {
private final List<Entry> entries = new ArrayList<>();
private final Project project;
private File file = null;
private String comment = "";
private boolean failOnWarning = false;
public PropertyFileOperation(Project project) {
this.project = project;
}
/**
* Adds an {@link Entry entry} to specify modifications to the {@link java.util.Properties properties}
* file.
*
* @param entry the {@link Entry entry}
*/
public PropertyFileOperation entry(Entry entry) {
entries.add(entry);
return this;
}
/**
* Sets the location of the {@link java.util.Properties} file to be edited.
*
* @param file the file to be edited
*/
public PropertyFileOperation file(String file) {
this.file = new File(file);
return this;
}
/**
* Sets the location of the {@link java.util.Properties} file to be edited.
*
* @param file the file to be edited
*/
public PropertyFileOperation file(File file) {
this.file = file;
return this;
}
/**
* Sets the command to return a failure on any warnings.
*
* @param failOnWarning if set to {@code true}, the task will fail on any warnings.
*/
public PropertyFileOperation failOnWarning(boolean failOnWarning) {
this.failOnWarning = failOnWarning;
return this;
}
/**
* Sets the comment to be inserted at the top of the {@link java.util.Properties} file.
*
* @param comment the header comment
*/
public PropertyFileOperation comment(String comment) {
this.comment = comment;
return this;
}
/**
* Performs the edits to the {@link java.util.Properties properties} file.
*/
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 success = false;
var properties = new Properties();
success = PropertyFileUtils.loadProperties(file, properties);
if (success) {
for (var entry : entries) {
if (entry.getKey().isBlank()) {
PropertyFileUtils.warn("At least one entry key must specified.");
success = false;
} else {
var key = entry.getKey();
var value = entry.getValue();
var defaultValue = entry.getDefaultValue();
if ((value == null || value.isBlank()) && (defaultValue == null || defaultValue.isBlank())
&& entry.getOperation() != Operations.DELETE) {
PropertyFileUtils.warn("An entry value or default must be specified: " + key);
success = false;
} else if (entry.getType() == Types.STRING && entry.getOperation() == Operations.SUBTRACT) {
PropertyFileUtils.warn("Subtraction is not supported for String properties: " + key);
success = false;
} else if (entry.getOperation() == Operations.DELETE) {
properties.remove(key);
} else {
switch (entry.getType()) {
case DATE -> success = PropertyFileUtils.processDate(properties, entry, failOnWarning);
case INT -> success = PropertyFileUtils.processInt(properties, entry, failOnWarning);
default -> success = PropertyFileUtils.processString(properties, entry);
}
}
}
}
}
if (failOnWarning && !success) {
throw new RuntimeException("Properties file configuration failed: " + file);
} else if (success) {
PropertyFileUtils.saveProperties(file, comment, properties);
}
}
}

View file

@ -0,0 +1,308 @@
/*
* 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 rife.bld.extension.propertyFile.Entry.Operations;
import rife.bld.extension.propertyFile.Entry.Units;
import rife.tools.Localization;
import javax.imageio.IIOException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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;
/**
* Collection of utility-type methods commonly used in this project.
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @since 1.0
*/
public final class PropertyFileUtils {
private final static Logger LOGGER = Logger.getLogger(PropertyFileUtils.class.getName());
private final static Map<Units, Integer> calendarFields =
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
}
/**
* Processes a date {@link Properties property}.
*
* @param p the {@link Properties property}
* @param entry the {@link Entry} containing the {@link Properties property} edits
* @return {@code true} if successful
*/
public static boolean processDate(Properties p, Entry entry, boolean failOnWarning) {
var success = true;
var cal = Calendar.getInstance();
var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getValue(),
entry.getDefaultValue(), entry.getOperation());
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 {
try {
cal.setTime(fmt.parse(value));
} catch (ParseException pe) {
warn("Date parse exception for: " + entry.getKey() + " --> " + pe.getMessage(), pe, failOnWarning);
success = false;
}
}
if (entry.getOperation() != Entry.Operations.SET) {
var offset = 0;
try {
offset = Integer.parseInt(entry.getValue());
if (entry.getOperation() == Entry.Operations.SUBTRACT) {
offset *= -1;
}
} catch (NumberFormatException nfe) {
warn("Non-integer value for: " + entry.getKey() + " --> " + nfe.getMessage(), nfe, failOnWarning);
success = false;
}
cal.add(calendarFields.getOrDefault(entry.getUnit(), Calendar.DATE), offset);
}
p.setProperty(entry.getKey(), fmt.format(cal.getTime()));
return success;
}
/**
* Return the current value, new value or default value based on the specified {@link Operations operation}.
*
* @param value the value
* @param newValue the new value
* @param defaultValue the default value
* @param operation the {@link Operations operation}
* @return the current value
*/
public static String currentValue(String value, String newValue, String defaultValue, Operations operation) {
String result = null;
if (operation == Entry.Operations.SET) {
if (newValue != null && defaultValue == null) {
result = newValue;
}
if (defaultValue != null) {
if (newValue == null && value != null) {
result = value;
}
if (newValue == null && value == null) {
result = defaultValue;
}
if (newValue != null && value != null) {
result = newValue;
}
if (newValue != null && value == null) {
result = defaultValue;
}
}
} else {
if (value == null) {
result = defaultValue;
} else {
result = value;
}
}
if (result == null) {
result = "";
}
return result;
}
/**
* Ensure that the given value is an integer.
*
* @param value the value
* @return the parsed value
* @throws NumberFormatException if the value could not be parsed as an integer
*/
static String parseInt(String value) throws NumberFormatException {
return String.valueOf(Integer.parseInt(value));
}
/**
* Processes an integer {@link Properties property}.
*
* @param p the {@link Properties property}
* @param entry the {@link Entry} containing the {@link Properties property} edits
* @return {@code true} if successful
*/
public static boolean processInt(Properties p, Entry entry, boolean failOnWarning) {
var success = true;
int intValue;
try {
var fmt = new DecimalFormat(entry.getPattern());
var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getValue(),
entry.getDefaultValue(), entry.getOperation());
if (value.isBlank()) {
intValue = fmt.parse("0").intValue();
} else {
intValue = fmt.parse(parseInt(value)).intValue();
}
if (entry.getOperation() != Entry.Operations.SET) {
var opValue = 1;
if (entry.getValue() != null) {
opValue = fmt.parse(parseInt(entry.getValue())).intValue();
}
if (entry.getOperation() == Entry.Operations.ADD) {
intValue += opValue;
} else if (entry.getOperation() == Entry.Operations.SUBTRACT) {
intValue -= opValue;
}
}
p.setProperty(entry.getKey(), fmt.format(intValue));
} catch (NumberFormatException nfe) {
warn("Number format exception for: " + entry.getKey() + " --> " + nfe.getMessage(), nfe, failOnWarning);
success = false;
} catch (ParseException pe) {
warn("Number parsing exception for: " + entry.getKey() + " --> " + pe.getMessage(), pe, failOnWarning);
success = false;
}
return success;
}
/**
* Processes a string {@link Properties property}.
*
* @param p the {@link Properties property}
* @param entry the {@link Entry} containing the {@link Properties property} edits
* @return {@code true} if successful
*/
public static boolean processString(Properties p, Entry entry) {
var value = PropertyFileUtils.currentValue(p.getProperty(entry.getKey()), entry.getValue(),
entry.getDefaultValue(), entry.getOperation());
if (entry.getOperation() == Entry.Operations.SET) {
p.setProperty(entry.getKey(), value);
} else if (entry.getOperation() == Entry.Operations.ADD) {
if (entry.getValue() != null) {
p.setProperty(entry.getValue(), "$value${entry.value}");
}
}
return true;
}
/**
* Logs a warning.
*
* @param message the message to log
*/
static void warn(String message) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.warning(message);
}
}
/**
* Logs a warning.
*
* @param message the message log
* @param e the related exception
* @param failOnWarning skips logging the exception if set to {@code false}
*/
static void warn(String message, Exception e, boolean failOnWarning) {
if (LOGGER.isLoggable(Level.WARNING)) {
if (failOnWarning) {
LOGGER.log(Level.WARNING, message, e);
} else {
LOGGER.warning(message);
}
}
}
/**
* Loads a {@link Properties properties} file.
*
* @param file the file location.
* @param p the {@link Properties properties} to load into.
* @return {@code true} if successful
*/
public static boolean loadProperties(File file, Properties p) {
boolean success = true;
if (file != null) {
if (file.exists()) {
try (var propStream = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) {
p.load(propStream);
} catch (IOException ioe) {
warn("Could not load properties file: " + ioe.getMessage(), ioe, true);
success = false;
}
} else {
warn("The '" + file + "' properties file could not be found.");
success = false;
}
} else {
warn("Please specify the properties file location.");
success = false;
}
return success;
}
/**
* Saves a {@link Properties properties} file.
*
* @param file the file location
* @param comment the header comment
* @param p the {@link Properties} to save into the file
*/
public static void saveProperties(File file, String comment, Properties p) throws IOException {
try (var output = Files.newOutputStream(file.toPath())) {
p.store(output, comment);
} catch (IIOException ioe) {
throw new IIOException("An IO error occurred while saving the Properties file: " + file, ioe);
}
}
}