diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549076d --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Eclipse +.classpath +.project +.settings/ + +# Intellij +.idea/ +*.iml +*.iws + +# Mac +.DS_Store + +# Maven +log/ +target/ +.gradle/ +build/ +out/ + +# Integration tests +build.log + +/bin/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a8d1088 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# Rundeck Conditional Logic Plugin + +This plugin provides node steps that create variables from if/else tests and switch/case structures. + +## Features + +### If/Else Test + +Uplifts a variable based on one of many available tests: + + - Text Comparisons: eq, ne, lt, le, ge, gt, begins with, ends with + - Numeric Comparisons, =, !=, <, <=, >=, > + +### Switch/Case Test + +Uplifts a variable based on a switch/case structure diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..9bb0a4f --- /dev/null +++ b/build.gradle @@ -0,0 +1,94 @@ +plugins { + id 'pl.allegro.tech.build.axion-release' version '1.10.1' + id 'java' +} + +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'idea' + +sourceCompatibility = 1.8 +defaultTasks 'clean','build' +ext.rundeckPluginVersion = '1.2' +ext.pluginClassNames='com.bioraft.rundeck.conditional.IfElseNodeStepPlugin,com.bioraft.rundeck.conditional.IfElseStepPlugin,com.bioraft.rundeck.conditional.SwitchCaseNodeStepPlugin,com.bioraft.rundeck.conditional.SwitchCaseStepPlugin' +ext.pluginName = 'RunDeck Conditional Logic Plugin' +ext.pluginDescription = 'Execute conditional logic in RunDeck workflows' + +scmVersion { + ignoreUncommittedChanges = true + tag { + prefix = '' + versionSeparator = '' + def origDeserialize=deserialize + //apend .0 to satisfy semver if the tag version is only X.Y + deserialize = { config, position, tagName -> + def orig = origDeserialize(config, position, tagName) + if (orig.split('\\.').length < 3) { + orig += ".0" + } + orig + } + } +} +project.version = scmVersion.version + + +repositories { + mavenLocal() + mavenCentral() +} + +configurations{ + //declare custom pluginLibs configuration to include only libs for this plugin + pluginLibs + + //declare compile to extend from pluginLibs so it inherits the dependencies + compile{ + extendsFrom pluginLibs + } +} + +dependencies { + implementation 'org.rundeck:rundeck-core:3.0.+' + + testImplementation group: 'junit', name: 'junit', version:'4.12' + + testImplementation ( + 'org.mockito:mockito-all:1.9.5', + 'org.powermock:powermock-module-junit4:1.5', + 'org.powermock:powermock-api-mockito:1.5' + ) +} + + +// task to copy plugin libs to output/lib dir +task copyToLib(type: Copy) { + into "$buildDir/output/lib" + from configurations.pluginLibs +} + +jar { + from "$buildDir/output" + manifest { + def libList = configurations.pluginLibs.collect{'lib/'+it.name}.join(' ') + + attributes 'Rundeck-Plugin-Classnames': pluginClassNames + attributes 'Rundeck-Plugin-File-Version': archiveVersion + attributes 'Rundeck-Plugin-Name': pluginName + attributes 'Rundeck-Plugin-Description': pluginDescription + attributes 'Rundeck-Plugin-Rundeck-Compatibility-Version': '3.x' + attributes 'Rundeck-Plugin-Tags': 'java,WorkflowNodeStep' + attributes 'Rundeck-Plugin-License': 'Apache 2.0' + attributes 'Rundeck-Plugin-Source-Link': 'https://github.com/' + attributes 'Rundeck-Plugin-Target-Host-Compatibility': 'all' + attributes 'Rundeck-Plugin-Version': rundeckPluginVersion + attributes 'Rundeck-Plugin-Archive': 'true' + attributes 'Rundeck-Plugin-Libs': "${libList}" + + } + dependsOn(copyToLib) +} + +wrapper { + gradleVersion = '6.0.1' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..cc4fdc2 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9492014 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..2fe81a7 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9618d8d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..8cc76aa --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'rundeck-conditional-logic-plugin' diff --git a/src/main/java/com/bioraft/rundeck/conditional/IfElse.java b/src/main/java/com/bioraft/rundeck/conditional/IfElse.java new file mode 100644 index 0000000..4786044 --- /dev/null +++ b/src/main/java/com/bioraft/rundeck/conditional/IfElse.java @@ -0,0 +1,127 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import com.dtolabs.rundeck.core.Constants; +import com.dtolabs.rundeck.core.dispatcher.ContextView; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; + +/** + * Workflow Node Step Plug-in to choose one of several values to uplift into a + * step variable. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +public class IfElse { + + public static final String STRING_NE = "ne"; + public static final String STRING_LT = "lt"; + public static final String STRING_LE = "le"; + public static final String STRING_EQ = "eq"; + public static final String STRING_GE = "ge"; + public static final String STRING_GT = "gt"; + public static final String STRING_BEG = "begins with"; + public static final String STRING_END = "ends with"; + public static final String NUMBER_NE = "!="; + public static final String NUMBER_LT = "<"; + public static final String NUMBER_LE = "<="; + public static final String NUMBER_EQ = "="; + public static final String NUMBER_GE = ">="; + public static final String NUMBER_GT = ">"; + + private PluginStepContext ctx; + + /** + * Constructor sets PluginStepContext. + * + * @param ctx + */ + public IfElse(PluginStepContext ctx) { + this.ctx = ctx; + } + + /** + * Add ifTrue value to SharedOutputContext if condition passes, otherwise add + * ifFalse if not null. + * + * @param group The group to place the variable in. + * @param name The name of the variable. + * @param testValue The value to test. + * @param operator The comparison operator. + * @param comparisonValue The value to test against. + * @param ifTrue The value to return if comparison is true. + * @param ifFalse The value to return if comparison is false. + * @param elevateToGlobal If specified, also create a variable in global export + * context. + */ + public void ifElse(String group, String name, String testValue, String operator, String comparisonValue, + String ifTrue, String ifFalse, boolean elevateToGlobal) { + + String value; + String matched = null; + + if (operator.equals(STRING_EQ) && testValue.endsWith(comparisonValue)) { + matched = STRING_EQ; + } else if (operator.equals(STRING_NE) && !testValue.equals(comparisonValue)) { + matched = STRING_NE; + } else if (operator.equals(STRING_BEG) && testValue.startsWith(comparisonValue)) { + matched = STRING_BEG; + } else if (operator.equals(STRING_END) && testValue.endsWith(comparisonValue)) { + matched = STRING_END; + } else if (operator.equals(STRING_LT) && testValue.compareTo(comparisonValue) < 0) { + matched = STRING_LT; + } else if (operator.equals(STRING_LE) && testValue.compareTo(comparisonValue) <= 0) { + matched = STRING_LE; + } else if (operator.equals(STRING_GE) && testValue.compareTo(comparisonValue) >= 0) { + matched = STRING_GE; + } else if (operator.equals(STRING_GT) && testValue.compareTo(comparisonValue) > 0) { + matched = STRING_GT; + } else if (operator.equals(NUMBER_LT) && Double.parseDouble(testValue) < Double.parseDouble(comparisonValue)) { + matched = NUMBER_LT; + } else if (operator.equals(NUMBER_LE) && Double.parseDouble(testValue) <= Double.parseDouble(comparisonValue)) { + matched = NUMBER_LE; + } else if (operator.equals(NUMBER_GE) && Double.parseDouble(testValue) >= Double.parseDouble(comparisonValue)) { + matched = NUMBER_GE; + } else if (operator.equals(NUMBER_GT) && Double.parseDouble(testValue) > Double.parseDouble(comparisonValue)) { + matched = NUMBER_GT; + } else if (operator.equals(NUMBER_EQ) && Double.parseDouble(testValue) == Double.parseDouble(comparisonValue)) { + matched = NUMBER_EQ; + } else if (operator.equals(NUMBER_NE) && Double.parseDouble(testValue) != Double.parseDouble(comparisonValue)) { + matched = NUMBER_NE; + } + + if (matched != null) { + value = ifTrue; + ctx.getLogger().log(Constants.DEBUG_LEVEL, "Matched " + matched + ", returning ifTrue value."); + } else { + if (ifFalse == null || ifFalse.length() == 0) { + ctx.getLogger().log(Constants.DEBUG_LEVEL, "No match, default is empty."); + return; + } + ctx.getLogger().log(Constants.DEBUG_LEVEL, "No match, using default."); + value = ifFalse; + } + + ctx.getOutputContext().addOutput(group, name, value); + if (elevateToGlobal) { + String groupName = group + "." + name; + ctx.getOutputContext().addOutput(ContextView.global(), "export", groupName, value); + ctx.getLogger().log(Constants.DEBUG_LEVEL, "Elevating to globsal ${export." + groupName + "}."); + } + } + +} diff --git a/src/main/java/com/bioraft/rundeck/conditional/IfElseNodeStepPlugin.java b/src/main/java/com/bioraft/rundeck/conditional/IfElseNodeStepPlugin.java new file mode 100644 index 0000000..7e16195 --- /dev/null +++ b/src/main/java/com/bioraft/rundeck/conditional/IfElseNodeStepPlugin.java @@ -0,0 +1,92 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import java.util.Map; + +import com.dtolabs.rundeck.core.Constants; +import com.dtolabs.rundeck.core.common.INodeEntry; +import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException; +import com.dtolabs.rundeck.core.plugins.Plugin; +import com.dtolabs.rundeck.plugins.ServiceNameConstants; +import com.dtolabs.rundeck.plugins.descriptions.PluginDescription; +import com.dtolabs.rundeck.plugins.descriptions.PluginProperty; +import com.dtolabs.rundeck.plugins.descriptions.SelectValues; +import com.dtolabs.rundeck.plugins.step.NodeStepPlugin; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; + +/** + * Workflow Node Step Plug-in to choose one of two values to uplift into a step + * variable. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@Plugin(name = IfElseNodeStepPlugin.SERVICE_PROVIDER_NAME, service = ServiceNameConstants.WorkflowNodeStep) +@PluginDescription(title = "If-Else Conditional Node Step", description = "Chooses between two options for a variable value based on if-else test.") +public class IfElseNodeStepPlugin implements NodeStepPlugin { + + public static final String SERVICE_PROVIDER_NAME = "com.bioraft.rundeck.conditional.IfTestWorkflowNodeStepPlugin"; + + @PluginProperty(title = "Group", description = "Variable group (i.e., ${group.x}", required = true) + private String group; + + @PluginProperty(title = "Name", description = "Variable name (i.e., ${group.name}", required = true) + private String name; + + @PluginProperty(title = "Test Value", description = "First test value", required = true) + private String testValue; + + @PluginProperty(title = "Operator", description = "Comparison operator", required = true) + @SelectValues(values = { IfElse.STRING_EQ, IfElse.STRING_NE, IfElse.STRING_LT, IfElse.STRING_LE, IfElse.STRING_GE, + IfElse.STRING_GT, IfElse.STRING_BEG, IfElse.STRING_END, IfElse.NUMBER_EQ, IfElse.NUMBER_NE, + IfElse.NUMBER_LT, IfElse.NUMBER_LE, IfElse.NUMBER_GE, IfElse.NUMBER_GT }, freeSelect = false) + private String operator; + + @PluginProperty(title = "Comparison Value", description = "Second test value", required = true) + private String comparisonValue; + + @PluginProperty(title = "If True", description = "Value to assign if comparison is true", required = true) + private String ifTrue; + + @PluginProperty(title = "If False", description = "Value to assign if comparison is false", required = false) + private String ifFalse; + + @PluginProperty(title = "Make global?", description = "Elevate this variable to global scope (default: false)", required = false) + private boolean elevateToGlobal; + + @Override + public void executeNodeStep(PluginStepContext ctx, Map cfg, INodeEntry node) + throws NodeStepException { + + String group = cfg.getOrDefault("group", this.group).toString(); + String name = cfg.getOrDefault("name", this.name).toString(); + String testValue = cfg.getOrDefault("testValue", this.testValue).toString(); + String operator = cfg.getOrDefault("operator", this.operator).toString(); + String comparisonValue = cfg.getOrDefault("comparisonValue", this.comparisonValue).toString(); + String ifTrue = cfg.getOrDefault("ifTrue", this.ifTrue).toString(); + boolean elevateToGlobal = (boolean) cfg.getOrDefault("elevateToGlobal", this.elevateToGlobal); + if (cfg.containsKey("ifFalse") && cfg.get("ifFalse") != null) { + ifFalse = cfg.getOrDefault("ifFalse", this.ifFalse).toString(); + } + + ctx.getLogger().log(Constants.DEBUG_LEVEL, + "Setting " + group + "." + name + " based on " + testValue + " " + operator + " " + comparisonValue); + + (new IfElse(ctx)).ifElse(group, name, testValue, operator, comparisonValue, ifTrue, ifFalse, elevateToGlobal); + } + +} diff --git a/src/main/java/com/bioraft/rundeck/conditional/IfElseStepPlugin.java b/src/main/java/com/bioraft/rundeck/conditional/IfElseStepPlugin.java new file mode 100644 index 0000000..b3276f2 --- /dev/null +++ b/src/main/java/com/bioraft/rundeck/conditional/IfElseStepPlugin.java @@ -0,0 +1,92 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import java.util.Map; + +import com.dtolabs.rundeck.core.Constants; +import com.dtolabs.rundeck.core.execution.workflow.steps.StepException; +import com.dtolabs.rundeck.core.plugins.Plugin; +import com.dtolabs.rundeck.plugins.ServiceNameConstants; +import com.dtolabs.rundeck.plugins.descriptions.PluginDescription; +import com.dtolabs.rundeck.plugins.descriptions.PluginProperty; +import com.dtolabs.rundeck.plugins.descriptions.SelectValues; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; +import com.dtolabs.rundeck.plugins.step.StepPlugin; + +/** + * Workflow Node Step Plug-in to choose one of two values to uplift into a step + * variable. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@Plugin(name = IfElseStepPlugin.SERVICE_PROVIDER_NAME, service = ServiceNameConstants.WorkflowStep) +@PluginDescription(title = "If-Else Conditional", description = "Chooses between two options for a variable value based on if-else test.") +public class IfElseStepPlugin implements StepPlugin { + + public static final String SERVICE_PROVIDER_NAME = "com.bioraft.rundeck.conditional.IfTestWorkflowStepPlugin"; + + @PluginProperty(title = "Group", description = "Variable group (i.e., ${group.x}", required = true) + private String group; + + @PluginProperty(title = "Name", description = "Variable name (i.e., ${group.name}", required = true) + private String name; + + @PluginProperty(title = "Test Value", description = "First test value", required = true) + private String testValue; + + @PluginProperty(title = "Operator", description = "Comparison operator", required = true) + @SelectValues(values = { IfElse.STRING_EQ, IfElse.STRING_NE, IfElse.STRING_LT, + IfElse.STRING_LE, IfElse.STRING_GE, IfElse.STRING_GT, + IfElse.STRING_BEG, IfElse.STRING_END, IfElse.NUMBER_EQ, + IfElse.NUMBER_NE, IfElse.NUMBER_LT, IfElse.NUMBER_LE, + IfElse.NUMBER_GE, IfElse.NUMBER_GT }, freeSelect = false) + private String operator; + + @PluginProperty(title = "Comparison Value", description = "Second test value", required = true) + private String comparisonValue; + + @PluginProperty(title = "If True", description = "Value to assign if comparison is true", required = true) + private String ifTrue; + + @PluginProperty(title = "If False", description = "Value to assign if comparison is false", required = false) + private String ifFalse; + + @PluginProperty(title = "Make global?", description = "Elevate this variable to global scope (default: false)", required = false) + private boolean elevateToGlobal; + + @Override + public void executeStep(final PluginStepContext ctx, final Map cfg) throws StepException { + + String group = cfg.getOrDefault("group", this.group).toString(); + String name = cfg.getOrDefault("name", this.name).toString(); + String testValue = cfg.getOrDefault("testValue", this.testValue).toString(); + String operator = cfg.getOrDefault("operator", this.operator).toString(); + String comparisonValue = cfg.getOrDefault("comparisonValue", this.comparisonValue).toString(); + String ifTrue = cfg.getOrDefault("ifTrue", this.ifTrue).toString(); + boolean elevateToGlobal = (boolean) cfg.getOrDefault("elevateToGlobal", this.elevateToGlobal); + if (cfg.containsKey("ifFalse") && cfg.get("ifFalse") != null) { + ifFalse = cfg.getOrDefault("ifFalse", this.ifFalse).toString(); + } + + ctx.getLogger().log(Constants.DEBUG_LEVEL, + "Setting " + group + "." + name + " based on " + testValue + " " + operator + " " + comparisonValue); + + (new IfElse(ctx)).ifElse(group, name, testValue, operator, comparisonValue, ifTrue, ifFalse, elevateToGlobal); + } + +} diff --git a/src/main/java/com/bioraft/rundeck/conditional/Switch.java b/src/main/java/com/bioraft/rundeck/conditional/Switch.java new file mode 100644 index 0000000..75b2044 --- /dev/null +++ b/src/main/java/com/bioraft/rundeck/conditional/Switch.java @@ -0,0 +1,106 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import com.dtolabs.rundeck.core.Constants; +import com.dtolabs.rundeck.core.dispatcher.ContextView; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; + +/** + * Workflow Node Step Plug-in to choose one of several values to uplift into a + * step variable. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +public class Switch { + + private PluginStepContext ctx; + + /** + * Constructor sets PluginStepContext. + * + * @param ctx + */ + public Switch(PluginStepContext ctx) { + this.ctx = ctx; + } + + /** + * Assign a value to SharedOutputContext if a test case is matched, otherwise + * assign default if non-null.. + * + * @param group The group to place the variable in. + * @param name The name of the variable. + * @param cases The switch cases as test1:value1;test2:value2 + * @param test The string to test the cases against. + * @param defaultValue The value to return if no cases match + * @param elevate If specified, also create a variable in global export + * context. + */ + public void switchCase(String group, String name, String cases, String test, String defaultValue, boolean elevate) { + // If no case was matched, assign defaultValue if it is not null. + if (!switchCase(group, name, cases, test, elevate)) { + if (defaultValue != null && defaultValue.length() > 0) { + addOutput(elevate, group, name, defaultValue); + ctx.getLogger().log(Constants.DEBUG_LEVEL, "No match, using default."); + } else { + ctx.getLogger().log(Constants.DEBUG_LEVEL, "No match, default is empty."); + } + } + } + + /** + * Performs the actual comparison, returning true if a match is found. + * + * @param group The group to place the variable in. + * @param name The name of the variable. + * @param cases The switch cases as test1:value1;test2:value2 + * @param test The string to test the cases against. + * @param elevate If specified, also create a variable in global export context. + * + * @return True if matched, false otherwise. + */ + public boolean switchCase(String group, String name, String cases, String test, boolean elevate) { + for (String keyValue : cases.split(";")) { + String[] values = keyValue.split(":"); + if (test.equals(values[0])) { + addOutput(elevate, group, name, values[1]); + ctx.getLogger().log(Constants.DEBUG_LEVEL, "Matched " + values[0] + "."); + return true; + } + } + return false; + } + + /** + * Adds output to shared context, also elevating to global if requested. + * + * @param elevate + * @param group + * @param name + * @param value + */ + private void addOutput(boolean elevate, String group, String name, String value) { + ctx.getOutputContext().addOutput(group, name, value); + if (elevate) { + String groupName = group + "." + name; + ctx.getOutputContext().addOutput(ContextView.global(), "export", groupName, value); + ctx.getLogger().log(Constants.DEBUG_LEVEL, "Elevating to globsal ${export." + groupName + "}."); + } + } + +} diff --git a/src/main/java/com/bioraft/rundeck/conditional/SwitchCaseNodeStepPlugin.java b/src/main/java/com/bioraft/rundeck/conditional/SwitchCaseNodeStepPlugin.java new file mode 100644 index 0000000..1526fb5 --- /dev/null +++ b/src/main/java/com/bioraft/rundeck/conditional/SwitchCaseNodeStepPlugin.java @@ -0,0 +1,87 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import java.util.Map; + +import com.dtolabs.rundeck.core.Constants; +import com.dtolabs.rundeck.core.common.INodeEntry; +import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException; +import com.dtolabs.rundeck.core.plugins.Plugin; +import com.dtolabs.rundeck.plugins.ServiceNameConstants; +import com.dtolabs.rundeck.plugins.descriptions.PluginDescription; +import com.dtolabs.rundeck.plugins.descriptions.PluginProperty; +import com.dtolabs.rundeck.plugins.step.NodeStepPlugin; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; + +/** + * Workflow Node Step Plug-in to choose one of several values to uplift into a + * step variable. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@Plugin(name = SwitchCaseNodeStepPlugin.SERVICE_PROVIDER_NAME, service = ServiceNameConstants.WorkflowNodeStep) +@PluginDescription(title = "Switch/Case Conditional Node Step", description = "Chooses between options for a variable value based on switch/case structure.") +public class SwitchCaseNodeStepPlugin implements NodeStepPlugin { + + public static final String SERVICE_PROVIDER_NAME = "com.bioraft.rundeck.conditional.SwitchCaseNodeStepPlugin"; + + @PluginProperty(title = "Group", description = "Variable group (i.e., ${group.x}", required = true) + private String group; + + @PluginProperty(title = "Name", description = "Variable name (i.e., ${group.name}", required = true) + private String name; + + @PluginProperty(title = "Cases", description = "Cases and results as colon-spliced pairs, seprated by semicolons", required = true) + private String cases; + + @PluginProperty(title = "Test Value", description = "Test value", required = true) + private String testValue; + + @PluginProperty(title = "Default", description = "Default value", required = false) + private String defaultValue; + + @PluginProperty(title = "Make global?", description = "Elevate this variable to global scope (default: false)", required = false) + private boolean elevateToGlobal; + + @Override + public void executeNodeStep(PluginStepContext ctx, Map cfg, INodeEntry node) + throws NodeStepException { + + String group = cfg.getOrDefault("group", this.group).toString(); + String name = cfg.getOrDefault("name", this.name).toString(); + String cases = cfg.getOrDefault("cases", this.cases).toString(); + String testValue = cfg.getOrDefault("testValue", this.testValue).toString(); + boolean elevateToGlobal = cfg.getOrDefault("elevateToGlobal", this.elevateToGlobal).equals("true"); + + boolean globalHasDefault = defaultValue != null && defaultValue.length() > 0; + boolean cfgHasDefault = cfg.containsKey("defaultValue") && cfg.get("defaultValue") != null; + if (cfgHasDefault) { + this.defaultValue = cfg.get("defaultValue").toString(); + } + + ctx.getLogger().log(Constants.DEBUG_LEVEL, + "Setting " + group + "." + name + " based on " + testValue + " " + cases); + + if (cfgHasDefault || globalHasDefault) { + (new Switch(ctx)).switchCase(group, name, cases, testValue, defaultValue, elevateToGlobal); + } else { + (new Switch(ctx)).switchCase(group, name, cases, testValue, elevateToGlobal); + } + } + +} diff --git a/src/main/java/com/bioraft/rundeck/conditional/SwitchCaseStepPlugin.java b/src/main/java/com/bioraft/rundeck/conditional/SwitchCaseStepPlugin.java new file mode 100644 index 0000000..061f8f8 --- /dev/null +++ b/src/main/java/com/bioraft/rundeck/conditional/SwitchCaseStepPlugin.java @@ -0,0 +1,83 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import java.util.Map; + +import com.dtolabs.rundeck.core.Constants; +import com.dtolabs.rundeck.core.execution.workflow.steps.StepException; +import com.dtolabs.rundeck.core.plugins.Plugin; +import com.dtolabs.rundeck.plugins.ServiceNameConstants; +import com.dtolabs.rundeck.plugins.descriptions.PluginDescription; +import com.dtolabs.rundeck.plugins.descriptions.PluginProperty; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; +import com.dtolabs.rundeck.plugins.step.StepPlugin; + +/** + * Workflow Node Step Plug-in to choose one of several values to uplift into a + * step variable. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@Plugin(name = SwitchCaseStepPlugin.SERVICE_PROVIDER_NAME, service = ServiceNameConstants.WorkflowStep) +@PluginDescription(title = "Switch/Case Conditional", description = "Chooses between options for a variable value based on switch/case structure.") +public class SwitchCaseStepPlugin implements StepPlugin { + public static final String SERVICE_PROVIDER_NAME = "com.bioraft.rundeck.conditional.SwitchCaseStepPlugin"; + + @PluginProperty(title = "Group", description = "Variable group (i.e., ${group.x}", required = true) + private String group; + + @PluginProperty(title = "Name", description = "Variable name (i.e., ${group.name}", required = true) + private String name; + + @PluginProperty(title = "Cases", description = "Cases and results as colon-spliced pairs, seprated by semicolons", required = true) + private String cases; + + @PluginProperty(title = "Test Value", description = "Test value", required = true) + private String testValue; + + @PluginProperty(title = "Default", description = "Default value", required = false) + private String defaultValue; + + @PluginProperty(title = "Make global?", description = "Elevate this variable to global scope (default: false)", required = false) + private boolean elevateToGlobal; + + @Override + public void executeStep(final PluginStepContext ctx, final Map cfg) throws StepException { + + String group = cfg.getOrDefault("group", this.group).toString(); + String name = cfg.getOrDefault("name", this.name).toString(); + String cases = cfg.getOrDefault("cases", this.cases).toString(); + String testValue = cfg.getOrDefault("testValue", this.testValue).toString(); + boolean elevateToGlobal = cfg.getOrDefault("elevateToGlobal", this.elevateToGlobal).toString().equals("true"); + boolean globalHasDefault = defaultValue != null && defaultValue.length() > 0; + boolean cfgHasDefault = cfg.containsKey("defaultValue") && cfg.get("defaultValue") != null; + if (cfgHasDefault) { + this.defaultValue = cfg.get("defaultValue").toString(); + } + + ctx.getLogger().log(Constants.DEBUG_LEVEL, + "Setting " + group + "." + name + " based on " + testValue + " " + cases); + + if (cfgHasDefault || globalHasDefault) { + (new Switch(ctx)).switchCase(group, name, cases, testValue, defaultValue, elevateToGlobal); + } else { + (new Switch(ctx)).switchCase(group, name, cases, testValue, elevateToGlobal); + } + } + +} diff --git a/src/test/java/com/bioraft/rundeck/conditional/IfElseNodeStepPluginTest.java b/src/test/java/com/bioraft/rundeck/conditional/IfElseNodeStepPluginTest.java new file mode 100644 index 0000000..2ffe44b --- /dev/null +++ b/src/test/java/com/bioraft/rundeck/conditional/IfElseNodeStepPluginTest.java @@ -0,0 +1,150 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import com.dtolabs.rundeck.core.data.DataContext; +import com.dtolabs.rundeck.core.execution.workflow.SharedOutputContext; +import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException; +import com.dtolabs.rundeck.plugins.PluginLogger; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; + +/** + * Tests for IfTestStepPlugin. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@RunWith(MockitoJUnitRunner.class) +public class IfElseNodeStepPluginTest { + + IfElseNodeStepPlugin plugin; + + @Mock + PluginStepContext context; + + @Mock + PluginLogger logger; + + @Mock + SharedOutputContext sharedOutputContext; + + @Mock + DataContext dataContext; + + @Before + public void setUp() { + this.plugin = new IfElseNodeStepPlugin(); + } + + @Test + public void runTrueTests() throws NodeStepException { + int i = 0; + this.runTestTrue("apple", "eq", "apple", ++i); + this.runTestTrue("apple", "ne", "pear", ++i); + this.runTestTrue("bannana", "lt", "strawberry", ++i); + this.runTestTrue("pear", "gt", "apple", ++i); + this.runTestTrue("apple", "le", "apple", ++i); + this.runTestTrue("applepie", "ge", "apple", ++i); + this.runTestTrue("apple pie", "begins with", "apple", ++i); + this.runTestTrue("layer cake", "ends with", " cake", ++i); + this.runTestTrue("1.00", "=", "1.000", ++i); + this.runTestTrue("3", "<", "200", ++i); + this.runTestTrue("1.23", ">", "1.199", ++i); + this.runTestTrue("1", "<=", "1", ++i); + this.runTestTrue("1", ">=", "0", ++i); + this.runTestTrue("1", "!=", "2", ++i); + } + + @Test + public void runFalseTests() throws NodeStepException { + int i = 0; + this.runTestFalse("apple", "eq", "apples", ++i); + this.runTestFalse("apple", "ne", "apple", ++i); + this.runTestFalse("bannana", "gt", "strawberry", ++i); + this.runTestFalse("pear", "lt", "apple", ++i); + this.runTestFalse("apples", "le", "apple", ++i); + this.runTestFalse("apple", "ge", "banana", ++i); + this.runTestFalse("apple pie", "begins with", "pie", ++i); + this.runTestFalse("layer cake", "ends with", "layer", ++i); + this.runTestFalse("1", "=", "2", ++i); + this.runTestFalse("300", "<", "200", ++i); + this.runTestFalse("1.13", ">", "1.199", ++i); + this.runTestFalse("1", "<=", "0", ++i); + this.runTestFalse("1", ">=", "2", ++i); + this.runTestFalse("2.0", "!=", "2.00", ++i); + } + + private void runTestTrue(String testValue, String operator, String comparison, int calls) throws NodeStepException { + String group = "raft"; + String name = "test"; + String ifTrue = "1"; + String ifFalse = "0"; + + Map configuration = new HashMap<>(); + configuration.put("group", group); + configuration.put("name", name); + configuration.put("testValue", testValue); + configuration.put("operator", operator); + configuration.put("comparisonValue", comparison); + configuration.put("ifTrue", ifTrue); + configuration.put("ifFalse", ifFalse); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeNodeStep(context, configuration, null); + verify(context, atLeast(calls)).getOutputContext(); + verify(sharedOutputContext, atLeast(calls)).addOutput(eq(group), eq(name), eq(ifTrue)); + } + + private void runTestFalse(String testValue, String operator, String comparison, int calls) + throws NodeStepException { + String group = "boat"; + String name = "real"; + String ifTrue = "yes"; + String ifFalse = "no"; + + Map configuration = new HashMap<>(); + configuration.put("group", group); + configuration.put("name", name); + configuration.put("testValue", testValue); + configuration.put("operator", operator); + configuration.put("comparisonValue", comparison); + configuration.put("ifTrue", ifTrue); + configuration.put("ifFalse", ifFalse); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeNodeStep(context, configuration, null); + verify(context, atLeast(calls)).getOutputContext(); + verify(sharedOutputContext, atLeast(calls)).addOutput(eq(group), eq(name), eq(ifFalse)); + } +} diff --git a/src/test/java/com/bioraft/rundeck/conditional/IfElseStepPluginTest.java b/src/test/java/com/bioraft/rundeck/conditional/IfElseStepPluginTest.java new file mode 100644 index 0000000..5bd199a --- /dev/null +++ b/src/test/java/com/bioraft/rundeck/conditional/IfElseStepPluginTest.java @@ -0,0 +1,150 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import com.dtolabs.rundeck.core.data.DataContext; +import com.dtolabs.rundeck.core.execution.workflow.SharedOutputContext; +import com.dtolabs.rundeck.core.execution.workflow.steps.StepException; +import com.dtolabs.rundeck.plugins.PluginLogger; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; + +/** + * Tests for IfTestStepPlugin. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@RunWith(MockitoJUnitRunner.class) +public class IfElseStepPluginTest { + + IfElseStepPlugin plugin; + + @Mock + PluginStepContext context; + + @Mock + PluginLogger logger; + + @Mock + SharedOutputContext sharedOutputContext; + + @Mock + DataContext dataContext; + + @Before + public void setUp() { + this.plugin = new IfElseStepPlugin(); + } + + @Test + public void runTrueTests() throws StepException { + int i = 0; + this.runTestTrue("apple", "eq", "apple", ++i); + this.runTestTrue("apple", "ne", "pear", ++i); + this.runTestTrue("bannana", "lt", "strawberry", ++i); + this.runTestTrue("pear", "gt", "apple", ++i); + this.runTestTrue("apple", "le", "apple", ++i); + this.runTestTrue("applepie", "ge", "apple", ++i); + this.runTestTrue("apple pie", "begins with", "apple", ++i); + this.runTestTrue("layer cake", "ends with", " cake", ++i); + this.runTestTrue("1.00", "=", "1.000", ++i); + this.runTestTrue("3", "<", "200", ++i); + this.runTestTrue("1.23", ">", "1.199", ++i); + this.runTestTrue("1", "<=", "1", ++i); + this.runTestTrue("1", ">=", "0", ++i); + this.runTestTrue("1", "!=", "2", ++i); + } + + @Test + public void runFalseTests() throws StepException { + int i = 0; + this.runTestFalse("apple", "eq", "apples", ++i); + this.runTestFalse("apple", "ne", "apple", ++i); + this.runTestFalse("bannana", "gt", "strawberry", ++i); + this.runTestFalse("pear", "lt", "apple", ++i); + this.runTestFalse("apples", "le", "apple", ++i); + this.runTestFalse("apple", "ge", "banana", ++i); + this.runTestFalse("apple pie", "begins with", "pie", ++i); + this.runTestFalse("layer cake", "ends with", "layer", ++i); + this.runTestFalse("1", "=", "2", ++i); + this.runTestFalse("300", "<", "200", ++i); + this.runTestFalse("1.13", ">", "1.199", ++i); + this.runTestFalse("1", "<=", "0", ++i); + this.runTestFalse("1", ">=", "2", ++i); + this.runTestFalse("2.0", "!=", "2.00", ++i); + } + + private void runTestTrue(String testValue, String operator, String comparison, int calls) throws StepException { + String group = "raft"; + String name = "test"; + String ifTrue = "1"; + String ifFalse = "0"; + + Map configuration = new HashMap<>(); + configuration.put("group", group); + configuration.put("name", name); + configuration.put("testValue", testValue); + configuration.put("operator", operator); + configuration.put("comparisonValue", comparison); + configuration.put("ifTrue", ifTrue); + configuration.put("ifFalse", ifFalse); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeStep(context, configuration); + verify(context, atLeast(calls)).getOutputContext(); + verify(sharedOutputContext, atLeast(calls)).addOutput(eq(group), eq(name), eq(ifTrue)); + } + + private void runTestFalse(String testValue, String operator, String comparison, int calls) + throws StepException { + String group = "boat"; + String name = "real"; + String ifTrue = "yes"; + String ifFalse = "no"; + + Map configuration = new HashMap<>(); + configuration.put("group", group); + configuration.put("name", name); + configuration.put("testValue", testValue); + configuration.put("operator", operator); + configuration.put("comparisonValue", comparison); + configuration.put("ifTrue", ifTrue); + configuration.put("ifFalse", ifFalse); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeStep(context, configuration); + verify(context, atLeast(calls)).getOutputContext(); + verify(sharedOutputContext, atLeast(calls)).addOutput(eq(group), eq(name), eq(ifFalse)); + } +} diff --git a/src/test/java/com/bioraft/rundeck/conditional/SwitchCaseNodeStepPluginTest.java b/src/test/java/com/bioraft/rundeck/conditional/SwitchCaseNodeStepPluginTest.java new file mode 100644 index 0000000..dc402fa --- /dev/null +++ b/src/test/java/com/bioraft/rundeck/conditional/SwitchCaseNodeStepPluginTest.java @@ -0,0 +1,148 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import com.dtolabs.rundeck.core.common.INodeEntry; +import com.dtolabs.rundeck.core.data.DataContext; +import com.dtolabs.rundeck.core.execution.workflow.SharedOutputContext; +import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException; +import com.dtolabs.rundeck.plugins.PluginLogger; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; +import com.google.common.collect.ImmutableMap; + +/** + * Tests for IfTestStepPlugin. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@RunWith(MockitoJUnitRunner.class) +public class SwitchCaseNodeStepPluginTest { + + SwitchCaseNodeStepPlugin plugin; + + @Mock + PluginStepContext context; + + @Mock + PluginLogger logger; + + @Mock + SharedOutputContext sharedOutputContext; + + @Mock + DataContext dataContext; + + @Mock + INodeEntry node; + + @Before + public void setUp() { + this.plugin = new SwitchCaseNodeStepPlugin(); + } + + @Test + public void runTestOne() throws NodeStepException { + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + this.runTest("v1", "k1", cases, "any"); + } + + @Test + public void runTestTwo() throws NodeStepException { + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + this.runTest("v2", "k2", cases, "any"); + } + + @Test + public void returnsDefaultOnNoMatch() throws NodeStepException { + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + this.runTest("any", "k3", cases, "any"); + } + + @Test + public void runTestDefaultIsNull() throws NodeStepException { + Map configuration = new HashMap<>(); + configuration.put("defaultValue", null); + this.runTestNoDefault("any", "k3", configuration); + } + + @Test + public void runTestNoDefaultValue() throws NodeStepException { + Map configuration = new HashMap<>(); + this.runTestNoDefault("any", "k3", configuration); + } + + private void runTest(String expected, String testValue, Map cases, String defaultValue) + throws NodeStepException { + String group = "raft"; + String name = "test"; + StringBuffer caseString = new StringBuffer(); + cases.forEach((k, v) -> caseString.append(k + ":" + v + ";")); + + Map configuration = new HashMap<>(); + configuration.put("group", group); + configuration.put("name", name); + configuration.put("cases", "k1:v1;k2:v2"); + configuration.put("testValue", testValue); + configuration.put("defaultValue", defaultValue); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeNodeStep(context, configuration, node); + verify(context, times(1)).getOutputContext(); + verify(sharedOutputContext, times(1)).addOutput(eq(group), eq(name), eq(expected)); + } + + public void runTestNoDefault(String expected, String testValue, Map configuration) + throws NodeStepException { + String group = "raft"; + String name = "test"; + + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + StringBuilder caseString = new StringBuilder(); + cases.forEach((k, v) -> caseString.append(k + ":" + v + ";")); + configuration.put("cases", caseString.toString()); + + configuration.put("group", group); + configuration.put("name", name); + configuration.put("testValue", "v3"); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeNodeStep(context, configuration, node); + verify(context, never()).getOutputContext(); + verify(sharedOutputContext, never()).addOutput(any(String.class), any(String.class), any(String.class)); + } + +} diff --git a/src/test/java/com/bioraft/rundeck/conditional/SwitchCaseStepPluginTest.java b/src/test/java/com/bioraft/rundeck/conditional/SwitchCaseStepPluginTest.java new file mode 100644 index 0000000..1f7aa2d --- /dev/null +++ b/src/test/java/com/bioraft/rundeck/conditional/SwitchCaseStepPluginTest.java @@ -0,0 +1,146 @@ +/* + * Copyright 2019 BioRAFT, Inc. (http://bioraft.com) + * + * 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 + * + * http://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 com.bioraft.rundeck.conditional; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import com.dtolabs.rundeck.core.common.INodeEntry; +import com.dtolabs.rundeck.core.data.DataContext; +import com.dtolabs.rundeck.core.execution.workflow.SharedOutputContext; +import com.dtolabs.rundeck.core.execution.workflow.steps.StepException; +import com.dtolabs.rundeck.plugins.PluginLogger; +import com.dtolabs.rundeck.plugins.step.PluginStepContext; +import com.google.common.collect.ImmutableMap; + +/** + * Tests for IfTestStepPlugin. + * + * @author Karl DeBisschop + * @since 2019-12-11 + */ +@RunWith(MockitoJUnitRunner.class) +public class SwitchCaseStepPluginTest { + + SwitchCaseStepPlugin plugin; + + @Mock + PluginStepContext context; + + @Mock + PluginLogger logger; + + @Mock + SharedOutputContext sharedOutputContext; + + @Mock + DataContext dataContext; + + @Mock + INodeEntry node; + + @Before + public void setUp() { + this.plugin = new SwitchCaseStepPlugin(); + } + + @Test + public void runTestOne() throws StepException { + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + this.runTest("v1", "k1", cases, "any"); + } + + @Test + public void runTestTwo() throws StepException { + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + this.runTest("v2", "k2", cases, "any"); + } + + @Test + public void returnsDefaultOnNoMatch() throws StepException { + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + this.runTest("any", "k3", cases, "any"); + } + + @Test + public void runTestFour() throws StepException { + Map configuration = new HashMap<>(); + configuration.put("defaultValue", null); + this.runTestNoDefault("any", "k3", configuration); + } + + @Test + public void runTestFive() throws StepException { + Map configuration = new HashMap<>(); + this.runTestNoDefault("any", "k3", configuration); + } + + private void runTest(String expected, String testValue, Map cases, String defaultValue) + throws StepException { + String group = "raft"; + String name = "test"; + StringBuffer caseString = new StringBuffer(); + cases.forEach((k, v) -> caseString.append(k + ":" + v + ";")); + + Map configuration = new HashMap<>(); + configuration.put("group", group); + configuration.put("name", name); + configuration.put("cases", "k1:v1;k2:v2"); + configuration.put("testValue", testValue); + configuration.put("defaultValue", defaultValue); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeStep(context, configuration); + verify(context, times(1)).getOutputContext(); + verify(sharedOutputContext, times(1)).addOutput(eq(group), eq(name), eq(expected)); + } + + public void runTestNoDefault(String expected, String testValue, Map configuration) throws StepException { + String group = "raft"; + String name = "test"; + + Map cases = ImmutableMap.builder().put("k1", "v1").put("k2", "v2").build(); + StringBuilder caseString = new StringBuilder(); + cases.forEach((k, v) -> caseString.append(k + ":" + v + ";")); + configuration.put("cases", caseString.toString()); + + configuration.put("group", group); + configuration.put("name", name); + configuration.put("testValue", "v3"); + + when(context.getOutputContext()).thenReturn(sharedOutputContext); + when(context.getLogger()).thenReturn(logger); + + this.plugin.executeStep(context, configuration); + verify(context, never()).getOutputContext(); + verify(sharedOutputContext, never()).addOutput(any(String.class), any(String.class), any(String.class)); + } +}