diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..3874610 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,36 @@ +version: 2.1 + +orbs: + win: circleci/windows@1.0.0 + +workflows: + test: + jobs: + - build-linux + - build-windows + +# This CI build just ensures that the demo compiles correctly. + +jobs: + build-linux: + docker: + - image: circleci/java + steps: + - checkout + - run: ./gradlew dependencies + - run: ./gradlew build + + build-test-windows: + executor: + name: win/vs2019 + shell: powershell.exe + steps: + - checkout + - run: + name: install OpenJDK + command: | + $ProgressPreference = "SilentlyContinue" # prevents console errors from CircleCI host + iwr -outf openjdk.msi https://developers.redhat.com/download-manager/file/java-11-openjdk-11.0.5.10-2.windows.redhat.x86_64.msi + Start-Process msiexec.exe -Wait -ArgumentList '/I openjdk.msi /quiet' + - run: .\gradlew.bat --no-daemon dependencies # must use --no-daemon because CircleCI in Windows will hang if there's a daemon running + - run: .\gradlew.bat --no-daemon build # must use --no-daemon because CircleCI in Windows will hang if there's a daemon running diff --git a/.gitignore b/.gitignore index 97fa749..fe64b5a 100644 --- a/.gitignore +++ b/.gitignore @@ -8,5 +8,6 @@ *.iws .idea/ -# Maven -target \ No newline at end of file +# Gradle +.gradle +build \ No newline at end of file diff --git a/README.md b/README.md index d6fdd3c..e8a35b6 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,21 @@ -### LaunchDarkly Sample Java Application
 ### -We've built a simple console application that demonstrates how LaunchDarkly's SDK works. 
Below, you'll find the basic build procedure, but for more comprehensive instructions, you can visit your [Quickstart page](https://app.launchdarkly.com/quickstart#/). -##### Build instructions
 ##### -1. Make sure you have [Maven](https://maven.apache.org/download.cgi) installed. We've tested against Maven 3 -2. Create a new project -3. Copy your SDK key and feature flag key from your LaunchDarkly dashboard into `main`
 -4. Make sure `pom.xml` is referencing the latest version of `launchdarkly-java-server-sdk`; you can see the latest release [here](https://github.com/launchdarkly/java-server-sdk/releases) -5. Run `mvn clean compile assembly:single` -6. Then run `java -jar target/hello-java-1.0-SNAPSHOT-jar-with-dependencies.jar` +# LaunchDarkly Sample Java Application
 + +We've built a simple console application that demonstrates how LaunchDarkly's SDK works. + +
Below, you'll find the basic build procedure, but for more comprehensive instructions, you can visit your [Quickstart page](https://app.launchdarkly.com/quickstart#/) or the [Java SDK reference guide](https://docs.launchdarkly.com/sdk/server-side/java). + +## Build instructions
 + +This project uses [Gradle](https://gradle.org/). It requires that Java is already installed on your system (version 7 or higher). It will automatically use the latest release of the LaunchDarkly SDK with major version 4. + +1. Edit `src/main/java/Hello.java` and set the value of `SDK_KEY` to your LaunchDarkly SDK key. If there is an existing boolean feature flag in your LaunchDarkly project that you want to evaluate, set `FEATURE_FLAG_KEY` to the flag key. + +```java + static final String SDK_KEY = "1234567890abcdef"; + + static final String FEATURE_FLAG_KEY = "my-flag"; +``` + +2. On the command line, run `./gradlew run` (or, on Windows, `gradlew run`). + +The demo should print `"Feature flag '' is for this user"`. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..90ef5de --- /dev/null +++ b/build.gradle @@ -0,0 +1,29 @@ + +plugins { + id "java" + id "application" +} + +repositories { + mavenCentral() +} + +allprojects { + sourceCompatibility = 1.7 + targetCompatibility = 1.7 +} + +application { + mainClassName = "Hello" +} + +ext.versions = [ + "sdk": "4.+", // will use the latest 4.x version + "slf4j": "1.7.22" +] + +dependencies { + implementation "com.launchdarkly:launchdarkly-java-server-sdk:4.+" + implementation "org.slf4j:slf4j-api:${versions.slf4j}" + implementation "org.slf4j:slf4j-simple:${versions.slf4j}" +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..29953ea 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..a2bf131 --- /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.2.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## 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="" + +# 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, switch paths to Windows format before running java +if $cygwin ; 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=$((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" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@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= + +@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/pom.xml b/pom.xml deleted file mode 100644 index 86bf75b..0000000 --- a/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - - com.launchdarkly.tutorial - hello-java - 1.0-SNAPSHOT - - - com.launchdarkly - launchdarkly-java-server-sdk - 4.12.1 - compile - - - org.slf4j - slf4j-simple - 1.7.14 - compile - - - - 7 - 7 - - - - - maven-assembly-plugin - - - - Hello - - - - jar-with-dependencies - - - - - - diff --git a/src/main/java/Hello.java b/src/main/java/Hello.java index 557a58a..e19f8fe 100644 --- a/src/main/java/Hello.java +++ b/src/main/java/Hello.java @@ -1,30 +1,42 @@ import com.launchdarkly.client.LDClient; import com.launchdarkly.client.LDUser; +import com.launchdarkly.client.value.LDValue; import java.io.IOException; -import static java.util.Collections.singletonList; - public class Hello { - public static void main(String... args) throws IOException { - LDClient client = new LDClient("YOUR_SDK_KEY"); + // Set SDK_KEY to your LaunchDarkly SDK key before compiling + static final String SDK_KEY = ""; + + // Set FEATURE_FLAG_KEY to the feature flag key you want to evaluate + static final String FEATURE_FLAG_KEY = "YOUR_FEATURE_KEY"; + + public static void main(String... args) throws IOException { + if (SDK_KEY.equals("")) { + System.out.println("Please edit Hello.java to set SDK_KEY to your LaunchDarkly SDK key first"); + System.exit(1); + } + + LDClient client = new LDClient(SDK_KEY); - LDUser user = new LDUser.Builder("bob@example.com") - .firstName("Bob") - .lastName("Loblaw") - .customString("groups", singletonList("beta_testers")) - .build(); + // Set up the user properties. This user should appear on your LaunchDarkly users dashboard + // soon after you run the demo. + LDUser user = new LDUser.Builder("bob@example.com") + .firstName("Bob") + .lastName("Loblaw") + .custom("groups", LDValue.buildArray().add("beta_testers").build()) + .build(); - boolean showFeature = client.boolVariation("YOUR_FEATURE_KEY", user, false); + boolean showFeature = client.boolVariation(FEATURE_FLAG_KEY, user, false); - if (showFeature) { - System.out.println("Showing your feature"); - } else { - System.out.println("Not showing your feature"); - } + System.out.println("Feature flag '" + FEATURE_FLAG_KEY + "' is " + showFeature + " for this user"); - client.flush(); - client.close(); - } + // Calling client.close() ensures that the SDK shuts down cleanly before the program exits. + // Unless you do this, the SDK may not have a chance to deliver analytics events to LaunchDarkly, + // so the user properties and the flag usage statistics may not appear on your dashboard. In a + // normal long-running application, events would be delivered automatically in the background + // and you would not need to close the client. + client.close(); + } } diff --git a/src/main/resources/simplelogger.properties b/src/main/resources/simplelogger.properties index 1d0e270..df45e59 100644 --- a/src/main/resources/simplelogger.properties +++ b/src/main/resources/simplelogger.properties @@ -1,34 +1,13 @@ # SLF4J's SimpleLogger configuration file -# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err. -# Default logging detail level for all instances of SimpleLogger. -# Must be one of ("trace", "debug", "info", "warn", or "error"). -# If not specified, defaults to "info". -org.slf4j.simpleLogger.defaultLogLevel=info +# For the purposes of this demo, we are using the simple console logging implementation that is +# provided by org.slf4j:slf4j-simple. In a real application, there are many possible ways to +# configure the logging behavior. See: http://www.slf4j.org/ -# Logging detail level for a SimpleLogger instance named "xxxxx". -# Must be one of ("trace", "debug", "info", "warn", or "error"). -# If not specified, the default logging detail level is used. -#org.slf4j.simpleLogger.log.xxxxx= +# Set defaultLogLevel to "info" or "debug" to see more detailed log output from the SDK. +org.slf4j.simpleLogger.defaultLogLevel=warn -# Set to true if you want the current date and time to be included in output messages. -# Default is false, and will output the number of milliseconds elapsed since startup. org.slf4j.simpleLogger.showDateTime=true - -# The date and time format to be used in the output messages. -# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. -# If the format is not specified or is invalid, the default format is used. -# The default format is yyyy-MM-dd HH:mm:ss:SSS Z. org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z - -# Set to true if you want to output the current thread name. -# Defaults to true. org.slf4j.simpleLogger.showThreadName=true - -# Set to true if you want the Logger instance name to be included in output messages. -# Defaults to true. org.slf4j.simpleLogger.showLogName=true - -# Set to true if you want the last component of the name to be included in output messages. -# Defaults to false. -#org.slf4j.simpleLogger.showShortLogName=false \ No newline at end of file