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

55
.gitignore vendored Normal file
View file

@ -0,0 +1,55 @@
.gradle
.DS_Store
build
lib/bld/**
lib/compile/**
lib/runtime/**
lib/standalone/**
lib/test/**
!bld-wrapper.jar
!bld-wrapper.properties
# IDEA ignores
# User-specific
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Editor-based Rest Client
.idea/httpRequests

3
.idea/.gitignore generated vendored Normal file
View file

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

28
.idea/app.iml generated Normal file
View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/build/main" />
<output-test url="file://$MODULE_DIR$/build/test" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/src/main/resources/templates" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library" scope="RUNTIME">
<library>
<CLASSES>
<root url="file://$MODULE_DIR$/src/main/resources/templates" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="library" name="compile" level="project" />
<orderEntry type="library" scope="RUNTIME" name="runtime" level="project" />
<orderEntry type="library" scope="TEST" name="test" level="project" />
</component>
</module>

14
.idea/bld.iml generated Normal file
View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/build/bld" />
<output-test url="file://$MODULE_DIR$/build/bld" />
<exclude-output />
<content url="file://$MODULE_DIR$/src/bld">
<sourceFolder url="file://$MODULE_DIR$/src/bld/java" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="bld" level="project" />
</component>
</module>

6
.idea/copyright/Apache_License.xml generated Normal file
View file

@ -0,0 +1,6 @@
<component name="CopyrightManager">
<copyright>
<option name="notice" value=" Copyright &amp;#36;today.year the original author or authors.&#10; &#10; Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);&#10; you may not use this file except in compliance with the License.&#10; You may obtain a copy of the License at&#10; &#10; https://www.apache.org/licenses/LICENSE-2.0&#10; &#10; Unless required by applicable law or agreed to in writing, software&#10; distributed under the License is distributed on an &quot;AS IS&quot; BASIS,&#10; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.&#10; See the License for the specific language governing permissions and&#10; limitations under the License." />
<option name="myName" value="Apache License" />
</copyright>
</component>

3
.idea/copyright/profiles_settings.xml generated Normal file
View file

@ -0,0 +1,3 @@
<component name="CopyrightManager">
<settings default="Apache License" />
</component>

View file

@ -0,0 +1,8 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JavadocDeclaration" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ADDITIONAL_TAGS" value="created" />
</inspection_tool>
</profile>
</component>

17
.idea/libraries/bld.xml generated Normal file
View file

@ -0,0 +1,17 @@
<component name="libraryTable">
<library name="bld">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/bld" />
<root url="jar://$USER_HOME$/.rife2/dist/rife2-1.5.11.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.rife2/dist/rife2-1.5.11-sources.jar!/" />
</SOURCES>
<excluded>
<root url="jar://$PROJECT_DIR$/lib/bld/bld-wrapper.jar!/" />
</excluded>
<jarDirectory url="file://$PROJECT_DIR$/lib/bld" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/bld" recursive="false" type="SOURCES" />
</library>
</component>

13
.idea/libraries/compile.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="compile">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/compile" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/compile" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib/compile" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/compile" recursive="false" type="SOURCES" />
</library>
</component>

13
.idea/libraries/runtime.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="runtime">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/runtime" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/runtime" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib/runtime" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/runtime" recursive="false" type="SOURCES" />
</library>
</component>

13
.idea/libraries/test.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="test">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/test" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/test" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib/test" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/test" recursive="false" type="SOURCES" />
</library>
</component>

16
.idea/misc.xml generated Normal file
View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<pattern value="rife.bld.extension.propertyFile.Entry" method="defaultValue" />
<pattern value="rife.bld.extension.propertyFile.Entry" />
<pattern value="rife.bld.extension.propertyFile.Entry" method="key" />
<pattern value="rife.bld.extension.propertyFile.Entry" method="operation" />
<pattern value="rife.bld.extension.propertyFile.Entry" method="unit" />
</component>
<component name="PDMPlugin">
<option name="skipTestSources" value="false" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build" />
</component>
</project>

9
.idea/modules.xml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/app.iml" filepath="$PROJECT_DIR$/.idea/app.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/bld.iml" filepath="$PROJECT_DIR$/.idea/bld.iml" />
</modules>
</component>
</project>

View file

@ -0,0 +1,9 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="PropertyFile" type="Application" factoryName="Application" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="rife.bld.plugin.PropertyFile" />
<module name="app" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

13
.idea/runConfigurations/Run Tests.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="JUnit" factoryName="JUnit">
<module name="app" />
<option name="PACKAGE_NAME" value="moog" />
<option name="MAIN_CLASS_NAME" value="rife.bld.plugin" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="directory" />
<dir value="$PROJECT_DIR$/src/test/java" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

24
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,24 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "Run Main",
"request": "launch",
"mainClass": "rife.bld.extension.propertyFile.PropertyFileOperation"
},
{
"type": "java",
"name": "Run Tests",
"request": "launch",
"mainClass": "org.junit.platform.console.ConsoleLauncher",
"args": [
"--details=verbose",
"--scan-classpath",
"--disable-banner",
"--disable-ansi-colors",
"--exclude-engine=junit-platform-suite",
"--exclude-engine=junit-vintage"]
}
]
}

15
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,15 @@
{
"java.project.sourcePaths": [
"src/main/java",
"src/main/resources",
"src/test/java",
"src/bld/java"
],
"java.configuration.updateBuildConfiguration": "automatic",
"java.project.referencedLibraries": [
"${HOME}/.rife2/dist/rife2-1.5.11.jar",
"lib/compile/*.jar",
"lib/runtime/*.jar",
"lib/test/*.jar"
]
}

177
LICENSE.txt Normal file
View file

@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

90
README.md Executable file
View file

@ -0,0 +1,90 @@
# [Bld](https://github.com/rife2/rife2/wiki/What-Is-Bld) Extension to Edit or Modify Properties Files
[![License (3-Clause BSD)](https://img.shields.io/badge/license-BSD%203--Clause-blue.svg?style=flat-square)](http://opensource.org/licenses/BSD-3-Clause)
An extension for creating or modifying [property files](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html) with [bld](https://github.com/rife2/rife2/wiki/What-Is-Bld). It is inspired by the [ant PropertyFile task](https://ant.apache.org/manual/Tasks/propertyfile.html).
```java
@BuildCommand
public void updateMajor() throws Exception {
new PropertyFileOperation(this)
.file("version.properties")
.entry(new Entry("version.major").defaultValue(1).type(Types.INT).operation(Operations.ADD))
.entry(new Entry("version.minor").value(0))
.entry(new Entry("version.patch").value(0))
.execute();
}
```
To invoke the `updateMajor` command:
```sh
./bld updateMajor
```
## PropertyFileOperation
Attribute | Description | Required
:---------------|:----------------------------------------------------------|:--------
`file` | The location of the properties files to modify. | Yes
`comment` | Comment to be inserted at the top of the properties file. | No
`failOnWarning` | If set to `true`, will fail on any warnings. | No
## Entry
The `entry` function is used to specify edits to be made to the properties file.
Attribute | Description
:-----------|:-----------------------------------------------------------------------------------------------------------------
`key` | The name of the property name/value pair.
`value` | The value of the property.
`default` | The initial value to set for the property if not already defined. For `Type.DATE`, the `now` keyword can be used.
`type` | Tread the value as `Types.INT`, `Types.DATE`, or `Types.STRING`. If none specified, `Types.STRING` is assumed.
`operation` | See [operations](#operations).
`pattern` | For `Types.INT` and `Types.DATE` 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.
`unit` | The unit value to be applied to `Operations.ADD` and `Operations.SUBTRACT` for `Types.DATE`. See [Units](#units).
`key` is required. `value` or `default` are required unless the `operation` is `Operations.DELETE`.
## Operations
The following operations are available:
Operation | Description
:---------------------|:-------------------------------------------------------------------------
`Operations.ADD` | Adds a value to an entry.
`Operations.DELETE` | Deletes an entry.
`Operations.SET` | Sets the entry value. This is the default operation.
`Operations.SUBTRACT` | Subtracts a value from the entry. For `Types.INT` and `Types.DATE` only.
## Units
The following units are available for `Types.DATE` with `Operations.ADD` and `Operations.SUBTRACT`:
* `Units.MILLISECOND`
* `Units.SECOND`
* `Units.MINUTE`
* `Units.HOUR`
* `Units.DAY`
* `Units.WEEK`
* `Units.MONTH`
* `Units.YEAR`
## Rules
The rules used when setting a property value are:
* If only `value` is specified, the property is set to it regardless of its previous value.
* If only `default` is specified and the property previously existed, it is unchanged.
* If only `default` is specified and the property did not exist, the property is set to `default`.
* If `value` and `default` are both specified and the property previously existed, the property is set to `value`.
* If `value` and `default` are both specified and the property did not exist, the property is set to `default`.
Operations occur after the rules are evaluated.
## Differences with the [ant PropertyFile task](https://ant.apache.org/manual/Tasks/propertyfile.html)
* The comments and layout of the original property file will not be preserved.
* The `jdkproperties` parameter is not implemented.
* The default `Entry.Types.DATE` pattern is `yyyy-MM-dd HH:mm` and not `yyyy/MM/dd HH:mm`.

2
bld Executable file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env sh
java -jar "$(dirname "$0")/lib/bld/bld-wrapper.jar" "$0" --build rife.bld.extension.propertyFile.PropertyFileBuild "$@"

4
bld.bat Normal file
View file

@ -0,0 +1,4 @@
@echo off
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
java -jar "%DIRNAME%/lib/bld/bld-wrapper.jar" "%0" --build rife.bld.extension.propertyFile.PropertyFileBuild %*

55
examples/.gitignore vendored Normal file
View file

@ -0,0 +1,55 @@
.gradle
.DS_Store
build
lib/bld/**
lib/compile/**
lib/runtime/**
lib/standalone/**
lib/test/**
!bld-wrapper.jar
!bld-wrapper.properties
# IDEA ignores
# User-specific
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Editor-based Rest Client
.idea/httpRequests

3
examples/.idea/.gitignore generated vendored Normal file
View file

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
examples/.idea/.name generated Normal file
View file

@ -0,0 +1 @@
bld-property-file-examples

28
examples/.idea/app.iml generated Normal file
View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/build/main" />
<output-test url="file://$MODULE_DIR$/build/test" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/src/main/resources/templates" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library" scope="RUNTIME">
<library>
<CLASSES>
<root url="file://$MODULE_DIR$/src/main/resources/templates" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="library" name="compile" level="project" />
<orderEntry type="library" scope="RUNTIME" name="runtime" level="project" />
<orderEntry type="library" scope="TEST" name="test" level="project" />
</component>
</module>

14
examples/.idea/bld.iml generated Normal file
View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/build/bld" />
<output-test url="file://$MODULE_DIR$/build/bld" />
<exclude-output />
<content url="file://$MODULE_DIR$/src/bld">
<sourceFolder url="file://$MODULE_DIR$/src/bld/java" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="bld" level="project" />
</component>
</module>

View file

@ -0,0 +1,8 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JavadocDeclaration" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ADDITIONAL_TAGS" value="created" />
</inspection_tool>
</profile>
</component>

17
examples/.idea/libraries/bld.xml generated Normal file
View file

@ -0,0 +1,17 @@
<component name="libraryTable">
<library name="bld">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/bld" />
<root url="jar://$USER_HOME$/.rife2/dist/rife2-1.5.11.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.rife2/dist/rife2-1.5.11-sources.jar!/" />
</SOURCES>
<excluded>
<root url="jar://$PROJECT_DIR$/lib/bld/bld-wrapper.jar!/" />
</excluded>
<jarDirectory url="file://$PROJECT_DIR$/lib/bld" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/bld" recursive="false" type="SOURCES" />
</library>
</component>

13
examples/.idea/libraries/compile.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="compile">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/compile" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/compile" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib/compile" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/compile" recursive="false" type="SOURCES" />
</library>
</component>

13
examples/.idea/libraries/runtime.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="runtime">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/runtime" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/runtime" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib/runtime" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/runtime" recursive="false" type="SOURCES" />
</library>
</component>

13
examples/.idea/libraries/test.xml generated Normal file
View file

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="test">
<CLASSES>
<root url="file://$PROJECT_DIR$/lib/test" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/lib/test" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/lib/test" recursive="false" />
<jarDirectory url="file://$PROJECT_DIR$/lib/test" recursive="false" type="SOURCES" />
</library>
</component>

9
examples/.idea/misc.xml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PDMPlugin">
<option name="skipTestSources" value="false" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build" />
</component>
</project>

9
examples/.idea/modules.xml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/app.iml" filepath="$PROJECT_DIR$/.idea/app.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/bld.iml" filepath="$PROJECT_DIR$/.idea/bld.iml" />
</modules>
</component>
</project>

View file

@ -0,0 +1,9 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Main" type="Application" factoryName="Application" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="com.example.PropertyFileExampleMain" />
<module name="app" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

View file

@ -0,0 +1,13 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="JUnit" factoryName="JUnit">
<module name="app" />
<option name="PACKAGE_NAME" value="moog" />
<option name="MAIN_CLASS_NAME" value="com.example" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="directory" />
<dir value="$PROJECT_DIR$/src/test/java" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

24
examples/.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,24 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "Run Main",
"request": "launch",
"mainClass": "com.example.PropertyFileExampleMain"
},
{
"type": "java",
"name": "Run Tests",
"request": "launch",
"mainClass": "org.junit.platform.console.ConsoleLauncher",
"args": [
"--details=verbose",
"--scan-classpath",
"--disable-banner",
"--disable-ansi-colors",
"--exclude-engine=junit-platform-suite",
"--exclude-engine=junit-vintage"]
}
]
}

15
examples/.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,15 @@
{
"java.project.sourcePaths": [
"src/main/java",
"src/main/resources",
"src/test/java",
"src/bld/java"
],
"java.configuration.updateBuildConfiguration": "automatic",
"java.project.referencedLibraries": [
"${HOME}/.rife2/dist/rife2-1.5.11.jar",
"lib/compile/*.jar",
"lib/runtime/*.jar",
"lib/test/*.jar"
]
}

2
examples/bld Executable file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env sh
java -jar "$(dirname "$0")/lib/bld/bld-wrapper.jar" "$0" --build com.example.PropertyFileExampleBuild "$@"

4
examples/bld.bat Normal file
View file

@ -0,0 +1,4 @@
@echo off
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
java -jar "%DIRNAME%/lib/bld/bld-wrapper.jar" "%0" --build com.example.PropertyFileExampleBuild %*

Binary file not shown.

View file

@ -0,0 +1,7 @@
#Sun Apr 02 10:32:44 PDT 2023
bld.extension=com.uwyn.rife2:bld-property-file:0.9.0
bld.repositories=https\://repo1.maven.org/maven2/,/home/erik/.m2/repository
rife2.downloadLocation=
rife2.version=1.5.11

View file

@ -0,0 +1,62 @@
package com.example;
import rife.bld.BuildCommand;
import rife.bld.Project;
import rife.bld.extension.propertyFile.Entry;
import rife.bld.extension.propertyFile.Entry.Operations;
import rife.bld.extension.propertyFile.Entry.Types;
import rife.bld.extension.propertyFile.PropertyFileOperation;
import java.util.List;
import static rife.bld.dependencies.Repository.MAVEN_CENTRAL;
import static rife.bld.dependencies.Repository.SONATYPE_SNAPSHOTS;
import static rife.bld.dependencies.Scope.test;
public class PropertyFileExampleBuild extends Project {
public PropertyFileExampleBuild() {
pkg = "com.example";
name = "PropertyFileExample";
mainClass = "com.example.PropertyFileExampleMain";
version = version(0, 1, 0);
downloadSources = true;
repositories = List.of(MAVEN_CENTRAL, SONATYPE_SNAPSHOTS);
scope(test)
.include(dependency("org.junit.jupiter", "junit-jupiter", version(5, 9, 2)))
.include(dependency("org.junit.platform", "junit-platform-console-standalone", version(1, 9, 2)));
}
public static void main(String[] args) {
new PropertyFileExampleBuild().start(args);
}
@BuildCommand
public void updateMajor() throws Exception {
new PropertyFileOperation(this)
.file("version.properties")
.entry(new Entry("version.major").defaultValue(1).type(Types.INT).operation(Operations.ADD))
.entry(new Entry("version.minor").value(0))
.entry(new Entry("version.patch").value(0))
.execute();
}
@BuildCommand
public void updateMinor() throws Exception {
new PropertyFileOperation(this)
.file("version.properties")
.entry(new Entry("version.minor").defaultValue(0).type(Types.INT).operation(Operations.ADD))
.entry(new Entry("version.patch").value(0))
.execute();
}
@BuildCommand
public void updatePatch() throws Exception {
new PropertyFileOperation(this)
.file("version.properties")
.entry(new Entry("version.patch").defaultValue(0).type(Types.INT).operation(Operations.ADD))
.execute();
}
}

View file

@ -0,0 +1,24 @@
package com.example;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class PropertyFileExampleMain {
public static void main(String[] args) throws IOException {
final Path path = Paths.get("version.properties");
if (Files.exists(path)) {
final List<String> content = Files.readAllLines(path);
System.out.println("> cat " + path.getFileName());
for (final String line : content) {
System.out.println(line);
}
}
}
public String getMessage() {
return "Hello World!";
}
}

View file

@ -0,0 +1,12 @@
package com.example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PropertyFileExampleTest {
@Test
void verifyHello() {
assertEquals("Hello World!", new PropertyFileExampleMain().getMessage());
}
}

View file

@ -0,0 +1,5 @@
#
#Sun Apr 02 15:20:15 PDT 2023
version.major=3
version.minor=0
version.patch=0

BIN
lib/bld/bld-wrapper.jar Normal file

Binary file not shown.

View file

@ -0,0 +1,2 @@
#Sat Apr 01 10:09:33 PDT 2023
rife2.version=1.5.11

View file

@ -0,0 +1,50 @@
package rife.bld.extension.propertyFile;
import rife.bld.Project;
import rife.bld.publish.PublishDeveloper;
import rife.bld.publish.PublishInfo;
import rife.bld.publish.PublishLicense;
import rife.bld.publish.PublishScm;
import java.util.List;
import static rife.bld.dependencies.Repository.*;
import static rife.bld.dependencies.Scope.compile;
import static rife.bld.dependencies.Scope.test;
public class PropertyFileBuild extends Project {
public PropertyFileBuild() {
pkg = "rife.bld.extension";
name = "bld-property-file";
version = version(0, 9, 0);
javadocOptions.add("-Xdoclint:-missing");
publishRepository = MAVEN_LOCAL;
publishInfo = new PublishInfo().groupId("com.uwyn.rife2").artifactId("bld-property-file")
.description("Bld Extension to Edit or Create Properties Files")
.url("https://github.com/rife2/bld-property-file")
.developer(new PublishDeveloper().id("ethauvin").name("Erik C. Thauvin").email("erik@thauvin.net")
.url("https://erik.thauvin.net/"))
.license(new PublishLicense().name("The Apache License, Version 2.0")
.url("http://www.apache.org/licenses/LICENSE-2.0.txt"))
.scm(new PublishScm().connection("scm:git:https://github.com/rife2/bld-property-file.git")
.developerConnection("scm:git:git@github.com:rife2/bld-property-file.git")
.url("https://github.com/rife2/bld-property-file"));
javaRelease = 17;
downloadSources = true;
repositories = List.of(MAVEN_CENTRAL, SONATYPE_SNAPSHOTS);
scope(compile)
.include(dependency("com.uwyn.rife2", "rife2", version(1, 5, 11)));
scope(test)
.include(dependency("org.jsoup", "jsoup", version(1, 15, 4)))
.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.assertj:assertj-joda-time:2.2.0"));
}
public static void main(String[] args) {
new PropertyFileBuild().start(args);
}
}

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);
}
}
}

View file

@ -0,0 +1,219 @@
/*
* 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 org.junit.jupiter.api.Test;
import rife.tools.Localization;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
/**
* PropertyFileUtilsTest class
*
* @author <a href="https://erik.thauvin.net/">Erik C. Thauvin</a>
* @since 1.0
*/
class PropertyFileUtilsTest {
final Properties p = new Properties();
@Test
void currentValueTest() {
String prev;
String value;
String defaultValue = null;
var operation = Entry.Operations.SET;
// If only value is specified, the property is set to it regardless of its previous value.
prev = "previous";
value = "value";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(value);
// If only defaultValue is specified and the property previously existed, it is unchanged.
prev = "previous";
value = null;
defaultValue = "defaultValue";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(prev);
// If only defaultValue is specified and the property did not exist, the property is set to defaultValue.
prev = null;
defaultValue = "defaultValue";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(defaultValue);
// If value and defaultValue are both specified and the property previously existed, the property is set to value.
prev = "previous";
value = "value";
defaultValue = "defaultValue";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(value);
// If value and defaultValue are both specified and the property did not exist, the property is set to defaultValue.
prev = null;
value = "value";
defaultValue = "defaultValue";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(defaultValue);
// ADD
operation = Entry.Operations.ADD;
value = "value";
defaultValue = "defaultValue";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(defaultValue);
prev = "prev";
value = "value";
defaultValue = null;
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(prev);
prev = null;
value = "value";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo("");
value = "value";
defaultValue = "defaultValue";
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo(defaultValue);
value = null;
defaultValue = null;
assertThat(PropertyFileUtils.currentValue(prev, value, defaultValue, operation)).as("currentValue(prev,value,defaultValue,operation)").isEqualTo("");
}
@Test
void processStringTest() {
var entry = new Entry("version.major").value("1");
PropertyFileUtils.processString(p, entry);
assertThat(entry.getValue()).as("processString(entry.getKey(), entry.getValue())").isEqualTo(p.getProperty(entry.getKey()));
entry.setKey("version.minor");
entry.setValue("0");
PropertyFileUtils.processString(p, entry);
assertThat(entry.getValue()).as("processString(entry.getKey(), entry.getValue())").isEqualTo(p.getProperty(entry.getKey()));
}
@Test
void processIntTest() {
var entry = new Entry("version.patch").value("a").type(Entry.Types.INT);
assertThat(PropertyFileUtils.processInt(p, entry, false)).as("parseInt(entry.getKey(), a)");
// ADD
entry.setOperation(Entry.Operations.ADD);
entry.setValue("1");
entry.setDefaultValue("-1");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 0)").isEqualTo("0");
entry.setKey("anint");
entry.setValue(null);
entry.setDefaultValue("0");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 1)").isEqualTo("1");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 2)").isEqualTo("2");
entry.setKey("formated.int");
entry.setValue(null);
entry.setDefaultValue("0013");
entry.setPattern("0000");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 0014)").isEqualTo("0014");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 0015)").isEqualTo("0015");
entry.setKey("formated.int");
entry.setValue("2");
entry.setDefaultValue("0013");
entry.setPattern("0000");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 0017)").isEqualTo("0017");
// SUBTRACT
entry.setOperation(Entry.Operations.SUBTRACT);
entry.setValue(null);
entry.setDefaultValue("0013");
entry.setPattern("0000");
PropertyFileUtils.processInt(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processInt(entry.getKey(), 0016)").isEqualTo("0016");
}
@Test
void processDateTest() {
var entry = new Entry("adate").type(Entry.Types.DATE).pattern("D").value("1");
var day = new SimpleDateFormat(entry.getPattern(), Localization.getLocale()).format(new Date());
var dayInt = Integer.parseInt(day);
entry.setValue("a");
assertThat(PropertyFileUtils.processDate(p, entry, false)).as("processDate(entry.getKey(), a)").isFalse();
entry.setValue("99");
PropertyFileUtils.processDate(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processDate(entry.getKey(), 99)").isEqualTo("99");
entry.setValue("now");
PropertyFileUtils.processDate(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processDate(entry.getKey(), now)").isEqualTo(day);
// ADD
entry.setOperation(Entry.Operations.ADD);
entry.setValue("1");
PropertyFileUtils.processDate(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processDate(entry.getKey(), now+1)").isEqualTo(String.valueOf(dayInt + 1));
entry.setValue("2");
PropertyFileUtils.processDate(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processDate(entry.getKey(), now+3)").isEqualTo(String.valueOf(dayInt + 3));
// SUBTRACT
entry.setOperation(Entry.Operations.SUBTRACT);
entry.setValue("3");
PropertyFileUtils.processDate(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processDate(entry.getKey(), now-3)").isEqualTo(String.valueOf(dayInt));
entry.setOperation(Entry.Operations.SUBTRACT);
entry.setValue("2");
PropertyFileUtils.processDate(p, entry, true);
assertThat(p.getProperty(entry.getKey())).as("processDate(entry.getKey(), now-2)").isEqualTo(String.valueOf(dayInt - 2));
}
@Test
void savePropertiesTest() throws IOException {
var p = new Properties();
var test = "test";
p.put(test, test);
var tmp = File.createTempFile(test, ".properties");
assertThatCode(() -> PropertyFileUtils.saveProperties(tmp, "Generated file - do not modify!", p))
.as("save properties").doesNotThrowAnyException();
assertThat(PropertyFileUtils.loadProperties(tmp, p)).as("load properties").isTrue();
assertThat(p.getProperty(test)).as("read property").isEqualTo(test);
tmp.deleteOnExit();
}
}